From cb21bc4d7a67f0974c2773fdd0f5376f177c068e Mon Sep 17 00:00:00 2001 From: Zenexer Date: Wed, 30 Mar 2011 04:03:21 +0000 Subject: 2.1 prerelease, part 2 of 3 git-svn-id: https://svn.java.net/svn/essentials~svn/trunk2.1@1015 e251c2fe-e539-e718-e476-b85c1f46cddb --- BuildAll/build.xml | 74 + BuildAll/nbproject/build-impl.xml | 1142 ++++++++++++++ BuildAll/nbproject/genfiles.properties | 8 + BuildAll/nbproject/private/config.properties | 0 BuildAll/nbproject/private/private.properties | 6 + BuildAll/nbproject/project.properties | 90 ++ BuildAll/nbproject/project.xml | 68 + Essentials/.gitignore | 7 + Essentials/build.xml | 75 + Essentials/nbproject/build-impl.xml | 1058 +++++++++++++ Essentials/nbproject/genfiles.properties | 11 + Essentials/nbproject/private/private.properties | 1 + Essentials/nbproject/project.properties | 76 + Essentials/nbproject/project.xml | 19 + Essentials/settings/Editor.zip | Bin 0 -> 18717 bytes Essentials/src/com/earth2me/essentials/Backup.java | 82 + .../src/com/earth2me/essentials/Essentials.java | 684 ++++++++ .../essentials/EssentialsBlockListener.java | 214 +++ .../com/earth2me/essentials/EssentialsConf.java | 120 ++ .../essentials/EssentialsEcoBlockListener.java | 159 ++ .../essentials/EssentialsEntityListener.java | 65 + .../essentials/EssentialsPlayerListener.java | 452 ++++++ Essentials/src/com/earth2me/essentials/IConf.java | 5 + .../earth2me/essentials/InventoryWorkaround.java | 136 ++ Essentials/src/com/earth2me/essentials/ItemDb.java | 110 ++ Essentials/src/com/earth2me/essentials/Jail.java | 117 ++ Essentials/src/com/earth2me/essentials/Mob.java | 122 ++ .../src/com/earth2me/essentials/NetherPortal.java | 167 ++ .../src/com/earth2me/essentials/OfflinePlayer.java | 351 +++++ .../com/earth2me/essentials/PlayerExtension.java | 141 ++ .../src/com/earth2me/essentials/PlayerWrapper.java | 416 +++++ .../src/com/earth2me/essentials/Settings.java | 348 +++++ Essentials/src/com/earth2me/essentials/Spawn.java | 87 ++ .../src/com/earth2me/essentials/TargetBlock.java | 599 +++++++ .../src/com/earth2me/essentials/TeleportTimer.java | 73 + Essentials/src/com/earth2me/essentials/User.java | 695 +++++++++ Essentials/src/com/earth2me/essentials/Warps.java | 244 +++ .../earth2me/essentials/commands/Commandafk.java | 32 + .../essentials/commands/Commandantioch.java | 39 + .../earth2me/essentials/commands/Commandback.java | 22 + .../essentials/commands/Commandbackup.java | 43 + .../essentials/commands/Commandbalance.java | 23 + .../earth2me/essentials/commands/Commandban.java | 42 + .../earth2me/essentials/commands/Commandbanip.java | 30 + .../essentials/commands/Commandbigtree.java | 56 + .../essentials/commands/Commandbroadcast.java | 32 + .../earth2me/essentials/commands/Commandburn.java | 32 + .../essentials/commands/Commandclearinventory.java | 99 ++ .../essentials/commands/Commandcompass.java | 32 + .../essentials/commands/Commanddeljail.java | 33 + .../essentials/commands/Commanddelwarp.java | 41 + .../earth2me/essentials/commands/Commanddepth.java | 24 + .../earth2me/essentials/commands/Commandeco.java | 82 + .../essentials/commands/Commandessentials.java | 30 + .../earth2me/essentials/commands/Commandext.java | 29 + .../earth2me/essentials/commands/Commandgc.java | 29 + .../essentials/commands/Commandgetpos.java | 33 + .../earth2me/essentials/commands/Commandgive.java | 49 + .../earth2me/essentials/commands/Commandgod.java | 32 + .../earth2me/essentials/commands/Commandheal.java | 53 + .../earth2me/essentials/commands/Commandhelp.java | 129 ++ .../essentials/commands/Commandhelpop.java | 33 + .../earth2me/essentials/commands/Commandhome.java | 21 + .../essentials/commands/Commandinvsee.java | 39 + .../earth2me/essentials/commands/Commanditem.java | 45 + .../earth2me/essentials/commands/Commandjails.java | 37 + .../earth2me/essentials/commands/Commandjump.java | 50 + .../earth2me/essentials/commands/Commandkick.java | 41 + .../essentials/commands/Commandkickall.java | 55 + .../earth2me/essentials/commands/Commandkill.java | 33 + .../earth2me/essentials/commands/Commandkit.java | 150 ++ .../earth2me/essentials/commands/Commandlist.java | 93 ++ .../earth2me/essentials/commands/Commandmail.java | 52 + .../earth2me/essentials/commands/Commandme.java | 43 + .../earth2me/essentials/commands/Commandmotd.java | 25 + .../earth2me/essentials/commands/Commandmsg.java | 85 + .../earth2me/essentials/commands/Commandmute.java | 64 + .../earth2me/essentials/commands/Commandnick.java | 129 ++ .../earth2me/essentials/commands/Commandnuble.java | 21 + .../earth2me/essentials/commands/Commandpay.java | 42 + .../earth2me/essentials/commands/Commandping.java | 26 + .../essentials/commands/Commandplugin.java | 161 ++ .../com/earth2me/essentials/commands/Commandr.java | 37 + .../essentials/commands/Commandrealname.java | 40 + .../essentials/commands/Commandreloadall.java | 37 + .../earth2me/essentials/commands/Commandrules.java | 23 + .../earth2me/essentials/commands/Commandsell.java | 63 + .../essentials/commands/Commandsethome.java | 22 + .../essentials/commands/Commandsetjail.java | 28 + .../essentials/commands/Commandsetwarp.java | 30 + .../essentials/commands/Commandspawner.java | 41 + .../essentials/commands/Commandspawnmob.java | 188 +++ .../essentials/commands/Commandsuicide.java | 23 + .../earth2me/essentials/commands/Commandtime.java | 63 + .../essentials/commands/Commandtogglejail.java | 67 + .../earth2me/essentials/commands/Commandtop.java | 26 + .../earth2me/essentials/commands/Commandtp.java | 61 + .../earth2me/essentials/commands/Commandtpa.java | 34 + .../essentials/commands/Commandtpaccept.java | 40 + .../essentials/commands/Commandtpahere.java | 33 + .../essentials/commands/Commandtpdeny.java | 37 + .../essentials/commands/Commandtphere.java | 34 + .../earth2me/essentials/commands/Commandtpo.java | 34 + .../essentials/commands/Commandtpohere.java | 31 + .../earth2me/essentials/commands/Commandtppos.java | 42 + .../essentials/commands/Commandtptoggle.java | 21 + .../earth2me/essentials/commands/Commandtree.java | 64 + .../earth2me/essentials/commands/Commandunban.java | 35 + .../essentials/commands/Commandunbanip.java | 35 + .../earth2me/essentials/commands/Commandwarp.java | 74 + .../earth2me/essentials/commands/Commandwhois.java | 44 + .../earth2me/essentials/commands/Commandworld.java | 67 + .../earth2me/essentials/commands/Commandworth.java | 48 + .../essentials/commands/EssentialsCommand.java | 80 + .../essentials/commands/IEssentialsCommand.java | 20 + Essentials/src/config.yml | 385 +++++ Essentials/src/items.csv | 887 +++++++++++ Essentials/src/plugin.yml | 248 +++ .../com/earth2me/essentials/EssentialsTest.java | 60 + .../com/earth2me/essentials/PermissionsTest.java | 17 + .../test/com/earth2me/essentials/UserTest.java | 72 + .../workdir/EssentialsGroupManager/config.yml | 0 Essentials/workdir/banned-ips.txt | 0 Essentials/workdir/banned-players.txt | 0 Essentials/workdir/ops.txt | 0 Essentials/workdir/plugins/Permissions/default.yml | 0 Essentials/workdir/server.log | 264 ++++ Essentials/workdir/server.log.1 | 0 Essentials/workdir/server.log.1.lck | 0 Essentials/workdir/server.properties | 13 + Essentials/workdir/userdata/TestPlayer1.yml | 2 + Essentials/workdir/white-list.txt | 0 EssentialsChat/build.xml | 76 + EssentialsChat/nbproject/build-impl.xml | 1072 +++++++++++++ EssentialsChat/nbproject/genfiles.properties | 8 + .../nbproject/private/private.properties | 1 + EssentialsChat/nbproject/project.properties | 79 + EssentialsChat/nbproject/project.xml | 28 + .../earth2me/essentials/chat/EssentialsChat.java | 43 + .../chat/EssentialsChatPlayerListener.java | 61 + .../essentials/chat/EssentialsChatWorker.java | 122 ++ EssentialsChat/src/plugin.yml | 8 + EssentialsGroupBridge/build.xml | 74 + EssentialsGroupBridge/nbproject/build-impl.xml | 1047 +++++++++++++ .../nbproject/genfiles.properties | 8 + .../nbproject/private/private.properties | 1 + EssentialsGroupBridge/nbproject/project.properties | 78 + EssentialsGroupBridge/nbproject/project.xml | 25 + .../src/com/nijiko/Messaging.class | Bin 0 -> 2604 bytes .../src/com/nijiko/Misc$string.class | Bin 0 -> 982 bytes EssentialsGroupBridge/src/com/nijiko/Misc.class | Bin 0 -> 3980 bytes .../configuration/ConfigurationHandler.class | Bin 0 -> 788 bytes .../configuration/DefaultConfiguration.class | Bin 0 -> 435 bytes .../src/com/nijiko/database/Wrapper$Type.class | Bin 0 -> 1107 bytes .../src/com/nijiko/database/Wrapper.class | Bin 0 -> 5428 bytes .../src/com/nijiko/permissions/Control.class | Bin 0 -> 27337 bytes .../com/nijiko/permissions/PermissionHandler.class | Bin 0 -> 3198 bytes .../nijikokun/bukkit/Permissions/Permissions.java | 102 ++ .../permissions/NijikoPermissionsProxy.java | 428 +++++ EssentialsGroupBridge/src/plugin.yml | 3 + EssentialsGroupManager/build.xml | 74 + EssentialsGroupManager/nbproject/build-impl.xml | 1033 +++++++++++++ .../nbproject/genfiles.properties | 8 + .../nbproject/private/private.properties | 1 + .../nbproject/project.properties | 73 + EssentialsGroupManager/nbproject/project.xml | 15 + EssentialsGroupManager/src/config.yml | 14 + EssentialsGroupManager/src/groups.yml | 172 +++ .../anjocaido/groupmanager/GMConfiguration.java | 120 ++ .../org/anjocaido/groupmanager/GroupManager.java | 1634 ++++++++++++++++++++ .../org/anjocaido/groupmanager/data/DataUnit.java | 114 ++ .../src/org/anjocaido/groupmanager/data/Group.java | 122 ++ .../groupmanager/data/GroupVariables.java | 87 ++ .../src/org/anjocaido/groupmanager/data/User.java | 187 +++ .../anjocaido/groupmanager/data/UserVariables.java | 45 + .../org/anjocaido/groupmanager/data/Variables.java | 192 +++ .../dataholder/OverloadedWorldHolder.java | 204 +++ .../groupmanager/dataholder/WorldDataHolder.java | 939 +++++++++++ .../dataholder/worlds/WorldsHolder.java | 423 +++++ .../permissions/AnjoPermissionsHandler.java | 856 ++++++++++ .../permissions/PermissionsReaderInterface.java | 163 ++ .../groupmanager/utils/GMLoggerHandler.java | 26 + .../utils/GroupManagerPermissions.java | 51 + .../groupmanager/utils/PermissionCheckResult.java | 66 + .../utils/StringPermissionComparator.java | 50 + .../org/anjocaido/groupmanager/utils/Tasks.java | 111 ++ EssentialsGroupManager/src/plugin.yml | 165 ++ EssentialsGroupManager/src/users.yml | 59 + EssentialsProtect/MANIFEST.MF | 2 + EssentialsProtect/build.xml | 86 ++ EssentialsProtect/nbproject/build-impl.xml | 1072 +++++++++++++ EssentialsProtect/nbproject/genfiles.properties | 8 + .../nbproject/private/private.properties | 1 + EssentialsProtect/nbproject/project.properties | 91 ++ EssentialsProtect/nbproject/project.xml | 28 + EssentialsProtect/src/README.TXT | 30 + .../essentials/protect/EssentialsProtect.java | 154 ++ .../protect/EssentialsProtectBlockListener.java | 272 ++++ .../essentials/protect/EssentialsProtectData.java | 533 +++++++ .../protect/EssentialsProtectEntityListener.java | 197 +++ .../protect/EssentialsProtectPlayerListener.java | 70 + .../protect/EssentialsProtectRegions.java | 5 + .../protect/EssentialsProtectSqlProperties.java | 12 + .../essentials/protect/data/IProtectedBlock.java | 15 + .../essentials/protect/data/OwnedBlock.java | 9 + .../protect/data/ProtectedBlockJDBC.java | 292 ++++ .../protect/data/ProtectedBlockMemory.java | 205 +++ .../protect/data/ProtectedBlockMySQL.java | 89 ++ .../protect/data/ProtectedBlockSQLite.java | 87 ++ EssentialsProtect/src/plugin.yml | 8 + EssentialsSpawn/build.xml | 76 + EssentialsSpawn/nbproject/build-impl.xml | 1072 +++++++++++++ EssentialsSpawn/nbproject/genfiles.properties | 8 + .../nbproject/private/private.properties | 1 + EssentialsSpawn/nbproject/project.properties | 76 + EssentialsSpawn/nbproject/project.xml | 28 + .../earth2me/essentials/spawn/Commandsetspawn.java | 24 + .../earth2me/essentials/spawn/Commandspawn.java | 23 + .../earth2me/essentials/spawn/EssentialsSpawn.java | 65 + .../spawn/EssentialsSpawnPlayerListener.java | 51 + .../essentials/spawn/EssentialsSpawnWorker.java | 56 + EssentialsSpawn/src/plugin.yml | 15 + build.inc.xml | 7 + ...beans-modules-java-j2seproject-copylibstask.jar | Bin 0 -> 17873 bytes lib/Permissions.jar | Bin 0 -> 32227 bytes lib/c3p0-0.9.1.2.jar | Bin 0 -> 610790 bytes lib/craftbukkit-0.0.1-SNAPSHOT.jar | Bin 0 -> 1458639 bytes lib/gson.jar | Bin 0 -> 164986 bytes lib/iConomy.jar | Bin 0 -> 65038 bytes lib/junit/junit-3.8.2-api.zip | Bin 0 -> 72555 bytes lib/junit/junit-3.8.2.jar | Bin 0 -> 118932 bytes lib/junit_4/junit-4.5-api.zip | Bin 0 -> 184067 bytes lib/junit_4/junit-4.5-src.jar | Bin 0 -> 109014 bytes lib/junit_4/junit-4.5.jar | Bin 0 -> 196787 bytes lib/mysql.jar | Bin 0 -> 703265 bytes lib/nblibraries.properties | 12 + lib/sqlite.jar | Bin 0 -> 1304214 bytes 237 files changed, 28831 insertions(+) create mode 100644 BuildAll/build.xml create mode 100644 BuildAll/nbproject/build-impl.xml create mode 100644 BuildAll/nbproject/genfiles.properties create mode 100644 BuildAll/nbproject/private/config.properties create mode 100644 BuildAll/nbproject/private/private.properties create mode 100644 BuildAll/nbproject/project.properties create mode 100644 BuildAll/nbproject/project.xml create mode 100644 Essentials/.gitignore create mode 100644 Essentials/build.xml create mode 100644 Essentials/nbproject/build-impl.xml create mode 100644 Essentials/nbproject/genfiles.properties create mode 100644 Essentials/nbproject/private/private.properties create mode 100644 Essentials/nbproject/project.properties create mode 100644 Essentials/nbproject/project.xml create mode 100644 Essentials/settings/Editor.zip create mode 100644 Essentials/src/com/earth2me/essentials/Backup.java create mode 100644 Essentials/src/com/earth2me/essentials/Essentials.java create mode 100644 Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java create mode 100644 Essentials/src/com/earth2me/essentials/EssentialsConf.java create mode 100644 Essentials/src/com/earth2me/essentials/EssentialsEcoBlockListener.java create mode 100644 Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java create mode 100644 Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java create mode 100644 Essentials/src/com/earth2me/essentials/IConf.java create mode 100644 Essentials/src/com/earth2me/essentials/InventoryWorkaround.java create mode 100644 Essentials/src/com/earth2me/essentials/ItemDb.java create mode 100644 Essentials/src/com/earth2me/essentials/Jail.java create mode 100644 Essentials/src/com/earth2me/essentials/Mob.java create mode 100644 Essentials/src/com/earth2me/essentials/NetherPortal.java create mode 100644 Essentials/src/com/earth2me/essentials/OfflinePlayer.java create mode 100644 Essentials/src/com/earth2me/essentials/PlayerExtension.java create mode 100644 Essentials/src/com/earth2me/essentials/PlayerWrapper.java create mode 100644 Essentials/src/com/earth2me/essentials/Settings.java create mode 100644 Essentials/src/com/earth2me/essentials/Spawn.java create mode 100644 Essentials/src/com/earth2me/essentials/TargetBlock.java create mode 100644 Essentials/src/com/earth2me/essentials/TeleportTimer.java create mode 100644 Essentials/src/com/earth2me/essentials/User.java create mode 100644 Essentials/src/com/earth2me/essentials/Warps.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandafk.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandantioch.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandback.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandbackup.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandbalance.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandban.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandbanip.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandburn.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandcompass.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commanddepth.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandeco.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandessentials.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandext.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandgc.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandgive.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandgod.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandheal.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandhelp.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandhome.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commanditem.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandjails.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandjump.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandkick.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandkickall.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandkill.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandkit.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandlist.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandmail.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandme.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandmotd.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandmsg.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandmute.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandnick.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandnuble.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandpay.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandping.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandplugin.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandr.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandrealname.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandreloadall.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandrules.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandsell.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandsethome.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandspawner.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtime.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtop.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtp.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtpa.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtphere.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtpo.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtppos.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandtree.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandunban.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandwarp.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandwhois.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandworld.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/Commandworth.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java create mode 100644 Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java create mode 100644 Essentials/src/config.yml create mode 100644 Essentials/src/items.csv create mode 100644 Essentials/src/plugin.yml create mode 100644 Essentials/test/com/earth2me/essentials/EssentialsTest.java create mode 100644 Essentials/test/com/earth2me/essentials/PermissionsTest.java create mode 100644 Essentials/test/com/earth2me/essentials/UserTest.java create mode 100644 Essentials/workdir/EssentialsGroupManager/config.yml create mode 100644 Essentials/workdir/banned-ips.txt create mode 100644 Essentials/workdir/banned-players.txt create mode 100644 Essentials/workdir/ops.txt create mode 100644 Essentials/workdir/plugins/Permissions/default.yml create mode 100644 Essentials/workdir/server.log create mode 100644 Essentials/workdir/server.log.1 create mode 100644 Essentials/workdir/server.log.1.lck create mode 100644 Essentials/workdir/server.properties create mode 100644 Essentials/workdir/userdata/TestPlayer1.yml create mode 100644 Essentials/workdir/white-list.txt create mode 100644 EssentialsChat/build.xml create mode 100644 EssentialsChat/nbproject/build-impl.xml create mode 100644 EssentialsChat/nbproject/genfiles.properties create mode 100644 EssentialsChat/nbproject/private/private.properties create mode 100644 EssentialsChat/nbproject/project.properties create mode 100644 EssentialsChat/nbproject/project.xml create mode 100644 EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java create mode 100644 EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListener.java create mode 100644 EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatWorker.java create mode 100644 EssentialsChat/src/plugin.yml create mode 100644 EssentialsGroupBridge/build.xml create mode 100644 EssentialsGroupBridge/nbproject/build-impl.xml create mode 100644 EssentialsGroupBridge/nbproject/genfiles.properties create mode 100644 EssentialsGroupBridge/nbproject/private/private.properties create mode 100644 EssentialsGroupBridge/nbproject/project.properties create mode 100644 EssentialsGroupBridge/nbproject/project.xml create mode 100644 EssentialsGroupBridge/src/com/nijiko/Messaging.class create mode 100644 EssentialsGroupBridge/src/com/nijiko/Misc$string.class create mode 100644 EssentialsGroupBridge/src/com/nijiko/Misc.class create mode 100644 EssentialsGroupBridge/src/com/nijiko/configuration/ConfigurationHandler.class create mode 100644 EssentialsGroupBridge/src/com/nijiko/configuration/DefaultConfiguration.class create mode 100644 EssentialsGroupBridge/src/com/nijiko/database/Wrapper$Type.class create mode 100644 EssentialsGroupBridge/src/com/nijiko/database/Wrapper.class create mode 100644 EssentialsGroupBridge/src/com/nijiko/permissions/Control.class create mode 100644 EssentialsGroupBridge/src/com/nijiko/permissions/PermissionHandler.class create mode 100644 EssentialsGroupBridge/src/com/nijikokun/bukkit/Permissions/Permissions.java create mode 100644 EssentialsGroupBridge/src/org/anjocaido/groupmanager/permissions/NijikoPermissionsProxy.java create mode 100644 EssentialsGroupBridge/src/plugin.yml create mode 100644 EssentialsGroupManager/build.xml create mode 100644 EssentialsGroupManager/nbproject/build-impl.xml create mode 100644 EssentialsGroupManager/nbproject/genfiles.properties create mode 100644 EssentialsGroupManager/nbproject/private/private.properties create mode 100644 EssentialsGroupManager/nbproject/project.properties create mode 100644 EssentialsGroupManager/nbproject/project.xml create mode 100644 EssentialsGroupManager/src/config.yml create mode 100644 EssentialsGroupManager/src/groups.yml create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/GMConfiguration.java create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/GroupManager.java create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/data/DataUnit.java create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/data/Group.java create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/data/GroupVariables.java create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/data/User.java create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/data/UserVariables.java create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/data/Variables.java create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/OverloadedWorldHolder.java create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/WorldDataHolder.java create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/worlds/WorldsHolder.java create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/permissions/AnjoPermissionsHandler.java create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/permissions/PermissionsReaderInterface.java create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/GMLoggerHandler.java create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/GroupManagerPermissions.java create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/PermissionCheckResult.java create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/StringPermissionComparator.java create mode 100644 EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/Tasks.java create mode 100644 EssentialsGroupManager/src/plugin.yml create mode 100644 EssentialsGroupManager/src/users.yml create mode 100644 EssentialsProtect/MANIFEST.MF create mode 100644 EssentialsProtect/build.xml create mode 100644 EssentialsProtect/nbproject/build-impl.xml create mode 100644 EssentialsProtect/nbproject/genfiles.properties create mode 100644 EssentialsProtect/nbproject/private/private.properties create mode 100644 EssentialsProtect/nbproject/project.properties create mode 100644 EssentialsProtect/nbproject/project.xml create mode 100644 EssentialsProtect/src/README.TXT create mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java create mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java create mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectData.java create mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java create mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectPlayerListener.java create mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectRegions.java create mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectSqlProperties.java create mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/data/IProtectedBlock.java create mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/data/OwnedBlock.java create mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockJDBC.java create mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMemory.java create mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMySQL.java create mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockSQLite.java create mode 100644 EssentialsProtect/src/plugin.yml create mode 100644 EssentialsSpawn/build.xml create mode 100644 EssentialsSpawn/nbproject/build-impl.xml create mode 100644 EssentialsSpawn/nbproject/genfiles.properties create mode 100644 EssentialsSpawn/nbproject/private/private.properties create mode 100644 EssentialsSpawn/nbproject/project.properties create mode 100644 EssentialsSpawn/nbproject/project.xml create mode 100644 EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandsetspawn.java create mode 100644 EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandspawn.java create mode 100644 EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawn.java create mode 100644 EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawnPlayerListener.java create mode 100644 EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawnWorker.java create mode 100644 EssentialsSpawn/src/plugin.yml create mode 100644 build.inc.xml create mode 100644 lib/CopyLibs/org-netbeans-modules-java-j2seproject-copylibstask.jar create mode 100644 lib/Permissions.jar create mode 100644 lib/c3p0-0.9.1.2.jar create mode 100644 lib/craftbukkit-0.0.1-SNAPSHOT.jar create mode 100644 lib/gson.jar create mode 100644 lib/iConomy.jar create mode 100644 lib/junit/junit-3.8.2-api.zip create mode 100644 lib/junit/junit-3.8.2.jar create mode 100644 lib/junit_4/junit-4.5-api.zip create mode 100644 lib/junit_4/junit-4.5-src.jar create mode 100644 lib/junit_4/junit-4.5.jar create mode 100644 lib/mysql.jar create mode 100644 lib/nblibraries.properties create mode 100644 lib/sqlite.jar diff --git a/BuildAll/build.xml b/BuildAll/build.xml new file mode 100644 index 000000000..496f85c34 --- /dev/null +++ b/BuildAll/build.xml @@ -0,0 +1,74 @@ + + + + + + + + + + + Builds, tests, and runs the project BuildAll. + + + diff --git a/BuildAll/nbproject/build-impl.xml b/BuildAll/nbproject/build-impl.xml new file mode 100644 index 000000000..09a0e0d9d --- /dev/null +++ b/BuildAll/nbproject/build-impl.xml @@ -0,0 +1,1142 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + Must select one file in the IDE or set profile.class + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/BuildAll/nbproject/genfiles.properties b/BuildAll/nbproject/genfiles.properties new file mode 100644 index 000000000..55c9a217a --- /dev/null +++ b/BuildAll/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=60061751 +build.xml.script.CRC32=7a797370 +build.xml.stylesheet.CRC32=28e38971@1.42.1.45 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=60061751 +nbproject/build-impl.xml.script.CRC32=5fce336c +nbproject/build-impl.xml.stylesheet.CRC32=19debb58@1.42.1.45 diff --git a/BuildAll/nbproject/private/config.properties b/BuildAll/nbproject/private/config.properties new file mode 100644 index 000000000..e69de29bb diff --git a/BuildAll/nbproject/private/private.properties b/BuildAll/nbproject/private/private.properties new file mode 100644 index 000000000..999794c06 --- /dev/null +++ b/BuildAll/nbproject/private/private.properties @@ -0,0 +1,6 @@ +compile.on.save=false +do.depend=false +do.jar=true +javac.debug=true +javadoc.preview=true +user.properties.file=C:\\Users\\Paul\\.netbeans\\7.0beta2\\build.properties diff --git a/BuildAll/nbproject/project.properties b/BuildAll/nbproject/project.properties new file mode 100644 index 000000000..6b8e235e1 --- /dev/null +++ b/BuildAll/nbproject/project.properties @@ -0,0 +1,90 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +application.title=BuildAll +application.vendor=Paul +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/BuildAll.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes= +includes=** +jar.compress=false +javac.classpath=\ + ${reference.Essentials.jar}:\ + ${reference.EssentialsChat.jar}:\ + ${reference.EssentialsGroupBridge.jar}:\ + ${reference.EssentialsGroupManager.jar}:\ + ${reference.EssentialsProtect.jar}:\ + ${reference.EssentialsSpawn.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.processorpath=\ + ${javac.classpath} +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${libs.junit.classpath}:\ + ${libs.junit_4.classpath} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +meta.inf.dir=${src.dir}/META-INF +mkdist.disabled=false +platform.active=default_platform +project.Essentials=../Essentials +project.EssentialsChat=../EssentialsChat +project.EssentialsGroupBridge=../EssentialsGroupBridge +project.EssentialsGroupManager=../EssentialsGroupManager +project.EssentialsProtect=../EssentialsProtect +project.EssentialsSpawn=../EssentialsSpawn +reference.Essentials.jar=${project.Essentials}/dist/Essentials.jar +reference.EssentialsChat.jar=${project.EssentialsChat}/dist/EssentialsChat.jar +reference.EssentialsGroupBridge.jar=${project.EssentialsGroupBridge}/dist/EssentialsGroupBridge.jar +reference.EssentialsGroupManager.jar=${project.EssentialsGroupManager}/dist/EssentialsGroupManager.jar +reference.EssentialsProtect.jar=${project.EssentialsProtect}/dist/original-EssentialsProtect.jar +reference.EssentialsSpawn.jar=${project.EssentialsSpawn}/dist/EssentialsSpawn.jar +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/BuildAll/nbproject/project.xml b/BuildAll/nbproject/project.xml new file mode 100644 index 000000000..86e1cc4a7 --- /dev/null +++ b/BuildAll/nbproject/project.xml @@ -0,0 +1,68 @@ + + + org.netbeans.modules.java.j2seproject + + + BuildAll + + + + + + + + + ..\lib\nblibraries.properties + + + + Essentials + jar + + jar + clean + jar + + + EssentialsChat + jar + + jar + clean + jar + + + EssentialsGroupBridge + jar + + jar + clean + jar + + + EssentialsGroupManager + jar + + jar + clean + jar + + + EssentialsProtect + jar + + jar + clean + jar + + + EssentialsSpawn + jar + + jar + clean + jar + + + + diff --git a/Essentials/.gitignore b/Essentials/.gitignore new file mode 100644 index 000000000..437c8c683 --- /dev/null +++ b/Essentials/.gitignore @@ -0,0 +1,7 @@ +# NetBeans cruft +/build +/dist +/nbproject/private + +# Mac cruft +.DS_Store diff --git a/Essentials/build.xml b/Essentials/build.xml new file mode 100644 index 000000000..0742d234f --- /dev/null +++ b/Essentials/build.xml @@ -0,0 +1,75 @@ + + + + + + + + + + + + Builds, tests, and runs the project Essentials. + + + diff --git a/Essentials/nbproject/build-impl.xml b/Essentials/nbproject/build-impl.xml new file mode 100644 index 000000000..131d7414d --- /dev/null +++ b/Essentials/nbproject/build-impl.xml @@ -0,0 +1,1058 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + Must select one file in the IDE or set profile.class + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Essentials/nbproject/genfiles.properties b/Essentials/nbproject/genfiles.properties new file mode 100644 index 000000000..169fb44fa --- /dev/null +++ b/Essentials/nbproject/genfiles.properties @@ -0,0 +1,11 @@ +build.xml.data.CRC32=7d758acf +build.xml.script.CRC32=3233ee78 +build.xml.stylesheet.CRC32=28e38971@1.38.2.45 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=ab78ce15 +nbproject/build-impl.xml.script.CRC32=4b464ee6 +nbproject/build-impl.xml.stylesheet.CRC32=19debb58@1.42.1.45 +nbproject/profiler-build-impl.xml.data.CRC32=ab78ce15 +nbproject/profiler-build-impl.xml.script.CRC32=abda56ed +nbproject/profiler-build-impl.xml.stylesheet.CRC32=f10cf54c@1.11.1 diff --git a/Essentials/nbproject/private/private.properties b/Essentials/nbproject/private/private.properties new file mode 100644 index 000000000..94183418a --- /dev/null +++ b/Essentials/nbproject/private/private.properties @@ -0,0 +1 @@ +user.properties.file=C:\\Users\\Paul\\.netbeans\\7.0beta2\\build.properties diff --git a/Essentials/nbproject/project.properties b/Essentials/nbproject/project.properties new file mode 100644 index 000000000..67c5646c9 --- /dev/null +++ b/Essentials/nbproject/project.properties @@ -0,0 +1,76 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +application.title=Essentials +application.vendor=Paul +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/Essentials.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes= +file.reference.craftbukkit-0.0.1-SNAPSHOT.jar=..\\lib\\craftbukkit-0.0.1-SNAPSHOT.jar +file.reference.iConomy.jar=..\\lib\\iConomy.jar +file.reference.Permissions.jar=..\\lib\\Permissions.jar +includes=** +jar.compress=false +javac.classpath=\ + ${file.reference.iConomy.jar}:\ + ${file.reference.Permissions.jar}:\ + ${file.reference.craftbukkit-0.0.1-SNAPSHOT.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.processorpath=\ + ${javac.classpath} +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +meta.inf.dir=${src.dir}/META-INF +mkdist.disabled=false +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs=-Djline.terminal=jline.UnsupportedTerminal +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/Essentials/nbproject/project.xml b/Essentials/nbproject/project.xml new file mode 100644 index 000000000..aa1a9f770 --- /dev/null +++ b/Essentials/nbproject/project.xml @@ -0,0 +1,19 @@ + + + org.netbeans.modules.java.j2seproject + + + Essentials + + + + + + + + + ../lib\nblibraries.properties + + + + diff --git a/Essentials/settings/Editor.zip b/Essentials/settings/Editor.zip new file mode 100644 index 000000000..7635328f8 Binary files /dev/null and b/Essentials/settings/Editor.zip differ diff --git a/Essentials/src/com/earth2me/essentials/Backup.java b/Essentials/src/com/earth2me/essentials/Backup.java new file mode 100644 index 000000000..aa0cb1476 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/Backup.java @@ -0,0 +1,82 @@ +package com.earth2me.essentials; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.command.CommandSender; +import org.bukkit.craftbukkit.CraftServer; + +public class Backup implements Runnable { + private static final Logger logger = Logger.getLogger("Minecraft"); + private CraftServer server; + private boolean running = false; + private int taskId = -1; + private boolean active = false; + + public Backup() { + server = (CraftServer)Essentials.getStatic().getServer(); + if (server.getOnlinePlayers().length > 0) { + startTask(); + } + } + + void onPlayerJoin() { + startTask(); + } + + private void startTask() { + if (!running) { + long interval = Essentials.getSettings().getBackupInterval()*1200; // minutes -> ticks + if (interval < 1200) { + return; + } + taskId = server.getScheduler().scheduleSyncRepeatingTask(Essentials.getStatic(), this, interval, interval); + running = true; + } + } + + public void run() { + if (active) return; + active = true; + final String command = Essentials.getSettings().getBackupCommand(); + if (command == null || "".equals(command)) { + return; + } + logger.log(Level.INFO, "Backup started"); + final CommandSender cs = server.getServer().console; + server.dispatchCommand(cs, "save-all"); + server.dispatchCommand(cs, "save-off"); + + server.getScheduler().scheduleAsyncDelayedTask(Essentials.getStatic(), + new Runnable() { + + public void run() { + try { + Process child = Runtime.getRuntime().exec(command); + child.waitFor(); + } catch (InterruptedException ex) { + logger.log(Level.SEVERE, null, ex); + } catch (IOException ex) { + logger.log(Level.SEVERE, null, ex); + } finally { + server.getScheduler().scheduleSyncDelayedTask(Essentials.getStatic(), + new Runnable() { + + public void run() { + server.dispatchCommand(cs, "save-on"); + if (server.getOnlinePlayers().length == 0) { + running = false; + if (taskId != -1) { + server.getScheduler().cancelTask(taskId); + } + } + active = false; + logger.log(Level.INFO, "Backup finished"); + } + }); + } + } + }); + } + +} diff --git a/Essentials/src/com/earth2me/essentials/Essentials.java b/Essentials/src/com/earth2me/essentials/Essentials.java new file mode 100644 index 000000000..f9bd1d655 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/Essentials.java @@ -0,0 +1,684 @@ +package com.earth2me.essentials; + +import com.earth2me.essentials.commands.EssentialsCommand; +import java.io.*; +import java.util.*; +import java.util.logging.*; +import org.bukkit.*; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.commands.IEssentialsCommand; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.bukkit.command.PluginCommand; +import org.bukkit.craftbukkit.scheduler.CraftScheduler; +import org.bukkit.entity.Player; +import org.bukkit.event.Event.Priority; +import org.bukkit.event.Event.Type; +import org.bukkit.plugin.*; +import org.bukkit.plugin.java.*; +import org.yaml.snakeyaml.*; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.reader.UnicodeReader; + + +public class Essentials extends JavaPlugin +{ + public static final String AUTHORS = "Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo and ceulemans."; + public static final int minBukkitBuildVersion = 556; + private static final Logger logger = Logger.getLogger("Minecraft"); + private static final Yaml yaml = new Yaml(new SafeConstructor()); + private static Map users; + private static Settings settings; + private static final Object usersLock = new Object(); + public static Object permissions = null; + public final Map tpcRequests = new HashMap(); + public final Map tpcHere = new HashMap(); + public final List away = new ArrayList(); + private EssentialsPlayerListener playerListener; + private EssentialsBlockListener blockListener; + private EssentialsEntityListener entityListener; + private static Essentials staticThis = null; + public Spawn spawn; + private Jail jail; + private Warps warps; + private List confList; + public ArrayList bans = new ArrayList(); + public ArrayList bannedIps = new ArrayList(); + public Backup backup; + + public Essentials() throws IOException + { + loadClasses(); + } + + public static void ensureEnabled(Server server) + { + PluginManager pm = server.getPluginManager(); + Essentials ess = (Essentials)pm.getPlugin("Essentials"); + if (!ess.isEnabled()) + pm.enablePlugin(ess); + loadClasses(); + } + + @SuppressWarnings("CallToThreadDumpStack") + public static void loadClasses() + { + final String[] classes = new String[] + { + "commands.IEssentialsCommand", + "commands.EssentialsCommand", + "User", + "TargetBlock", + "Spawn", + "Settings", + "OfflinePlayer", + "ItemDb", + "Mob" + }; + + try + { + for (String c : classes) + Essentials.class.getClassLoader().loadClass("com.earth2me.essentials." + c); + } + catch (Throwable ex) + { + ex.printStackTrace(); + } + } + + public static Essentials getStatic() + { + return staticThis; + } + + public static Settings getSettings() + { + return settings; + } + + public void setupPermissions() + { + Plugin permPlugin = this.getServer().getPluginManager().getPlugin("Permissions"); + if (permissions == null && permPlugin != null) permissions = permPlugin; + } + + public Player getPlayer(String[] args, int pos) + throws IndexOutOfBoundsException, NoSuchFieldException + { + if (args.length <= pos) throw new IndexOutOfBoundsException("§cInvalid command syntax. Did you forget an argument?"); + List matches = getServer().matchPlayer(args[0]); + if (matches.size() < 1) throw new NoSuchFieldException("§cNo matching players could be found."); + return matches.get(0); + } + + public void setStatic() + { + staticThis = this; + } + + @SuppressWarnings("LoggerStringConcat") + public void onEnable() + { + setStatic(); + confList = new ArrayList(); + settings = new Settings(this.getDataFolder()); + confList.add(settings); + this.spawn = new Spawn(getServer(), this.getDataFolder()); + confList.add(spawn); + warps = new Warps(getServer(), this.getDataFolder()); + confList.add(warps); + reload(); + this.backup = new Backup(); + + PluginManager pm = getServer().getPluginManager(); + for (Plugin plugin : pm.getPlugins()) { + if (plugin.getDescription().getName().startsWith("Essentials")) { + if (!plugin.getDescription().getVersion().equals(this.getDescription().getVersion())) { + logger.log(Level.WARNING, "Version mismatch! Please update "+plugin.getDescription().getName()+" to the same version."); + } + } + } + Matcher versionMatch = Pattern.compile("git-Bukkit-([0-9]+).([0-9]+).([0-9]+)-[0-9]+-[0-9a-z]+-b([0-9]+)jnks.*").matcher(getServer().getVersion()); + if (versionMatch.matches()) { + int versionNumber = Integer.parseInt(versionMatch.group(4)); + if (versionNumber < minBukkitBuildVersion) { + logger.log(Level.WARNING, "Bukkit version is not the recommended build for Essentials."); + } + } else { + logger.log(Level.INFO, "Bukkit version format changed. Version not checked."); + } + + + playerListener = new EssentialsPlayerListener(this); + pm.registerEvent(Type.PLAYER_JOIN, playerListener, Priority.Monitor, this); + pm.registerEvent(Type.PLAYER_QUIT, playerListener, Priority.Monitor, this); + pm.registerEvent(Type.PLAYER_CHAT, playerListener, Priority.Monitor, this); + if (getSettings().getNetherPortalsEnabled()) + pm.registerEvent(Type.PLAYER_MOVE, playerListener, Priority.High, this); + pm.registerEvent(Type.PLAYER_LOGIN, playerListener, Priority.High, this); + pm.registerEvent(Type.PLAYER_TELEPORT, playerListener, Priority.High, this); + pm.registerEvent(Type.PLAYER_INTERACT, playerListener, Priority.Monitor, this); + + blockListener = new EssentialsBlockListener(this); + pm.registerEvent(Type.SIGN_CHANGE, blockListener, Priority.Monitor, this); + pm.registerEvent(Type.BLOCK_BREAK, blockListener, Priority.Monitor, this); + pm.registerEvent(Type.BLOCK_PLACE, blockListener, Priority.Monitor, this); + + entityListener = new EssentialsEntityListener(this); + pm.registerEvent(Type.ENTITY_DAMAGE, entityListener, Priority.Lowest, this); + pm.registerEvent(Type.ENTITY_COMBUST, entityListener, Priority.Lowest, this); + pm.registerEvent(Type.ENTITY_DEATH, entityListener, Priority.Lowest, this); + + jail = new Jail(this.getDataFolder()); + confList.add(jail); + pm.registerEvent(Type.BLOCK_BREAK, jail, Priority.High, this); + pm.registerEvent(Type.BLOCK_DAMAGE, jail, Priority.High, this); + pm.registerEvent(Type.BLOCK_PLACE, jail, Priority.High, this); + + attachEcoListeners(); + + if (settings.isNetherEnabled() && getServer().getWorlds().size() < 2) + { + getServer().createWorld(settings.getNetherName(), World.Environment.NETHER); + } + + logger.info("Loaded " + this.getDescription().getName() + " build " + this.getDescription().getVersion() + " maintained by " + AUTHORS); + } + + public void onDisable() + { + staticThis = null; + } + + public void reload() + { + loadData(); + loadBanList(); + + for (IConf iConf : confList) + { + iConf.reloadConfig(); + } + + try + { + ItemDb.load(getDataFolder(), "items.csv"); + } + catch (Exception ex) + { + logger.log(Level.WARNING, "Could not load items.csv.", ex); + } + } + + public static Map getData(User player) + { + return getData(player.getName()); + } + + public static Map getData(String player) + { + try + { + Map retval; + synchronized (usersLock) + { + retval = (Map)users.get(player.toLowerCase()); + } + return retval == null ? new HashMap() : retval; + } + catch (Throwable ex) + { + return new HashMap(); + } + } + + public static void flushData() + { + Thread run = new Thread(new Runnable() + { + @Override + public void run() + { + try + { + if (!Essentials.getStatic().getDataFolder().exists()) + Essentials.getStatic().getDataFolder().mkdirs(); + File file = new File(Essentials.getStatic().getDataFolder(), "users.yml"); + if (!file.exists()) + file.createNewFile(); + + FileWriter tx = new FileWriter(file); + synchronized (usersLock) + { + tx.write(yaml.dump(users)); + } + tx.flush(); + tx.close(); + } + catch (Throwable ex) + { + Logger.getLogger(Essentials.class.getName()).log(Level.SEVERE, null, ex); + } + } + }); + run.setDaemon(false); + run.start(); + } + + public static void loadData() + { + try + { + if (!Essentials.getStatic().getDataFolder().exists()) Essentials.getStatic().getDataFolder().mkdirs(); + File file = new File(Essentials.getStatic().getDataFolder(), "users.yml"); + if (!file.exists()) file.createNewFile(); + + FileInputStream rx = new FileInputStream(file); + synchronized (usersLock) + { + users = (Map)yaml.load(new UnicodeReader(rx)); + } + rx.close(); + } + catch (Exception ex) + { + Logger.getLogger(Essentials.class.getName()).log(Level.SEVERE, null, ex); + synchronized (usersLock) + { + users = new HashMap(); + } + } + finally + { + synchronized (usersLock) + { + if (users == null) users = new HashMap(); + } + } + } + + public static void setData(User player, Map data) + { + setData(player.getName(), data); + } + + public static void setData(String player, Map data) + { + synchronized (usersLock) + { + users.put(player.toLowerCase(), data); + } + } + + public static List readMail(User player) + { + return readMail(player.getName()); + } + + public static List readMail(String player) + { + try + { + Map data = getData(player); + List retval = (List)data.get("mail"); + return retval == null ? new ArrayList() : retval; + } + catch (Throwable ex) + { + return new ArrayList(); + } + } + + public static void clearMail(User player) + { + try + { + Map data = getData(player); + data.put("mail", new ArrayList()); + setData(player, data); + flushData(); + } + catch (Throwable ex) + { + } + } + + public static void sendMail(User from, String to, String message) + throws Exception + { + try + { + Map data = getData(ChatColor.stripColor(to)); + List mail = readMail(to); + mail.add(ChatColor.stripColor(from.getDisplayName()) + ": " + message); + data.put("mail", mail); + setData(to, data); + flushData(); + } + catch (Throwable ex) + { + throw new Exception("An error was encountered while sending the mail.", ex); + } + } + + public String readNickname(User player) + { + try + { + Map data = getData(player); + String nick = (String)data.get("nickname"); + if (nick == null) + return player.getName(); + if (nick.equals(player.getName())) + return player.getName(); + return getSettings().getNicknamePrefix() + nick; + } + catch (Exception ex) + { + return player.getName(); + } + } + + public void saveNickname(User player, String nickname) throws Exception + { + try + { + Map data = getData(player); + data.put("nickname", nickname); + setData(player, data); + flushData(); + } + catch (Throwable ex) + { + throw new Exception("An error was encountered while saving the nickname.", ex); + } + } + + public String[] getMotd(CommandSender sender, String def) + { + return getLines(sender, "motd", def); + } + + public String[] getLines(CommandSender sender, String node, String def) + { + List lines = (List)getConfiguration().getProperty(node); + if (lines == null) return new String[0]; + String[] retval = new String[lines.size()]; + + if (lines == null || lines.isEmpty() || lines.get(0) == null) + { + try + { + lines = new ArrayList(); + // "[]" in YaML indicates empty array, so respect that + if (!getConfiguration().getString(node, def).equals("[]")) + { + lines.add(getConfiguration().getString(node, def)); + retval = new String[lines.size()]; + } + } + catch (Throwable ex2) + { + System.out.println(ChatColor.DARK_RED + "Notice: Your configuration file has a corrupt " + node + " node."); + return new String[0]; + } + } + + // if still empty, call it a day + if (lines == null || lines.isEmpty() || lines.get(0) == null) + return new String[0]; + + for (int i = 0; i < lines.size(); i++) + { + String m = lines.get(i); + if (m == null) + continue; + m = m.replace('&', '§').replace("§§", "&"); + + if (sender instanceof User || sender instanceof Player) + { + User user = User.get(sender); + m = m.replace("{PLAYER}", user.getDisplayName()); + m = m.replace("{IP}", user.getAddress().toString()); + m = m.replace("{BALANCE}", Double.toString(user.getMoney())); + } + + m = m.replace("{ONLINE}", Integer.toString(getServer().getOnlinePlayers().length)); + + if (m.matches(".*\\{PLAYERLIST\\}.*")) + { + StringBuilder online = new StringBuilder(); + for (Player p : getServer().getOnlinePlayers()) + { + if (online.length() > 0) + online.append(", "); + online.append(p.getDisplayName()); + } + m = m.replace("{PLAYERLIST}", online.toString()); + } + + if (sender instanceof Player) + { + try + { + Class User = getClassLoader().loadClass("bukkit.Vandolis.User"); + Object vuser = User.getConstructor(User.class).newInstance((Player)sender); + m = m.replace("{RED:BALANCE}", User.getMethod("getMoney").invoke(vuser).toString()); + m = m.replace("{RED:BUYS}", User.getMethod("getNumTransactionsBuy").invoke(vuser).toString()); + m = m.replace("{RED:SELLS}", User.getMethod("getNumTransactionsSell").invoke(vuser).toString()); + } + catch (Throwable ex) + { + m = m.replace("{RED:BALANCE}", "N/A"); + m = m.replace("{RED:BUYS}", "N/A"); + m = m.replace("{RED:SELLS}", "N/A"); + } + } + + retval[i] = m + " "; + } + return retval; + } + + public static String FormatTime(long Milliseconds) + { // format time into a string showing hours, minutes, or seconds + if (Milliseconds > 3600000) + { + double val = Math.round((double)Milliseconds / 360000D) / 10D; + return val + " hour" + (val > 1 ? "s" : ""); + } + else if (Milliseconds > 60000) + { + double val = Math.round((double)Milliseconds / 6000D) / 10D; + return val + " minute" + (val > 1 ? "s" : ""); + } + else if (Milliseconds <= 1000) + return "1 second"; + else + return (Milliseconds / 1000L) + " seconds"; + } + + @SuppressWarnings("LoggerStringConcat") + public static void previewCommand(CommandSender sender, Command command, String commandLabel, String[] args) + { + if (sender instanceof Player) + logger.info(ChatColor.BLUE + "[PLAYER_COMMAND] " + ((Player)sender).getName() + ": /" + commandLabel + " " + EssentialsCommand.getFinalArg(args, 0)); + } + + @Override + @SuppressWarnings( + { + "LoggerStringConcat", "CallToThreadDumpStack" + }) + public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) + { + // Allow plugins to override the command via onCommand + for (Plugin p : getServer().getPluginManager().getPlugins()) + { + if (p == this) + continue; + + PluginDescriptionFile desc = p.getDescription(); + if (desc == null) + continue; + + if (desc.getName() == null) + continue; + + if (!(desc.getCommands() instanceof Map)) + continue; + + Map cmds = (Map)desc.getCommands(); + if (!cmds.containsKey(command.getName())) + continue; + + PluginCommand pcmd = getServer().getPluginCommand(desc.getName() + ":" + commandLabel); + + if (pcmd == null) + continue; + + return getServer().getPluginCommand(p.getDescription().getName() + ":" + commandLabel).execute(sender, commandLabel, args); + } + + try + { + previewCommand(sender, command, commandLabel, args); + User user = sender instanceof Player ? User.get(sender) : null; + + // New mail notification + if (user != null && !Essentials.getSettings().isCommandDisabled("mail") && !commandLabel.equals("mail")) + { + List mail = Essentials.readMail(user); + if (!mail.isEmpty()) user.sendMessage(ChatColor.RED + "You have " + mail.size() + " messages!§f Type §7/mail read§f to view your mail."); + } + + // Check for disabled commands + if (Essentials.getSettings().isCommandDisabled(commandLabel)) return true; + + IEssentialsCommand cmd; + try + { + cmd = (IEssentialsCommand)Essentials.class.getClassLoader().loadClass("com.earth2me.essentials.commands.Command" + command.getName()).newInstance(); + } + catch (Exception ex) + { + sender.sendMessage(ChatColor.RED + "That command is improperly loaded."); + ex.printStackTrace(); + return true; + } + + // Check authorization + if (user != null && !user.isAuthorized(cmd)) + { + logger.warning(user.getName() + " was denied access to command."); + user.sendMessage(ChatColor.RED + "You do not have access to that command."); + return true; + } + + // Run the command + try + { + if (user == null) + cmd.run(getServer(), this, sender, commandLabel, command, args); + else + cmd.run(getServer(), this, user, commandLabel, command, args); + return true; + } + catch (Throwable ex) + { + sender.sendMessage(ChatColor.RED + "Error: " + ex.getMessage()); + return true; + } + } + catch (Throwable ex) + { + ex.printStackTrace(); + return true; + } + } + + public void loadBanList() + { + //I don't like this but it needs to be done until CB fixors + File file = new File("banned-players.txt"); + File ipFile = new File("banned-ips.txt"); + try + { + if (!file.exists()) throw new FileNotFoundException("banned-players.txt not found"); + + BufferedReader rx = new BufferedReader(new FileReader(file)); + bans.clear(); + try + { + for (int i = 0; rx.ready(); i++) + { + + String line = rx.readLine().trim().toLowerCase(); + if (line.startsWith("#")) continue; + bans.add(line); + + } + } + catch (IOException io) + { + logger.log(Level.SEVERE, "Error reading banned-players.txt", io); + } + } + catch (FileNotFoundException ex) + { + logger.log(Level.SEVERE, "Error reading banned-players.txt", ex); + } + + try + { + if (!ipFile.exists()) throw new FileNotFoundException("banned-ips.txt not found"); + + BufferedReader rx = new BufferedReader(new FileReader(ipFile)); + bannedIps.clear(); + try + { + for (int i = 0; rx.ready(); i++) + { + + String line = rx.readLine().trim().toLowerCase(); + if (line.startsWith("#")) continue; + bannedIps.add(line); + + } + } + catch (IOException io) + { + logger.log(Level.SEVERE, "Error reading banned-ips.txt", io); + } + } + catch (FileNotFoundException ex) + { + logger.log(Level.SEVERE, "Error reading banned-ips.txt", ex); + } + } + + private void attachEcoListeners() + { + PluginManager pm = getServer().getPluginManager(); + EssentialsEcoBlockListener blockListener = new EssentialsEcoBlockListener(); + pm.registerEvent(Type.BLOCK_BREAK, blockListener, Priority.High, this); + pm.registerEvent(Type.SIGN_CHANGE, blockListener, Priority.Monitor, this); + } + + public CraftScheduler getScheduler() + { + return (CraftScheduler)this.getServer().getScheduler(); + } + + public static Jail getJail() + { + return getStatic().jail; + } + + public static Warps getWarps() + { + return getStatic().warps; + } +} diff --git a/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java b/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java new file mode 100644 index 000000000..a52a6c225 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java @@ -0,0 +1,214 @@ +package com.earth2me.essentials; + +import java.util.ArrayList; +import org.bukkit.*; +import org.bukkit.block.*; +import org.bukkit.craftbukkit.block.CraftSign; +import org.bukkit.event.block.*; + + +public class EssentialsBlockListener extends BlockListener +{ + private final Essentials parent; + public final static ArrayList protectedBlocks = new ArrayList(4); + + static + { + protectedBlocks.add(Material.CHEST); + protectedBlocks.add(Material.BURNING_FURNACE); + protectedBlocks.add(Material.FURNACE); + protectedBlocks.add(Material.DISPENSER); + } + + public EssentialsBlockListener(Essentials parent) + { + this.parent = parent; + } + + @Override + public void onBlockBreak(BlockBreakEvent event) + { + if (event.isCancelled()) return; + if (Essentials.getSettings().areSignsDisabled()) return; + User user = User.get(event.getPlayer()); + if (protectedBlocks.contains(event.getBlock().getType()) && !user.isAuthorized("essentials.signs.protection.override")) + { + if (isBlockProtected(event.getBlock(), user)) + { + event.setCancelled(true); + user.sendMessage("§cYou do not have permission to destroy that chest."); + return; + } + } + + if (checkProtectionSign(event.getBlock(), user) == NOT_ALLOWED) + { + event.setCancelled(true); + user.sendMessage("§cYou do not have permission to destroy that sign."); + } + } + + @Override + public void onSignChange(SignChangeEvent event) + { + if (event.isCancelled()) return; + if (Essentials.getSettings().areSignsDisabled()) return; + User user = User.get(event.getPlayer()); + + try + { + if (event.getLine(0).equalsIgnoreCase("[Protection]")) + { + Block block = event.getBlock(); + if (user.isAuthorized("essentials.signs.protection.create") && hasAdjacentChest(block) && !isBlockProtected(block, user)) + event.setLine(0, "§1[Protection]"); + else + event.setLine(0, "§4[Protection]"); + event.setLine(3, user.getName()); + return; + } + if (event.getLine(0).equalsIgnoreCase("[Disposal]")) + { + if (user.isAuthorized("essentials.signs.disposal.create")) + event.setLine(0, "§1[Disposal]"); + else + event.setLine(0, "§4[Disposal]"); + return; + } + if (event.getLine(0).equalsIgnoreCase("[Heal]")) + { + if (user.isAuthorized("essentials.signs.heal.create")) + event.setLine(0, "§1[Heal]"); + else + event.setLine(0, "§4[Heal]"); + return; + } + if (event.getLine(0).equalsIgnoreCase("[Free]")) + { + event.setLine(0, "§4[Free]"); + ItemDb.get(event.getLine(1)); + if (user.isAuthorized("essentials.signs.free.create")) + event.setLine(0, "§1[Free]"); + return; + } + if (event.getLine(0).equalsIgnoreCase("[Mail]")) + { + if (user.isAuthorized("essentials.signs.mail.create")) + + event.setLine(0, "§1[Mail]"); + else + event.setLine(0, "§4[Mail]"); + return; + } + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + } + } + + @Override + public void onBlockPlace(BlockPlaceEvent event) { + Block signBlock = event.getBlockAgainst(); + if (signBlock.getType() == Material.WALL_SIGN || signBlock.getType() == Material.SIGN_POST) { + Sign sign = new CraftSign(signBlock); + if (sign.getLine(0).matches("§1\\[[a-zA-Z]+\\]")) { + event.setCancelled(true); + return; + } + } + } + + + + public boolean hasAdjacentChest(Block block) + { + Block[] faces = getAdjacentBlocks(block); + for (Block b : faces) + { + if (protectedBlocks.contains(b.getType())) + { + return true; + } + } + return false; + } + private static final int NOT_ALLOWED = 0; + private static final int ALLOWED = 1; + private static final int NOSIGN = 2; + + private static int checkProtectionSign(Block block, User user) + { + if (block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN) + { + Sign sign = new CraftSign(block); + if (sign.getLine(0).equalsIgnoreCase("§1[Protection]") && !user.isAuthorized("essentials.signs.protection.override")) + { + if (sign.getLine(1).equalsIgnoreCase(user.getName())) + { + return ALLOWED; + } + if (sign.getLine(2).equalsIgnoreCase(user.getName())) + { + return ALLOWED; + } + if (sign.getLine(3).equalsIgnoreCase(user.getName())) + { + return ALLOWED; + } + return NOT_ALLOWED; + } + } + return NOSIGN; + } + + private static Block[] getAdjacentBlocks(Block block) + { + return new Block[] + { + block.getFace(BlockFace.NORTH), + block.getFace(BlockFace.SOUTH), + block.getFace(BlockFace.EAST), + block.getFace(BlockFace.WEST), + block.getFace(BlockFace.DOWN), + block.getFace(BlockFace.UP) + }; + } + + public static boolean isBlockProtected(Block block, User user) + { + Block[] faces = getAdjacentBlocks(block); + boolean protect = false; + for (Block b : faces) + { + int check = checkProtectionSign(b, user); + if (check == NOT_ALLOWED) + { + protect = true; + } + if (check == ALLOWED) + { + return false; + } + + if (protectedBlocks.contains(b.getType())) + { + Block[] faceChest = getAdjacentBlocks(b); + + for (Block a : faceChest) + { + check = checkProtectionSign(a, user); + if (check == NOT_ALLOWED) + { + protect = true; + } + if (check == ALLOWED) + { + return false; + } + } + } + } + return protect; + } +} diff --git a/Essentials/src/com/earth2me/essentials/EssentialsConf.java b/Essentials/src/com/earth2me/essentials/EssentialsConf.java new file mode 100644 index 000000000..616f39a6c --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/EssentialsConf.java @@ -0,0 +1,120 @@ +package com.earth2me.essentials; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.HashMap; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.util.config.Configuration; + + +public class EssentialsConf extends Configuration +{ + private static final Logger logger = Logger.getLogger("Minecraft"); + private File configFile; + private String templateName = null; + private Class resourceClass = EssentialsConf.class; + + public EssentialsConf(File configFile) + { + super(configFile); + this.configFile = configFile; + if (this.root == null) { + this.root = new HashMap(); + } + } + + @Override + public void load() + { + configFile = configFile.getAbsoluteFile(); + if (!configFile.getParentFile().exists()) + { + configFile.getParentFile().mkdirs(); + } + if (!configFile.exists()) + { + if (templateName != null) + { + logger.log(Level.INFO, "Creating config from template: " + configFile.toString()); + createFromTemplate(); + } + else + { + try + { + logger.log(Level.INFO, "Creating empty config: " + configFile.toString()); + configFile.createNewFile(); + } + catch (IOException ex) + { + logger.log(Level.SEVERE, "Failed to create config " + configFile.toString(), ex); + } + } + } + super.load(); + if (this.root == null) { + this.root = new HashMap(); + } + } + + private void createFromTemplate() + { + OutputStream ostr = null; + try + { + InputStream istr = resourceClass.getResourceAsStream(templateName); + if (istr == null) + { + logger.log(Level.SEVERE, "Could not find template " + templateName); + return; + } + ostr = new FileOutputStream(configFile); + byte[] buffer = new byte[1024]; + int length = 0; + length = istr.read(buffer); + while (length > 0) + { + ostr.write(buffer, 0, length); + length = istr.read(buffer); + } + ostr.close(); + istr.close(); + } + catch (IOException ex) + { + logger.log(Level.SEVERE, "Failed to write config " + configFile.toString(), ex); + return; + } + finally + { + try + { + ostr.close(); + } + catch (IOException ex) + { + logger.log(Level.SEVERE, "Failed to close config " + configFile.toString(), ex); + return; + } + } + } + + public void setTemplateName(String templateName) + { + this.templateName = templateName; + } + + public File getFile() + { + return configFile; + } + + public void setTemplateName(String templateName, Class resClass) { + this.templateName = templateName; + this.resourceClass = resClass; + } +} diff --git a/Essentials/src/com/earth2me/essentials/EssentialsEcoBlockListener.java b/Essentials/src/com/earth2me/essentials/EssentialsEcoBlockListener.java new file mode 100644 index 000000000..885985ebc --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/EssentialsEcoBlockListener.java @@ -0,0 +1,159 @@ +package com.earth2me.essentials; + +import org.bukkit.Material; +import org.bukkit.block.Sign; +import org.bukkit.craftbukkit.block.CraftSign; +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockListener; +import org.bukkit.event.block.SignChangeEvent; +import org.bukkit.inventory.ItemStack; + + +public class EssentialsEcoBlockListener extends BlockListener +{ + @Override + public void onBlockBreak(BlockBreakEvent event) + { + if (event.isCancelled()) return; + if (Essentials.getSettings().areSignsDisabled()) return; + User user = User.get(event.getPlayer()); + if (event.getBlock().getType() != Material.WALL_SIGN && event.getBlock().getType() != Material.SIGN_POST) + return; + Sign sign = new CraftSign(event.getBlock()); + + if (sign.getLine(0).equals("§1[Trade]")) + { + if (!sign.getLine(3).substring(2).equals(user.getName())) { + if (!user.isOp()) { + event.setCancelled(true); + } + return; + } + try + { + String[] l1 = sign.getLines()[1].split("[ :-]+"); + String[] l2 = sign.getLines()[2].split("[ :-]+"); + boolean m1 = l1[0].matches("\\$[0-9]+"); + boolean m2 = l2[0].matches("\\$[0-9]+"); + int q1 = Integer.parseInt(m1 ? l1[0].substring(1) : l1[0]); + int q2 = Integer.parseInt(m2 ? l2[0].substring(1) : l2[0]); + int r1 = Integer.parseInt(l1[m1 ? 1 : 2]); + int r2 = Integer.parseInt(l2[m2 ? 1 : 2]); + if (q1 < 1 || q2 < 1) throw new Exception("Quantities must be greater than 0."); + + ItemStack i1 = m1 || r1 <= 0 ? null : ItemDb.get(l1[1], r1); + ItemStack i2 = m2 || r2 <= 0 ? null : ItemDb.get(l2[1], r2); + + if (m1) + user.giveMoney(r1); + else if (i1 != null) + user.getWorld().dropItem(user.getLocation(), i1); + + if (m2) + user.giveMoney(r2); + else if (i2 != null) + user.getWorld().dropItem(user.getLocation(), i2); + + sign.setType(Material.AIR); + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + } + return; + } + } + + @Override + public void onSignChange(SignChangeEvent event) + { + if (Essentials.getSettings().areSignsDisabled()) return; + User user = User.get(event.getPlayer()); + + if (event.getLine(0).equalsIgnoreCase("[Buy]") && user.isAuthorized("essentials.signs.buy.create")) + { + try + { + event.setLine(0, "§1[Buy]"); + event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1)))); + ItemDb.get(event.getLine(2)); + event.setLine(3, "$" + Integer.parseInt(event.getLine(3).replaceAll("[^0-9]", ""))); + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + event.setLine(0, "§4[Buy]"); + event.setLine(1, "#"); + event.setLine(2, "Item"); + event.setLine(3, "$Price"); + } + return; + } + + if (event.getLine(0).equalsIgnoreCase("[Sell]") && user.isAuthorized("essentials.signs.sell.create")) + { + try + { + event.setLine(0, "§1[Sell]"); + event.setLine(1, "" + Math.abs(Integer.parseInt(event.getLine(1)))); + ItemDb.get(event.getLine(2)); + event.setLine(3, "$" + Integer.parseInt(event.getLine(3).replaceAll("[^0-9]", ""))); + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + event.setLine(0, "§4[Sell]"); + event.setLine(1, "#"); + event.setLine(2, "Item"); + event.setLine(3, "$Price"); + } + return; + } + + if (event.getLine(0).equalsIgnoreCase("[Trade]") && user.isAuthorized("essentials.signs.trade.create")) + { + try + { + String[] l1 = event.getLines()[1].split("[ :-]+"); + String[] l2 = event.getLines()[2].split("[ :-]+"); + boolean m1 = l1[0].matches("\\$[0-9]+"); + boolean m2 = l2[0].matches("\\$[0-9]+"); + int q1 = Integer.parseInt(m1 ? l1[0].substring(1) : l1[0]); + int q2 = Integer.parseInt(m2 ? l2[0].substring(1) : l2[0]); + int r2 = Integer.parseInt(l2[m2 ? 1 : 2]); + r2 = r2 - r2 % q2; + if (q1 < 1 || q2 < 1 || r2 < 1) throw new Exception("Quantities must be greater than 0."); + if (!m1) ItemDb.get(l1[1]); + + if (m2) + { + if (user.getMoney() < r2) throw new Exception("You do not have sufficient funds."); + user.takeMoney(r2); + user.sendMessage("r2: " + r2 + " q2: " + q2); + } + else + { + ItemStack i2 = ItemDb.get(l2[1], r2); + if (!InventoryWorkaround.containsItem((CraftInventory)user.getInventory(), true, i2)) throw new Exception("You do not have " + r2 + "x " + l2[1] + "."); + InventoryWorkaround.removeItem((CraftInventory)user.getInventory(), true, i2); + user.updateInventory(); + } + + event.setLine(0, "§1[Trade]"); + event.setLine(1, (m1 ? "$" + q1 : q1 + " " + l1[1]) + ":0"); + event.setLine(2, (m2 ? "$" + q2 : q2 + " " + l2[1]) + ":" + r2); + event.setLine(3, "§8" + user.getName()); + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + event.setLine(0, "§4[Trade]"); + event.setLine(1, "# ItemOr$"); + event.setLine(2, "# ItemOr$:#"); + event.setLine(3, "§8" + user.getName()); + } + return; + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java b/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java new file mode 100644 index 000000000..15355021a --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java @@ -0,0 +1,65 @@ +package com.earth2me.essentials; + +import org.bukkit.Server; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityCombustEvent; +import org.bukkit.event.entity.EntityDamageByBlockEvent; +import org.bukkit.event.entity.EntityDamageByProjectileEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityDeathEvent; +import org.bukkit.event.entity.EntityListener; + + +public class EssentialsEntityListener extends EntityListener +{ + private final Server server; + private final Essentials parent; + + public EssentialsEntityListener(Essentials parent) + { + this.parent = parent; + this.server = parent.getServer(); + } + + @Override + public void onEntityDamage(EntityDamageEvent event) + { + if (event instanceof EntityDamageEvent || event instanceof EntityDamageByBlockEvent || event instanceof EntityDamageByProjectileEvent) + { + + if (event.getEntity() instanceof Player && User.get(event.getEntity()).isGodModeEnabled()) + { + CraftPlayer player = (CraftPlayer)event.getEntity(); + player.getHandle().fireTicks = 0; + player.setRemainingAir(player.getMaximumAir()); + event.setCancelled(true); + } + } + } + + + @Override + public void onEntityCombust(EntityCombustEvent event) + { + if (event.getEntity() instanceof Player && User.get(event.getEntity()).isGodModeEnabled()) + { + event.setCancelled(true); + } + } + + @Override + public void onEntityDeath(EntityDeathEvent event) + { + if (event.getEntity() instanceof Player) + { + User user = User.get(event.getEntity()); + if(user.isAuthorized("essentials.back.ondeath")) + { + user.lastLocation = user.getLocation(); + user.sendMessage("§7Use the /back command to return to your death point"); + } + } + } + +} diff --git a/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java b/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java new file mode 100644 index 000000000..58cddcacd --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java @@ -0,0 +1,452 @@ +package com.earth2me.essentials; + +import java.util.List; +import java.util.logging.Logger; +import net.minecraft.server.InventoryPlayer; +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.block.Sign; +import org.bukkit.craftbukkit.block.CraftSign; +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.craftbukkit.inventory.CraftInventoryPlayer; +import org.bukkit.event.player.*; +import org.bukkit.event.player.PlayerLoginEvent.Result; +import org.bukkit.inventory.ItemStack; + + +public class EssentialsPlayerListener extends PlayerListener +{ + private static final Logger logger = Logger.getLogger("Minecraft"); + private final Server server; + private final Essentials parent; + + public EssentialsPlayerListener(Essentials parent) + { + this.parent = parent; + this.server = parent.getServer(); + } + + private void onPlayerInteractEco(PlayerInteractEvent event) + { + if (Essentials.getSettings().areSignsDisabled()) return; + User user = User.get(event.getPlayer()); + if (event.getClickedBlock().getType() != Material.WALL_SIGN && event.getClickedBlock().getType() != Material.SIGN_POST) + return; + Sign sign = new CraftSign(event.getClickedBlock()); + + if (sign.getLine(0).equals("§1[Buy]") && user.isAuthorized("essentials.signs.buy.use")) + { + try + { + int amount = Integer.parseInt(sign.getLine(1)); + ItemStack item = ItemDb.get(sign.getLine(2), amount); + int cost = Integer.parseInt(sign.getLine(3).substring(1)); + if (user.getMoney() < cost) throw new Exception("You do not have sufficient funds."); + user.takeMoney(cost); + user.getInventory().addItem(item); + user.updateInventory(); + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + } + return; + } + + if (sign.getLine(0).equals("§1[Sell]") && user.isAuthorized("essentials.signs.sell.use")) + { + try + { + int amount = Integer.parseInt(sign.getLine(1)); + ItemStack item = ItemDb.get(sign.getLine(2), amount); + int cost = Integer.parseInt(sign.getLine(3).substring(1)); + if (!InventoryWorkaround.containsItem((CraftInventory)user.getInventory(), true, item)) throw new Exception("You do not have enough items to sell."); + user.giveMoney(cost); + InventoryWorkaround.removeItem((CraftInventory)user.getInventory(), true, item); + user.updateInventory(); + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + } + return; + } + + if (sign.getLine(0).equals("§1[Trade]") && user.isAuthorized("essentials.signs.trade.use")) + { + try + { + String[] l1 = sign.getLines()[1].split("[ :-]+"); + String[] l2 = sign.getLines()[2].split("[ :-]+"); + boolean m1 = l1[0].matches("\\$[0-9]+"); + boolean m2 = l2[0].matches("\\$[0-9]+"); + int q1 = Integer.parseInt(m1 ? l1[0].substring(1) : l1[0]); + int q2 = Integer.parseInt(m2 ? l2[0].substring(1) : l2[0]); + int r1 = Integer.parseInt(l1[m1 ? 1 : 2]); + int r2 = Integer.parseInt(l2[m2 ? 1 : 2]); + r1 = r1 - r1 % q1; + r2 = r2 - r2 % q2; + if (q1 < 1 || q2 < 1) throw new Exception("Quantities must be greater than 0."); + + ItemStack i1 = m1 || r1 <= 0 ? null : ItemDb.get(l1[1], r1); + ItemStack qi1 = m1 ? null : ItemDb.get(l1[1], q1); + ItemStack qi2 = m2 ? null : ItemDb.get(l2[1], q2); + + if (user.getName().equals(sign.getLines()[3].substring(2))) + { + if (m1) + { + user.giveMoney(r1); + } + else if (i1 != null) + { + user.getInventory().addItem(i1); + user.updateInventory(); + } + r1 = 0; + sign.setLine(1, (m1 ? "$" + q1 : q1 + " " + l1[1]) + ":" + r1); + } + else + { + if (m1) + { + if (user.getMoney() < q1) + throw new Exception("You do not have sufficient funds."); + } + else + { + if (!InventoryWorkaround.containsItem((CraftInventory)user.getInventory(), true, qi1)) + throw new Exception("You do not have " + q1 + "x " + l1[1] + "."); + } + + if (r2 < q2) throw new Exception("The trade sign does not have enough supply left."); + + if (m1) + user.takeMoney(q1); + else + InventoryWorkaround.removeItem((CraftInventory)user.getInventory(), true, qi1); + + if (m2) + user.giveMoney(q2); + else + user.getInventory().addItem(qi2); + + user.updateInventory(); + + r1 += q1; + r2 -= q2; + + sign.setLine(0, "§1[Trade]"); + sign.setLine(1, (m1 ? "$" + q1 : q1 + " " + l1[1]) + ":" + r1); + sign.setLine(2, (m2 ? "$" + q2 : q2 + " " + l2[1]) + ":" + r2); + + user.sendMessage("§7Trade completed."); + } + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + } + return; + } + } + + @Override + public void onPlayerInteract(PlayerInteractEvent event) + { + if (event.isCancelled()) return; + User user = User.get(event.getPlayer()); + if (user.isJailed()) + { + event.setCancelled(true); + return; + } + + onPlayerInteractEco(event); + onPlayerInteractSigns(event); + + if (!Essentials.getSettings().areSignsDisabled() && EssentialsBlockListener.protectedBlocks.contains(event.getClickedBlock().getType())) + { + if (!user.isAuthorized("essentials.signs.protection.override")) + { + if (EssentialsBlockListener.isBlockProtected(event.getClickedBlock(), user)) + { + event.setCancelled(true); + user.sendMessage("§cYou do not have permission to access that chest."); + return; + } + } + } + + if (Essentials.getSettings().getBedSetsHome() && event.getClickedBlock().getType() == Material.BED_BLOCK) + { + try + { + user.setHome(); + user.sendMessage("§7Your home is now set to this bed."); + } + catch (Throwable ex) + { + } + } + } + + private void onPlayerInteractSigns(PlayerInteractEvent event) + { + User user = User.get(event.getPlayer()); + if (user.isJailed()) return; + if (Essentials.getSettings().areSignsDisabled()) return; + if (event.getClickedBlock().getType() != Material.WALL_SIGN && event.getClickedBlock().getType() != Material.SIGN_POST) + return; + Sign sign = new CraftSign(event.getClickedBlock()); + + try + { + if (sign.getLine(0).equals("§1[Free]") && user.isAuthorized("essentials.signs.free.use")) + { + ItemStack item = ItemDb.get(sign.getLine(1)); + CraftInventoryPlayer inv = new CraftInventoryPlayer(new InventoryPlayer(user.getHandle())); + inv.clear(); + item.setAmount(9 * 4 * 64); + inv.addItem(item); + user.showInventory(inv); + return; + } + if (sign.getLine(0).equals("§1[Disposal]") && user.isAuthorized("essentials.signs.disposal.use")) + { + CraftInventoryPlayer inv = new CraftInventoryPlayer(new InventoryPlayer(user.getHandle())); + inv.clear(); + user.showInventory(inv); + return; + } + if (sign.getLine(0).equals("§1[Heal]") && user.isAuthorized("essentials.signs.heal.use")) + { + user.setHealth(20); + user.sendMessage("§7You have been healed."); + return; + } + if (sign.getLine(0).equals("§1[Mail]") && user.isAuthorized("essentials.signs.mail.use") && user.isAuthorized("essentials.mail")) + { + List mail = Essentials.readMail(user); + if (mail.isEmpty()) + { + user.sendMessage("§cYou do not have any mail!"); + return; + } + for (String s : mail) user.sendMessage(s); + user.sendMessage("§cTo mark your mail as read, type §c/mail clear"); + return; + } + } + catch (Throwable ex) + { + user.sendMessage("§cError: " + ex.getMessage()); + } + } + + @Override + public void onPlayerRespawn(PlayerRespawnEvent event) + { + User user = User.get(event.getPlayer()); + user.setDisplayName(user.getNick()); + updateCompass(user); + } + + @Override + public void onPlayerChat(PlayerChatEvent event) + { + User user = User.get(event.getPlayer()); + if (user.isMuted()) + { + event.setCancelled(true); + logger.info(user.getName() + " tried to speak, but is muted."); + } + } + + @Override + public void onPlayerMove(PlayerMoveEvent event) + { + if (event.isCancelled()) return; + final User user = User.get(event.getPlayer()); + + if (!Essentials.getSettings().getNetherPortalsEnabled()) return; + + final Block block = event.getPlayer().getWorld().getBlockAt(event.getTo().getBlockX(), event.getTo().getBlockY(), event.getTo().getBlockZ()); + List worlds = server.getWorlds(); + + if (block.getType() == Material.PORTAL && worlds.size() > 1 && user.isAuthorized("essentials.portal")) + { + if (user.getJustPortaled()) return; + + Location loc = event.getTo(); + final World world = worlds.get(user.getWorld() == worlds.get(0) ? 1 : 0); + + double factor; + if (user.getWorld().getEnvironment() == World.Environment.NETHER && world.getEnvironment() == World.Environment.NORMAL) + factor = 16.0; + else if (user.getWorld().getEnvironment() != world.getEnvironment()) + factor = 1.0 / 16.0; + else + factor = 1.0; + + int x = loc.getBlockX(); + int y = loc.getBlockY(); + int z = loc.getBlockZ(); + + if (user.getWorld().getBlockAt(x, y, z - 1).getType() == Material.PORTAL) + z--; + if (user.getWorld().getBlockAt(x - 1, y, z).getType() == Material.PORTAL) + x--; + + x = (int)(x * factor); + z = (int)(z * factor); + loc = new Location(world, x + .5, y, z + .5); + + Block dest = world.getBlockAt(x, y, z); + NetherPortal portal = NetherPortal.findPortal(dest); + if (portal == null) + { + if (world.getEnvironment() == World.Environment.NETHER || Essentials.getSettings().getGenerateExitPortals()) + { + portal = NetherPortal.createPortal(dest); + logger.info(event.getPlayer().getName() + " used a portal and generated an exit portal."); + user.sendMessage("§7Generating an exit portal."); + loc = portal.getSpawn(); + } + } + else + { + logger.info(event.getPlayer().getName() + " used a portal and used an existing exit portal."); + user.sendMessage("§7Teleporting via portal to an existing portal."); + loc = portal.getSpawn(); + } + + event.setFrom(loc); + event.setTo(loc); + try + { + user.teleportToNow(loc); + } + catch (Exception ex) + { + user.sendMessage(ex.getMessage()); + } + user.setJustPortaled(true); + user.sendMessage("§7Teleporting via portal."); + + event.setCancelled(true); + return; + } + + user.setJustPortaled(false); + } + + @Override + public void onPlayerQuit(PlayerQuitEvent event) + { + if (!Essentials.getSettings().getReclaimSetting()) + return; + + User.get(event.getPlayer()).dispose(); + Thread thread = new Thread(new Runnable() + { + @SuppressWarnings("LoggerStringConcat") + public void run() + { + try + { + Thread.sleep(1000); + Runtime rt = Runtime.getRuntime(); + double mem = rt.freeMemory(); + rt.runFinalization(); + rt.gc(); + mem = rt.freeMemory() - mem; + mem /= 1024 * 1024; + logger.info("Freed " + mem + " MB."); + } + catch (InterruptedException ex) + { + return; + } + } + }); + thread.setPriority(Thread.MIN_PRIORITY); + thread.start(); + } + + @Override + public void onPlayerJoin(PlayerJoinEvent event) + { + Essentials.getStatic().backup.onPlayerJoin(); + User user = User.get(event.getPlayer()); + + //we do not know the ip address on playerlogin so we need to do this here. + if (user.isIpBanned()) + { + user.kickPlayer("The Ban Hammer has spoken!"); + return; + } + + user.setDisplayName(user.getNick()); + + if (!Essentials.getSettings().isCommandDisabled("motd") && user.isAuthorized("essentials.motd")) + { + for (String m : parent.getMotd(user, null)) + { + if (m == null) continue; + user.sendMessage(m); + } + } + + if (!Essentials.getSettings().isCommandDisabled("mail")) + { + List mail = Essentials.readMail(user); + if (mail.isEmpty()) user.sendMessage("§7You have no new mail."); + else user.sendMessage("§cYou have " + mail.size() + " messages!§f Type §7/mail read§f to view your mail."); + } + } + + @Override + public void onPlayerLogin(PlayerLoginEvent event) + { + User user = User.get(event.getPlayer()); + if (event.getResult() != Result.ALLOWED) + return; + + if (user.isBanned()) + { + event.disallow(Result.KICK_BANNED, "The Ban Hammer has spoken!"); + return; + } + + if (server.getOnlinePlayers().length >= server.getMaxPlayers() && !user.isOp()) + { + event.disallow(Result.KICK_FULL, "Server is full"); + return; + } + + updateCompass(user); + } + + private void updateCompass(User user) + { + try + { + if (server.getPluginManager().isPluginEnabled("EssentialsHome")) + user.setCompassTarget(user.getHome()); + } + catch (Throwable ex) + { + } + } + + @Override + public void onPlayerTeleport(PlayerTeleportEvent event) + { + User user = User.get(event.getPlayer()); + if (user.currentJail == null || user.currentJail.isEmpty()) + return; + event.setCancelled(true); + user.sendMessage(ChatColor.RED + "You do the crime, you do the time."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/IConf.java b/Essentials/src/com/earth2me/essentials/IConf.java new file mode 100644 index 000000000..a523f8638 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/IConf.java @@ -0,0 +1,5 @@ +package com.earth2me.essentials; + +public interface IConf { + public void reloadConfig(); +} diff --git a/Essentials/src/com/earth2me/essentials/InventoryWorkaround.java b/Essentials/src/com/earth2me/essentials/InventoryWorkaround.java new file mode 100644 index 000000000..aabd7b02b --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/InventoryWorkaround.java @@ -0,0 +1,136 @@ +package com.earth2me.essentials; + +import java.util.HashMap; +import org.bukkit.craftbukkit.inventory.CraftInventory; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.inventory.ItemStack; + +/* + * This class can be removed when + * https://github.com/Bukkit/CraftBukkit/pull/193 + * is accepted to CraftBukkit + */ +public class InventoryWorkaround { + + public static int first(CraftInventory ci, ItemStack item, boolean forceDurability, boolean forceAmount) { + return next(ci, item, 0, forceDurability, forceAmount); + } + + public static int next(CraftInventory ci, ItemStack item, int start, boolean forceDurability, boolean forceAmount) { + CraftItemStack[] inventory = ci.getContents(); + for (int i = start; i < inventory.length; i++) { + CraftItemStack cItem = inventory[i]; + if (item.getTypeId() == cItem.getTypeId() && (!forceAmount || item.getAmount() == cItem.getAmount()) && (!forceDurability || cItem.getDurability() == item.getDurability())) { + return i; + } + } + return -1; + } + + public static HashMap removeItem(CraftInventory ci, boolean forceDurability, ItemStack... items) { + HashMap leftover = new HashMap(); + + // TODO: optimization + + for (int i = 0; i < items.length; i++) { + ItemStack item = items[i]; + if (item == null) { + continue; + } + int toDelete = item.getAmount(); + + while (true) { + + // Bail when done + if (toDelete <= 0) { + break; + } + + // get first Item, ignore the amount + int first = first(ci, item, forceDurability, false); + + // Drat! we don't have this type in the inventory + if (first == -1) { + item.setAmount(toDelete); + leftover.put(i, item); + break; + } else { + CraftItemStack itemStack = ci.getItem(first); + int amount = itemStack.getAmount(); + + if (amount <= toDelete) { + toDelete -= amount; + // clear the slot, all used up + ci.clear(first); + } else { + // split the stack and store + itemStack.setAmount(amount - toDelete); + ci.setItem(first, itemStack); + toDelete = 0; + } + } + } + } + return leftover; + } + + public static boolean containsItem(CraftInventory ci, boolean forceDurability, ItemStack... items) { + HashMap leftover = new HashMap(); + + // TODO: optimization + + // combine items + + ItemStack[] combined = new ItemStack[items.length]; + for (int i = 0; i < items.length; i++) { + if (items[i] == null) { + continue; + } + for (int j = 0; j < combined.length; j++) { + if (combined[j] == null) { + combined[j] = new ItemStack(items[i].getType(), items[i].getAmount(), items[i].getDurability()); + break; + } + if (combined[j].getTypeId() == items[i].getTypeId() && (!forceDurability || combined[j].getDurability() == items[i].getDurability())) { + combined[j].setAmount(combined[j].getAmount() + items[i].getAmount()); + break; + } + } + } + + for (int i = 0; i < combined.length; i++) { + ItemStack item = combined[i]; + if (item == null) { + continue; + } + int mustHave = item.getAmount(); + int position = 0; + + while (true) { + // Bail when done + if (mustHave <= 0) { + break; + } + + int slot = next(ci, item, position, forceDurability, false); + + // Drat! we don't have this type in the inventory + if (slot == -1) { + leftover.put(i, item); + break; + } else { + CraftItemStack itemStack = ci.getItem(slot); + int amount = itemStack.getAmount(); + + if (amount <= mustHave) { + mustHave -= amount; + } else { + mustHave = 0; + } + position = slot + 1; + } + } + } + return leftover.isEmpty(); + } +} diff --git a/Essentials/src/com/earth2me/essentials/ItemDb.java b/Essentials/src/com/earth2me/essentials/ItemDb.java new file mode 100644 index 000000000..8c3c47bab --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/ItemDb.java @@ -0,0 +1,110 @@ +package com.earth2me.essentials; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.util.*; +import java.util.logging.Logger; +import org.bukkit.inventory.ItemStack; + + +public class ItemDb +{ + private final static Logger logger = Logger.getLogger("Minecraft"); + private static Map items = new HashMap(); + private static Map durabilities = new HashMap(); + + @SuppressWarnings("LoggerStringConcat") + public static void load(File folder, String fname) throws IOException + { + folder.mkdirs(); + File file = new File(folder, fname); + + if (!file.exists()) + { + file.createNewFile(); + InputStream res = ItemDb.class.getResourceAsStream("/items.csv"); + FileWriter tx = new FileWriter(file); + try + { + for (int i = 0; (i = res.read()) > 0;) tx.write(i); + } + finally + { + try + { + tx.flush(); + tx.close(); + res.close(); + } + catch (Exception ex) + { + } + } + } + + BufferedReader rx = new BufferedReader(new FileReader(file)); + try + { + items.clear(); + + for (int i = 0; rx.ready(); i++) + { + try + { + String line = rx.readLine().trim().toLowerCase(); + if (line.startsWith("#")) + continue; + + String[] parts = line.split("[^a-z0-9]"); + if (parts.length < 2) + continue; + + int numeric = Integer.parseInt(parts[1]); + + durabilities.put(parts[0], parts.length > 2 && !parts[2].equals("0") ? Short.parseShort(parts[2]) : 0); + items.put(parts[0], numeric); + } + catch (Exception ex) + { + logger.warning("Error parsing " + fname + " on line " + i); + } + } + } + finally + { + rx.close(); + } + } + + public static ItemStack get(String id, int quantity) throws Exception { + ItemStack retval = get(id); + retval.setAmount(quantity); + return retval; + } + + public static ItemStack get(String id) throws Exception + { + ItemStack retval = new ItemStack(getUnsafe(id)); + retval.setAmount(Essentials.getSettings().getDefaultStackSize()); + retval.setDurability(durabilities.containsKey(id) ? durabilities.get(id) : 0); + if (items.containsValue(retval.getTypeId()) || true) return retval; + throw new Exception("Unknown item numeric: " + retval); + } + + private static int getUnsafe(String id) throws Exception + { + try + { + return Integer.parseInt(id); + } + catch (NumberFormatException ex) + { + if (items.containsKey(id)) return items.get(id); + throw new Exception("Unknown item name: " + id); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/Jail.java b/Essentials/src/com/earth2me/essentials/Jail.java new file mode 100644 index 000000000..5e0dd87ee --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/Jail.java @@ -0,0 +1,117 @@ +package com.earth2me.essentials; + +import java.io.File; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockDamageEvent; +import org.bukkit.event.block.BlockListener; +import org.bukkit.event.block.BlockPlaceEvent; + + +public class Jail extends BlockListener implements IConf +{ + private static final Logger logger = Logger.getLogger("Minecraft"); + private EssentialsConf config; + + public Jail(File dataFolder) + { + config = new EssentialsConf(new File(dataFolder, "jail.yml")); + config.load(); + } + + public void setJail(Location loc, String jailName) throws Exception + { + Map map = new HashMap(); + map.put("world", loc.getWorld().getName()); + map.put("x", loc.getX()); + map.put("y", loc.getY()); + map.put("z", loc.getZ()); + map.put("yaw", loc.getYaw()); + map.put("pitch", loc.getPitch()); + config.setProperty(jailName.toLowerCase(), map); + config.save(); + } + + public Location getJail(String jailName) throws Exception + { + if (config.getProperty(jailName.toLowerCase()) == null) + { + throw new Exception("That jail does not exist"); + } + + World jWorld = null; + String world = config.getString(jailName + ".world", ""); // wh.spawnX + double x = config.getDouble(jailName + ".x", 0); // wh.spawnX + double y = config.getDouble(jailName + ".y", 0); // wh.spawnY + double z = config.getDouble(jailName + ".z", 0); // wh.spawnZ + float yaw = (float)config.getDouble(jailName + ".yaw", 0); + float pitch = (float)config.getDouble(jailName + ".pitch", 0); + for (World w : Essentials.getStatic().getServer().getWorlds()) + { + if (w.getName().equalsIgnoreCase(world)) + { + jWorld = w; + break; + } + + } + return new Location(jWorld, x, y, z, yaw, pitch); + } + + public void sendToJail(User user, String jail) throws Exception + { + user.teleport(getJail(jail)); + user.currentJail = jail; + } + + public void delJail(String jail) throws Exception + { + config.removeProperty(jail.toLowerCase()); + config.save(); + } + + public List getJails() throws Exception + { + return config.getKeys(null); + } + + public void reloadConfig() + { + config.load(); + } + + @Override + public void onBlockBreak(BlockBreakEvent event) + { + User user = User.get(event.getPlayer()); + if (user.isJailed()) + { + event.setCancelled(true); + } + } + + @Override + public void onBlockPlace(BlockPlaceEvent event) + { + User user = User.get(event.getPlayer()); + if (user.isJailed()) + { + event.setCancelled(true); + } + } + + @Override + public void onBlockDamage(BlockDamageEvent event) + { + User user = User.get(event.getPlayer()); + if (user.isJailed()) + { + event.setCancelled(true); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/Mob.java b/Essentials/src/com/earth2me/essentials/Mob.java new file mode 100644 index 000000000..3c0d9bd1e --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/Mob.java @@ -0,0 +1,122 @@ +package com.earth2me.essentials; + +import java.lang.reflect.Constructor; +import java.util.HashMap; +import java.util.logging.Logger; +import net.minecraft.server.Entity; +import net.minecraft.server.WorldServer; +import org.bukkit.Server; +import org.bukkit.craftbukkit.entity.CraftEntity; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Player; + + +public enum Mob +{ + CHICKEN("Chicken", Enemies.FRIENDLY), + COW("Cow", Enemies.FRIENDLY), + CREEPER("Creeper", Enemies.ENEMY), + GHAST("Ghast", Enemies.ENEMY), + GIANT("Giant", "GiantZombie", Enemies.ENEMY), + PIG("Pig", Enemies.FRIENDLY), + PIGZOMB("PigZombie", Enemies.NEUTRAL), + SHEEP("Sheep", Enemies.FRIENDLY, ""), + SKELETON("Skeleton", Enemies.ENEMY), + SLIME("Slime", Enemies.ENEMY), + SPIDER("Spider", Enemies.ENEMY), + SQUID("Squid", Enemies.FRIENDLY), + ZOMBIE("Zombie", Enemies.ENEMY), + MONSTER("Monster", Enemies.ENEMY); + + public static final Logger logger = Logger.getLogger("Minecraft"); + + private Mob(String n, Enemies en, String s) + { + this.s = s; + this.name = n; + this.craftClass = n; + this.entityClass = n; + this.type = en; + } + + private Mob(String n, Enemies en) + { + this.name = n; + this.craftClass = n; + this.entityClass = n; + this.type = en; + } + + private Mob(String n, String ec, Enemies en) + { + this.name = n; + this.craftClass = n; + this.entityClass = ec; + this.type = en; + } + + private Mob(String n, String ec, String cc, Enemies en) + { + this.name = n; + this.entityClass = ec; + this.craftClass = cc; + this.type = en; + } + public String s = "s"; + public String name; + public Enemies type; + private String entityClass; + private String craftClass; + private static final HashMap hashMap = new HashMap(); + + static + { + for (Mob mob : Mob.values()) + { + hashMap.put(mob.name, mob); + } + } + + @SuppressWarnings({"unchecked", "CallToThreadDumpStack"}) + public CraftEntity spawn(Player player, Server server) throws MobException + { + try + { + WorldServer world = ((org.bukkit.craftbukkit.CraftWorld)player.getWorld()).getHandle(); + Constructor craft = (Constructor)ClassLoader.getSystemClassLoader().loadClass("org.bukkit.craftbukkit.entity.Craft" + craftClass).getConstructors()[0]; + Constructor entity = (Constructor)ClassLoader.getSystemClassLoader().loadClass("net.minecraft.server.Entity" + entityClass).getConstructors()[0]; + return craft.newInstance((CraftServer)server, entity.newInstance(world)); + } + catch (Exception ex) + { + logger.warning("Unable to spawn mob."); + ex.printStackTrace(); + throw new MobException(); + } + } + + + public enum Enemies + { + FRIENDLY("friendly"), + NEUTRAL("neutral"), + ENEMY("enemy"); + + private Enemies(String t) + { + this.type = t; + } + protected String type; + } + + + public class MobException extends Exception + { + private static final long serialVersionUID = 1L; + } + + public static Mob fromName(String n) + { + return hashMap.get(n); + } +} diff --git a/Essentials/src/com/earth2me/essentials/NetherPortal.java b/Essentials/src/com/earth2me/essentials/NetherPortal.java new file mode 100644 index 000000000..25ebe5e23 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/NetherPortal.java @@ -0,0 +1,167 @@ +/** + * @author SpaceManiac + * @licent MIT + * @origin https://github.com/SpaceManiac/Nether/blob/master/org/innectis/Nether/NetherPortal.java + */ +package com.earth2me.essentials; + +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.Location; +import org.bukkit.Material; +import java.util.ArrayList; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class NetherPortal +{ + private Block block; + + public NetherPortal(Block b) + { + block = b; + } + + public Block getBlock() + { + return block; + } + + public void setBlock(Block b) + { + block = b; + } + + // Return a random spawnable location + public Location getSpawn() + { + if (block.getWorld().getBlockAt(block.getX() + 1, block.getY(), block.getZ()).getType().equals(Material.PORTAL) + || block.getWorld().getBlockAt(block.getX() - 1, block.getY(), block.getZ()).getType().equals(Material.PORTAL)) + { + // portal is in X direction + return new Location(block.getWorld(), block.getX() + 1, + block.getY(), block.getZ() + 1.5 - 2 * Math.round(Math.random())); + } + else + { + // portal is in Z direction + return new Location(block.getWorld(), block.getX() + 1.5 - 2 * Math.round(Math.random()), + block.getY(), block.getZ() + 1); + } + } + + // ============================== + // Find a nearby portal within 16 blocks of the given block + // Not guaranteed to be the nearest + public static NetherPortal findPortal(Block dest) + { + World world = dest.getWorld(); + + // Get list of columns in a circle around the block + ArrayList columns = new ArrayList(); + for (int x = dest.getX() - 16; x <= dest.getX() + 16; ++x) + { + for (int z = dest.getZ() - 16; z <= dest.getZ() + 16; ++z) + { + int dx = dest.getX() - x, dz = dest.getZ() - z; + if (dx * dx + dz * dz <= 256) + { + columns.add(world.getBlockAt(x, 0, z)); + } + } + } + + // For each column try to find a portal block + for (Block col : columns) + { + for (int y = 127; y >= 0; --y) + { + Block b = world.getBlockAt(col.getX(), y, col.getZ()); + if (b.getType().equals(Material.PORTAL) && Math.abs(dest.getY() - y) <= 16) + { + // Huzzah! + return new NetherPortal(b); + } + } + } + + // Nope! + return null; + } + + // Create a new portal at the specified block, fudging position if needed + // Will occasionally end up making portals in bad places, but let's hope not + public static NetherPortal createPortal(Block dest) + { + World world = dest.getWorld(); + + // Try not to spawn within water or lava + Material m = dest.getType(); + while (((m.equals(Material.LAVA) || m.equals(Material.WATER) || m.equals(Material.STATIONARY_LAVA) + || m.equals(Material.STATIONARY_WATER) || m.equals(Material.SAND) || m.equals(Material.GRAVEL))) && + dest.getY() < 120) + { + dest = world.getBlockAt(dest.getX(), dest.getY() + 4, dest.getZ()); + m = dest.getType(); + } + + // Not too high or too low overall + if (dest.getY() > 120) + { + dest = world.getBlockAt(dest.getX(), 120, dest.getZ()); + } + else if (dest.getY() < 8) + { + dest = world.getBlockAt(dest.getX(), 8, dest.getZ()); + } + + // Create the physical portal + // For now, don't worry about direction + + int x = dest.getX(), y = dest.getY(), z = dest.getZ(); + Logger.getLogger("Minecraft").log(Level.INFO, "Creating portal at "+x+","+y+","+z+"."); + + // Clear area around portal + ArrayList columns = new ArrayList(); + for (int x2 = x - 4; x2 <= x + 4; ++x2) + { + for (int z2 = z - 4; z2 <= z + 4; ++z2) + { + double dx = x + 0.5f - x2, dz = z - z2; + if (dx * dx + dz * dz <= 13) + { + columns.add(world.getBlockAt(x2, 0, z2)); + } + } + } + + // Clear area around portal + for (Block col : columns) + { + // Stone platform + world.getBlockAt(col.getX(), y - 1, col.getZ()).setType(Material.STONE); + for (int yd = 0; yd < 4; ++yd) + { + world.getBlockAt(col.getX(), y + yd, col.getZ()).setType(Material.AIR); + } + } + + // Build obsidian frame + for (int xd = -1; xd < 3; ++xd) + { + for (int yd = -1; yd < 4; ++yd) + { + if (xd == -1 || yd == -1 || xd == 2 || yd == 3) + { + world.getBlockAt(x + xd, y + yd, z).setType(Material.OBSIDIAN); + } + } + } + + // Set it alight! + dest.setType(Material.FIRE); + + return new NetherPortal(dest); + } +} diff --git a/Essentials/src/com/earth2me/essentials/OfflinePlayer.java b/Essentials/src/com/earth2me/essentials/OfflinePlayer.java new file mode 100644 index 000000000..5fffdfa99 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/OfflinePlayer.java @@ -0,0 +1,351 @@ +package com.earth2me.essentials; + +import java.net.InetSocketAddress; +import java.util.HashSet; +import java.util.List; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Egg; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Snowball; +import org.bukkit.entity.Vehicle; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.util.Vector; + + +public class OfflinePlayer implements Player +{ + private final String name; + private Location location = new Location(null, 0, 0, 0, 0, 0); + + public OfflinePlayer(String name) + { + this.name = name; + } + + public boolean isOnline() + { + return false; + } + + public boolean isOp() + { + return false; + } + + public void sendMessage(String string) + { + } + + public String getDisplayName() + { + return name; + } + + public void setDisplayName(String string) + { + } + + public void setCompassTarget(Location lctn) + { + } + + public InetSocketAddress getAddress() + { + return null; + } + + public void kickPlayer(String string) + { + } + + public String getName() + { + return name; + } + + public PlayerInventory getInventory() + { + return null; + } + + public ItemStack getItemInHand() + { + return null; + } + + public void setItemInHand(ItemStack is) + { + } + + public int getHealth() + { + return 0; + } + + public void setHealth(int i) + { + } + + public Egg throwEgg() + { + return null; + } + + public Snowball throwSnowball() + { + return null; + } + + public Arrow shootArrow() + { + return null; + } + + public boolean isInsideVehicle() + { + return false; + } + + public boolean leaveVehicle() + { + return false; + } + + public Vehicle getVehicle() + { + return null; + } + + public Location getLocation() + { + return location; + } + + public World getWorld() + { + return null; + } + + public void teleportTo(Location lctn) + { + } + + public void teleportTo(Entity entity) + { + } + + public int getEntityId() + { + return -1; + } + + public boolean performCommand(String string) + { + return false; + } + + public boolean isPlayer() + { + return false; + } + + public int getRemainingAir() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void setRemainingAir(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public int getMaximumAir() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void setMaximumAir(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public boolean isSneaking() + { + return false; + } + + public void setSneaking(boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void updateInventory() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void chat(String string) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public double getEyeHeight() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public double getEyeHeight(boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public List getLineOfSight(HashSet hs, int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public Block getTargetBlock(HashSet hs, int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public List getLastTwoTargetBlocks(HashSet hs, int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public int getFireTicks() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public int getMaxFireTicks() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void setFireTicks(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void remove() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public Server getServer() + { + return Essentials.getStatic() == null ? null : Essentials.getStatic().getServer(); + } + + public Vector getMomentum() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void setMomentum(Vector vector) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void setVelocity(Vector vector) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public Vector getVelocity() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void damage(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void damage(int i, Entity entity) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public Location getEyeLocation() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void sendRawMessage(String string) { + throw new UnsupportedOperationException("Not supported yet."); + } + + public Location getCompassTarget() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public int getMaximumNoDamageTicks() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void setMaximumNoDamageTicks(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public int getLastDamage() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void setLastDamage(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public int getNoDamageTicks() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void setNoDamageTicks(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public boolean teleport(Location lctn) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public boolean teleport(Entity entity) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public Entity getPassenger() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public boolean setPassenger(Entity entity) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public boolean isEmpty() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public boolean eject() + { + throw new UnsupportedOperationException("Not supported yet."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/PlayerExtension.java b/Essentials/src/com/earth2me/essentials/PlayerExtension.java new file mode 100644 index 000000000..758f8076d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/PlayerExtension.java @@ -0,0 +1,141 @@ +package com.earth2me.essentials; + +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.entity.CraftPlayer; +import net.minecraft.server.EntityPlayer; +import net.minecraft.server.IInventory; +import org.bukkit.craftbukkit.inventory.CraftInventoryPlayer; +import org.bukkit.entity.*; + + +public class PlayerExtension extends PlayerWrapper +{ + public PlayerExtension(Player base) + { + super(base); + } + + public boolean isBanned() + { + return Essentials.getStatic().bans.contains(getName()); + } + + public boolean isIpBanned() + { + return Essentials.getStatic().bannedIps.contains(getAddress().getAddress().toString().replace("/", "")); + } + + public float getCorrectedYaw() + { + float angle = (getLocation().getYaw() - 90) % 360; + if (angle < 0) angle += 360.0F; + return angle; + } + + public void showInventory(IInventory inventory) + { + getHandle().a(inventory); + } + + public void showInventory(CraftInventoryPlayer inventory) + { + showInventory((IInventory)inventory.getInventory()); + } + + public Location getSafeDestination(Location loc) throws Exception + { + World world = loc.getWorld(); + double x = loc.getX(); + double y = loc.getY(); + double z = loc.getZ(); + + while (isBlockAboveAir(world, x, y, z)) + { + y -= 1.0D; + if (y < 0) { + throw new Exception("Hole in floor"); + } + } + + while (isBlockUnsafe(world, x, y, z)) + { + y += 1.0D; + if (y >= 110.0D) { + x += 1.0D; + break; + } + } + while (isBlockUnsafe(world, x, y, z)) + { + y -= 1.0D; + if (y <= 1.0D) + { + y = 110.0D; + x += 1.0D; + } + } + return new Location(world, x, y, z, loc.getYaw(), loc.getPitch()); + } + + private boolean isBlockAboveAir(World world, double x, double y, double z) + { + return world.getBlockAt((int)Math.floor(x), (int)Math.floor(y - 1.0D), (int)Math.floor(z)).getType() == Material.AIR; + } + + public boolean isBlockUnsafe(World world, double x, double y, double z) + { + Block below = world.getBlockAt((int)Math.floor(x), (int)Math.floor(y - 1.0D), (int)Math.floor(z)); + if (below.getType() == Material.LAVA || below.getType() == Material.STATIONARY_LAVA) + return true; + + if (below.getType() == Material.FIRE) + return true; + + if ((world.getBlockAt((int)Math.floor(x), (int)Math.floor(y), (int)Math.floor(z)).getType() != Material.AIR) + || (world.getBlockAt((int)Math.floor(x), (int)Math.floor(y + 1.0D), (int)Math.floor(z)).getType() != Material.AIR)) + { + return true; + } + return isBlockAboveAir(world, x, y, z); + } + + public TargetBlock getTarget() + { + return new TargetBlock(getBase()); + } + + public String getGroup() + { + try + { + return com.nijikokun.bukkit.Permissions.Permissions.Security.getGroup(getWorld().getName(), getName()); + } + catch (Throwable ex) + { + return "default"; + } + } + + public boolean canBuild() + { + try + { + return com.nijikokun.bukkit.Permissions.Permissions.Security.canGroupBuild(getWorld().getName(), getGroup()); + } + catch (Throwable ex) + { + return true; + } + } + + public EntityPlayer getHandle() + { + return (EntityPlayer)getCraftPlayer().getHandle(); + } + + public CraftPlayer getCraftPlayer() + { + return (CraftPlayer)base; + } +} diff --git a/Essentials/src/com/earth2me/essentials/PlayerWrapper.java b/Essentials/src/com/earth2me/essentials/PlayerWrapper.java new file mode 100644 index 000000000..0de6f669e --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/PlayerWrapper.java @@ -0,0 +1,416 @@ +package com.earth2me.essentials; + +import java.net.InetSocketAddress; +import java.util.*; +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.entity.*; +import org.bukkit.inventory.*; +import org.bukkit.util.Vector; + +public class PlayerWrapper implements Player +{ + protected Player base; + + public PlayerWrapper(Player base) + { + this.base = base; + } + + public final Player getBase() + { + return base; + } + + public final Player setBase(Player base) + { + return this.base = base; + } + + @Override + public void setDisplayName(String string) + { + base.setDisplayName(string); + } + + @Override + public void setCompassTarget(Location lctn) + { + base.setCompassTarget(lctn); + } + + @Override + public InetSocketAddress getAddress() + { + return base.getAddress(); + } + + @Override + public void kickPlayer(String string) + { + base.kickPlayer(string); + } + + @Override + public String getName() + { + return base.getName(); + } + + @Override + public PlayerInventory getInventory() + { + return base.getInventory(); + } + + @Override + public ItemStack getItemInHand() + { + return base.getItemInHand(); + } + + @Override + public void setItemInHand(ItemStack is) + { + base.setItemInHand(is); + } + + @Override + public int getHealth() + { + return base.getHealth(); + } + + @Override + public void setHealth(int i) + { + base.setHealth(i); + } + + @Override + public Egg throwEgg() + { + return base.throwEgg(); + } + + @Override + public Snowball throwSnowball() + { + return base.throwSnowball(); + } + + @Override + public Arrow shootArrow() + { + return base.shootArrow(); + } + + @Override + public boolean isInsideVehicle() + { + return base.isInsideVehicle(); + } + + @Override + public boolean leaveVehicle() + { + return base.leaveVehicle(); + } + + @Override + public Vehicle getVehicle() + { + return base.getVehicle(); + } + + @Override + public Location getLocation() + { + return base.getLocation(); + } + + @Override + public World getWorld() + { + return base.getWorld(); + } + + @Override + public Server getServer() + { + return base.getServer(); + } + + @Override + public boolean isOnline() + { + return base.isOnline(); + } + + @Override + public boolean isOp() + { + return base.isOp(); + } + + @Override + public boolean teleport(Location lctn) + { + return base.teleport(lctn); + } + + @Override + public boolean teleport(Entity entity) + { + return base.teleport(entity); + } + + @Override + public void sendMessage(String string) + { + base.sendMessage(string); + } + + @Override + public void setVelocity(Vector vector) + { + base.setVelocity(vector); + } + + @Override + public Vector getVelocity() + { + return base.getVelocity(); + } + + @Override + public double getEyeHeight() + { + return base.getEyeHeight(); + } + + @Override + public double getEyeHeight(boolean bln) + { + return base.getEyeHeight(bln); + } + + @Override + public List getLineOfSight(HashSet hs, int i) + { + return base.getLineOfSight(hs, i); + } + + @Override + public Block getTargetBlock(HashSet hs, int i) + { + return base.getTargetBlock(hs, i); + } + + @Override + public List getLastTwoTargetBlocks(HashSet hs, int i) + { + return base.getLastTwoTargetBlocks(hs, i); + } + + @Override + public int getFireTicks() + { + return base.getFireTicks(); + } + + @Override + public int getMaxFireTicks() + { + return base.getMaxFireTicks(); + } + + @Override + public void setFireTicks(int i) + { + base.setFireTicks(i); + } + + @Override + public void remove() + { + base.remove(); + } + + /** + * This is not deprecated because the underlying method isn't really deprecated; rather, it's just "imperfect". By + * We will continue to use this method even after the underlying CraftBukkit method is changed, so do not deprecate + * it. Chances are Bukkit will also choose to un-deprecate this method at some point. + */ + @Override + public void updateInventory() + { + base.updateInventory(); + } + + @Override + public void chat(String string) + { + base.chat(string); + } + + @Override + public boolean isSneaking() + { + return base.isSneaking(); + } + + @Override + public void setSneaking(boolean bln) + { + base.setSneaking(bln); + } + + @Override + public int getEntityId() + { + return base.getEntityId(); + } + + @Override + public boolean performCommand(String string) + { + return base.performCommand(string); + } + + @Override + public int getRemainingAir() + { + return base.getRemainingAir(); + } + + @Override + public void setRemainingAir(int i) + { + base.setRemainingAir(i); + } + + @Override + public int getMaximumAir() + { + return base.getMaximumAir(); + } + + @Override + public void setMaximumAir(int i) + { + base.setMaximumAir(i); + } + + @Override + public String getDisplayName() + { + if (base.getDisplayName() != null) + return base.getDisplayName(); + else + return base.getName(); + } + + @Override + public void damage(int i) + { + base.damage(i); + } + + @Override + public void damage(int i, Entity entity) + { + base.damage(i, entity); + } + + @Override + public Location getEyeLocation() + { + return base.getEyeLocation(); + } + + @Override + public void sendRawMessage(String string) { + base.sendRawMessage(string); + } + + @Override + public Location getCompassTarget() + { + return base.getCompassTarget(); + } + + @Override + public int getMaximumNoDamageTicks() + { + return base.getMaximumNoDamageTicks(); + } + + @Override + public void setMaximumNoDamageTicks(int i) + { + base.setMaximumNoDamageTicks(i); + } + + @Override + public int getLastDamage() + { + return base.getLastDamage(); + } + + @Override + public void setLastDamage(int i) + { + base.setLastDamage(i); + } + + @Override + public int getNoDamageTicks() + { + return base.getNoDamageTicks(); + } + + @Override + public void setNoDamageTicks(int i) + { + base.setNoDamageTicks(i); + } + + @Override + public Entity getPassenger() + { + return base.getPassenger(); + } + + @Override + public boolean setPassenger(Entity entity) + { + return base.setPassenger(entity); + } + + @Override + public boolean isEmpty() + { + return base.isEmpty(); + } + + @Override + public boolean eject() + { + return base.eject(); + } + + @Override + @Deprecated + public void teleportTo(Location lctn) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + @Deprecated + public void teleportTo(Entity entity) + { + throw new UnsupportedOperationException("Not supported yet."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/Settings.java b/Essentials/src/com/earth2me/essentials/Settings.java new file mode 100644 index 000000000..9c774b848 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/Settings.java @@ -0,0 +1,348 @@ +package com.earth2me.essentials; + +import java.util.*; +import org.bukkit.ChatColor; +import com.earth2me.essentials.commands.IEssentialsCommand; +import java.io.File; +import java.util.ArrayList; +import org.bukkit.entity.CreatureType; + + +public class Settings implements IConf +{ + private EssentialsConf config; + + public Settings(File dataFolder) + { + config = new EssentialsConf(new File(dataFolder, "config.yml")); + config.setTemplateName("/config.yml"); + config.load(); + } + + public boolean getRespawnAtHome() + { + return config.getBoolean("respawn-at-home", false); + } + + public boolean getBedSetsHome() + { + return config.getBoolean("bed-sethome", false); + } + + public int getChatRadius() + { + return config.getInt("chat.radius", config.getInt("chat-radius", 0)); + } + + public long getTeleportDelay() + { + return config.getInt("teleport-delay", 0) * 1000L; + } + + public int getDefaultStackSize() + { + return config.getInt("default-stack-size", 64); + } + + public int getStartingBalance() + { + return config.getInt("starting-balance", 0); + } + + public boolean getNetherPortalsEnabled() + { + return isNetherEnabled() && config.getBoolean("nether.portals-enabled", false); + } + + public String getMcslKey() + { + return config.getString("mcsl-key", "").replaceAll("[^a-zA-Z0-9]", ""); + } + + public boolean getWhitelistEnabled() + { + return false; + } + + public boolean isCommandDisabled(IEssentialsCommand cmd) + { + return isCommandDisabled(cmd.getName()); + } + + public boolean isCommandDisabled(String label) + { + for (String c : config.getStringList("disabled-commands", new ArrayList(0))) + { + if (!c.equalsIgnoreCase(label)) continue; + return true; + } + return config.getBoolean("disable-" + label.toLowerCase(), false); + } + + public boolean isCommandRestricted(IEssentialsCommand cmd) + { + return isCommandRestricted(cmd.getName()); + } + + public boolean isCommandRestricted(String label) + { + for (String c : config.getStringList("restricted-commands", new ArrayList(0))) + { + if (!c.equalsIgnoreCase(label)) continue; + return true; + } + return config.getBoolean("restrict-" + label.toLowerCase(), false); + } + + public int getCommandCost(IEssentialsCommand cmd) + { + return getCommandCost(cmd.getName()); + } + + public int getCommandCost(String label) + { + int cost = config.getInt("command-costs." + label, 0); + if (cost == 0) + cost = config.getInt("cost-" + label, 0); + return cost; + } + + public String getCommandPrefix() + { + return config.getString("command-prefix", ""); + } + + public String getNicknamePrefix() + { + return config.getString("nickname-prefix", ""); + } + + public long getTeleportCooldown() + { + return (long)config.getInt("teleport-cooldown", 60) * 1000L; + } + + public long getHealCooldown() + { + return (long)config.getInt("heal-cooldown", 60) * 1000L; + } + + public Object getKit(String name) + { + Map kits = (Map)config.getProperty("kits"); + return kits.get(name.replace('.', '_').replace('/', '_')); + } + + public ChatColor getOperatorColor() + { + String colorName = config.getString("ops-name-color", null); + + if (colorName == null) + return ChatColor.RED; + + try + { + return ChatColor.valueOf(colorName.toUpperCase()); + } + catch (IllegalArgumentException ex) + { + } + + return ChatColor.getByCode(Integer.parseInt(colorName, 16)); + } + + public boolean getReclaimSetting() + { + return config.getBoolean("reclaim-onlogout", true); + } + + public String getNetherName() + { + return config.getString("nether.folder", "nether"); + } + + public boolean isNetherEnabled() + { + return config.getBoolean("nether.enabled", true); + } + + public int getSpawnMobLimit() + { + return config.getInt("spawnmob-limit", 10); + } + + public boolean showNonEssCommandsInHelp() + { + return config.getBoolean("non-ess-in-help", true); + } + + public HashMap getEpSettings() + { + HashMap epSettings = new HashMap(); + + epSettings.put("protect.protect.signs", config.getBoolean("protect.protect.signs", true)); + epSettings.put("protect.protect.rails", config.getBoolean("protect.protect.rails", true)); + epSettings.put("protect.protect.block-below", config.getBoolean("protect.protect.block-below", true)); + epSettings.put("protect.protect.prevent-block-on-rails", config.getBoolean("protect.protect.prevent-block-on-rails", false)); + return epSettings; + } + + public HashMap getEpDBSettings() + { + HashMap epSettings = new HashMap(); + epSettings.put("protect.datatype", config.getString("protect.datatype", "sqlite")); + epSettings.put("protect.username", config.getString("protect.username", "root")); + epSettings.put("protect.password", config.getString("protect.password", "root")); + epSettings.put("protect.mysqlDb", config.getString("protect.mysqlDb", "jdbc:mysql://localhost:3306/minecraft")); + return epSettings; + } + + public ArrayList getEpAlertOnPlacement() + { + ArrayList epAlertPlace = new ArrayList(); + epAlertPlace.addAll(Arrays.asList(config.getString("protect.alert.on-placement", "").split(","))); + return epAlertPlace; + } + + public ArrayList getEpAlertOnUse() + { + ArrayList epAlertUse = new ArrayList(); + epAlertUse.addAll(Arrays.asList(config.getString("protect.alert.on-use", "").split(","))); + return epAlertUse; + } + + public ArrayList getEpAlertOnBreak() + { + ArrayList epAlertPlace = new ArrayList(); + epAlertPlace.addAll(Arrays.asList(config.getString("protect.alert.on-break", "").split(","))); + return epAlertPlace; + } + + public ArrayList epBlackListPlacement() + { + ArrayList epBlack = new ArrayList(); + epBlack.addAll(Arrays.asList(config.getString("protect.blacklist.placement", "").split(","))); + return epBlack; + } + + public ArrayList epBlackListUsage() + { + ArrayList epBlack = new ArrayList(); + epBlack.addAll(Arrays.asList(config.getString("protect.blacklist.usage", "").split(","))); + return epBlack; + } + + public HashMap getEpGuardSettings() + { + HashMap epSettings = new HashMap(); + epSettings.put("protect.prevent.lava-flow", config.getBoolean("protect.prevent.lava-flow", false)); + epSettings.put("protect.prevent.water-flow", config.getBoolean("protect.prevent.water-flow", false)); + epSettings.put("protect.prevent.water-bucket-flow", config.getBoolean("protect.prevent.water-bucket-flow", false)); + epSettings.put("protect.prevent.fire-spread", config.getBoolean("protect.prevent.fire-spread", false)); + epSettings.put("protect.prevent.flint-fire", config.getBoolean("protect.prevent.flint-fire", false)); + epSettings.put("protect.prevent.lava-fire-spread", config.getBoolean("protect.prevent.lava-fire-spread", false)); + epSettings.put("protect.prevent.tnt-explosion", config.getBoolean("protect.prevent.tnt-explosion", false)); + epSettings.put("protect.prevent.creeper-explosion", config.getBoolean("protect.prevent.creeper-explosion", false)); + epSettings.put("protect.prevent.creeper-playerdamage", config.getBoolean("protect.prevent.creeper-playerdamage", false)); + epSettings.put("protect.prevent.creeper-blockdamage", config.getBoolean("protect.prevent.creeper-blockdamage", false)); + for (CreatureType ct : CreatureType.values()) { + String name = ct.toString().toLowerCase(); + epSettings.put("protect.prevent.spawn."+name, config.getBoolean("protect.prevent.spawn."+name, false)); + } + return epSettings; + } + + public HashMap getEpPlayerSettings() + { + HashMap epPlayerSettings = new HashMap(); + epPlayerSettings.put("protect.disable.fall", config.getBoolean("protect.disable.fall", false)); + epPlayerSettings.put("protect.disable.pvp", config.getBoolean("protect.disable.pvp", false)); + epPlayerSettings.put("protect.disable.drown", config.getBoolean("protect.disable.drown", false)); + epPlayerSettings.put("protect.disable.suffocate", config.getBoolean("protect.disable.suffocate", false)); + epPlayerSettings.put("protect.disable.lavadmg", config.getBoolean("protect.disable.lavadmg", false)); + epPlayerSettings.put("protect.disable.projectiles", config.getBoolean("protect.disable.projectiles", false)); + epPlayerSettings.put("protect.disable.contactdmg", config.getBoolean("protect.disable.contactdmg", false)); + epPlayerSettings.put("protect.disable.firedmg", config.getBoolean("protect.disable.firedmg", false)); + epPlayerSettings.put("protect.disable.build", config.getBoolean("protect.disable.build", false)); + return epPlayerSettings; + + } + + public int getEpCreeperMaxHeight() + { + return config.getInt("protect.creeper.max-height", -1); + } + + public boolean areSignsDisabled() + { + return config.getBoolean("signs-disabled", false); + } + + public long getBackupInterval() + { + return config.getInt("backup.interval", 1440); // 1440 = 24 * 60 + } + + public String getBackupCommand() + { + return config.getString("backup.command", null); + } + + public String getChatFormat(String group) + { + return config.getString("chat.group-formats." + (group == null ? "Default" : group), + config.getString("chat.format", "&7[{GROUP}]&f {DISPLAYNAME}&7:&f {MESSAGE}")); + } + + public boolean getGenerateExitPortals() + { + return config.getBoolean("nether.generate-exit-portals", true); + } + + public boolean getAnnounceNewPlayers() + { + return !config.getString("newbies.announce-format", "-").isEmpty(); + } + + public String getAnnounceNewPlayerFormat(User user) + { + return format(config.getString("newbies.announce-format", "&dWelcome {DISPLAYNAME} to the server!"), user); + } + + public String format(String format, User user) + { + return format.replace('&', '§').replace("§§", "&").replace("{PLAYER}", user.getDisplayName()).replace("{DISPLAYNAME}", user.getDisplayName()).replace("{GROUP}", user.getGroup()).replace("{USERNAME}", user.getName()).replace("{ADDRESS}", user.getAddress().toString()); + } + + public String getNewbieSpawn() + { + return config.getString("newbies.spawnpoint", "default"); + } + public boolean getPerWarpPermission() + { + return config.getBoolean("per-warp-permission", false); + } + + public boolean getSortListByGroups() + { + return config.getBoolean("sort-list-by-groups", true); + } + + public void reloadConfig() { + config.load(); + } + + public ArrayList itemSpawnBlacklist() + { + ArrayList epItemSpwn = new ArrayList(); + epItemSpwn.addAll(Arrays.asList(config.getString("item-spawn-blacklist", "").split(","))); + return epItemSpwn; + } + + public ArrayList epBlockBreakingBlacklist() + { + ArrayList epBreakList = new ArrayList(); + epBreakList.addAll(Arrays.asList(config.getString("protect.blacklist.break", "").split(","))); + return epBreakList; + } +} diff --git a/Essentials/src/com/earth2me/essentials/Spawn.java b/Essentials/src/com/earth2me/essentials/Spawn.java new file mode 100644 index 000000000..f3c4de06a --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/Spawn.java @@ -0,0 +1,87 @@ +package com.earth2me.essentials; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Logger; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.World.Environment; + +public class Spawn implements IConf { + + private static final Logger logger = Logger.getLogger("Minecraft"); + private EssentialsConf config; + private Server server; + + public Spawn(Server server, File dataFolder) { + File configFile = new File(dataFolder, "spawn.yml"); + this.server = server; + config = new EssentialsConf(configFile); + config.load(); + } + + public void setSpawn(Location loc, String group) { + Map map = new HashMap(); + map.put("world", loc.getWorld().getName()); + map.put("x", loc.getX()); + map.put("y", loc.getY()); + map.put("z", loc.getZ()); + map.put("yaw", loc.getYaw()); + map.put("pitch", loc.getPitch()); + config.setProperty(group, map); + config.save(); + + if ("default".equals(group)) { + loc.getWorld().setSpawnLocation(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); + } + } + + public Location getSpawn(String group) { + if (config.getProperty(group) == null) { + group = "default"; + } + if (config.getProperty(group) == null) { + for (World w : server.getWorlds()) { + if (w.getEnvironment() != Environment.NORMAL) { + continue; + } + return w.getSpawnLocation(); + } + } + String worldId = config.getString(group + ".world", ""); + World world = server.getWorlds().get(server.getWorlds().size() > 1 ? 1 : 0); + for (World w : server.getWorlds()) { + if (w.getEnvironment() != Environment.NORMAL) { + continue; + } + world = w; + break; + } + for (World w : server.getWorlds()) { + if (!w.getName().equals(worldId)) { + continue; + } + world = w; + break; + } + + double x = config.getDouble(group + ".x", config.getDouble("default.x", 0)); + double y = config.getDouble(group + ".y", config.getDouble("default.y", 0)); + double z = config.getDouble(group + ".z", config.getDouble("default.z", 0)); + float yaw = (float) config.getDouble(group + ".yaw", config.getDouble("default.yaw", 0)); + float pitch = (float) config.getDouble(group + ".pitch", config.getDouble("default.pitch", 0)); + Location retval = new Location(world, x, y, z, yaw, pitch); + + if (y < 1) { + retval.setY(world.getHighestBlockYAt(retval)); + } + + return retval; + } + + public void reloadConfig() { + config.load(); + } +} diff --git a/Essentials/src/com/earth2me/essentials/TargetBlock.java b/Essentials/src/com/earth2me/essentials/TargetBlock.java new file mode 100644 index 000000000..d3ac30d2d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/TargetBlock.java @@ -0,0 +1,599 @@ +package com.earth2me.essentials; + +import java.util.ArrayList; +import org.bukkit.block.Block; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; +/** + * @author toi + * Thanks to Raphfrk for optimization of this class. + */ +public class TargetBlock { + + private Location loc; + private double viewHeight; + private int maxDistance; + private int[] blockToIgnore; + private double checkDistance, curDistance; + private double xRotation, yRotation; + private Vector targetPos = new Vector(); + private Vector targetPosDouble = new Vector(); + private Vector prevPos = new Vector(); + private Vector offset = new Vector(); + + /** + * Constructor requiring a player, uses default values + * + * @param player Player to work with + */ + public TargetBlock(Player player) + { + this.setValues(player.getLocation(), 300, 1.65, 0.2, null); + } + + /** + * Constructor requiring a location, uses default values + * + * @param loc Location to work with + */ + public TargetBlock(Location loc) + { + this.setValues(loc, 300, 0, 0.2, null); + } + + /** + * Constructor requiring a player, max distance and a checking distance + * + * @param player Player to work with + * @param maxDistance How far it checks for blocks + * @param checkDistance How often to check for blocks, the smaller the more precise + */ + public TargetBlock(Player player, int maxDistance, double checkDistance) + { + this.setValues(player.getLocation(), maxDistance, 1.65, checkDistance, null); + } + + /** + * Constructor requiring a location, max distance and a checking distance + * + * @param loc What location to work with + * @param maxDistance How far it checks for blocks + * @param checkDistance How often to check for blocks, the smaller the more precise + */ + public TargetBlock(Location loc, int maxDistance, double checkDistance) { + this.setValues(loc, maxDistance, 0, checkDistance, null); + } + + /** + * Constructor requiring a player, max distance, checking distance and an array of blocks to ignore + * + * @param player What player to work with + * @param maxDistance How far it checks for blocks + * @param checkDistance How often to check for blocks, the smaller the more precise + * @param blocksToIgnore Integer array of what block ids to ignore while checking for viable targets + */ + public TargetBlock (Player player, int maxDistance, double checkDistance, int[] blocksToIgnore) + { + this.setValues(player.getLocation(), maxDistance, 1.65, checkDistance, blocksToIgnore); + } + + /** + * Constructor requiring a location, max distance, checking distance and an array of blocks to ignore + * + * @param loc What location to work with + * @param maxDistance How far it checks for blocks + * @param checkDistance How often to check for blocks, the smaller the more precise + * @param blocksToIgnore Array of what block ids to ignore while checking for viable targets + */ + public TargetBlock (Location loc, int maxDistance, double checkDistance, int[] blocksToIgnore) + { + this.setValues(loc, maxDistance, 0, checkDistance, blocksToIgnore); + } + + /** + * Constructor requiring a player, max distance, checking distance and an array of blocks to ignore + * + * @param player What player to work with + * @param maxDistance How far it checks for blocks + * @param checkDistance How often to check for blocks, the smaller the more precise + * @param blocksToIgnore String ArrayList of what block ids to ignore while checking for viable targets + */ + public TargetBlock (Player player, int maxDistance, double checkDistance, ArrayList blocksToIgnore) + { + int[] bti = this.convertStringArraytoIntArray(blocksToIgnore); + this.setValues(player.getLocation(), maxDistance, 1.65, checkDistance, bti); + } + + /** + * Constructor requiring a location, max distance, checking distance and an array of blocks to ignore + * + * @param loc What location to work with + * @param maxDistance How far it checks for blocks + * @param checkDistance How often to check for blocks, the smaller the more precise + * @param blocksToIgnore String ArrayList of what block ids to ignore while checking for viable targets + */ + public TargetBlock (Location loc, int maxDistance, double checkDistance, ArrayList blocksToIgnore) + { + int[] bti = this.convertStringArraytoIntArray(blocksToIgnore); + this.setValues(loc, maxDistance, 0, checkDistance, bti); + } + + /** + * Set the values, all constructors uses this function + * + * @param loc Location of the view + * @param maxDistance How far it checks for blocks + * @param viewPos Where the view is positioned in y-axis + * @param checkDistance How often to check for blocks, the smaller the more precise + * @param blocksToIgnore Ids of blocks to ignore while checking for viable targets + */ + private void setValues(Location loc, int maxDistance, double viewHeight, double checkDistance, int[] blocksToIgnore) + { + this.loc = loc; + this.maxDistance = maxDistance; + this.viewHeight = viewHeight; + this.checkDistance = checkDistance; + this.blockToIgnore = blocksToIgnore; + this.curDistance = 0; + xRotation = (loc.getYaw() + 90) % 360; + yRotation = loc.getPitch() * -1; + + double h = (checkDistance * Math.cos(Math.toRadians(yRotation))); + offset.setY((checkDistance * Math.sin(Math.toRadians(yRotation)))); + offset.setX((h * Math.cos(Math.toRadians(xRotation)))); + offset.setZ((h * Math.sin(Math.toRadians(xRotation)))); + + targetPosDouble = new Vector(loc.getX(), loc.getY() + viewHeight, loc.getZ()); + targetPos = new Vector( targetPosDouble.getBlockX(), targetPosDouble.getBlockY(), targetPosDouble.getBlockZ()); + prevPos = targetPos.clone(); + } + + /** + * Call this to reset checking position to allow you to check for a new target with the same TargetBlock instance. + */ + public void reset() + { + targetPosDouble = new Vector(loc.getX(), loc.getY() + viewHeight, loc.getZ()); + targetPos = new Vector( targetPosDouble.getBlockX(), targetPosDouble.getBlockY(), targetPosDouble.getBlockZ()); + prevPos = targetPos.clone(); + this.curDistance = 0; + } + + /** + * Gets the distance to a block. Measures from the block underneath the player to the targetblock + * Should only be used when passing player as an constructor parameter + * + * @return double + */ + public double getDistanceToBlock() + { + Vector blockUnderPlayer = new Vector( + (int) Math.floor(loc.getX() + 0.5), + (int) Math.floor(loc.getY() - 0.5), + (int) Math.floor(loc.getZ() + 0.5)); + + Block blk = getTargetBlock(); + double x = blk.getX() - blockUnderPlayer.getBlockX(); + double y = blk.getY() - blockUnderPlayer.getBlockY(); + double z = blk.getZ() - blockUnderPlayer.getBlockZ(); + + return Math.sqrt((Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2))); + } + + /** + * Gets the rounded distance to a block. Measures from the block underneath the player to the targetblock + * Should only be used when passing player as an constructor parameter + * + * @return int + */ + public int getDistanceToBlockRounded() + { + Vector blockUnderPlayer = new Vector( + (int) Math.floor(loc.getX() + 0.5), + (int) Math.floor(loc.getY() - 0.5), + (int) Math.floor(loc.getZ() + 0.5)); + + Block blk = getTargetBlock(); + double x = blk.getX() - blockUnderPlayer.getBlockX(); + double y = blk.getY() - blockUnderPlayer.getBlockY(); + double z = blk.getZ() - blockUnderPlayer.getBlockZ(); + + return (int) Math.round((Math.sqrt((Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2))))); + } + + /** + * Gets the floored x distance to a block. + * + * @return int + */ + public int getXDistanceToBlock() + { + this.reset(); + return (int) Math.floor(getTargetBlock().getX() - loc.getBlockX() + 0.5); + } + + /** + * Gets the floored y distance to a block + * + * @return int + */ + public int getYDistanceToBlock() + { + this.reset(); + return (int) Math.floor(getTargetBlock().getY() - loc.getBlockY() + viewHeight); + } + + /** + * Gets the floored z distance to a block + * + * @return int + */ + public int getZDistanceToBlock() + { + this.reset(); + return (int) Math.floor(getTargetBlock().getZ() - loc.getBlockZ() + 0.5); + } + + /** + * Returns the block at the sight. Returns null if out of range or if no viable target was found + * + * @return Block + */ + @SuppressWarnings("empty-statement") + public Block getTargetBlock() + { + this.reset(); + while ((getNextBlock() != null) && ((getCurrentBlock().getTypeId() == 0) || this.blockToIgnoreHasValue(getCurrentBlock().getTypeId()))); + return getCurrentBlock(); + } + + /** + * Sets the type of the block at the sight. Returns false if the block wasn't set. + * + * @param typeID ID of type to set the block to + * @return boolean + */ + @SuppressWarnings("empty-statement") + public boolean setTargetBlock(int typeID) + { + if (Material.getMaterial(typeID) != null) + { + this.reset(); + while (getNextBlock() != null && getCurrentBlock().getTypeId() == 0); + if (getCurrentBlock() != null) + { + Block blk = loc.getWorld().getBlockAt(targetPos.getBlockX(), targetPos.getBlockY(), targetPos.getBlockZ()); + blk.setTypeId(typeID); + return true; + } + } + return false; + } + + /** + * Sets the type of the block at the sight. Returns false if the block wasn't set. + * + * @param type Material to set the block to + * @return boolean + */ + @SuppressWarnings("empty-statement") + public boolean setTargetBlock(Material type) + { + this.reset(); + while ((getNextBlock() != null) && ((getCurrentBlock().getTypeId() == 0) || this.blockToIgnoreHasValue(getCurrentBlock().getTypeId()))); + if (getCurrentBlock() != null) + { + Block blk = loc.getWorld().getBlockAt(targetPos.getBlockX(), targetPos.getBlockY(), targetPos.getBlockZ()); + blk.setType(type); + return true; + } + return false; + } + + /** + * Sets the type of the block at the sight. Returns false if the block wasn't set. + * Observe! At the moment this function is using the built-in enumerator function .valueOf(String) but would preferably be changed to smarter function, when implemented + * + * @param type Name of type to set the block to + * @return boolean + */ + @SuppressWarnings("empty-statement") + public boolean setTargetBlock(String type) + { + Material mat = Material.valueOf(type); + if (mat != null) + { + this.reset(); + while ((getNextBlock() != null) && ((getCurrentBlock().getTypeId() == 0) || this.blockToIgnoreHasValue(getCurrentBlock().getTypeId()))); + if (getCurrentBlock() != null) + { + Block blk = loc.getWorld().getBlockAt(targetPos.getBlockX(), targetPos.getBlockY(), targetPos.getBlockZ()); + blk.setType(mat); + return true; + } + } + return false; + } + + /** + * Returns the block attached to the face at the sight. Returns null if out of range or if no viable target was found + * + * @return Block + */ + @SuppressWarnings("empty-statement") + public Block getFaceBlock() + { + while ((getNextBlock() != null) && ((getCurrentBlock().getTypeId() == 0) || this.blockToIgnoreHasValue(getCurrentBlock().getTypeId()))); + if (getCurrentBlock() != null) + { + return getPreviousBlock(); + } + else + { + return null; + } + } + + /** + * Sets the type of the block attached to the face at the sight. Returns false if the block wasn't set. + * + * @param typeID + * @return boolean + */ + public boolean setFaceBlock(int typeID) + { + if (Material.getMaterial(typeID) != null) + { + if (getCurrentBlock() != null) + { + Block blk = loc.getWorld().getBlockAt(prevPos.getBlockX(), prevPos.getBlockY(), prevPos.getBlockZ()); + blk.setTypeId(typeID); + return true; + } + } + return false; + } + + /** + * Sets the type of the block attached to the face at the sight. Returns false if the block wasn't set. + * + * @param type + * @return boolean + */ + public boolean setFaceBlock(Material type) + { + if (getCurrentBlock() != null) + { + Block blk = loc.getWorld().getBlockAt(prevPos.getBlockX(), prevPos.getBlockY(), prevPos.getBlockZ()); + blk.setType(type); + return true; + } + return false; + } + + /** + * Sets the type of the block attached to the face at the sight. Returns false if the block wasn't set. + * Observe! At the moment this function is using the built-in enumerator function .valueOf(String) but would preferably be changed to smarter function, when implemented + * + * @param type + * @return boolean + */ + public boolean setFaceBlock(String type) + { + Material mat = Material.valueOf(type); + if (mat != null) + { + if (getCurrentBlock() != null) + { + Block blk = loc.getWorld().getBlockAt(prevPos.getBlockX(), prevPos.getBlockY(), prevPos.getBlockZ()); + blk.setType(mat); + return true; + } + } + return false; + } + + /** + * Get next block + * + * @return Block + */ + public Block getNextBlock() + { + prevPos = targetPos.clone(); + do + { + curDistance += checkDistance; + + targetPosDouble.setX(offset.getX() + targetPosDouble.getX()); + targetPosDouble.setY(offset.getY() + targetPosDouble.getY()); + targetPosDouble.setZ(offset.getZ() + targetPosDouble.getZ()); + targetPos = new Vector( targetPosDouble.getBlockX(), targetPosDouble.getBlockY(), targetPosDouble.getBlockZ()); + } + while (curDistance <= maxDistance && targetPos.getBlockX() == prevPos.getBlockX() && targetPos.getBlockY() == prevPos.getBlockY() && targetPos.getBlockZ() == prevPos.getBlockZ()); + if (curDistance > maxDistance) + { + return null; + } + + return this.loc.getWorld().getBlockAt(this.targetPos.getBlockX(), this.targetPos.getBlockY(), this.targetPos.getBlockZ()); + } + + /** + * Returns the current block along the line of vision + * + * @return Block + */ + public Block getCurrentBlock() + { + if (curDistance > maxDistance) + { + return null; + } + else + { + return this.loc.getWorld().getBlockAt(this.targetPos.getBlockX(), this.targetPos.getBlockY(), this.targetPos.getBlockZ()); + } + } + + /** + * Sets current block type. Returns false if the block wasn't set. + * + * @param typeID + */ + public boolean setCurrentBlock(int typeID) + { + if (Material.getMaterial(typeID) != null) + { + Block blk = getCurrentBlock(); + if (blk != null) + { + blk.setTypeId(typeID); + return true; + } + } + return false; + } + + /** + * Sets current block type. Returns false if the block wasn't set. + * + * @param type + */ + public boolean setCurrentBlock(Material type) + { + Block blk = getCurrentBlock(); + if (blk != null) + { + blk.setType(type); + return true; + } + return false; + } + + /** + * Sets current block type. Returns false if the block wasn't set. + * Observe! At the moment this function is using the built-in enumerator function .valueOf(String) but would preferably be changed to smarter function, when implemented + * + * @param type + */ + public boolean setCurrentBlock(String type) + { + Material mat = Material.valueOf(type); + if (mat != null) + { + Block blk = getCurrentBlock(); + if (blk != null) + { + blk.setType(mat); + return true; + } + } + return false; + } + + /** + * Returns the previous block in the aimed path + * + * @return Block + */ + public Block getPreviousBlock() + { + return this.loc.getWorld().getBlockAt(prevPos.getBlockX(), prevPos.getBlockY(), prevPos.getBlockZ()); + } + + /** + * Sets previous block type id. Returns false if the block wasn't set. + * + * @param typeID + */ + public boolean setPreviousBlock(int typeID) + { + if (Material.getMaterial(typeID) != null) + { + Block blk = getPreviousBlock(); + if (blk != null) + { + blk.setTypeId(typeID); + return true; + } + } + return false; + } + + /** + * Sets previous block type id. Returns false if the block wasn't set. + * + * @param type + */ + public boolean setPreviousBlock(Material type) + { + Block blk = getPreviousBlock(); + if (blk != null) + { + blk.setType(type); + return true; + } + return false; + } + + /** + * Sets previous block type id. Returns false if the block wasn't set. + * Observe! At the moment this function is using the built-in enumerator function .valueOf(String) but would preferably be changed to smarter function, when implemented + * + * @param type + */ + public boolean setPreviousBlock(String type) + { + Material mat = Material.valueOf(type); + if (mat != null) + { + Block blk = getPreviousBlock(); + if (blk != null) + { + blk.setType(mat); + return true; + } + } + return false; + } + + private int[] convertStringArraytoIntArray(ArrayList array) + { + if (array != null) + { + int intarray[] = new int[array.size()]; + for (int i = 0; i < array.size(); i++) + { + try + { + intarray[i] = Integer.parseInt(array.get(i)); + } + catch (NumberFormatException nfe) + { + intarray[i] = 0; + } + } + return intarray; + } + return null; + } + + private boolean blockToIgnoreHasValue(int value) + { + if (this.blockToIgnore != null) + { + if (this.blockToIgnore.length > 0) + { + for (int i : this.blockToIgnore) + { + if (i == value) + return true; + } + } + } + return false; + } +} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/TeleportTimer.java b/Essentials/src/com/earth2me/essentials/TeleportTimer.java new file mode 100644 index 000000000..11d65170f --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/TeleportTimer.java @@ -0,0 +1,73 @@ +package com.earth2me.essentials; + +import java.util.TimerTask; +import java.util.Calendar; + + +public abstract class TeleportTimer implements Runnable +{ + private long started; // time this task was initiated + private long delay; // how long to delay the teleport + public User user; // the person doing the teleport + private int health; + // note that I initially stored a clone of the location for reference, but... + // when comparing locations, I got incorrect mismatches (rounding errors, looked like) + // so, the X/Y/Z values are stored instead and rounded off + private long initX; + private long initY; + private long initZ; + + public TeleportTimer(User tUser, long tDelay) + { + this.started = Calendar.getInstance().getTimeInMillis(); + this.delay = tDelay; + this.user = tUser; + this.health = user.getHealth(); + this.initX = Math.round(user.getLocation().getX() * 10000); + this.initY = Math.round(user.getLocation().getY() * 10000); + this.initZ = Math.round(user.getLocation().getZ() * 10000); + } + + // This function needs to be defined when creating a new TeleportTimer + // The actual teleport command by itself should be stuck in there, such as teleportToNow(loc) + public abstract void DoTeleport(); + + public abstract void DoCancel(); + + public void run() + { + if (user == null || !user.isOnline() || user.getLocation() == null) + { + DoCancel(); + return; + } + if (Math.round(user.getLocation().getX() * 10000) != initX + || Math.round(user.getLocation().getY() * 10000) != initY + || Math.round(user.getLocation().getZ() * 10000) != initZ + || user.getHealth() < health) + { // user moved, cancel teleport + user.cancelTeleport(true); + return; + } + + health = user.getHealth(); // in case user healed, then later gets injured + + long now = Calendar.getInstance().getTimeInMillis(); + if (now > started + delay) + { + try + { + user.teleportCooldown(false); + user.sendMessage("§7Teleportation commencing..."); + this.DoTeleport(); + return; + } + catch (Exception ex) + { + user.sendMessage("§cCooldown: " + ex.getMessage()); + } + } + //else // uncomment for timing debug + // user.sendMessage("§7" + (started + delay - now)); + } +} diff --git a/Essentials/src/com/earth2me/essentials/User.java b/Essentials/src/com/earth2me/essentials/User.java new file mode 100644 index 000000000..472015997 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/User.java @@ -0,0 +1,695 @@ +package com.earth2me.essentials; + +import java.util.*; +import java.util.logging.*; +import java.io.*; +import org.bukkit.*; +import com.earth2me.essentials.commands.IEssentialsCommand; +import net.minecraft.server.EntityHuman; +import org.bukkit.craftbukkit.inventory.CraftItemStack; +import org.bukkit.entity.*; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.reader.UnicodeReader; + + +public class User extends PlayerExtension implements Comparable +{ + private static final Logger logger = Logger.getLogger("Minecraft"); + private final Yaml yaml = new Yaml(new SafeConstructor()); + private boolean isLoaded = false; + private final File folder; + private Map data = new HashMap(); + private static Map users = new HashMap(); + private boolean teleEnabled = true; + private long lastTeleport = 0; + private long lastHeal = 0; + private boolean justPortaled = false; + //private TimerTask teleTimer = null; + private int teleTimer = -1; + public Location lastLocation = null; + private User replyTo = null; + private boolean isNew = false; + public String currentJail; + public CraftItemStack[] savedInventory; + + private User(Player base) + { + super(base); + this.folder = new File((Essentials.getStatic() == null ? new File(".") : Essentials.getStatic().getDataFolder()), "userdata"); + + if (base instanceof EntityHuman) + { + this.lastLocation = getBase().getLocation(); + } + load(); + } + + public static int size() + { + return users.size(); + } + + public static User get(T base) + { + if (base instanceof Player) + return get((Player)base); + return null; + } + + public static User get(T base) + { + if (base == null) + return null; + + if (base instanceof User) + return (User)base; + + if (users.containsKey(base.getName())) + return users.get(base.getName()).update(base); + + User u = new User(base); + users.put(u.getName(), u); + return u; + } + + public static void charge(T base, IEssentialsCommand cmd) throws Exception + { + if (base instanceof Player) + User.get(base).charge(cmd); + } + + public boolean isNew() + { + return isNew; + } + + public void respawn(Spawn spawn) throws Exception + { + respawn(spawn, null); + } + + public void respawn(Spawn spawn, final String chargeFor) throws Exception + { + teleport(getSafeDestination(spawn.getSpawn(getGroup())), chargeFor); + } + + private User update(Player base) + { + setBase(base); + return this; + } + + public boolean isAuthorized(IEssentialsCommand cmd) + { + return isAuthorized("essentials." + (cmd.getName().equals("r") ? "msg" : cmd.getName())); + } + + public boolean isAuthorized(String node) + { + if (isOp()) + return true; + + if (isJailed()) + return false; + + try + { + return com.nijikokun.bukkit.Permissions.Permissions.Security.permission(base, node); + } + catch (Throwable ex) + { + String[] cmds = node.split("\\.", 2); + return !Essentials.getSettings().isCommandRestricted(cmds[cmds.length - 1]); + } + } + + public boolean isTeleEnabled() + { + return teleEnabled; + } + + public boolean toggleTeleEnabled() + { + return teleEnabled = !teleEnabled; + } + + public void teleportCooldown(boolean justCheck) throws Exception + { + long now = Calendar.getInstance().getTimeInMillis(); + long cooldown = Essentials.getSettings().getTeleportCooldown(); + long left = lastTeleport + cooldown - now; + if (left > 0 && !isOp() && !isAuthorized("essentials.teleport.cooldown.bypass")) + throw new Exception("Time before next teleport: " + Essentials.FormatTime(left)); + // if justCheck is set, don't update lastTeleport; we're just checking + if (!justCheck) lastTeleport = now; + } + + public void teleportCooldown() throws Exception + { + teleportCooldown(true); + } + + public void healCooldown() throws Exception + { + long now = Calendar.getInstance().getTimeInMillis(); + long cooldown = Essentials.getSettings().getHealCooldown(); + long left = lastHeal + cooldown - now; + if (left > 0 && !isOp() && !isAuthorized("essentials.heal.cooldown.bypass")) + throw new Exception("Time before next heal: " + Essentials.FormatTime(left)); + lastHeal = now; + } + + private void load() + { + if (isLoaded) return; + isLoaded = true; + + data = Essentials.getData(this); + + try + { + if (!folder.exists()) folder.mkdirs(); + File file = new File(folder, getName() + ".yml"); + if (!file.exists()) + { + isNew = true; + file.createNewFile(); + logger.info(getName() + " has logged in for the first time."); + } + + FileInputStream rx = new FileInputStream(file); + Map userData = (Map)yaml.load(new UnicodeReader(rx)); + if (userData != null) data.putAll(userData); + rx.close(); + } + catch (Throwable ex) + { + logger.log(Level.SEVERE, null, ex); + } + finally + { + if (data == null) data = new HashMap(); + } + } + + private void flush() + { + try + { + if (!folder.exists()) folder.mkdirs(); + File file = new File(folder, getName() + ".yml"); + if (!file.exists()) file.createNewFile(); + + FileWriter tx = new FileWriter(file); + tx.write(yaml.dump(data)); + tx.flush(); + tx.close(); + } + catch (Throwable ex) + { + logger.log(Level.SEVERE, null, ex); + } + } + + public boolean isGodModeEnabled() + { + load(); + return data.containsKey("godmode") && (Boolean)data.get("godmode"); + } + + public boolean toggleGodMode() + { + boolean retval = !isGodModeEnabled(); + data.put("godmode", retval); + flush(); + return retval; + } + + public boolean isMuted() + { + load(); + return data.containsKey("muted") && (Boolean)data.get("muted"); + } + + public boolean toggleMuted() + { + boolean retval = !isMuted(); + data.put("muted", retval); + flush(); + return retval; + } + + public boolean isJailed() + { + //load(); Do not load config everytime time! + return data.containsKey("jailed") && (Boolean)data.get("jailed"); + } + + public boolean toggleJailed() + { + boolean retval = !isJailed(); + data.put("jailed", retval); + flush(); + load(); + return retval; + } + + public double getMoney() + { + load(); + if (data.containsKey("money")) + { + if (data.get("money") instanceof Integer) + return (double)((Integer)data.get("money")); + return (Double)data.get("money"); + } + + try + { + return com.nijiko.coelho.iConomy.iConomy.getBank().getAccount(getName()).getBalance(); + } + catch (Throwable ex) + { + try + { + Map idata = Essentials.getData(this); + return (Integer)idata.get("money"); + } + catch (Throwable ex2) + { + return Essentials.getSettings().getStartingBalance(); + } + } + } + + public void setMoney(double value) + { + try + { + com.nijiko.coelho.iConomy.iConomy.getBank().getAccount(getName()).setBalance(value); + } + catch (Throwable ex) + { + data.put("money", value); + flush(); + } + } + + public void giveMoney(double value) + { + if (value == 0) return; + setMoney(getMoney() + value); + sendMessage("§a$" + value + " has been added to your account."); + } + + public void payUser(User reciever, int value) throws Exception + { + if (value == 0) return; + if (!canAfford(value)) + { + throw new Exception("You do not have sufficient funds."); + } + else + { + setMoney(getMoney() - value); + reciever.setMoney(reciever.getMoney() + value); + sendMessage("§a$" + value + " has been sent to " + reciever.getDisplayName()); + reciever.sendMessage("§a$" + value + " has been recieved from " + getDisplayName()); + } + } + + public void takeMoney(double value) + { + if (value == 0) return; + setMoney(getMoney() - value); + sendMessage("§c$" + value + " has been taken from your account."); + } + + public void charge(String cmd) throws Exception + { + double mon = getMoney(); + double cost = Essentials.getSettings().getCommandCost(cmd.startsWith("/") ? cmd.substring(1) : cmd); + if (mon < cost && !isOp()) + throw new Exception("You do not have sufficient funds."); + takeMoney(cost); + } + + public void canAfford(String cmd) throws Exception + { + double mon = getMoney(); + double cost = Essentials.getSettings().getCommandCost(cmd.startsWith("/") ? cmd.substring(1) : cmd); + if (mon < cost && !isOp()) + throw new Exception("You do not have sufficient funds."); + } + + public boolean canAfford(double cost) + { + double mon = getMoney(); + if (mon < cost && !isOp()) + { + return false; + } + else + { + return true; + } + } + + public void canAfford(IEssentialsCommand cmd) throws Exception + { + canAfford(cmd.getName()); + } + + public void cancelTeleport(boolean notifyUser) + { + if (teleTimer == -1) return; + try + { + getServer().getScheduler().cancelTask(teleTimer); + if (notifyUser) sendMessage("§cPending teleportation request cancelled."); + } + catch (Throwable ex) + { + } + finally + { + teleTimer = -1; + } + } + + public void cancelTeleport() + { + cancelTeleport(false); + } + + public boolean teleport(final Location loc, final String chargeFor) + { + final long delay = Essentials.getSettings().getTeleportDelay(); + + if (delay <= 0 || isOp() || isAuthorized("essentials.teleport.timer.bypass")) + { + try + { + if (chargeFor != null) charge(chargeFor); + teleportCooldown(false); + return teleportToNow(loc); + } + catch (Throwable ex) + { + sendMessage("§cError: " + ex.getMessage()); + return false; + } + } + + cancelTeleport(); + sendMessage("§7Teleportation will commence in " + Essentials.FormatTime(delay) + ". Don't move."); + teleTimer = getServer().getScheduler().scheduleSyncRepeatingTask(Essentials.getStatic(), new TeleportTimer(this, delay) + { + public void DoTeleport() + { + try + { + if (chargeFor != null) charge(chargeFor); + teleportToNow(loc); + } + catch (Throwable ex) + { + sendMessage("§cError: " + ex.getMessage()); + } + } + + public void DoCancel() + { + cancelTeleport(); + } + }, 10, 10); + return true; + } + + @Override + public boolean teleport(final Location loc) + { + return teleport(loc, null); + } + + public boolean teleport(final Entity entity, final String chargeFor) + { + final long delay = Essentials.getSettings().getTeleportDelay(); + + if (delay <= 0 || isOp() || isAuthorized("essentials.teleport.timer.bypass")) + { + try + { + if (chargeFor != null) charge(chargeFor); + teleportCooldown(false); + return teleportToNow(entity); + } + catch (Throwable ex) + { + sendMessage("§cError: " + ex.getMessage()); + return false; + } + } + + cancelTeleport(); + sendMessage("§7Teleportation will commence in " + Essentials.FormatTime(delay) + ". Don't move."); + teleTimer = getServer().getScheduler().scheduleSyncRepeatingTask(Essentials.getStatic(), new TeleportTimer(this, delay) + { + public void DoTeleport() + { + try + { + if (chargeFor != null) charge(chargeFor); + teleportToNow(entity); + } + catch (Throwable ex) + { + sendMessage("§cError: " + ex.getMessage()); + } + } + + public void DoCancel() + { + cancelTeleport(); + } + }, 10, 10); + return true; + } + + @Override + public boolean teleport(final Entity entity) + { + return teleport(entity, null); + } + + public Location getHome() throws Exception + { + if (data.containsKey("home")) + { + List vals = (List)data.get("home"); + World world = getServer() == null ? null : getServer().getWorlds().get(0); + if (vals.size() > 5 && getServer() != null) + getServer().getWorld((String)vals.get(5)); + return new Location( + world, + (Double)vals.get(0), + (Double)vals.get(1), + (Double)vals.get(2), + ((Double)vals.get(3)).floatValue(), + ((Double)vals.get(4)).floatValue()); + } + + try + { + Map gdata = Essentials.getData(this); + List vals = (List)gdata.get("home"); + World world = getServer().getWorlds().get(0); + if (vals.size() > 5) + getServer().getWorld((String)vals.get(5)); + return new Location(world, + (Double)vals.get(0), + (Double)vals.get(1), + (Double)vals.get(2), + ((Double)vals.get(3)).floatValue(), + ((Double)vals.get(4)).floatValue()); + } + catch (Throwable ex) + { + throw new Exception("You have not set a home."); + } + } + + public void teleportToHome(final String chargeFor) + { + final long delay = Essentials.getSettings().getTeleportDelay(); + + Location loc = null; + try + { + // check this first in case user hasn't set a home yet + loc = getHome(); + } + catch (Throwable ex) + { + sendMessage("§cTeleport: " + ex.getMessage()); + return; + } + + if (delay <= 0 || isOp() || isAuthorized("essentials.teleport.timer.bypass")) + { + try + { + if (chargeFor != null) charge(chargeFor); + teleportCooldown(false); + teleportToNow(loc); + sendMessage("§7Teleporting home..."); + } + catch (Throwable ex) + { + sendMessage("§cError: " + ex.getMessage()); + } + return; + } + + cancelTeleport(); + sendMessage("§7Teleportation will commence in " + Essentials.FormatTime(delay) + ". Don't move."); + teleTimer = getServer().getScheduler().scheduleSyncRepeatingTask(Essentials.getStatic(), new TeleportTimer(this, delay) + { + public void DoTeleport() + { + try + { + if (chargeFor != null) charge(chargeFor); + teleportToNow(getHome()); + } + catch (Throwable ex) + { + sendMessage("§cError: " + ex.getMessage()); + } + } + + public void DoCancel() + { + cancelTeleport(); + } + }, 10, 10); + } + + public void teleportToHome() + { + teleportToHome(null); + } + + public boolean teleportToNow(Location loc) throws Exception + { + cancelTeleport(); + lastLocation = getLocation(); + return getBase().teleport(getSafeDestination(loc)); + } + + public boolean teleportToNow(Entity entity) + { + cancelTeleport(); + lastLocation = getLocation(); + return getBase().teleport(entity); + } + + public void teleportBack(final String chargeFor) + { + teleport(lastLocation, chargeFor); + } + + public void teleportBack() + { + teleportBack(null); + } + + public void dispose() + { + this.base = new OfflinePlayer(getName()); + } + + public void charge(IEssentialsCommand cmd) throws Exception + { + charge(cmd.getName()); + } + + public boolean getJustPortaled() + { + return justPortaled; + } + + public void setJustPortaled(boolean value) + { + justPortaled = value; + } + + public void setReplyTo(User user) + { + replyTo = user; + } + + public User getReplyTo() + { + return replyTo; + } + + public void setHome() + { + setHome(getLocation()); + } + + public void setHome(Location home) + { + List vals = new ArrayList(6); + vals.add(new Double(home.getX())); + vals.add(new Double(home.getY())); + vals.add(new Double(home.getZ())); + vals.add(new Double(home.getYaw())); + vals.add(new Double(home.getPitch())); + vals.add(home.getWorld() == null ? "world" : home.getWorld().getName()); + data.put("home", vals); + flush(); + + setCompassTarget(home); + } + + public String getNick() + { + Essentials ess = Essentials.getStatic(); + String name = ess.getConfiguration().getBoolean("disable-nick", false) ? getName() : ess.readNickname(this); + if (isOp() && ess.getConfiguration().getString("ops-name-color", "c").matches("^[0-9a-f]$")) { + name = "§" + ess.getConfiguration().getString("ops-name-color", "c") + name + "§f"; + } + return name; + } + + public void warpTo(String warp, final String chargeFor) throws Exception + { + lastLocation = getLocation(); + Location loc = Essentials.getWarps().getWarp(warp); + teleport(loc, chargeFor); + sendMessage("§7Warping to " + warp + "."); + } + + public void warpTo(String string) throws Exception + { + warpTo(string, null); + } + + public void clearNewFlag() + { + isNew = false; + } + + public int compareTo(User t) { + return ChatColor.stripColor(this.getDisplayName()).compareToIgnoreCase(ChatColor.stripColor(t.getDisplayName())); + } + + public Boolean canSpawnItem(int itemId) + { + if(Essentials.getSettings().itemSpawnBlacklist().contains(itemId))return false; + return true; + } +} diff --git a/Essentials/src/com/earth2me/essentials/Warps.java b/Essentials/src/com/earth2me/essentials/Warps.java new file mode 100644 index 000000000..beaeddf29 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/Warps.java @@ -0,0 +1,244 @@ +package com.earth2me.essentials; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.World; + +public class Warps implements IConf { + + private static final Logger logger = Logger.getLogger("Minecraft"); + Map warpPoints = new HashMap(); + File warpsFolder; + Server server; + + public Warps(Server server, File dataFolder) { + this.server = server; + warpsFolder = new File(dataFolder, "warps"); + if (!warpsFolder.exists()) { + warpsFolder.mkdirs(); + } else { + convertWarps(dataFolder); + } + reloadConfig(); + } + + private String convertToFileName(String name) { + return name.toLowerCase().replaceAll("[^a-z0-9]", "_"); + } + + public boolean isEmpty() { + return warpPoints.isEmpty(); + } + + public Iterable getWarpNames() { + List keys = new ArrayList(); + for (StringIgnoreCase stringIgnoreCase : warpPoints.keySet()) { + keys.add(stringIgnoreCase.string); + } + Collections.sort(keys, String.CASE_INSENSITIVE_ORDER); + return keys; + } + + public Location getWarp(String warp) throws Exception { + EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp)); + if (conf == null) { + throw new Exception("That warp does not exist."); + } + double x = conf.getDouble("x", 0); + double y = conf.getDouble("y", 0); + double z = conf.getDouble("z", 0); + float yaw = (float) conf.getDouble("yaw", 0); + float pitch = (float) conf.getDouble("pitch", 0); + String world = conf.getString("world"); + World w = server.getWorld(world); + if (w == null) { + throw new Exception("World of warp does not exist."); + } + return new Location(w, x, y, z, yaw, pitch); + } + + public void setWarp(String name, Location loc) throws Exception { + setWarp(name, loc, null); + } + + private void setWarp(String name, Location loc, String worldName) throws Exception { + String filename = convertToFileName(name); + EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); + if (conf == null) { + File confFile = new File(warpsFolder, filename + ".yml"); + if (confFile.exists()) { + throw new Exception("A warp with a similar name already exists."); + } + conf = new EssentialsConf(confFile); + conf.setProperty("name", name); + warpPoints.put(new StringIgnoreCase(name), conf); + } + conf.setProperty("x", loc.getBlockX()); + conf.setProperty("y", loc.getBlockY()); + conf.setProperty("z", loc.getBlockZ()); + conf.setProperty("yaw", loc.getYaw()); + conf.setProperty("pitch", loc.getPitch()); + if (worldName != null) { + conf.setProperty("world", worldName); + } else { + conf.setProperty("world", loc.getWorld().getName()); + } + conf.save(); + } + + public void delWarp(String name) throws Exception { + EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); + if (conf == null) { + throw new Exception("Warp does not exist."); + } + if (!conf.getFile().delete()) { + throw new Exception("Problem deleting the warp file."); + } + warpPoints.remove(new StringIgnoreCase(name)); + } + + private void convertWarps(File dataFolder) { + File[] listOfFiles = warpsFolder.listFiles(); + if (listOfFiles.length >= 1) { + for (int i = 0; i < listOfFiles.length; i++) { + String filename = listOfFiles[i].getName(); + if (listOfFiles[i].isFile() && filename.endsWith(".dat")) { + try { + BufferedReader rx = new BufferedReader(new FileReader(listOfFiles[i])); + double x = Double.parseDouble(rx.readLine().trim()); + double y = Double.parseDouble(rx.readLine().trim()); + double z = Double.parseDouble(rx.readLine().trim()); + float yaw = Float.parseFloat(rx.readLine().trim()); + float pitch = Float.parseFloat(rx.readLine().trim()); + String worldName = rx.readLine(); + rx.close(); + World w = null; + for (World world : server.getWorlds()) { + if (world.getEnvironment() != World.Environment.NETHER) { + w = world; + break; + } + } + boolean forceWorldName = false; + if (worldName != null) { + worldName.trim(); + World w1 = null; + for (World world : server.getWorlds()) { + if (world.getName().equalsIgnoreCase(worldName)) { + w1 = world; + break; + } + } + if (w1 != null) { + w = w1; + } else { + File worldFolder = new File(dataFolder.getAbsoluteFile().getParentFile().getParentFile(), worldName); + if (worldFolder.exists() && worldFolder.isDirectory()) { + logger.log(Level.WARNING, "World " + worldName + " not loaded, but directory found. Converting warp anyway."); + forceWorldName = true; + } + } + } + Location loc = new Location(w, x, y, z, yaw, pitch); + setWarp(filename.substring(0, filename.length() - 4), loc, forceWorldName ? worldName : null); + if(!listOfFiles[i].renameTo(new File(warpsFolder, filename + ".old"))) + { + throw new Exception("Renaming file " + filename + " failed"); + } + } catch (Exception ex) { + logger.log(Level.SEVERE, null, ex); + } + } + } + + } + File warpFile = new File(dataFolder, "warps.txt"); + if (warpFile.exists()) { + try { + BufferedReader rx = new BufferedReader(new FileReader(warpFile)); + for (String[] parts = new String[0]; rx.ready(); parts = rx.readLine().split(":")) { + if (parts.length < 6) { + continue; + } + String name = parts[0]; + double x = Double.parseDouble(parts[1].trim()); + double y = Double.parseDouble(parts[2].trim()); + double z = Double.parseDouble(parts[3].trim()); + float yaw = Float.parseFloat(parts[4].trim()); + float pitch = Float.parseFloat(parts[5].trim()); + if (name.isEmpty()) { + continue; + } + World w = null; + for (World world : server.getWorlds()) { + if (world.getEnvironment() != World.Environment.NETHER) { + w = world; + break; + } + } + Location loc = new Location(w, x, y, z, yaw, pitch); + setWarp(name, loc); + if(!warpFile.renameTo(new File(dataFolder, "warps.txt.old"))); + { + throw new Exception("Renaming warps.txt failed"); + } + } + } catch (Exception ex) { + logger.log(Level.SEVERE, null, ex); + } + } + } + + public final void reloadConfig() { + warpPoints.clear(); + File[] listOfFiles = warpsFolder.listFiles(); + if (listOfFiles.length >= 1) { + for (int i = 0; i < listOfFiles.length; i++) { + String filename = listOfFiles[i].getName(); + if (listOfFiles[i].isFile() && filename.endsWith(".yml")) { + EssentialsConf conf = new EssentialsConf(listOfFiles[i]); + conf.load(); + String name = conf.getString("name"); + if (name != null) { + warpPoints.put(new StringIgnoreCase(name), conf); + } + } + } + } + } + + private class StringIgnoreCase { + + String string; + + public StringIgnoreCase(String string) { + this.string = string; + } + + @Override + public int hashCode() { + return string.toLowerCase().hashCode(); + } + + @Override + public boolean equals(Object o) { + if (o instanceof String) { + return string.equalsIgnoreCase((String) o); + } + if (o instanceof StringIgnoreCase) { + return string.equalsIgnoreCase(((StringIgnoreCase) o).string); + } + return false; + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandafk.java b/Essentials/src/com/earth2me/essentials/commands/Commandafk.java new file mode 100644 index 000000000..eb1ade4cd --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandafk.java @@ -0,0 +1,32 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandafk extends EssentialsCommand +{ + public Commandafk() + { + super("afk"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + + if (parent.away.contains(user)) + { + user.sendMessage("§7You are no longer marked as away."); + server.broadcastMessage("§7" + user.getDisplayName() + " is no longer AFK"); + parent.away.remove(user); + return; + } + + user.sendMessage("§7You are now marked as away."); + server.broadcastMessage("§7" + user.getDisplayName() + " is now AFK"); + parent.away.add(user); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandantioch.java b/Essentials/src/com/earth2me/essentials/commands/Commandantioch.java new file mode 100644 index 000000000..9e234ea15 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandantioch.java @@ -0,0 +1,39 @@ +package com.earth2me.essentials.commands; + +import net.minecraft.server.EntityTNTPrimed; +import net.minecraft.server.World; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.craftbukkit.CraftWorld; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.earth2me.essentials.TargetBlock; + + +public class Commandantioch extends EssentialsCommand +{ + public Commandantioch() + { + super("antioch"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (!user.isOp()) + { + user.sendMessage("§cNone shall pass."); + return; + } + + server.broadcastMessage("...lobbest thou thy Holy Hand Grenade of Antioch towards thy foe,"); + server.broadcastMessage("who being naughty in My sight, shall snuff it."); + + Location loc = user.getLocation(); + World world = ((CraftWorld)user.getWorld()).getHandle(); + loc = new TargetBlock(user).getTargetBlock().getLocation(); + EntityTNTPrimed tnt = new EntityTNTPrimed(world, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); + world.a(tnt); + world.a(tnt, "random.fuse", 1.0F, 1.0F); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandback.java b/Essentials/src/com/earth2me/essentials/commands/Commandback.java new file mode 100644 index 000000000..03ceba9b6 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandback.java @@ -0,0 +1,22 @@ +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.Server; + + +public class Commandback extends EssentialsCommand +{ + public Commandback() + { + super("back"); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.canAfford(this); + user.sendMessage("§7Returning to previous location."); + user.teleportBack(this.getName()); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java b/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java new file mode 100644 index 000000000..7682cd141 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java @@ -0,0 +1,43 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.Backup; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; + +/** + * + * @author schlex + */ +public class Commandbackup extends EssentialsCommand { + + public Commandbackup() { + super("backup"); + } + + @Override + protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception { + Backup backup = Essentials.getStatic().backup; + if (backup == null) return; + backup.run(); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { + Backup backup = Essentials.getStatic().backup; + if (backup == null) return; + user.charge(this); + backup.run(); + user.sendMessage("Backup started"); + } + + + + +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java b/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java new file mode 100644 index 000000000..6789af570 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java @@ -0,0 +1,23 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.earth2me.essentials.commands.EssentialsCommand; + + +public class Commandbalance extends EssentialsCommand +{ + public Commandbalance() + { + super("balance"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.sendMessage("§7Balance: $" + (args.length < 1 || !user.isAuthorized("essentials.balance.other") + ? user + : getPlayer(server, args, 0)).getMoney()); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandban.java b/Essentials/src/com/earth2me/essentials/commands/Commandban.java new file mode 100644 index 000000000..c341d4645 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandban.java @@ -0,0 +1,42 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import org.bukkit.craftbukkit.CraftServer; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandban extends EssentialsCommand +{ + public Commandban() + { + super("ban"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("§cUsage: /" + commandLabel + " [player] "); + return; + } + + + User p = null; + if (server.matchPlayer(args[0]).isEmpty()) + { + ((CraftServer)server).getHandle().c.f.a(args[0]); + sender.sendMessage("§cPlayer" + args[0] + " banned"); + } + else + { + p = User.get(server.matchPlayer(args[0]).get(0)); + p.kickPlayer(args.length > 1 ? getFinalArg(args, 1) : "Banned from server"); + ((CraftServer)server).getHandle().c.f.a(p.getName()); + sender.sendMessage("§cPlayer" + p.getName() + " banned"); + } + Essentials.getStatic().loadBanList(); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java b/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java new file mode 100644 index 000000000..080bfa663 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java @@ -0,0 +1,30 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import org.bukkit.craftbukkit.CraftServer; +import com.earth2me.essentials.Essentials; + + +public class Commandbanip extends EssentialsCommand +{ + public Commandbanip() + { + super("banip"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("Usage: /" + commandLabel + " [address]"); + return; + } + + ((CraftServer)server).getHandle().c.f.c(args[0]); + sender.sendMessage("§7Banned IP address."); + Essentials.getStatic().loadBanList(); + + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java b/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java new file mode 100644 index 000000000..a7546bb35 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java @@ -0,0 +1,56 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.TreeType; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.Location; + + +public class Commandbigtree extends EssentialsCommand +{ + public Commandbigtree() + { + super("bigtree"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + Object tree = new Object(); + if (args.length > 0 && args[0].equalsIgnoreCase("redwood")) + { + tree = TreeType.TALL_REDWOOD; + } + else if (args.length > 0 && args[0].equalsIgnoreCase("tree")) + { + tree = TreeType.BIG_TREE; + } + else + { + user.sendMessage("§cUsage: /" + commandLabel + " [tree|redwood]"); + return; + } + + double x = user.getLocation().getX(); + double y = user.getLocation().getY(); + double z = user.getLocation().getZ(); + + // offset tree in direction player is facing + int r = (int)user.getCorrectedYaw(); + if (r < 68 || r > 292) x -= 3.0D; // north + else if (r > 112 && r < 248) x += 3.0D; // south + if (r > 22 && r < 158) z -= 3.0D; // east + else if (r > 202 && r < 338) z += 3.0D; // west + + Location safeLocation = user.getSafeDestination(new Location(user.getWorld(), x, y, z)); + boolean success = user.getWorld().generateTree(safeLocation, (TreeType)tree); + if (success) + { + user.charge(this); + user.sendMessage("Big tree spawned."); + } + else + user.sendMessage("§cBig tree generation failure. Try again on grass or dirt."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java b/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java new file mode 100644 index 000000000..2069e61b9 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java @@ -0,0 +1,32 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandbroadcast extends EssentialsCommand +{ + public Commandbroadcast() + { + super("broadcast"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("Usage: /" + commandLabel + " [msg]"); + } + + StringBuilder message = new StringBuilder(); + for (int i = 0; i < args.length; i++) + { + message.append(args[i]); + message.append(' '); + } + + server.broadcastMessage("[§cBroadcast§f]§a " + message.toString()); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandburn.java b/Essentials/src/com/earth2me/essentials/commands/Commandburn.java new file mode 100644 index 000000000..0c190a0f2 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandburn.java @@ -0,0 +1,32 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.entity.Player; + +public class Commandburn extends EssentialsCommand +{ + + public Commandburn() + { + super("burn"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 2) + { + user.sendMessage("§cUsage: /burn [player] [seconds]"); + return; + } + + User.charge(user, this); + for (Player p : server.matchPlayer(args[0])) + { + p.setFireTicks(Integer.parseInt(args[1]) * 20); + user.sendMessage("§cYou set " + p.getDisplayName() + " on fire for " + Integer.parseInt(args[1]) + "seconds."); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java b/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java new file mode 100644 index 000000000..de5c11376 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java @@ -0,0 +1,99 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; +import java.util.List; +import org.bukkit.ChatColor; + + +public class Commandclearinventory extends EssentialsCommand +{ + public Commandclearinventory() + { + super("clearinventory"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length > 0 && user.isAuthorized("essentials.clearinventory.others")) + { + if (args[0].length() >= 3) + { + List online = server.matchPlayer(args[0]); + + if (!online.isEmpty()) + { + for (Player p : online) + { + p.getInventory().clear(); + user.sendMessage("§7Inventory of §c" + p.getDisplayName() + "§7 cleared."); + user.charge(this); + } + } + throw new Exception("Player not found"); + } + else + { + Player u = server.getPlayer(args[0]); + if (u != null) + { + u.getInventory().clear(); + user.sendMessage("§7Inventory of §c" + u.getDisplayName() + "§7 cleared."); + user.charge(this); + } + else + { + throw new Exception("Player not found"); + } + } + } + else + { + user.getInventory().clear(); + user.sendMessage("§7Inventory cleared."); + user.charge(this); + } + } + + @Override + protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage(ChatColor.RED + "Usage: " + commandLabel + " [player]"); + return; + } + + if (args[0].length() >= 3) + { + List online = server.matchPlayer(args[0]); + + if (!online.isEmpty()) + { + for (Player p : online) + { + p.getInventory().clear(); + sender.sendMessage("§7Inventory of §c" + p.getDisplayName() + "§7 cleared."); + } + } + throw new Exception("Player not found"); + } + else + { + Player u = server.getPlayer(args[0]); + if (u != null) + { + u.getInventory().clear(); + sender.sendMessage("§7Inventory of §c" + u.getDisplayName() + "§7 cleared."); + } + else + { + throw new Exception("Player not found"); + } + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java b/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java new file mode 100644 index 000000000..f891f0bab --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java @@ -0,0 +1,32 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandcompass extends EssentialsCommand +{ + public Commandcompass() + { + super("compass"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + int r = (int)user.getCorrectedYaw(); + String dir; + if (r < 23) dir = "N"; + else if (r < 68) dir = "NE"; + else if (r < 113) dir = "E"; + else if (r < 158) dir = "SE"; + else if (r < 203) dir = "S"; + else if (r < 248) dir = "SW"; + else if (r < 293) dir = "W"; + else if (r < 338) dir = "NW"; + else dir = "N"; + user.sendMessage("§7Bearing: " + dir + " (" + r + " degrees)"); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java b/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java new file mode 100644 index 000000000..620db000c --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java @@ -0,0 +1,33 @@ +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; + +public class Commanddeljail extends EssentialsCommand { + + public Commanddeljail() { + super("deljail"); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { + if (args.length < 1) + { + user.sendMessage("§cUsage: /" + commandLabel + " [jailname]"); + return; + } + user.charge(this); + Essentials.getJail().delJail(args[0]); + user.sendMessage("§7Jail " + args[0] + " has been removed"); + } + + @Override + protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception { + super.run(server, parent, sender, commandLabel, args); + } + + + +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java new file mode 100644 index 000000000..a9811fb8e --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java @@ -0,0 +1,41 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commanddelwarp extends EssentialsCommand +{ + public Commanddelwarp() + { + super("delwarp"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /" + commandLabel + " [warp name]"); + return; + } + user.charge(this); + Essentials.getWarps().delWarp(args[0]); + user.sendMessage("§7Warp removed."); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("§cUsage: /" + commandLabel + " [warp name]"); + return; + } + + Essentials.getWarps().delWarp(args[0]); + sender.sendMessage("§7Warp removed."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java b/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java new file mode 100644 index 000000000..d01594809 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java @@ -0,0 +1,24 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commanddepth extends EssentialsCommand +{ + public Commanddepth() + { + super("depth"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + int y = user.getLocation().getBlockY() - 63; + if (y > 0) user.sendMessage("§7You are " + y + " block(s) above sea level."); + else if (y < 0) user.sendMessage("§7You are " + (-y) + " block(s) below sea level."); + else user.sendMessage("§7You are at sea level."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandeco.java b/Essentials/src/com/earth2me/essentials/commands/Commandeco.java new file mode 100644 index 000000000..79a55f986 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandeco.java @@ -0,0 +1,82 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; + + +public class Commandeco extends EssentialsCommand +{ + public Commandeco() + { + super("eco"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + EcoCommands cmd; + int amount; + try + { + cmd = EcoCommands.valueOf(args[0].toUpperCase()); + amount = Integer.parseInt(args[2].replaceAll("[^0-9]", "")); + } + catch (Exception ex) + { + sender.sendMessage("§cUsage: /eco [give|take|reset] [player] [money]"); + return; + } + + if (args[1].contentEquals("*")) + { + for (Player p : server.getOnlinePlayers()) + { + User u = User.get(p); + switch (cmd) + { + case GIVE: + u.giveMoney(amount); + break; + + case TAKE: + u.takeMoney(amount); + break; + + case RESET: + u.setMoney(amount == 0 ? Essentials.getSettings().getStartingBalance() : amount); + break; + } + } + } + else + { + for (Player p : server.matchPlayer(args[1])) + { + User u = User.get(p); + switch (cmd) + { + case GIVE: + u.giveMoney(amount); + break; + + case TAKE: + u.takeMoney(amount); + break; + + case RESET: + u.setMoney(amount == 0 ? Essentials.getSettings().getStartingBalance() : amount); + break; + } + } + } + } + + + private enum EcoCommands + { + GIVE, TAKE, RESET + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java b/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java new file mode 100644 index 000000000..d4cc4038d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java @@ -0,0 +1,30 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandessentials extends EssentialsCommand +{ + public Commandessentials() + { + super("essentials"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + parent.reload(); + user.charge(this); + user.sendMessage("§7Essentials Reloaded " + parent.getDescription().getVersion()); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + parent.reload(); + sender.sendMessage("Essentials Reloaded " + parent.getDescription().getVersion()); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandext.java b/Essentials/src/com/earth2me/essentials/commands/Commandext.java new file mode 100644 index 000000000..1313ba5b9 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandext.java @@ -0,0 +1,29 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.entity.Player; + +public class Commandext extends EssentialsCommand { + + public Commandext() { + super("ext"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { + if (args.length < 1) { + User.charge(user, this); + user.setFireTicks(0); + user.sendMessage("§7You extinguished yourself."); + return; + } + + for (Player p : server.matchPlayer(args[0])) { + User.charge(user, this); + p.setFireTicks(0); + user.sendMessage("§7You extinguished " + p.getDisplayName() + "."); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgc.java b/Essentials/src/com/earth2me/essentials/commands/Commandgc.java new file mode 100644 index 000000000..08640e15b --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgc.java @@ -0,0 +1,29 @@ +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.Essentials; +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.command.CommandSender; + + +public class Commandgc extends EssentialsCommand +{ + public Commandgc() + { + super("gc"); + } + + @Override + protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + sender.sendMessage("Maximum memory: " + (Runtime.getRuntime().maxMemory() / 1024 / 1024) + " MB"); + sender.sendMessage("Free memory: " + (Runtime.getRuntime().freeMemory() / 1024 / 1024) + " MB"); + for (World w : parent.getServer().getWorlds()) + { + sender.sendMessage( + (w.getEnvironment() == World.Environment.NETHER ? "Nether" : "World") + " \"" + w.getName() + "\": " + + w.getLoadedChunks().length + " chunks, " + + w.getEntities().size() + " entities"); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java b/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java new file mode 100644 index 000000000..39be2c524 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java @@ -0,0 +1,33 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Location; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandgetpos extends EssentialsCommand +{ + public Commandgetpos() + { + super("getpos"); + } + + @Override + public String[] getTriggers() + { + return new String[] { getName(), "coords" }; + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + Location coords = user.getLocation(); + user.sendMessage("§7X: " + coords.getBlockX() + " (-North <-> +South)"); + user.sendMessage("§7Y: " + coords.getBlockY() + " (+Up <-> -Down)"); + user.sendMessage("§7Z: " + coords.getBlockZ() + " (+East <-> -West)"); + user.sendMessage("§7Yaw: " + user.getCorrectedYaw() + " (Rotation)"); + user.sendMessage("§7Pitch: " + coords.getPitch() + " (Head angle)"); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgive.java b/Essentials/src/com/earth2me/essentials/commands/Commandgive.java new file mode 100644 index 000000000..559fc5c32 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgive.java @@ -0,0 +1,49 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.ItemDb; +import com.earth2me.essentials.User; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + + +public class Commandgive extends EssentialsCommand +{ + public Commandgive() + { + super("give"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 2) + { + sender.sendMessage(ChatColor.RED + "Usage: /" + commandLabel + " [player] [item]<:data> "); + return; + } + + String[] itemArgs = args[1].split("[^a-zA-Z0-9]"); + ItemStack stack = ItemDb.get(itemArgs[0]); + + if(sender instanceof Player && !User.get(sender).isAuthorized("essentials.itemspawn.exempt") && !User.get(sender).canSpawnItem(stack.getTypeId())) + { + sender.sendMessage(ChatColor.RED + "You are not allowed to spawn that item"); + return; + } + if (itemArgs.length > 1) + stack.setDurability(Short.parseShort(itemArgs[1])); + if (args.length > 2) + stack.setAmount(Integer.parseInt(args[2])); + + User giveTo = getPlayer(server, args, 0); + String itemName = stack.getType().name().toLowerCase().replace('_', ' '); + if (sender instanceof Player) + User.get(sender).charge(this); + sender.sendMessage(ChatColor.BLUE + "Giving " + stack.getAmount() + " of " + itemName + " to " + giveTo.getDisplayName() + "."); + giveTo.getInventory().addItem(stack); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgod.java b/Essentials/src/com/earth2me/essentials/commands/Commandgod.java new file mode 100644 index 000000000..700be8c88 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgod.java @@ -0,0 +1,32 @@ +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.Server; +import org.bukkit.entity.Player; + + +public class Commandgod extends EssentialsCommand +{ + public Commandgod() + { + super("god"); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length > 0 && (user.isAuthorized("essentials.god.others") || user.isOp())) + { + for (Player p : server.matchPlayer(args[0])) + { + User u = User.get(p); + boolean enabled = u.toggleGodMode(); + u.sendMessage("§7God mode " + (enabled ? "enabled." : "disabled.")); + user.sendMessage("§7God mode " + (enabled ? "enabled for " : "disabled for ") + p.getDisplayName() + "."); + } + return; + } + user.sendMessage("§7God mode " + (user.toggleGodMode() ? "enabled." : "disabled.")); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandheal.java b/Essentials/src/com/earth2me/essentials/commands/Commandheal.java new file mode 100644 index 000000000..ddadda860 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandheal.java @@ -0,0 +1,53 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; + + +public class Commandheal extends EssentialsCommand +{ + public Commandheal() + { + super("heal"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length > 0 && user.isAuthorized("essentials.heal.others")) + { + if (!user.isAuthorized("essentials.heal.cooldown.bypass")) user.healCooldown(); + user.charge(this); + for (Player p : server.matchPlayer(args[0])) + { + p.setHealth(20); + user.sendMessage("§7Healed " + p.getDisplayName() + "."); + } + return; + } + + if (!user.isAuthorized("essentials.heal.cooldown.bypass")) user.healCooldown(); + user.charge(this); + user.setHealth(20); + user.sendMessage("§7You have been healed."); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("Usage: /" + commandLabel + " [player]"); + return; + } + + for (Player p : server.matchPlayer(args[0])) + { + p.setHealth(20); + sender.sendMessage("Healed " + p.getDisplayName() + "."); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java b/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java new file mode 100644 index 000000000..1468cced5 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java @@ -0,0 +1,129 @@ +package com.earth2me.essentials.commands; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandhelp extends EssentialsCommand +{ + public final Yaml yaml = new Yaml(new SafeConstructor()); + + public Commandhelp() + { + super("help"); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + int page; + try + { + page = args.length > 0 ? Integer.parseInt(args[0]) : 1; + } + catch (Exception ex) + { + page = 1; + } + + List lines = getHelpLines(parent, user); + int start = (page - 1) * 9; + int pages = lines.size() / 9 + (lines.size() % 9 > 0 ? 1 : 0); + + user.sendMessage("Page §c" + page + "§f of §c" + pages + "§f:"); + for (int i = start; i < lines.size() && i < start + 9; i++) + { + user.sendMessage(lines.get(i)); + } + } + + @Override + protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + sender.sendMessage("To view help from the console, type \"?\"."); + } + + @SuppressWarnings("CallToThreadDumpStack") + private List getHelpLines(Essentials parent, User user) throws Exception + { + List retval = new ArrayList(); + File file = new File(parent.getDataFolder(), "help.txt"); + if (file.exists()) + { + BufferedReader rx = new BufferedReader(new FileReader(file)); + for (String l = null; rx.ready() && (l = rx.readLine()) != null;) + { + retval.add(l.replace('&', '§')); + } + return retval; + } + + boolean reported = false; + for (Plugin p : parent.getServer().getPluginManager().getPlugins()) + { + try + { + PluginDescriptionFile desc = p.getDescription(); + HashMap> cmds = (HashMap>)desc.getCommands(); + for (String k : cmds.keySet()) + { + if (p.getDescription().getName().toLowerCase().contains("essentials")) + { + String node = "essentials." + k; + if (!Essentials.getSettings().isCommandDisabled(k) && user.isAuthorized(node)) + { + HashMap v = cmds.get(k); + retval.add("§c" + k + "§7: " + v.get("description")); + } + } + else + { + if (Essentials.getSettings().showNonEssCommandsInHelp()) + { + HashMap v = cmds.get(k); + if (v.containsKey("permission") && v.get("permission") != null && !(v.get("permission").equals(""))) + { + if (user.isAuthorized(v.get("permission"))) + { + retval.add("§c" + k + "§7: " + v.get("description")); + } + } + else + { + retval.add("§c" + k + "§7: " + v.get("description")); + } + } + + } + } + } + catch (NullPointerException ex) + { + + continue; + } + catch (Exception ex) + { + if (!reported) + { + ex.printStackTrace(); + } + reported = true; + continue; + } + } + return retval; + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java b/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java new file mode 100644 index 000000000..03dbad50e --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java @@ -0,0 +1,33 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; + + +public class Commandhelpop extends EssentialsCommand +{ + public Commandhelpop() + { + super("helpop"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cTo request help from an op, type §f/" + commandLabel+ "§c, followed by your question."); + return; + } + + user.charge(this); + for (Player p : server.getOnlinePlayers()) + { + User u = User.get(p); + if (!u.isOp() && !u.isAuthorized("essentials.helpop.receive")) continue; + u.sendMessage("§c[HelpOp]§f §7" + user.getDisplayName() + ":§f " + getFinalArg(args, 0)); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhome.java b/Essentials/src/com/earth2me/essentials/commands/Commandhome.java new file mode 100644 index 000000000..0dc92d25a --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhome.java @@ -0,0 +1,21 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + +public class Commandhome extends EssentialsCommand +{ + public Commandhome() + { + super("home"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.canAfford(this); + user.teleportCooldown(); + user.teleportToHome(this.getName()); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java b/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java new file mode 100644 index 000000000..2e7ec407a --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java @@ -0,0 +1,39 @@ +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.Server; +import org.bukkit.craftbukkit.inventory.CraftInventory; + +public class Commandinvsee extends EssentialsCommand { + + public Commandinvsee() { + super("invsee"); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { + + if (args.length == 0 && user.savedInventory == null) { + user.sendMessage("§cUsage: /" + commandLabel + " "); + } + User invUser = user; + if (args.length == 1) { + invUser = getPlayer(server, args, 0); + } + if (invUser == user && user.savedInventory != null) { + ((CraftInventory)invUser.getInventory()).setContents(user.savedInventory); + user.savedInventory = null; + user.sendMessage("Your inventory has been restored."); + return; + } + + user.charge(this); + if (user.savedInventory == null) { + user.savedInventory = ((CraftInventory)user.getInventory()).getContents(); + } + ((CraftInventory)user.getInventory()).setContents(((CraftInventory)invUser.getInventory()).getContents()); + user.sendMessage("You see the inventory of "+invUser.getDisplayName()+"."); + user.sendMessage("Use /invsee to restore your inventory."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanditem.java b/Essentials/src/com/earth2me/essentials/commands/Commanditem.java new file mode 100644 index 000000000..97d1d2218 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commanditem.java @@ -0,0 +1,45 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.ItemDb; +import com.earth2me.essentials.User; +import org.bukkit.ChatColor; +import org.bukkit.inventory.ItemStack; + + +public class Commanditem extends EssentialsCommand +{ + public Commanditem() + { + super("item"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /" + commandLabel + " [item] "); + return; + } + String[] itemArgs = args[0].split("[^a-zA-Z0-9]"); + ItemStack stack = ItemDb.get(itemArgs[0]); + + if(!user.isAuthorized("essentials.itemspawn.exempt") && !user.canSpawnItem(stack.getTypeId())) + { + user.sendMessage(ChatColor.RED + "You are not allowed to spawn that item"); + return; + } + if (itemArgs.length > 1) + stack.setDurability(Short.parseShort(itemArgs[1])); + + if (args.length > 1) + stack.setAmount(Integer.parseInt(args[1])); + + String itemName = stack.getType().name().toLowerCase().replace('_', ' '); + user.charge(this); + user.sendMessage("§7Giving " + stack.getAmount() + " of " + itemName + " to " + user.getDisplayName() + "."); + user.getInventory().addItem(stack); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandjails.java b/Essentials/src/com/earth2me/essentials/commands/Commandjails.java new file mode 100644 index 000000000..75018eb19 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandjails.java @@ -0,0 +1,37 @@ +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; + +public class Commandjails extends EssentialsCommand { + + public Commandjails() { + super("jails"); + } + + @Override + protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception { + StringBuilder jailList = new StringBuilder(); + for (String j : Essentials.getJail().getJails()) + { + jailList.append(j); + jailList.append(' '); + } + sender.sendMessage("§7" + jailList); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { + StringBuilder jailList = new StringBuilder(); + for (String j : Essentials.getJail().getJails()) + { + jailList.append(j); + jailList.append(' '); + } + user.sendMessage("§7" + jailList); + } + + +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandjump.java b/Essentials/src/com/earth2me/essentials/commands/Commandjump.java new file mode 100644 index 000000000..b753fc4b3 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandjump.java @@ -0,0 +1,50 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Location; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.TargetBlock; +import com.earth2me.essentials.User; + + +public class Commandjump extends EssentialsCommand +{ + public Commandjump() + { + super("jump"); + } + + @Override + public String[] getTriggers() + { + return new String[] + { + getName(), "j" + }; + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + Location loc; + Location cloc = user.getLocation(); + + try + { + loc = new TargetBlock(user, 100, 2.65).getTargetBlock().getLocation(); + loc.setYaw(cloc.getYaw()); + loc.setPitch(cloc.getPitch()); + loc = new TargetBlock(loc).getPreviousBlock().getLocation(); + loc.setYaw(cloc.getYaw()); + loc.setPitch(cloc.getPitch()); + loc.setY(loc.getY() + 1); + } + catch (NullPointerException ex) + { + throw new Exception("That would hurt your computer's brain.", ex); + } + + user.canAfford(this); + user.teleport(loc, this.getName()); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkick.java b/Essentials/src/com/earth2me/essentials/commands/Commandkick.java new file mode 100644 index 000000000..ddf5de5f5 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkick.java @@ -0,0 +1,41 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.ChatColor; + + +public class Commandkick extends EssentialsCommand +{ + public Commandkick() + { + super("kick"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage(ChatColor.RED + "Usage: /" + commandLabel + " [player] "); + return; + } + + User p; + try + { + p = User.get(server.matchPlayer(args[0]).get(0)); + } + catch (Throwable ex) + { + sender.sendMessage(ChatColor.RED + "That player does not exist!"); + return; + } + + charge(sender); + p.kickPlayer(args.length > 1 ? getFinalArg(args, 1) : "Kicked from server"); + + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java b/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java new file mode 100644 index 000000000..e73f57a00 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java @@ -0,0 +1,55 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + +public class Commandkickall extends EssentialsCommand +{ + public Commandkickall() + { + super("kickall"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§7Usage: /" + commandLabel + ""); + return; + } + + + for (Player p : server.getOnlinePlayers()) + { + if (server.getOnlinePlayers().length == 1 && p.getName().equalsIgnoreCase(user.getName())) + { + user.sendMessage("§7Only you online..."); + return; + } + else + { + if (!p.getName().equalsIgnoreCase(user.getName())) + { + p.kickPlayer(args.length < 1 ? args[0] : "Kicked from server"); + } + } + } + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("Usage: /" + commandLabel + ""); + return; + } + + for (Player p : server.getOnlinePlayers()) + p.kickPlayer(args.length < 1 ? args[0] : "Kicked from server"); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkill.java b/Essentials/src/com/earth2me/essentials/commands/Commandkill.java new file mode 100644 index 000000000..ef5315c85 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkill.java @@ -0,0 +1,33 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; + + +public class Commandkill extends EssentialsCommand +{ + public Commandkill() + { + super("kill"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("§cUsage: /kill [player]"); + return; + } + + User.charge(sender, this); + for (Player p : server.matchPlayer(args[0])) + { + p.setHealth(0); + sender.sendMessage("§cKilled " + p.getDisplayName() + "."); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkit.java b/Essentials/src/com/earth2me/essentials/commands/Commandkit.java new file mode 100644 index 000000000..eb251b06b --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkit.java @@ -0,0 +1,150 @@ +package com.earth2me.essentials.commands; + +import java.util.Calendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.inventory.ItemStack; + + +public class Commandkit extends EssentialsCommand +{ + static private final Map> kitPlayers = new HashMap>(); + + public Commandkit() + { + super("kit"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + try + { + Map kits = (Map)parent.getConfiguration().getProperty("kits"); + StringBuilder list = new StringBuilder(); + for (String k : kits.keySet()) + { + if (user.isAuthorized("essentials.kit." + k)) + { + list.append(" ").append(k); + } + } + if (list.length() > 0) + { + user.sendMessage("§7Kits:" + list.toString()); + } + else + { + user.sendMessage("§7There are no kits available yet"); + } + } + catch (Exception ex) + { + user.sendMessage("§cThere are no valid kits."); + } + } + else + { + try + { + String kitName = args[0].toLowerCase(); + Object kit = Essentials.getSettings().getKit(kitName); + List items; + + if (!user.isAuthorized("essentials.kit." + kitName)) + { + user.sendMessage("§cYou need the §fessentials.kit." + kitName + "§c permission to use that kit."); + return; + } + + try + { + + System.out.println("Kit is timed"); + Map els = (Map)kit; + items = (List)els.get("items"); + long delay = els.containsKey("delay") ? (Integer)els.get("delay") * 1000L : 0L; + long time = Calendar.getInstance().getTimeInMillis(); + + Map kitTimes; + if (!kitPlayers.containsKey(user)) + { + kitTimes = new HashMap(); + kitTimes.put(kitName, time); + kitPlayers.put(user, kitTimes); + } + else + { + kitTimes = kitPlayers.get(user); + if (!kitTimes.containsKey(kitName)) + { + kitTimes.put(kitName, time); + } + else if (kitTimes.get(kitName) + delay <= time) + { + kitTimes.put(kitName, time); + } + else + { + long left = kitTimes.get(kitName) + delay - time; + user.sendMessage("§cYou can't use that kit again for another " + Essentials.FormatTime(left) + "."); + + return; + } + } + } + catch (Exception ex) + { + items = (List)kit; + } + + try { + user.canAfford("kit-" + kitName); + } catch (Exception ex) { + user.sendMessage(ex.getMessage()); + return; + } + + boolean spew = false; + for (String d : items) + { + String[] parts = d.split("[^0-9]+", 3); + int id = Integer.parseInt(parts[0]); + int amount = parts.length > 1 ? Integer.parseInt(parts[parts.length > 2 ? 2 : 1]) : 1; + short data = parts.length > 2 ? Short.parseShort(parts[1]) : 0; + if(user.getInventory().firstEmpty() != -1) + { + user.getInventory().addItem(new ItemStack(id, amount, data)); + } + else + { + spew = true; + user.getWorld().dropItemNaturally(user.getLocation(), new ItemStack(id, amount, data)); + } + } + if(spew) + { + user.sendMessage("§7Your inventory was full, placing kit on the floor"); + } + try { + user.charge(this); + user.charge("kit-" + kitName); + } catch (Exception ex) { + user.sendMessage(ex.getMessage()); + } + user.sendMessage("§7Giving kit " + args[0].toLowerCase() + "."); + } + catch (Exception ex) + { + user.sendMessage("§cThat kit does not exist or is improperly defined."); + user.sendMessage("§cPerhaps an item is missing a quantity in the configuration?"); + } + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandlist.java b/Essentials/src/com/earth2me/essentials/commands/Commandlist.java new file mode 100644 index 000000000..aeef26ac7 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandlist.java @@ -0,0 +1,93 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.bukkit.ChatColor; + + +public class Commandlist extends EssentialsCommand +{ + public Commandlist() + { + super("list"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + User.charge(sender, this); + StringBuilder online = new StringBuilder(); + online.append(ChatColor.BLUE).append("There are ").append(ChatColor.RED).append(server.getOnlinePlayers().length); + online.append(ChatColor.BLUE).append(" out of a maximum ").append(ChatColor.RED).append(server.getMaxPlayers()); + online.append(ChatColor.BLUE).append(" players online."); + sender.sendMessage(online.toString()); + + if (Essentials.getSettings().getSortListByGroups()) { + Map> sort = new HashMap>(); + for (Player p : server.getOnlinePlayers()) + { + User u = User.get(p); + String group = u.getGroup(); + List list = sort.get(group); + if (list == null) { + list = new ArrayList(); + sort.put(group, list); + } + list.add(u); + } + String[] groups = sort.keySet().toArray(new String[0]); + Arrays.sort(groups, String.CASE_INSENSITIVE_ORDER); + for (String group : groups) { + StringBuilder groupString = new StringBuilder(); + groupString.append(group).append(": "); + List users = sort.get(group); + Collections.sort(users); + boolean first = true; + for (User user : users) { + if (!first) { + groupString.append(", "); + } else { + first = false; + } + if (parent.away.contains(user)) { + groupString.append("§7[AFK]"); + } + groupString.append(user.getDisplayName()); + } + sender.sendMessage(groupString.toString()); + } + } else { + List users = new ArrayList(); + for (Player p : server.getOnlinePlayers()) + { + users.add(User.get(p)); + } + Collections.sort(users); + + StringBuilder onlineUsers = new StringBuilder(); + onlineUsers.append("Connected players: "); + boolean first = true; + for (User user : users) { + if (!first) { + onlineUsers.append(", "); + } else { + first = false; + } + if (parent.away.contains(user)) { + onlineUsers.append("§7[AFK]"); + } + onlineUsers.append(user.getDisplayName()); + } + sender.sendMessage(onlineUsers.toString()); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmail.java b/Essentials/src/com/earth2me/essentials/commands/Commandmail.java new file mode 100644 index 000000000..3e55c982d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmail.java @@ -0,0 +1,52 @@ +package com.earth2me.essentials.commands; + +import java.util.List; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandmail extends EssentialsCommand +{ + public Commandmail() + { + super("mail"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) + { + List mail = Essentials.readMail(user); + if (mail.isEmpty()) + { + user.sendMessage("§cYou do not have any mail!"); + return; + } + for (String s : mail) user.sendMessage(s); + user.sendMessage("§cTo mark your mail as read, type §c/mail clear"); + return; + } + if(args.length >= 3 && "send".equalsIgnoreCase(args[0])) + { + if (!user.isAuthorized("essentials.mail.send")) + { + user.sendMessage("§cYou do not have the §fessentials.mail.send§c permission."); + return; + } + + user.charge(this); + Essentials.sendMail(user, args[1], getFinalArg(args, 2)); + user.sendMessage("§7Mail sent!"); + return; + } + if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) + { + Essentials.clearMail(user); + user.sendMessage("§7Mail cleared!"); + return; + } + user.sendMessage("§7Usage: /mail [read|clear|send [to] [message]]"); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandme.java b/Essentials/src/com/earth2me/essentials/commands/Commandme.java new file mode 100644 index 000000000..6b3deaf1d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandme.java @@ -0,0 +1,43 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandme extends EssentialsCommand +{ + public Commandme() + { + super("me"); + } + + @Override + public String[] getTriggers() + { + return new String[] { getName(), "describe", "action" }; + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (user.isMuted()) + { user.sendMessage("§7Your voice has been silenced"); + return; + } + + if (args.length < 1) + { + user.sendMessage("§cUsage: /me [description]"); + return; + } + StringBuilder message = new StringBuilder(); + for (int i = 0; i < args.length; i++) + { + message.append(args[i]); + message.append(' '); + } + user.charge(this); + server.broadcastMessage("* " + user.getDisplayName() + " " + message); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java b/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java new file mode 100644 index 000000000..652310e36 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java @@ -0,0 +1,25 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.command.CommandSender; + + +public class Commandmotd extends EssentialsCommand +{ + public Commandmotd() + { + super("motd"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + User.charge(sender, this); + for (String m : parent.getMotd(sender, "§cThere is no message of the day.")) + { + sender.sendMessage(m); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java b/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java new file mode 100644 index 000000000..8b02bbf19 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java @@ -0,0 +1,85 @@ +package com.earth2me.essentials.commands; + +import java.util.List; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; +import org.bukkit.command.CommandSender; + +public class Commandmsg extends EssentialsCommand +{ + public Commandmsg() + { + super("msg"); + } + + @Override + public String[] getTriggers() + { + return new String[] { getName(), "m", "tell", "whisper" }; + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 2 || args[0].trim().length() == 0 || args[1].trim().length() == 0) + { + user.sendMessage("§cUsage: /" + commandLabel + " [player] [message]"); + return; + } + + StringBuilder message = new StringBuilder(); + for (int i = 1; i < args.length; i++) + { + message.append(args[i]); + message.append(' '); + } + + List matches = server.matchPlayer(args[0]); + + if (matches.isEmpty()) + { + user.sendMessage("§cThere are no players matching that name."); + return; + } + + user.charge(this); + for (Player p : matches) + { + user.sendMessage("[Me -> " + p.getDisplayName() + "§f] " + message); + p.sendMessage("[" + user.getDisplayName() + " -> Me§f] " + message); + user.setReplyTo(User.get(p)); + User.get(p).setReplyTo(user); + } + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 2 || args[0].trim().length() == 0 || args[1].trim().length() == 0) + { + sender.sendMessage("§cUsage: /" + commandLabel + " [player] [message]"); + return; + } + + StringBuilder message = new StringBuilder(); + for (int i = 1; i < args.length; i++) + { + message.append(args[i]); + message.append(' '); + } + List matches = server.matchPlayer(args[0]); + + if (matches.isEmpty()) + { + sender.sendMessage("§cThere are no players matching that name."); + } + + for (Player p : matches) + { + sender.sendMessage("[§2Me -> " + p.getDisplayName() + "§f] " + message); + p.sendMessage("[§2{Console} -> Me§f] " + message); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmute.java b/Essentials/src/com/earth2me/essentials/commands/Commandmute.java new file mode 100644 index 000000000..30164e25d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmute.java @@ -0,0 +1,64 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandmute extends EssentialsCommand +{ + public Commandmute() + { + super("kick"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§7Usage: /" + commandLabel + " [player] "); + return; + } + + String[] sects2 = args[0].split(" +"); + User p; + try + { + p = User.get(server.matchPlayer(args[0]).get(0)); + } + catch (Exception ex) + { + user.sendMessage("§cThat player does not exist!"); + return; + } + + user.sendMessage("§7Player " + p.getName() + " " + (p.toggleMuted() ? "muted." : "unmuted.")); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("Usage: /" + commandLabel + " [player] "); + return; + } + + String[] sects2 = args[0].split(" +"); + User p; + try + { + p = User.get(server.matchPlayer(args[0]).get(0)); + } + catch (Exception ex) + { + sender.sendMessage("§cThat player does not exist!"); + return; + } + + sender.sendMessage("Player " + p.getName() + " " + (p.toggleMuted() ? "muted." : "unmuted.")); + + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnick.java b/Essentials/src/com/earth2me/essentials/commands/Commandnick.java new file mode 100644 index 000000000..fb65539b6 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandnick.java @@ -0,0 +1,129 @@ +package com.earth2me.essentials.commands; + +import java.util.List; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; + + +public class Commandnick extends EssentialsCommand +{ + public Commandnick() + { + super("nick"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /" + commandLabel + " [nickname]"); + return; + } + + if (args.length > 1) + { + if (!user.isOp()) + { + user.sendMessage("§cOnly operators can change the nicknames of other users."); + return; + } + + List matches = server.matchPlayer(args[0]); + if (matches.isEmpty()) + { + user.sendMessage("§cThat player does not exist."); + return; + } + + User target = User.get(matches.get(0)); + String nick = args[1]; + if ("off".equalsIgnoreCase(nick) || target.getName().equalsIgnoreCase(nick)) + { + target.setDisplayName(target.getName()); + parent.saveNickname(target, target.getName()); + target.sendMessage("§7You no longer have a nickname."); + } + else + { + user.charge(this); + target.setDisplayName(parent.getConfiguration().getString("nickname-prefix", "~") + nick); + parent.saveNickname(target, nick); + target.sendMessage("§7Your nickname is now §c" + target.getDisplayName() + "§7."); + } + user.sendMessage("§7Nickname changed."); + } + else + { + String nick = args[0]; + if ("off".equalsIgnoreCase(nick) || user.getName().equalsIgnoreCase(nick)) + { + user.setDisplayName(user.getName()); + parent.saveNickname(user, user.getName()); + user.sendMessage("§7You no longer have a nickname."); + } + else + { + if (nick.matches("[^a-zA-Z_0-9]")) + { + user.sendMessage("§cNicknames must be alphanumeric."); + return; + } + + for (Player p : server.getOnlinePlayers()) + { + if (user == p) continue; + String dn = p.getDisplayName().toLowerCase(); + String n = p.getName().toLowerCase(); + String nk = nick.toLowerCase(); + if (nk.equals(dn) || nk.equals(n)) + { + user.sendMessage("§cThat name is already in use."); + return; + } + } + + user.charge(this); + user.setDisplayName(parent.getConfiguration().getString("nickname-prefix", "~") + nick); + parent.saveNickname(user, nick); + user.sendMessage("§7Your nickname is now §c" + user.getDisplayName() + "§7."); + } + } + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 2) + { + sender.sendMessage("Usage: /" + commandLabel + " [target] [nickname]"); + return; + } + + List matches = server.matchPlayer(args[0]); + if (matches.isEmpty()) + { + sender.sendMessage("That player does not exist."); + return; + } + + User target = User.get(matches.get(0)); + String nick = args[1]; + if ("off".equalsIgnoreCase(nick) || target.getName().equalsIgnoreCase(nick)) + { + target.setDisplayName(target.getName()); + parent.saveNickname(target, target.getName()); + target.sendMessage("§7You no longer have a nickname."); + } + else + { + target.setDisplayName(parent.getConfiguration().getString("nickname-prefix", "~") + nick); + parent.saveNickname(target, nick); + target.sendMessage("§7Your nickname is now §c" + target.getDisplayName() + "§7."); + } + sender.sendMessage("Nickname changed."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnuble.java b/Essentials/src/com/earth2me/essentials/commands/Commandnuble.java new file mode 100644 index 000000000..dc6ab3ac3 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandnuble.java @@ -0,0 +1,21 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandnuble extends EssentialsCommand +{ + public Commandnuble() + { + super("nuble"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + user.sendMessage("§7Flight is allowed on this server."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpay.java b/Essentials/src/com/earth2me/essentials/commands/Commandpay.java new file mode 100644 index 000000000..085f8febe --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpay.java @@ -0,0 +1,42 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; +import com.earth2me.essentials.commands.EssentialsCommand; + + +public class Commandpay extends EssentialsCommand +{ + public Commandpay() + { + super("pay"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + + int amount; + try + { + amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); + } + catch (Exception ex) + { + user.sendMessage("§cUsage: /" + commandLabel + " [player] [money]"); + return; + } + + for (Player p : server.matchPlayer(args[0])) + { + User u = User.get(p); + user.payUser(u, amount); + } + } + + + +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandping.java b/Essentials/src/com/earth2me/essentials/commands/Commandping.java new file mode 100644 index 000000000..36d8e33c3 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandping.java @@ -0,0 +1,26 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandping extends EssentialsCommand +{ + public Commandping() + { + super("ping"); + } + + @Override + public String[] getTriggers() + { + return new String[] { getName(), "pong" }; + } + + @Override + public void run(Server server, Essentials parent, User player, String commandLabel, String[] args) throws Exception + { + player.sendMessage("Pong!"); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandplugin.java b/Essentials/src/com/earth2me/essentials/commands/Commandplugin.java new file mode 100644 index 000000000..df1ecdaad --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandplugin.java @@ -0,0 +1,161 @@ +package com.earth2me.essentials.commands; + +import java.io.File; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; + + +public class Commandplugin extends EssentialsCommand +{ + private Server server; + + public Commandplugin() + { + super("plugin"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + this.server = server; + + PluginCommands sub = null; + try + { + sub = PluginCommands.valueOf(args[0].toUpperCase()); + } + catch (Exception ex) + { + sender.sendMessage("§cUsage: /plugin [load|reload|enable|disable|list] [PluginName]"); + return; + } + + switch (sub) + { + case LOAD: + if (args.length < 2) return; + User.charge(sender, this); + loadPlugin(args[1], sender); + return; + + case RELOAD: + if (args.length < 2) return; + User.charge(sender, this); + reloadPlugin(args[1], sender); + return; + + case ENABLE: + if (args.length < 2) return; + User.charge(sender, this); + enablePlugin(args[1], sender); + return; + + case DISABLE: + if (args.length < 2) return; + User.charge(sender, this); + disablePlugin(args[1], sender); + return; + + case LIST: + User.charge(sender, this); + listPlugins(sender); + return; + } + } + + private void listPlugins(CommandSender player) + { + StringBuilder plugins = new StringBuilder(); + for (Plugin p : server.getPluginManager().getPlugins()) + { + plugins.append(p.isEnabled() ? " §a" : " §c"); + plugins.append(p.getDescription().getName()); + } + + plugins.insert(0, "§7Plugins:§f"); + player.sendMessage(plugins.toString()); + } + + private boolean reloadPlugin(String name, CommandSender player) + { + return disablePlugin(name, player) && enablePlugin(name, player); + } + + private boolean loadPlugin(String name, CommandSender sender) + { + try + { + PluginManager pm = server.getPluginManager(); + pm.loadPlugin(new File("plugins", name + ".jar")); + sender.sendMessage("§7Plugin loaded."); + return enablePlugin(name, sender); + } + catch (Throwable ex) + { + sender.sendMessage("§cCould not load plugin. Is the file named properly?"); + return false; + } + } + + private boolean enablePlugin(String name, CommandSender sender) + { + try + { + final PluginManager pm = server.getPluginManager(); + final Plugin plugin = pm.getPlugin(name); + if (!plugin.isEnabled()) new Thread(new Runnable() + { + public void run() + { + synchronized (pm) + { + pm.enablePlugin(plugin); + } + } + }).start(); + sender.sendMessage("§7Plugin enabled."); + return true; + } + catch (Throwable ex) + { + listPlugins(sender); + return false; + } + } + + private boolean disablePlugin(String name, CommandSender sender) + { + try + { + final PluginManager pm = server.getPluginManager(); + final Plugin plugin = pm.getPlugin(name); + if (plugin.isEnabled()) new Thread(new Runnable() + { + public void run() + { + synchronized (pm) + { + pm.disablePlugin(plugin); + } + } + }).start(); + sender.sendMessage("§7Plugin disabled."); + return true; + } + catch (Throwable ex) + { + listPlugins(sender); + return false; + } + } + + + private enum PluginCommands + { + LOAD, RELOAD, LIST, ENABLE, DISABLE + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandr.java b/Essentials/src/com/earth2me/essentials/commands/Commandr.java new file mode 100644 index 000000000..9bc7f2f97 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandr.java @@ -0,0 +1,37 @@ +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.*; +import org.bukkit.*; + + +public class Commandr extends EssentialsCommand +{ + public Commandr() + { + super("r"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /" + commandLabel + " [message]"); + return; + } + + String message = getFinalArg(args, 0); + User target = user.getReplyTo(); + + if (target == null) + { + user.sendMessage("§cYou have nobody to whom you can reply."); + } + + user.charge(this); + user.sendMessage("[Me -> " + target.getDisplayName() + "] " + message); + target.sendMessage("[" + user.getDisplayName() + " -> Me] " + message); + user.setReplyTo(target); + target.setReplyTo(user); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java b/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java new file mode 100644 index 000000000..6bec3f633 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java @@ -0,0 +1,40 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; + + +public class Commandrealname extends EssentialsCommand +{ + public Commandrealname() + { + super("realname"); + } + + @Override + public String[] getTriggers() + { + return new String[] { getName(), "realnick" }; + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /whois [nickname]"); + return; + } + String whois = args[0].toLowerCase(); + user.charge(this); + for (Player p : server.getOnlinePlayers()) + { + User u = User.get(p); + String dn = u.getDisplayName().toLowerCase(); + if (!whois.equals(dn) && !whois.equals(parent.getSettings().getNicknamePrefix() + dn) && !whois.equals(u.getName().toLowerCase())) continue; + user.sendMessage(u.getDisplayName() + " is " + u.getName()); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandreloadall.java b/Essentials/src/com/earth2me/essentials/commands/Commandreloadall.java new file mode 100644 index 000000000..c677bc1c6 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandreloadall.java @@ -0,0 +1,37 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandreloadall extends EssentialsCommand +{ + + public Commandreloadall() + { + super("reloadall"); + } + + @Override + public String[] getTriggers() + { + return new String[] { getName(), "rel", "pr" }; + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + server.reload(); + user.sendMessage("§7Reloaded all plugins."); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + server.reload(); + sender.sendMessage("Reloaded all plugins."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrules.java b/Essentials/src/com/earth2me/essentials/commands/Commandrules.java new file mode 100644 index 000000000..e94b98755 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrules.java @@ -0,0 +1,23 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.*; + + +public class Commandrules extends EssentialsCommand +{ + public Commandrules() + { + super("rules"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + for (String m : parent.getLines(user, "rules", "§cThere are no rules specified yet.")) + { + user.sendMessage(m); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsell.java b/Essentials/src/com/earth2me/essentials/commands/Commandsell.java new file mode 100644 index 000000000..11ce4ba6d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsell.java @@ -0,0 +1,63 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.earth2me.essentials.commands.EssentialsCommand; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + + +public class Commandsell extends EssentialsCommand +{ + public Commandsell() + { + super("sell"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + ItemStack is = user.getInventory().getItemInHand(); + if(is.getType() == Material.AIR) + throw new Exception("You really tried to sell Air? Put an item in your hand."); + + int id = is.getTypeId(); + int amount = 0; + if (args.length > 0) amount = Integer.parseInt(args[0].replaceAll("[^0-9]", "")); + int worth = parent.getConfiguration().getInt("worth-" + id, 0); + boolean stack = args.length > 0 && args[0].endsWith("s"); + boolean requireStack = parent.getConfiguration().getBoolean("trade-in-stacks-" + id, false); + + if (worth < 1) throw new Exception("That item cannot be sold to the server."); + if (requireStack && !stack) throw new Exception("Item must be traded in stacks. A quantity of 2s would be two stacks, etc."); + + int max = 0; + for (ItemStack s : user.getInventory().all(is).values()) + { + max += s.getAmount(); + } + + if (stack) amount *= 64; + if (amount < 1) amount += max; + + if (requireStack) + { + amount -= amount % 64; + } + + if (amount > max || amount < 1) + { + user.sendMessage("§cYou do not have enough of that item to sell."); + user.sendMessage("§7If you meant to sell all of your items of that type, use /sell without parameters."); + user.sendMessage("§7/sell -1 will sell all but one item, etc."); + return; + } + + user.charge(this); + user.getInventory().removeItem(new ItemStack(id, amount)); + user.updateInventory(); + user.giveMoney(worth * amount); + user.sendMessage("§7Sold for §c$" + (worth * amount) + "§7 (" + amount + " items at $" + worth + " each)"); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java b/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java new file mode 100644 index 000000000..f4729ead8 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java @@ -0,0 +1,22 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandsethome extends EssentialsCommand +{ + public Commandsethome() + { + super("sethome"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.setHome(); + user.charge(this); + user.sendMessage("§7Home set."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java new file mode 100644 index 000000000..f5c330188 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java @@ -0,0 +1,28 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandsetjail extends EssentialsCommand +{ + public Commandsetjail() + { + super("setjail"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /" + commandLabel + " [jailname]"); + return; + } + user.charge(this); + Essentials.getJail().setJail(user.getLocation(), args[0]); + user.sendMessage("§7Jail " + args[0] + " has been set"); + + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java new file mode 100644 index 000000000..e510a8f73 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java @@ -0,0 +1,30 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Location; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandsetwarp extends EssentialsCommand +{ + public Commandsetwarp() + { + super("setwarp"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /setwarp [warp name]"); + return; + } + + user.charge(this); + Location loc = user.getLocation(); + Essentials.getWarps().setWarp(args[0], loc); + user.sendMessage("§7Warp set."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java b/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java new file mode 100644 index 000000000..d73c0b843 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java @@ -0,0 +1,41 @@ +package com.earth2me.essentials.commands; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.Server; +import org.bukkit.block.Block; +import org.bukkit.block.CreatureSpawner; +import org.bukkit.entity.CreatureType; + +public class Commandspawner extends EssentialsCommand +{ + public Commandspawner() + { + super("spawner"); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage(ChatColor.RED + "Usage: /" + commandLabel + " [mob]"); + return; + } + + Block target = user.getTarget().getTargetBlock(); + if (target.getType() != Material.MOB_SPAWNER) + throw new Exception("Target block must be a mob spawner."); + + try + { + ((CreatureSpawner)target).setCreatureType(CreatureType.fromName(args[0])); + } + catch (Throwable ex) + { + + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java b/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java new file mode 100644 index 000000000..c1c883a75 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java @@ -0,0 +1,188 @@ +package com.earth2me.essentials.commands; + +import net.minecraft.server.WorldServer; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.craftbukkit.entity.CraftEntity; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.earth2me.essentials.Mob; +import com.earth2me.essentials.Mob.MobException; +import com.earth2me.essentials.TargetBlock; + + +public class Commandspawnmob extends EssentialsCommand +{ + public Commandspawnmob() + { + super("spawnmob"); + } + + @Override + public String[] getTriggers() + { + return new String[] + { + getName(), "mob" + }; + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /spawnmob [mob]<,mount><:size> "); + user.sendMessage("§7Mobs: Zombie PigZombie Skeleton Slime Chicken Pig Monster Spider Creeper Ghast Squid Giant Cow Sheep"); + return; + } + + String[] split1 = args[0].split(":"); + String[] split0 = null; + CraftEntity spawned1 = null; + Mob mob2 = null; + if (split1.length == 1 && !split1[0].equalsIgnoreCase("Slime")) + { + split0 = args[0].split(","); + split1[0] = split0[0]; + } + if (split1.length == 2) + { + args[0] = split1[0] + ""; + } + Mob mob = Mob.fromName(split1[0].equalsIgnoreCase("PigZombie") ? "PigZombie" : capitalCase(split1[0])); + if (mob == null) + { + user.sendMessage("Invalid mob type."); + return; + } + WorldServer world = ((org.bukkit.craftbukkit.CraftWorld)user.getWorld()).getHandle(); + CraftEntity spawned = null; + try + { + spawned = mob.spawn(user, server); + } + catch (MobException e) + { + user.sendMessage("Unable to spawn mob."); + return; + } + int[] ignore = {8, 9}; + Location loc = (new TargetBlock(user, 300, 0.2, ignore)).getTargetBlock().getLocation(); + int blkId = user.getWorld().getBlockTypeIdAt(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); + while (!(blkId == 0 || blkId == 8 || blkId == 9)) + { + loc.setY(loc.getY() + 1); + blkId = user.getWorld().getBlockTypeIdAt(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); + } + spawned.teleportTo(loc); + world.a(spawned.getHandle()); + if (split0 != null && split0.length == 2) + { + mob2 = Mob.fromName(split0[1].equalsIgnoreCase("PigZombie") ? "PigZombie" : capitalCase(split0[1])); + if (mob2 == null) + { + user.sendMessage("Invalid mob type."); + return; + } + try + { + spawned1 = mob2.spawn(user, server); + } + catch (MobException e) + { + user.sendMessage("Unable to spawn mob."); + return; + } + spawned1.teleportTo(spawned); + spawned1.getHandle().setPassengerOf(spawned.getHandle()); + world.a(spawned1.getHandle()); + } + if (split1.length == 2 && "Slime".equals(mob.name)) + { + try + { + //((EntitySlime)spawned.getHandle()).a(Integer.parseInt(split1[1])); + } + catch (Exception e) + { + user.sendMessage("Malformed size."); + return; + } + } + if (args.length == 2) + { + int mobCount = Integer.parseInt(args[1]); + int serverLimit = Essentials.getSettings().getSpawnMobLimit(); + if(mobCount > serverLimit) + { + mobCount = serverLimit; + user.sendMessage("Mob quantity limited to server limit"); + } + user.charge(this); + try + { + for (int i = 1; i < mobCount; i++) + { + spawned = mob.spawn(user, server); + spawned.teleportTo(loc); + if (split1.length > 1 && "Slime".equals("Slime")) + { + try + { + //((EntitySlime)spawned.getHandle()).a(Integer.parseInt(split1[1])); + } + catch (Exception e) + { + user.sendMessage("Malformed size."); + return; + } + } + world.a(spawned.getHandle()); + if (split0.length == 2) + { + if (mob2 == null) + { + user.sendMessage("Invalid mob mount."); + return; + } + try + { + spawned1 = mob2.spawn(user, server); + } + catch (MobException e) + { + user.sendMessage("Unable to spawn mob."); + return; + } + spawned1.teleportTo(spawned); + spawned1.getHandle().setPassengerOf(spawned.getHandle()); + world.a(spawned1.getHandle()); + } + } + user.sendMessage(args[1] + " " + mob.name.toLowerCase() + mob.s + " spawned."); + } + catch (MobException e1) + { + throw new Exception("Unable to spawn mobs. Insert bad excuse here."); + } + catch (NumberFormatException e2) + { + throw new Exception("A number goes there, silly."); + } + catch (NullPointerException np) + { + throw new Exception("That mob likes to be alone"); + } + } + else + { + user.sendMessage(mob.name + " spawned."); + } + } + + private String capitalCase(String s) + { + return s.toUpperCase().charAt(0) + s.toLowerCase().substring(1); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java b/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java new file mode 100644 index 000000000..07ac23e94 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java @@ -0,0 +1,23 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandsuicide extends EssentialsCommand +{ + public Commandsuicide() + { + super("suicide"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + user.setHealth(0); + user.sendMessage("§cGoodbye Cruel World..."); + server.broadcastMessage("§7" + user.getDisplayName() + " took their own life" ); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtime.java b/Essentials/src/com/earth2me/essentials/commands/Commandtime.java new file mode 100644 index 000000000..63e565de8 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtime.java @@ -0,0 +1,63 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtime extends EssentialsCommand +{ + public Commandtime() + { + super("time"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + World world = user.getWorld(); + long time = world.getTime(); + time = time - time % 24000; + if (args.length < 1) + { + user.sendMessage("§cUsage: /time [day|night]"); + return; + } + if ("day".equalsIgnoreCase(args[0])) + { + user.charge(this); + world.setTime(time + 24000); + return; + } + if ("night".equalsIgnoreCase(args[0])) + { + user.charge(this); + world.setTime(time + 37700); + return; + } + throw new Exception("/time only supports day/night."); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + for (World world : server.getWorlds()) + { + long time = world.getTime(); + time = time - time % 24000; + if (args.length < 1) + { + sender.sendMessage("Usage: /time [day|night]"); + return; + } + + if ("day".equalsIgnoreCase(args[0])) world.setTime(time + 24000); + else if ("night".equalsIgnoreCase(args[0])) world.setTime(time + 37700); + else throw new Exception("/time only supports day/night."); + } + + sender.sendMessage("Time set in all worlds."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java b/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java new file mode 100644 index 000000000..f6d399a0d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java @@ -0,0 +1,67 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtogglejail extends EssentialsCommand +{ + public Commandtogglejail() + { + super("togglejail"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1 || args.length > 2) + { + sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]"); + return; + } + + User p; + try + { + p = User.get(server.matchPlayer(args[0]).get(0)); + } + catch (Exception ex) + { + sender.sendMessage("§cThat player does not exist."); + return; + } + + if (p.isOp() || p.isAuthorized("essentials.jail.exempt")) + { + sender.sendMessage("§cYou may not jail that person"); + return; + } + + if (args.length == 2 && !p.isJailed()) { + User.charge(sender, this); + sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed.")); + p.sendMessage("§7You have been jailed"); + Essentials.getJail().sendToJail(p, args[1]); + p.currentJail = (args[1]); + return; + } + + if (args.length == 2 && p.isJailed() && !args[1].equalsIgnoreCase(p.currentJail)) { + sender.sendMessage("§cPerson is already in jail "+ p.currentJail); + return; + } + + if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase(p.currentJail))) { + if (!p.isJailed()) { + sender.sendMessage("Usage: /" + commandLabel + " [player] [jailname]"); + return; + } + sender.sendMessage("§7Player " + p.getName() + " " + (p.toggleJailed() ? "jailed." : "unjailed.")); + p.sendMessage("§7You have been released"); + p.teleportBack(); + p.currentJail = ""; + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtop.java b/Essentials/src/com/earth2me/essentials/commands/Commandtop.java new file mode 100644 index 000000000..a928701a2 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtop.java @@ -0,0 +1,26 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Location; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtop extends EssentialsCommand +{ + public Commandtop() + { + super("top"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + int topX = user.getLocation().getBlockX(); + int topZ = user.getLocation().getBlockZ(); + int topY = user.getWorld().getHighestBlockYAt(topX, topZ); + user.charge(this); + user.teleport(new Location(user.getWorld(), user.getLocation().getX(), topY + 1, user.getLocation().getZ()), this.getName()); + user.sendMessage("§7Teleporting to top."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtp.java b/Essentials/src/com/earth2me/essentials/commands/Commandtp.java new file mode 100644 index 000000000..a36a7e415 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtp.java @@ -0,0 +1,61 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.command.CommandSender; + + +public class Commandtp extends EssentialsCommand +{ + public Commandtp() + { + super("tp"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + switch (args.length) + { + case 0: + user.sendMessage("§cUsage: /" + commandLabel + " [to-player]"); + return; + + case 1: + User p = getPlayer(server, args, 0); + user.teleportCooldown(); + if (!p.isTeleEnabled()) throw new Exception(p.getDisplayName() + " has teleportation disabled."); + user.sendMessage("§7Teleporting..."); + user.canAfford(this); + user.teleport(p, this.getName()); + break; + + case 2: + if (!user.isAuthorized("essentials.tpohere")) throw new Exception("You need access to /tpohere to teleport other players."); + user.sendMessage("§7Teleporting..."); + user.charge(this); + User target = getPlayer(server, args, 0); + User toPlayer = getPlayer(server, args, 1); + target.teleportToNow(toPlayer); + target.sendMessage("§7" + user.getDisplayName() + "§7 teleported you to " + toPlayer.getDisplayName() + "§7."); + break; + } + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 2) + { + sender.sendMessage("Usage: /" + commandLabel + " [target] [to-player]"); + return; + } + + sender.sendMessage("§7Teleporting..."); + User target = getPlayer(server, args, 0); + User toPlayer = getPlayer(server, args, 1); + target.teleportToNow(toPlayer); + target.sendMessage("§7{Console}§7 teleported you to " + toPlayer.getDisplayName() + "§7."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java new file mode 100644 index 000000000..491c4363e --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java @@ -0,0 +1,34 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtpa extends EssentialsCommand +{ + public Commandtpa() + { + super("tpa"); + } + + @Override + public void run(Server server, Essentials parent, User player, String commandLabel, String[] args) throws Exception + { + if(args.length < 1) + { + player.sendMessage("§cUsage: /tpa [playername]"); + return; + } + + User p = getPlayer(server, args, 0); + if (!p.isTeleEnabled()) throw new Exception(p.getDisplayName() + " has teleportation disabled."); + player.charge(this); + parent.tpcRequests.put(p, player); + parent.tpcHere.put(p, false); + p.sendMessage("§c" + player.getDisplayName() + "§c has requested to teleport to you."); + p.sendMessage("§7To teleport, type §c/tpaccept§7."); + p.sendMessage("§7To deny this request, type §c/tpdeny§7."); + player.sendMessage("§7Request sent to " + p.getDisplayName() + "§7."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java new file mode 100644 index 000000000..84acdf82c --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java @@ -0,0 +1,40 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.earth2me.essentials.commands.EssentialsCommand; + + +public class Commandtpaccept extends EssentialsCommand +{ + public Commandtpaccept() + { + super("tpaccept"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + + User p = parent.tpcRequests.get(user); + if (p == null) throw new Exception("You do not have a pending request."); + parent.tpcRequests.remove(user); + + if (parent.tpcHere.get(user)) + { + user.teleportCooldown(); + user.canAfford(this); + user.sendMessage("§7Teleport request accepted."); + p.sendMessage("§7Teleport request accepted."); + user.teleport(p, this.getName()); + } + else + { + user.canAfford(this); + user.sendMessage("§7Teleport request accepted."); + p.sendMessage("§7Teleport request accepted."); + p.teleport(user, this.getName()); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java new file mode 100644 index 000000000..bf179cc59 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java @@ -0,0 +1,33 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtpahere extends EssentialsCommand +{ + public Commandtpahere() + { + super("tpahere"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§cUsage: /tpahere [playername]"); + return; + } + + User p = getPlayer(server, args, 0); + if (!p.isTeleEnabled()) throw new Exception(p.getDisplayName() + " has teleportation disabled."); + user.charge(this); + parent.tpcRequests.put(p, user); + parent.tpcHere.put(p, true); + p.sendMessage("§c" + user.getDisplayName() + "§c has requested that you teleport to him/her."); + p.sendMessage("§7To teleport, type §c/tpaccept§7."); + user.sendMessage("§7Request sent to " + p.getDisplayName() + "§c."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java new file mode 100644 index 000000000..6ed5fc8dc --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java @@ -0,0 +1,37 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtpdeny extends EssentialsCommand +{ + public Commandtpdeny() + { + super("tpdeny"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + User p = parent.tpcRequests.get(user); + if (p == null) throw new Exception("You do not have a pending request."); + parent.tpcRequests.remove(user); + + if (parent.tpcHere.get(user)) + { + user.charge(this); + user.sendMessage("§7Teleport request denied."); + p.sendMessage("§7Teleport request denied."); + parent.tpcHere.remove(user); + } + else + { + user.charge(this); + user.sendMessage("§7Teleport request denied."); + p.sendMessage("§7Teleport request denied."); + parent.tpcRequests.remove(user); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java new file mode 100644 index 000000000..3a003b257 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java @@ -0,0 +1,34 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtphere extends EssentialsCommand +{ + public Commandtphere() + { + super("tphere"); + } + + @Override + public String[] getTriggers() + { + return new String[] + { + getName(), "telehere", "s" + }; + } + + @Override + public void run(Server server, Essentials parent, User player, String commandLabel, String[] args) throws Exception + { + User p = getPlayer(server, args, 0); + if (!p.isTeleEnabled()) throw new Exception(p.getDisplayName() + " has teleportation disabled."); + player.charge(this); + p.teleportTo(player); + player.sendMessage("§7Teleporting..."); + p.sendMessage("§7Teleporting..."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java new file mode 100644 index 000000000..f3fa6900c --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java @@ -0,0 +1,34 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.earth2me.essentials.commands.EssentialsCommand; + + +public class Commandtpo extends EssentialsCommand +{ + public Commandtpo() + { + super("tpo"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§c Usage: /tpo [playername]"); + } + else + { + //Just basically the old tp command + User p = getPlayer(server, args, 0); + user.teleportCooldown(); + user.charge(this); + user.teleportToNow(p); + user.sendMessage("§7Teleporting..."); + } + + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java new file mode 100644 index 000000000..082f49452 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java @@ -0,0 +1,31 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtpohere extends EssentialsCommand +{ + public Commandtpohere() + { + super("tpohere"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.sendMessage("§c Usage: /tpohere [playername]"); + } + else + { + //Just basically the old tphere command + User p = getPlayer(server, args, 0); + user.charge(this); + p.teleportToNow(user); + user.sendMessage("§7Teleporting..."); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java b/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java new file mode 100644 index 000000000..031735e9a --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java @@ -0,0 +1,42 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Location; +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtppos extends EssentialsCommand +{ + public Commandtppos() + { + super("tppos"); + } + + @Override + public String[] getTriggers() + { + return new String[] + { + getName(), "tpp" + }; + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + if (args.length < 3) + { + user.sendMessage("§cUsage: /tppos [x] [y] [z]"); + return; + } + int x = Integer.parseInt(args[0]); + int y = Integer.parseInt(args[1]); + int z = Integer.parseInt(args[2]); + Location l = new Location(user.getWorld(),x,y,z); + user.canAfford(this); + user.teleportCooldown(); + user.sendMessage("§7Teleporting..."); + user.teleport(user.getSafeDestination(l), this.getName()); + } +} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java b/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java new file mode 100644 index 000000000..7e93cc4cf --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java @@ -0,0 +1,21 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandtptoggle extends EssentialsCommand +{ + public Commandtptoggle() + { + super("tptoggle"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + user.sendMessage("§7Teleportation " + (user.toggleTeleEnabled() ? "enabled." : "disabled.")); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtree.java b/Essentials/src/com/earth2me/essentials/commands/Commandtree.java new file mode 100644 index 000000000..27ce617c9 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtree.java @@ -0,0 +1,64 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.TreeType; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + +public class Commandtree extends EssentialsCommand +{ + public Commandtree() + { + super("tree"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + Object tree = new Object(); + if (args.length < 1) + { + user.sendMessage("§cUsage: /tree [tree|birch|redwood]"); + return; + } + else if (args[0].equalsIgnoreCase("birch")) + { + tree = TreeType.BIRCH; + } + else if (args[0].equalsIgnoreCase("redwood")) + { + tree = TreeType.REDWOOD; + } + else if (args[0].equalsIgnoreCase("tree")) + { + tree = TreeType.TREE; + } + else + { + user.sendMessage("§cUsage: /tree [tree|birch|redwood]"); + return; + } + + double x = user.getLocation().getX(); + double y = user.getLocation().getY(); + double z = user.getLocation().getZ(); + + // offset tree in direction player is facing + int r = (int)user.getCorrectedYaw(); + if (r < 68 || r > 292) x -= 3.0D; // north + else if (r > 112 && r < 248) x += 3.0D; // south + if (r > 22 && r < 158) z -= 3.0D; // east + else if (r > 202 && r < 338) z += 3.0D; // west + + Location safeLocation = user.getSafeDestination(new Location(user.getWorld(), x, y, z)); + boolean success = user.getWorld().generateTree(safeLocation, (TreeType)tree); + if (success) + { + user.charge(this); + user.sendMessage("§7Tree spawned."); + } + else + user.sendMessage("§cTree generation failure. Try again on grass or dirt."); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunban.java b/Essentials/src/com/earth2me/essentials/commands/Commandunban.java new file mode 100644 index 000000000..55fd54fad --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandunban.java @@ -0,0 +1,35 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import org.bukkit.craftbukkit.CraftServer; +import com.earth2me.essentials.Essentials; + + +public class Commandunban extends EssentialsCommand +{ + public Commandunban() + { + super("unban"); + } + + @Override + public String[] getTriggers() + { + return new String[] { getName(), "pardon" }; + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("Usage: /" + commandLabel + " [player]"); + return; + } + + ((CraftServer)server).getHandle().c.f.b(args[0]); + sender.sendMessage("Unbanned player."); + Essentials.getStatic().loadBanList(); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java b/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java new file mode 100644 index 000000000..df152c23f --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java @@ -0,0 +1,35 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import org.bukkit.craftbukkit.CraftServer; +import com.earth2me.essentials.Essentials; + + +public class Commandunbanip extends EssentialsCommand +{ + public Commandunbanip() + { + super("unbanip"); + } + + @Override + public String[] getTriggers() + { + return new String[] { getName(), "pardonip" }; + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("Usage: /" + commandLabel + " [address]"); + return; + } + + ((CraftServer)server).getHandle().c.f.d(args[0]); + sender.sendMessage("Unbanned IP address."); + Essentials.getStatic().loadBanList(); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java new file mode 100644 index 000000000..c5471f831 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java @@ -0,0 +1,74 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.earth2me.essentials.Warps; + + +public class Commandwarp extends EssentialsCommand +{ + public Commandwarp() + { + super("warp"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + boolean perWarpPermission = Essentials.getSettings().getPerWarpPermission(); + if (args.length == 0) { + if (!user.isAuthorized("essentials.warp.list")) + { + user.sendMessage("§cYou do not have Permission to list that warps."); + return; + } + + Warps warps = Essentials.getWarps(); + if (warps.isEmpty()) { + throw new Exception("No warps defined"); + } + StringBuilder sb = new StringBuilder(); + int i = 0; + for (String warpName : warps.getWarpNames()) + { + if (perWarpPermission) + { + if (user.isAuthorized("essentials.warp." + warpName)) + { + if (i++ > 0) sb.append(", "); + sb.append(warpName); + } + } + else + { + if (i++ > 0) sb.append(", "); + sb.append(warpName); + } + + } + user.sendMessage(sb.toString()); + return; + } + + try { + if (perWarpPermission) + { + if (user.isAuthorized("essentials.warp." + args[0])) + { + user.canAfford(this); + user.teleportCooldown(); + user.warpTo(args[0], this.getName()); + return; + } + user.sendMessage("§cYou do not have Permission to use that warp."); + return; + } + user.canAfford(this); + user.teleportCooldown(); + user.warpTo(args[0], this.getName()); + } catch (Exception ex) { + user.sendMessage(ex.getMessage()); + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java b/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java new file mode 100644 index 000000000..508e69a58 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java @@ -0,0 +1,44 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; +import org.bukkit.ChatColor; + + +public class Commandwhois extends EssentialsCommand +{ + public Commandwhois() + { + super("whois"); + } + + @Override + public void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + sender.sendMessage("§cUsage: /whois [nickname]"); + return; + } + String whois = args[0].toLowerCase(); + User.charge(sender, this); + int prefixLength = ChatColor.stripColor(Essentials.getSettings().getNicknamePrefix()).length(); + for (Player p : server.getOnlinePlayers()) + { + User u = User.get(p); + String dn = ChatColor.stripColor(u.getNick()); + if (!whois.equalsIgnoreCase(dn) && !whois.equalsIgnoreCase(dn.substring(prefixLength)) && !whois.equalsIgnoreCase(u.getName())) continue; + sender.sendMessage(""); + sender.sendMessage(u.getDisplayName() + " is " + u.getName()); + sender.sendMessage(ChatColor.BLUE + " - Health: " + u.getHealth() + "/20"); + sender.sendMessage(ChatColor.BLUE + " - Location: (" + u.getLocation().getBlockX() + ", " + u.getLocation().getBlockY() + ", " + u.getLocation().getBlockZ() + ")"); + if (!parent.getConfiguration().getBoolean("disable-eco", false)) sender.sendMessage(ChatColor.BLUE + " - Money: $" + u.getMoney()); + sender.sendMessage(ChatColor.BLUE + " - Status: " + (parent.away.contains(u) ? "§cAway" : "Available")); + sender.sendMessage(ChatColor.BLUE + " - IP Address: " + u.getAddress().getAddress().toString()); + + } + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandworld.java b/Essentials/src/com/earth2me/essentials/commands/Commandworld.java new file mode 100644 index 000000000..8f3ad45e7 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandworld.java @@ -0,0 +1,67 @@ +package com.earth2me.essentials.commands; + +import java.util.List; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.World; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; + + +public class Commandworld extends EssentialsCommand +{ + public Commandworld() + { + super("world"); + } + + @Override + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + World world; + List worlds = server.getWorlds(); + + if (args.length < 1) + { + world = worlds.get(user.getWorld() == worlds.get(0) && worlds.size() > 1 ? 1 : 0); + } + else + { + try + { + int wid = Integer.parseInt(args[0]); + world = server.getWorlds().get(wid); + } + catch (Throwable ex) + { + try + { + world = server.getWorld(getFinalArg(args, 0)); + if (world == null) throw new Exception(); + } + catch (Throwable ex2) + { + user.sendMessage("§cInvalid world."); + user.sendMessage("§7Possible worlds are the numbers 0 through " + (server.getWorlds().size() - 1) + "."); + user.sendMessage("§7You can also type the name of a specific world."); + return; + } + } + } + + double factor; + if (user.getWorld().getEnvironment() == World.Environment.NETHER && world.getEnvironment() == World.Environment.NORMAL) + factor = 16; + else if (user.getWorld().getEnvironment() != world.getEnvironment()) + factor = 1 / 16; + else + factor = 1; + + Location loc = user.getLocation(); + loc = new Location(world, loc.getBlockX() * factor + .5, loc.getBlockY(), loc.getBlockZ() * factor + .5); + + user.canAfford(this); + user.teleportCooldown(); + user.teleport(loc, this.getName()); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandworth.java b/Essentials/src/com/earth2me/essentials/commands/Commandworth.java new file mode 100644 index 000000000..0933ef4a2 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/Commandworth.java @@ -0,0 +1,48 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.ItemDb; +import com.earth2me.essentials.User; +import com.earth2me.essentials.commands.EssentialsCommand; +import org.bukkit.inventory.ItemStack; + + +public class Commandworth extends EssentialsCommand +{ + public Commandworth() + { + super("worth"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + ItemStack is = user.getInventory().getItemInHand(); + int id = is.getTypeId(); + int amount = is.getAmount(); + + try + { + if (args.length > 0) id = Integer.parseInt(args[0]); + } + catch (NumberFormatException ex) + { + id = ItemDb.get(args[0]).getTypeId(); + } + + try + { + if (args.length > 1) amount = Integer.parseInt(args[1]); + } + catch (NumberFormatException ex) + { + amount = 64; + } + + int worth = parent.getConfiguration().getInt("worth-" + id, 0); + + user.charge(this); + user.sendMessage("§7Stack of " + id + " worth §c$" + (worth * amount) + "§7 (" + amount + " item(s) at $" + worth + " each)"); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java new file mode 100644 index 000000000..782f48287 --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java @@ -0,0 +1,80 @@ +package com.earth2me.essentials.commands; + +import java.util.List; +import org.bukkit.Server; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.Essentials; +import org.bukkit.entity.Player; +import com.earth2me.essentials.User; + + +public abstract class EssentialsCommand implements IEssentialsCommand +{ + private final String name; + + protected EssentialsCommand(String name) + { + this.name = name; + } + + public String getName() + { + return name; + } + + public String[] getTriggers() + { + return new String[] + { + getName() + }; + } + + protected User getPlayer(Server server, String[] args, int pos) throws IndexOutOfBoundsException, NoSuchFieldException + { + if (args.length <= pos) throw new IndexOutOfBoundsException("§cInvalid command syntax. Did you forget an argument?"); + List matches = server.matchPlayer(args[pos]); + if (matches.size() < 1) throw new NoSuchFieldException("§cNo matching players could be found."); + return User.get(matches.get(0)); + } + + @Override + public final void run(Server server, Essentials parent, User user, String commandLabel, Command cmd, String[] args) throws Exception + { + run(server, parent, user, commandLabel, args); + } + + protected void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + run(server, parent, (CommandSender)user.getBase(), commandLabel, args); + } + + @Override + public final void run(Server server, Essentials parent, CommandSender sender, String commandLabel, Command cmd, String[] args) throws Exception + { + run(server, parent, sender, commandLabel, args); + } + + protected void run(Server server, Essentials parent, CommandSender sender, String commandLabel, String[] args) throws Exception + { + throw new Exception("Only in-game players can use " + commandLabel + "."); + } + + public static String getFinalArg(String[] args, int start) + { + StringBuilder bldr = new StringBuilder(); + for (int i = start; i < args.length; i++) + { + if (i != start) bldr.append(" "); + bldr.append(args[i]); + } + return bldr.toString(); + } + + protected void charge(CommandSender sender) throws Exception + { + if (sender instanceof Player) + User.get((Player)sender).charge(this); + } +} diff --git a/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java b/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java new file mode 100644 index 000000000..d1debd29d --- /dev/null +++ b/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java @@ -0,0 +1,20 @@ +package com.earth2me.essentials.commands; + +import org.bukkit.*; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import com.earth2me.essentials.*; + + +public interface IEssentialsCommand +{ + String getName(); + + String[] getTriggers(); + + void run(Server server, Essentials parent, User user, String commandLabel, Command cmd, String[] args) + throws Exception; + + void run(Server server, Essentials parent, CommandSender sender, String commandLabel, Command cmd, String[] args) + throws Exception; +} diff --git a/Essentials/src/config.yml b/Essentials/src/config.yml new file mode 100644 index 000000000..7da7426f6 --- /dev/null +++ b/Essentials/src/config.yml @@ -0,0 +1,385 @@ +############################################################ +# +------------------------------------------------------+ # +# | Notes | # +# +------------------------------------------------------+ # +############################################################ + +# If you want to use special characters in this document, such as accented letters, you MUST save the file as UTF-8, not ANSI. +# If you receive an error when Essentials loads, ensure that: +# - No tabs are present: YAML only allows spaces +# - Indents are correct: YAML heirarchy is based entirely on indentation +# - You have "escaped" all apostrophes in your text: If you want to write "don't", for example, write "don''t" instead (note the doubled apostrphe) +# - List items are prefixed with a hyphen and indented: +# lists: +# - look like this +# not: +# - like this +# - Text with symbols is enclosed in single or double quotation marks +# - CraftBukkit and Permissions have been updated: CraftBukkit and Essentials almost always line up, but sometimes other plugins fall behind CraftBukkit's multiple daily updates +# - You have saved the document as UTF-8, NOT the default, ANSI + + + + + +############################################################ +# +------------------------------------------------------+ # +# | Essentials (Global) | # +# +------------------------------------------------------+ # +############################################################ + +# A color code between 0-9 or a-f. Set to 'none' to disable. +ops-name-color: 'c' + +# The character(s) to prefix all nicknames, so that you know they are not true usernames. +nickname-prefix: '~' + +# The delay, in seconds, required between /home, /tp, etc. +teleport-cooldown: 0 + +# The delay, in seconds, before a user actually teleports. If the user moves or gets attacked in this timeframe, the teleport never occurs. +teleport-delay: 0 + +# The delay, in seconds, required between /heal attempts +heal-cooldown: 60 + +# The number of items given if the quantity parameter is left out in /item or /give. +default-stack-size: 64 + +#what to prevent from /i /give +#e.g item-spawn-blacklist: 46,11,10 +item-spawn-blacklist: + +# Whether or not to reclaim memory on player logout; this is technical, and should only be changed under special circumstances. +# This generally increases server stability unless very specific runtime configurations are used. +# HOWEVER, it is known to cause lag upon users logging OUT, so beware! +reclaim-onlogout: false + +# Should primitive spawn protection be enabled? For most servers, this should be flase; it is better to use a third-party plugin to protect it. +spawn-protection: false + +# Nether settings (switch between worlds with "/world nether" and "/world normal") +# Sets whether the nether system is enabled, what folder to save the world in, and whether portals should teleport players between worlds. +nether: + enabled: false + folder: nether + portals-enabled: false + generate-exit-portals: false + +# Mob limit on spawnmob +spawnmob-limit: 10 + +# The message of the day, displayed on connect and by typing /motd. +motd: + - '&cWelcome, {PLAYER}&c!' + - '&fType &c/help&f for a list of commands.' + - 'Currently online: {PLAYERLIST}' + +# The server rules, available by typing /rules +rules: + - '[1] Be respectful' + - '[2] Be ethical' + - '[3] Use common sense' + +# Disabled commands will be completelly unavailable on the server. +disabled-commands: +# - nick + +# Restricted commands will only be available to ops. +# These will have NO EFFECT if you have Permissions installed! +# These are here only if you want something simpler than Permissions. +restricted-commands: + - bigtree + - item + - give + - heal + - plugin + - time + - top + - tp + - tphere + - tree + - setspawn + - antioch + - kick + - ban + - unban + - top + - jump + - tpo + - tppos + - tpohere + - economy + - setwarp + - delwarp + - essentials + - gc + - spawnmob + - broadcast + - burn + - ext + - kill + - ping + - banip + - unban + - mute + - kick + - kickall + - unbanip + - togglejail + - setjail + +# Note: All items MUST be followed by a quantity! +# Times are measured in seconds. +kits: + tools: + delay: 10 + items: + - 277 1 + - 278 1 + - 279 1 + +# Disable all signs +signs-disabled: false + +# Backup runs a command while saving is disabled +backup: + # Interval in minutes + interval: 60 + # Add a command that backups your data, e.g. + # command: 'rdiff-backup World1 backups/World1' + +# Set this true to enable permission per warp. +per-warp-permission: false + +# Sort output of /list command by groups +sort-list-by-groups: false + +############################################################ +# +------------------------------------------------------+ # +# | EssentialsHome | # +# +------------------------------------------------------+ # +############################################################ + +# When users die, should they respawn at their homes, instead of the spawnpoint? +respawn-at-home: false + +# When a user interacts with a bed, should their home be set to that location? +# If you enable this and remove default user access to the /sethome command, you can make beds the only way for players to set their home location. +bed-sethome: false + + + + +############################################################ +# +------------------------------------------------------+ # +# | EssentialsEco | # +# +------------------------------------------------------+ # +############################################################ + +# Defines the balance with which new players begin. Defaults to 0. +starting-balance: 0 + +# worth-# defines the value of an item when it is sold to the server via /sell. +#worth-1: 1 +#worth-278: 1000 + +# Defines the cost to use the given commands PER USE +command-costs: + # /example costs $1000 PER USE + #example: 1000 + # /kit tools costs $1500 PER USE + # kit-tools: 1500 + + + + + +############################################################ +# +------------------------------------------------------+ # +# | EssentialsHelp | # +# +------------------------------------------------------+ # +############################################################ + +#Show other plugins commands in help +non-ess-in-help: true + + + + + +############################################################ +# +------------------------------------------------------+ # +# | EssentialsServerlist | # +# +------------------------------------------------------+ # +############################################################ + +# This is your server's mcserverlist.net API key. Register your server at mcserverlist.net if you haven't already. +mcsl-key: '' + + + + + +############################################################ +# +------------------------------------------------------+ # +# | EssentialsChat | # +# +------------------------------------------------------+ # +############################################################ + +# If EssentialsChat is installed, this will define how far a player's voice travels, in blocks. Set to 0 to make all chat global. +# Note that users with the "essentials.chat.spy" permission will hear everything, regardless of this setting. +# Users with essentials.chat.shout can override this by prefixing text with an exclamation mark (!) +# Or with essentials.chat.question can override this by prefixing text with a question mark (?) +chat: + radius: 0 + + # If you want the default chat format, uncomment the next line and comment the other format. + #format: '<{DISPLAYNAME}> {MESSAGE}' + format: '&7[{GROUP}]&f {DISPLAYNAME}&7:&f {MESSAGE}' + + # You can also have group-specific formats: + group-formats: + Default: '{WORLDNAME} {DISPLAYNAME}&7:&f {MESSAGE}' + Admins: '{WORLDNAME} &c[{GROUP}]&f {DISPLAYNAME}&7:&c {MESSAGE}' + + + + + +############################################################ +# +------------------------------------------------------+ # +# | EssentialsProtect | # +# +------------------------------------------------------+ # +############################################################ + +protect: + # Database settings for sign/rail protection + # get mysql.jar and sqlite and place it in your serverroot/lib directory from here: + # http://java.net/projects/essentials/sources/svn/show/lib?rev=435 + + # mysql, sqlite or none + datatype: 'sqlite' + + # If you specified MySQL above, you MUST enter the appropriate details here. + # If you specified SQLite above, these will be IGNORED. + username: 'root' + password: 'root' + mysqlDb: 'jdbc:mysql://localhost:3306/minecraft' + + # For which block types would you like to be alerted? + # You can find a list of IDs in plugins/Essentials/Items.csv after loading Essentials for the first time. + alert: + # 10: lava + # 11: still lava + # 46: TNT + on-placement: 10,11,46 + # 1: rock (just an example--doesn't actually do much) + on-use: 1 + # 46: TNT + on-break: 46 + + # Users cannot PLACE these types of blocks/items. + # < 255 designates a BLOCK + # > 255 designates an ITEM (Some blocks can be placed as blocks OR items; lava blocks can be placed by lava buckets, for example.) + blacklist: + placement: 327,326,14,56,46,11,10,9,8 + usage: 327,326,325 + + #prevent people from breaking blocks + #break: 20,50 + break: + + + # General physics/behavior modifications + prevent: + lava-flow: false + water-flow: false + water-bucket-flow: false + fire-spread: false + lava-fire-spread: false + flint-fire: false + tnt-explosion: false + creeper-explosion: false + creeper-playerdamage: false + creeper-blockdamage: false + # Prevent the spawning of creatures + spawn: + creeper: false + ghast: true + slime: true + + # Maximum height the creeper should explode. -1 allows them to explode everywhere. + # Set prevent.creeper-explosion to true, if you want to disable creeper explosions. + creeper: + max-height: -1 + + # Protect various blocks. + protect: + # Protect all signs + signs: true + + # Prevent users from destroying rails + rails: true + + # Blocks below rails/signs are also protected if the respective rail/sign is protected. + # This makes it more difficult to circumvent protection, and should be enabled. + # This only has an effect if "rails" or "signs" is also enabled. + block-below: true + + # Prevent placing blocks above protected rails, this is to stop a potential griefing + prevent-block-on-rails: false + + # Disable various default physics and behaviors + disable: + # Should fall damage be disabled? + fall: false + + # Users with the essentials.protect.pvp permission will still be able to attack each other if this is set to true. + # They will be unable to attack users without that same permission node. + pvp: false + + # Should drowning damage be disabled? + # (Split into two behaviors; generally, you want both set to the same value) + drown: false + suffocate: false + + # Should damage via lava be disabled? Items that fall into lava will still burn to a crisp. ;) + lavadmg: false + + # Should arrow damage be disabled + projectiles: false + + # This will disable damage from touching cacti. + contactdmg: false + + # Burn, baby, burn! Should fire damage be disabled? + firedmg: false + + # Should people with build: false in permissions be allowed to build + # Set true to disable building for those people + build: false + + + + + + + +############################################################ +# +------------------------------------------------------+ # +# | New Players | # +# +------------------------------------------------------+ # +############################################################ + +newbies: + # Should we announce to the server when someone logs in for the first time? + # If so, use this format, replacing {DISPLAYNAME} with the player name. + # If not, set to '' + #announce-format: '' + announce-format: '&dWelcome {DISPLAYNAME} to the server!' + + # When we spawn for the first time, which spawnpoint do we use? + spawnpoint: newbies + +# End of File <-- No seriously, you're done with configuration. \ No newline at end of file diff --git a/Essentials/src/items.csv b/Essentials/src/items.csv new file mode 100644 index 000000000..3bf204167 --- /dev/null +++ b/Essentials/src/items.csv @@ -0,0 +1,887 @@ +#item,id,metadata +air,0,0 +stone,1,0 +rock,1,0 +grass,2,0 +dirt,3,0 +cobblestone,4,0 +cstone,4,0 +cobble,4,0 +plank,5,0 +woodplank,5,0 +wplank,5,0 +sapling,6,0 +bedrock,7,0 +admin,7,0 +adminium,7,0 +water,8,0 +stationarywater,9,0 +swater,9,0 +lava,10,0 +stationarylava,11,0 +slava,11,0 +sand,12,0 +gravel,13,0 +goldore,14,0 +gore,14,0 +ironore,15,0 +iore,15,0 +coalore,16,0 +core,16,0 +log,17,0 +trunk,17,0 +wood,17,0 +redwood,5,1 +rwood,5,1 +birchwood,5,2 +birch,5,2 +bwood,5,2 +leaves,18,0 +sponge,19,0 +glass,20,0 +lapislazuliore,21,0 +lapisore,21,0 +lore,21,0 +lapislazuliblock,22,0 +lapisblock,22,0 +lblock,22,0 +dispenser,23,0 +dispense,23,0 +sandstone,24,0 +sstone,24,0 +noteblock,25,0 +musicblock,25,0 +nblock,25,0 +mblock,25,0 +bedblock,26,0 +whitecloth,35,0 +cloth,35,0 +whitewool,35,0 +wool,35,0 +whitecotton,35,0 +cotton,35,0 +orangecloth,35,1 +orangewool,35,1 +orangecotton,35,1 +magentacloth,35,2 +magentawool,35,2 +magantacotton,35,2 +lightbluecloth,35,3 +lightbluewool,35,3 +lightbluecotton,35,3 +lbluecloth,35,3 +lbluewool,35,3 +lbluecotton,35,3 +yellowcloth,35,4 +yellowwool,35,4 +yellowcotton,35,4 +lightgreencloth,35,5 +lightgreenwool,35,5 +lightgreencotton,35,5 +lgreencloth,35,5 +lgreenwool,35,5 +lgreencotton,35,5 +pinkcloth,35,6 +pinkwool,35,6 +pinkcotton,35,6 +graycloth,35,7 +graywool,35,7 +graycotton,35,7 +lightgraycloth,35,8 +lightgraywool,35,8 +lightgraycotton,35,8 +lgraycloth,35,8 +lgraywool,35,8 +lgraycotton,35,8 +cyancloth,35,9 +cyanwool,35,9 +cyancotton,35,9 +purplecloth,35,10 +purplewool,35,10 +purplecotton,35,10 +bluecloth,35,11 +bluewool,35,11 +bluecotton,35,11 +browncloth,35,12 +brownwool,35,12 +browncotton,35,12 +darkgreencloth,35,13 +darkgreenwool,35,13 +darkgreencotton,35,13 +dgreencloth,35,13 +dgreenwool,35,13 +dgreencotton,35,13 +greencloth,35,13 +greenwool,35,13 +greencotton,35,13 +redcloth,35,14 +redwool,35,14 +redcotton,35,14 +blackcloth,35,15 +blackwool,35,15 +blackcotton,35,15 +yellowflower,37,0 +yflower,37,0 +flower,37,0 +redrose,38,0 +rrose,38,0 +redflower,38,0 +rflower,38,0 +brownmushroom,39,0 +brownmush,39,0 +bmushroom,39,0 +bmush,39,0 +redmushroom,40,0 +redmush,40,0 +rmushroom,40,0 +rmush,40,0 +goldblock,41,0 +gblock,41,0 +ironblock,42,0 +iblock,42,0 +smoothstonedoublestep,43,0 +stonedoublestep,43,0 +sdoublestep,43,0 +sdstep,43,0 +doublestep,43,0 +step,43,0 +smoothstonedoubleslab,43,0 +stonedoubleslab,43,0 +sdoubleslab,43,0 +sdslab,43,0 +doubleslab,43,0 +slab,43,0 +sanddstonedoublestep,43,1 +sstonedoublestep,43,1 +ssdoublestep,43,1 +ssdstep,43,1 +sanddstonedoubleslab,43,1 +sstonedoubleslab,43,1 +ssdoubleslab,43,1 +ssdslab,43,1 +woodplankdoublestep,43,2 +wplankdoublestep,43,2 +plankdoublestep,43,2 +wpdoublestep,43,2 +pdoublestep,43,2 +wpdstep,43,2 +pdstep,43,2 +woodplankdoubleslab,43,2 +wplankdoubleslab,43,2 +plankdoubleslab,43,2 +wpdoubleslab,43,2 +pdoubleslab,43,2 +wpdslab,43,2 +pdslab,43,2 +cobblestonedoublestep,43,3 +cobbledoublestep,43,3 +cstonedoublestep,43,3 +csdoublestep,43,3 +csdstep,43,3 +cobblestonedoubleslab,43,3 +cobbledoubleslab,43,3 +cstonedoubleslab,43,3 +csdoubleslab,43,3 +csdslab,43,3 +smoothstonestep,44,0 +stonestep,44,0 +sstep,44,0 +step,44,0 +smoothstoneslab,44,0 +stoneslab,44,0 +sslab,44,0 +slab,44,0 +sanddstonestep,44,1 +sstonestep,44,1 +ssstep,44,1 +sanddstoneslab,44,1 +sstoneslab,44,1 +ssslab,44,1 +woodplankstep,44,2 +wplankstep,44,2 +plankstep,44,2 +wpstep,44,2 +pstep,44,2 +woodplankslab,44,2 +wplankslab,44,2 +plankslab,44,2 +wpslab,44,2 +pslab,44,2 +cobblestonestep,44,3 +cobblestep,44,3 +cstonestep,44,3 +csstep,44,3 +cobblestoneslab,44,3 +cobbleslab,44,3 +cstoneslab,44,3 +csslab,44,3 +brickblock,45,0 +bblock,45,0 +tnt,46,0 +bookshelf,47,0 +bookblock,47,0 +mossycobblestone,48,0 +mosscobblestone,48,0 +mcobblestone,48,0 +mossycobble,48,0 +mosscobble,48,0 +mcobble,48,0 +obsidian,49,0 +obsi,49,0 +obby,49,0 +torch,50,0 +fire,51,0 +mobspawner,52,0 +monsterspawner,52,0 +mspawner,52,0 +spawner,52,0 +woodenstairs,53,0 +woodstairs,53,0 +wstairs,53,0 +chest,54,0 +redstonewireblock,55,0 +rstonewireblock,55,0 +redswireblock,55,0 +redwireblock,55,0 +rswireblock,55,0 +rwireblock,55,0 +redstonewire,55,0 +rstonewire,55,0 +redswire,55,0 +redwire,55,0 +rswire,55,0 +rwire,55,0 +diamondore,56,0 +dore,56,0 +diamondblock,57,0 +dblock,57,0 +workbench,58,0 +craftingbench,58,0 +crafterbench,58,0 +craftbench,58,0 +worktable,58,0 +craftingtable,58,0 +craftertable,58,0 +crafttable,58,0 +wbench,58,0 +cbench,58,0 +crops,59,0 +crop,59,0 +soil,60,0 +furnace,61,0 +burningfurnace,62,0 +bfurnace,62,0 +signpost,63,0 +spost,63,0 +woodendoorhalf,64,0 +wooddoorhalf,64,0 +wdoorhalf,64,0 +woodendoorbottom,64,0 +wooddoorbottom,64,0 +wdoorbottom,64,0 +woodendoorblock,64,0 +wooddoorblock,64,0 +wdoorblock,64,0 +ladder,65,0 +minecarttrack,66,0 +minecartrail,66,0 +mcarttrack,66,0 +mcartrail,66,0 +mctrack,66,0 +mcrail,66,0 +track,66,0 +rail,66,0 +cobblestonestairs,67,0 +cstonestairs,67,0 +stonestairs,67,0 +cobblestairs,67,0 +csstairs,67,0 +sstairs,67,0 +cstairs,67,0 +cobblestonestair,67,0 +cstonestair,67,0 +stonestair,67,0 +cobblestair,67,0 +csstair,67,0 +sstair,67,0 +cstair,67,0 +wallsign,68,0 +wsign,68,0 +lever,69,0 +stonepressureplate,70,0 +stonepressplate,70,0 +stonepplate,70,7 +stoneplate,70,0 +splate,70,0 +irondoorhalf,71,0 +idoorhalf,71,0 +irondoorbottom,71,0 +idoorbottom,71,0 +irondoorblock,71,0 +idoorblock,71,0 +woodenpressureplate,72,0 +woodenpressplate,72,0 +woodenpplate,72,0 +woodenplate,72,0 +woodpressureplate,72,0 +woodpressplate,72,0 +woodpplate,72,0 +woodplate,72,0 +wplate,72,0 +redstoneore,73,0 +redsore,73,0 +redore,73,0 +rstoneore,73,0 +rsore,73,0 +glowingredstoneore,74,0 +glowredstoneore,74,0 +gredstoneore,74,0 +glowingrstoneore,74,0 +glowrstoneore,74,0 +grstoneore,74,0 +glowingredsore,74,0 +glowredsore,74,0 +gredsore,74,0 +glowingredore,74,0 +glowredore,74,0 +gredore,74,0 +glowingrsore,74,0 +glowrsore,74,0 +grsore,74,0 +redstonetorchoff,75,0 +rstonetorchoff,75,0 +redstorchoff,75,0 +redtorchoff,75,0 +rstorchoff,75,0 +redstonetorchon,76,0 +redstonetorch,76,0 +rstonetorchon,76,0 +rstonetorch,76,0 +redstorchon,76,0 +redstorch,76,0 +redtorchon,76,0 +redtorch,76,0 +rstorchon,76,0 +rstorch,76,0 +stonebutton,77,0 +sbutton,77,0 +button,77,0 +snowcovering,78,0 +snowcover,78,0 +scover,78,0 +ice,79,0 +snowblock,80,0 +sblock,80,0 +cactus,81,0 +clayblock,82,0 +cblock,82,0 +reedblock,83,0 +rblock,83,0 +jukebox,84,0 +jbox,84,0 +fence,85,0 +pumpkin,86,0 +netherrack,87,0 +netherrock,87,0 +netherstone,87,0 +hellstone,87,0 +nstone,87,0 +hstone,87,0 +soulsand,88,0 +slowsand,88,0 +slowmud,88,0 +ssand,88,0 +smud,88,0 +mud,88,0 +glowingstone,89,0 +glowstone,89,0 +lightstone,89,0 +lstone,89,0 +portal,90,0 +jackolantern,91,0 +pumpkinlantern,91,0 +glowingpumpkin,91,0 +lightpumpkin,91,0 +jpumpkin,91,0 +plantren,91,0 +glowpumpkin,91,0 +gpumpkin,91,0 +lpumpkin,91,0 +cakeblock,92,0 +repeateroff,93,0 +repeatoff,93,0 +delayeroff,93,0 +delayoff,93,0 +dioderoff,93,0 +diodeoff,93,0 +repeateron,94,0 +repeaton,94,0 +delayeron,94,0 +delayon,94,0 +dioderon,94,0 +diodeon,94,0 +ironshovel,256,0 +ironspade,256,0 +ishovel,256,0 +ispade,256,0 +ironpickaxe,257,0 +ironpick,257,0 +ipickaxe,257,0 +ipick,257,0 +ironaxe,258,0 +iaxe,258,0 +flintandsteel,259,0 +lighter,259,0 +apple,260,0 +bow,261,0 +arrow,262,0 +coal,263,0 +diamond,264,0 +ironingot,265,0 +ironbar,265,0 +iingot,265,0 +ibar,265,0 +goldingot,266,0 +goldbar,266,0 +gingot,266,0 +gbar,266,0 +ironsword,267,0 +isword,267,0 +woodensword,268,0 +woodsword,268,0 +wsword,268,0 +woodenshovel,269,0 +woodenspade,269,0 +woodshovel,269,0 +woodspade,269,0 +wshovel,269,0 +wspade,269,0 +woodenpickaxe,270,0 +woodenpick,270,0 +woodpickaxe,270,0 +woodpick,270,0 +wpickaxe,270,0 +wpick,270,0 +woodenaxe,271,0 +woodaxe,271,0 +waxe,271,0 +stonesword,272,0 +ssword,272,0 +stoneshovel,273,0 +stonespade,273,0 +sshovel,273,0 +sspade,273,0 +stonepickaxe,274,0 +stonepick,274,0 +spickaxe,274,0 +spick,274,0 +stoneaxe,275,0 +saxe,275,0 +diamondsword,276,0 +dsword,276,0 +diamondshovel,277,0 +diamondspade,277,0 +dshovel,277,0 +dspade,277,0 +diamondpickaxe,278,0 +diamondpick,278,0 +dpickaxe,278,0 +dpick,278,0 +diamondaxe,279,0 +daxe,279,0 +stick,280,0 +bowl,281,0 +mushroomsoup,282,0 +mrsoup,282,0 +soup,282,0 +goldsword,283,0 +gsword,283,0 +goldshovel,284,0 +goldspade,284,0 +gshovel,284,0 +gspade,284,0 +goldpickaxe,285,0 +goldpick,285,0 +gpickaxe,285,0 +gpick,285,0 +goldaxe,286,0 +gaxe,286,0 +string,287,0 +rope,287,0 +feather,288,0 +gunpowder,289,0 +sulfur,289,0 +woodenhoe,290,0 +woodhoe,290,0 +whoe,290,0 +stonehoe,291,0 +shoe,291,0 +ironhoe,292,0 +ihoe,292,0 +diamondhoe,293,0 +dhoe,293,0 +goldhoe,294,0 +ghoe,294,0 +seeds,295 +seed,295,0 +wheat,296,0 +bread,297,0 +leatherhelmet,298,0 +leatherhelm,298,0 +leatherhat,298,0 +lhelmet,298,0 +lhelm,298,0 +lhat,298,0 +leatherchestplate,299,0 +leatherplatebody,299,0 +leatherplate,299,0 +leathershirt,299,0 +lchestplate,299,0 +lplatebody,299,0 +lplate,299,0 +lshirt,299,0 +leatherleggings,300,0 +leatherlegs,300,0 +leatherpants,300,0 +lleggings,300,0 +llegs,300,0 +lpants,300,0 +leatherboots,301,0 +leathershoes,301,0 +lboots,301,0 +lshoes,301,0 +chainmailhelmet,302,0 +chainmailhelm,302,0 +chainmailhat,302,0 +chainmhelmet,302,0 +chainmhelm,302,0 +chainmhat,302,0 +cmailhelmet,302,0 +cmailhelm,302,0 +cmailhat,302,0 +chainhelmet,302,0 +chainhelm,302,0 +chainhat,302,0 +cmhelmet,302,0 +cmhelm,302,0 +cmhat,302,0 +chelmet,302,0 +chelm,302,0 +chat,302,0 +chainmailchestplate,303,0 +chainmailplatebody,303,0 +chainmailplate,303,0 +chainmailshirt,303,0 +chainmchestplate,303,0 +chainmplatebody,303,0 +chainmplate,303,0 +chainmshirt,303,0 +cmailchestplate,303,0 +cmailplatebody,303,0 +cmailplate,303,0 +cmailshirt,303,0 +chainchestplate,303,0 +chainplatebody,303,0 +chainplate,303,0 +chainshirt,303,0 +cmchestplate,303,0 +cmplatebody,303,0 +cmplate,303,0 +cmshirt,303,0 +clchestplate,303,0 +cplatebody,303,0 +cplate,303,0 +cshirt,303,0 +chainmailleggings,304,0 +chainmaillegs,304,0 +chainmailpants,304,0 +chainmleggings,304,0 +chainmlegs,304,0 +chainmpants,304,0 +cmailleggings,304,0 +cmaillegs,304,0 +cmailpants,304,0 +chainleggings,304,0 +chainlegs,304,0 +chainpants,304,0 +cmleggings,304,0 +cmlegs,304,0 +cmpants,304,0 +cleggings,304,0 +clegs,304,0 +cpants,304,0 +chainmailboots,305,0 +chainmailshoes,305,0 +chainmboots,305,0 +chainmshoes,305,0 +cmailboots,305,0 +cmailshoes,305,0 +chainboots,305,0 +chainshoes,305,0 +cmboots,305,0 +cmshoes,305,0 +cboots,305,0 +cshoes,305,0 +ironhelmet,306,0 +ironhelm,306,0 +ironhat,306,0 +ihelmet,306,0 +ihelm,306,0 +ihat,306,0 +ironchestplate,307,0 +ironplatebody,307,0 +ironplate,307,0 +ironshirt,307,0 +ichestplate,307,0 +iplatebody,307,0 +iplate,307,0 +ishirt,307,0 +ironleggings,308,0 +ironlegs,308,0 +ironpants,308,0 +ileggings,308,0 +ilegs,308,0 +ipants,308,0 +ironboots,309,0 +ironshoes,309,0 +iboots,309,0 +ishoes,309,0 +diamondhelmet,310,0 +diamondhelm,310,0 +diamondhat,310,0 +dhelmet,310,0 +dhelm,310,0 +dhat,310,0 +diamondchestplate,311,0 +diamondplatebody,311,0 +diamondplate,311,0 +diamondshirt,311,0 +dchestplate,311,0 +dplatebody,311,0 +dplate,311,0 +dshirt,311,0 +diamondleggings,312,0 +diamondlegs,312,0 +diamondpants,312,0 +dleggings,312,0 +dlegs,312,0 +dpants,312,0 +diamondboots,313,0 +diamondshoes,313,0 +dboots,313,0 +dshoes,313,0 +goldhelmet,314,0 +goldhelm,314,0 +goldhat,314,0 +ghelmet,314,0 +ghelm,314,0 +ghat,314,0 +goldchestplate,315,0 +goldplatebody,315,0 +goldplate,315,0 +goldshirt,315,0 +gchestplate,315,0 +gplatebody,315,0 +gplateplate,315,0 +gshirt,315,0 +goldleggings,316,0 +goldlegs,316,0 +goldpants,316,0 +gleggings,316,0 +glegs,316,0 +gpants,316,0 +goldboots,317,0 +goldshoes,317,0 +gboots,317,0 +gshoes,317,0 +flint,318,0 +pork,319,0 +rawpork,319,0 +grilledpork,320,0 +cookedpork,320,0 +bacon,320,0 +painting,321,0 +picture,321,0 +goldenapple,322,0 +goldapple,322,0 +gapple,322,0 +sign,323,0 +woodendoor,324,0 +wooddoor,324,0 +wdoor,324,0 +bucket,325,0 +waterbucket,326,0 +wbucket,326,0 +lavabucket,327,0 +lbucket,327,0 +minecart,328,0 +mcart,328,0 +cart,328,0 +saddle,329,0 +irondoor,330,0 +idoor,330,0 +redstone,331,0 +rstone,331,0 +snowball,332,0 +snball,332,0 +boat,333,0 +leather,334,0 +milkbucket,335,0 +mbucket,335,0 +claybrick,336,0 +brick,336,0 +clayball,337,0 +cball,337,0 +clay,337,0 +reeds,338,0 +reed,338,0 +paper,339,0 +papyrus,339,0 +book,340,0 +slimeball,341,0 +slball,341,0 +storageminecart,342,0 +chestminecart,342,0 +storagemcart,342,0 +chestmcart,342,0 +storagecart,342,0 +chestcart,342,0 +sminecart,342,0 +cminecart,342,0 +smcart,342,0 +cmcart,342,0 +scart,342,0 +ccart,342,0 +engineminecart,343,0 +poweredminecart,343,0 +powerminecart,343,0 +furnaceminecart,343,0 +enginemcart,343,0 +poweredmcart,343,0 +powermcart,343,0 +furnacemcart,343,0 +enginecart,343,0 +poweredcart,343,0 +powercart,343,0 +furnacecart,343,0 +eminecart,343,0 +pminecart,343,0 +fminecart,343,0 +emcart,343,0 +pmcart,343,0 +cmcart,343,0 +ecart,343,0 +pcart,343,0 +fcart,343,0 +egg,344,0 +compass,345,0 +fishingrod,346,0 +fishrod,346,0 +frod,346,0 +rod,346,0 +watch,347,0 +clock,347,0 +lightstonedust,348,0 +glowstonedust,348,0 +lsdust,348,0 +gsdust,348,0 +rawfish,349,0 +rfish,349,0 +fish,349,0 +cookedfish,350,0 +cookfish,350,0 +cfish,350,0 +roastedfish,350,0 +roastfish,350,0 +rfish,350,0 +inksack,351,0 +inksac,351,0 +isack,351,0 +isac,351,0 +sack,351,0 +sac,351,0 +blackcolor,351,0 +blackdye,351,0 +rosered,351,1 +redrose,351,1 +redr,351,1 +redcolor,351,1 +reddye,351,1 +cactusgreen,351,2 +greencactus,351,2 +greencolor,351,2 +greendye,351,2 +cocobeans,351,3 +cocobean,351,3 +cbeans,351,3 +cbean,351,3 +beans,351,3 +bean,351,3 +browncocobeans,351,3 +browncocobean,351,3 +browncbeans,351,3 +browncbean,351,3 +brownbeans,351,3 +brownbean,351,3 +brownb,351,3 +browncolor,351,3 +browndye,351,3 +bluelapislzuli,351,4 +bluelapisl,351,4 +bluelapis,351,4 +bluel,351,4 +lapislzuli,351,4 +lapisl,351,4 +lapis,351,4 +bluecolor,351,4 +bluedye,351,4 +purplecolor,351,5 +purpledye,351,5 +cyancolor,351,6 +cyandye,351,6 +lightgraycolor,351,7 +lightgraydye,351,7 +lgraycolor,351,7 +lgraydye,351,7 +graycolor,351,8 +graydye,351,8 +pinkcolor,351,9 +pinkdye,351,9 +limecolor,351,10 +limedye,351,10 +dandelionyellow,351,11 +yellowdandelion,351,11 +yellowd,351,11 +yellowcolor,351,11 +yellowdye,351,11 +lightbluecolor,351,12 +lightbluedye,351,12 +lbluecolor,351,12 +lbluedye,351,12 +magentacolor,351,13 +magentadye,351,13 +orangecolor,351,14 +orangedye,351,14 +whitebonemeal,351,15 +whitebonem,351,15 +bonemeal,351,15 +bonem,351,15 +whitecolor,351,15 +whitedye,351,15 +bone,352,0 +sugar,353,0 +cake,354,0 +bed,355,0 +repeater,356,0 +repeat,356,0 +delayer,356,0 +delay,356,0 +diode,356,0 +goldrecord,2256,0 +golddisk,2256,0 +gorecord,2256,0 +godisk,2256,0 +greenrecord,2257,0 +greendisk,2257,0 +grrecord,2257,0 +grdisk,2257,0 \ No newline at end of file diff --git a/Essentials/src/plugin.yml b/Essentials/src/plugin.yml new file mode 100644 index 000000000..30e1f2cc3 --- /dev/null +++ b/Essentials/src/plugin.yml @@ -0,0 +1,248 @@ +# This determines the command prefix when there are conflicts (/name:home, /name:help, etc.) +name: Essentials +main: com.earth2me.essentials.Essentials +# Note to developers: This next line cannot change, or the automatic versioning system will break. +version: TeamCity +website: http://www.earth2me.net:8001/ +description: Provides an essential, core set of commands for Bukkit. +authors: [Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo] +commands: + afk: + description: Marks you as away-from-keyboard. + usage: / + antioch: + description: 'A little surprise for operators. Warning: Point away from face.' + usage: / + back: + description: Teleports you to your location prior to teleporting/spawning/warping. + usage: / + backup: + description: Runs the backup command + usage: / + balance: + description: States the current balance of a player. Defaults to self. + usage: / + aliases: bal,money + ban: + description: Bans a player. + usage: / [player] + banip: + description: Bans an IP address. + usage: / [address] + broadcast: + description: Broadcasts a message to the entire server. + usage: / [msg] + bigtree: + description: Spawn a big tree where you are looking. + usage: / [tree|redwood] + burn: + description: Set a player on fire. + usage: / [player] [seconds] + clearinventory: + description: Clear all items in your inventory. + usage: / + compass: + description: Describes your current bearing. + usage: / + deljail: + description: Removes a jail + usage: / [jailname] + delwarp: + description: Deletes the specified warp. + usage: / [warp] + aliases: [remwarp,rmwarp] + depth: + description: States current depth, relative to sea level. + usage: /depth + eco: + description: Manages the server economy. + usage: / [give|take|reset] [player] [amount] + aliases: economy + essentials: + description: Reloads essentials. + usage: / + ext: + description: Extinguish players. + usage: / + getpos: + description: Get your current coordinates. + usage: / + aliases: [coords] + gc: + description: Reports garbage collection info; useful to plugin/CraftBukkit developers + usage: / + aliases: [mem,memory] + give: + description: Give a player an item. + usage: / [player] [item|numeric] + god: + description: Enables your godly powers. + usage: / + aliases: [tgm,godmode] + heal: + description: Heals you or the given player. + usage: / + help: + description: Views a list of available commands. + usage: / + helpop: + description: Request help from online operators. + usage: / [message] + home: + description: Teleport to your home. + usage: / + invsee: + description: See the inventory of other players. + usage: / + item: + description: Spawn an item. + usage: / [item|numeric] + aliases: [i] + jails: + description: List all jails. + usage: / + jump: + description: Jumps to the nearest block in the line of sight. + usage: / + aliases: [j] + kick: + description: Kicks a specified player with a reason. + usage: / + kickall: + description: Kicks all players off the server except the issuer. + usage: / + kit: + description: Obtains the specified kit or views all available kits. + usage: / + kill: + description: Kills specified player. + usage: / + list: + description: List all online players. + usage: / + aliases: [playerlist,who,online] + mail: + description: Manages inter-player, intra-server mail. + usage: / [read|clear|send [to] [message]] + me: + description: Describes an action in the context of the player. + usage: / [description] + motd: + description: Views the Message Of The Day. + usage: / + msg: + description: Sends a private message to the specified player. + usage: / + aliases: [m,t] + mute: + description: Mutes or unmutes a player. + usage: / [player] + nick: + description: Change your nickname or that of another player. + usage: / [nickname|off] + nuble: + description: Used by Nuble to request permission for takeoff. + usage: / identify [id] + pay: + description: Pays another player from your balance + usage: / [player] [amount] + ping: + description: Pong! + usage: / + aliases: [pong] + plugin: + description: Enables, disables, or reloads a plugin. + usage: / [enable|disable|reload] [plugin] + r: + description: Quickly reply to the last player to message you. + usage: / [message] + rules: + description: Views the server rules. + usage: / + reloadall: + description: Reloads all plugins. + usage: / + aliases: [rel] + sell: + description: Sells the item currently in your hand. + usage: / <-> + sethome: + description: Set your home to your current location. + usage: / + setjail: + description: Creates a jail where you specified named [jailname] + usage: / [jailname] + setwarp: + description: Creates a new warp. + usage: / [warp] + aliases: [createwarp] + spawnmob: + description: Spawns a mob. + usage: / [mob],: + suicide: + description: Causes you to perish + usage: / + time: + description: Change the server time to day or night. + usage: / [day|night] + togglejail: + description: Prevents a player from interacting with the world and teleports him/her to the the jail specified + usage: / [player] [jailname] + aliases: [tjail] + top: + description: Teleport to the highest block at your current coordinates. + usage: / + tp: + description: Teleport to a player. + usage: / [player] + tpa: + description: Request to teleport to the specified player. + usage: / + tpaccept: + description: Accepts a teleport request. + usage: / + tpahere: + description: Request that the specified player teleport to you. + usage: / + tpdeny: + description: Reject a teleport request. + usage: / + tphere: + description: Teleport a player to you. + usage: / [player] + aliases: s + tpo: + description: Teleport override for tptoggle. + usage: / + tpohere: + description: Teleport here override for tptoggle. + usage: / + tppos: + description: Teleport to coordinates. + usage: / + tptoggle: + description: Blocks all forms of teleportation. + usage: / + tree: + description: Spawn a tree where you are looking. + usage: / [tree|birch|redwood] + unban: + description: Unbans the specified player. + usage: / [player] + aliases: pardon + unbanip: + description: Unbans the specified IP address. + usage: / [address] + aliases: pardonip + warp: + description: List all warps or warp to the specified location. + usage: / + whois: + description: Determine the username behind a nickname. + usage: / [nickname] + world: + description: Switch between worlds. + usage: / [world] + worth: + description: Calculates the worth of items in hand or as specified. + usage: / \ No newline at end of file diff --git a/Essentials/test/com/earth2me/essentials/EssentialsTest.java b/Essentials/test/com/earth2me/essentials/EssentialsTest.java new file mode 100644 index 000000000..da98978df --- /dev/null +++ b/Essentials/test/com/earth2me/essentials/EssentialsTest.java @@ -0,0 +1,60 @@ +package com.earth2me.essentials; + +import junit.framework.TestCase; + + +public class EssentialsTest extends TestCase +{ + public EssentialsTest(String testName) + { + super(testName); + } + + private static void should(String what) + { + System.out.println("Essentials should " + what); + } + + @Override + protected void setUp() throws Exception + { + super.setUp(); + } + + @Override + protected void tearDown() throws Exception + { + super.tearDown(); + } + + public void testLoadClasses() + { + should("make all classes accessible"); + Essentials.loadClasses(); + try + { + ItemDb itemDb = null; + Mob mob = null; + NetherPortal netherPortal = null; + OfflinePlayer offlinePlayer = null; + Settings settings = null; + Spawn spawn = null; + TargetBlock targetBlock = null; + TeleportTimer teleportTimer = null; + User user = null; + assertNull(itemDb); + assertNull(mob); + assertNull(netherPortal); + assertNull(offlinePlayer); + assertNull(settings); + assertNull(spawn); + assertNull(targetBlock); + assertNull(teleportTimer); + assertNull(user); + } + catch (Throwable ex) + { + fail(ex.toString()); + } + } +} diff --git a/Essentials/test/com/earth2me/essentials/PermissionsTest.java b/Essentials/test/com/earth2me/essentials/PermissionsTest.java new file mode 100644 index 000000000..a630edf85 --- /dev/null +++ b/Essentials/test/com/earth2me/essentials/PermissionsTest.java @@ -0,0 +1,17 @@ +package com.earth2me.essentials; + +import junit.framework.TestCase; + + +public class PermissionsTest extends TestCase +{ + @Override + protected void setUp() throws Exception + { + super.setUp(); + } + + public void test() + { + } +} diff --git a/Essentials/test/com/earth2me/essentials/UserTest.java b/Essentials/test/com/earth2me/essentials/UserTest.java new file mode 100644 index 000000000..011ba4770 --- /dev/null +++ b/Essentials/test/com/earth2me/essentials/UserTest.java @@ -0,0 +1,72 @@ +package com.earth2me.essentials; + +import junit.framework.TestCase; +import org.bukkit.Location; + + +public class UserTest extends TestCase +{ + private OfflinePlayer base1; + + public UserTest(String testName) + { + super(testName); + base1 = new OfflinePlayer("TestPlayer1"); + } + + private void should(String what) + { + System.out.println(getName() + " should " + what); + } + + @Override + protected void setUp() throws Exception + { + super.setUp(); + } + + @Override + protected void tearDown() throws Exception + { + super.tearDown(); + } + + public void testUpdate() + { + should("update an existing player with the same name, rather than creating a new player"); + User.get(base1); + int size1 = User.size(); + OfflinePlayer base1alt = new OfflinePlayer(base1.getName()); + assertEquals(base1alt, User.get(base1alt).getBase()); + assertTrue(size1 == User.size()); + } + + public void testHome() throws Exception + { + should("return the home set by setHome"); + Location home = new Location(null, 1, 2, 3, 4, 5); + User user = User.get(base1); + user.setHome(home); + assertEquals(user.getHome(), home); + } + + public void testMoney() + { + should("properly set, take, give, and get money"); + User user = User.get(base1); + double i; + user.setMoney(i = 100.5); + user.takeMoney(50); + i -= 50; + user.giveMoney(25); + i += 25; + assertEquals(user.getMoney(), i); + } + + public void testGetGroup() + { + should("return the default group"); + User user = User.get(base1); + assertEquals(user.getGroup(), "default"); + } +} diff --git a/Essentials/workdir/EssentialsGroupManager/config.yml b/Essentials/workdir/EssentialsGroupManager/config.yml new file mode 100644 index 000000000..e69de29bb diff --git a/Essentials/workdir/banned-ips.txt b/Essentials/workdir/banned-ips.txt new file mode 100644 index 000000000..e69de29bb diff --git a/Essentials/workdir/banned-players.txt b/Essentials/workdir/banned-players.txt new file mode 100644 index 000000000..e69de29bb diff --git a/Essentials/workdir/ops.txt b/Essentials/workdir/ops.txt new file mode 100644 index 000000000..e69de29bb diff --git a/Essentials/workdir/plugins/Permissions/default.yml b/Essentials/workdir/plugins/Permissions/default.yml new file mode 100644 index 000000000..e69de29bb diff --git a/Essentials/workdir/server.log b/Essentials/workdir/server.log new file mode 100644 index 000000000..de34fdb17 --- /dev/null +++ b/Essentials/workdir/server.log @@ -0,0 +1,264 @@ +2011-02-28 16:56:00 [INFO] Starting minecraft server version Beta 1.3 +2011-02-28 16:56:00 [INFO] Loading properties +2011-02-28 16:56:00 [WARNING] server.properties does not exist +2011-02-28 16:56:00 [INFO] Generating new properties file +2011-02-28 16:56:00 [INFO] Starting Minecraft server on *:25565 +2011-02-28 16:56:00 [INFO] This server is running Craftbukkit version git-Bukkit-0.0.0-468-ga3bf56c-b450jnks (MC: 1.3) +2011-02-28 16:56:00 [WARNING] Failed to load ban list: java.io.FileNotFoundException: banned-players.txt (The system cannot find the file specified) +2011-02-28 16:56:00 [WARNING] Failed to load ip ban list: java.io.FileNotFoundException: banned-ips.txt (The system cannot find the file specified) +2011-02-28 16:56:00 [WARNING] Failed to load ops: java.io.FileNotFoundException: ops.txt (The system cannot find the file specified) +2011-02-28 16:56:00 [WARNING] Failed to load white-list: java.io.FileNotFoundException: white-list.txt (The system cannot find the file specified) +2011-02-28 16:56:00 [INFO] Preparing level "world" +2011-02-28 16:56:00 [INFO] Preparing start region +2011-02-28 16:56:01 [INFO] §eLoaded Essentials build TeamCity maintained by Zenexer, ementalo, Aelux, and Brettflan +2011-02-28 16:56:02 [INFO] Preparing spawn area: 4% +2011-02-28 16:56:03 [INFO] Preparing spawn area: 8% +2011-02-28 16:56:04 [INFO] Preparing spawn area: 20% +2011-02-28 16:56:05 [INFO] Preparing spawn area: 32% +2011-02-28 16:56:06 [INFO] Preparing spawn area: 40% +2011-02-28 16:56:07 [INFO] Preparing spawn area: 48% +2011-02-28 16:56:08 [INFO] Starting minecraft server version Beta 1.3 +2011-02-28 16:56:08 [INFO] Loading properties +2011-02-28 16:56:08 [INFO] Starting Minecraft server on *:25565 +2011-02-28 16:56:08 [INFO] This server is running Craftbukkit version git-Bukkit-0.0.0-468-ga3bf56c-b450jnks (MC: 1.3) +2011-02-28 16:56:09 [INFO] Preparing level "world" +2011-02-28 16:56:09 [INFO] Preparing start region +2011-02-28 16:56:10 [INFO] §eLoaded Essentials build TeamCity maintained by Zenexer, ementalo, Aelux, and Brettflan +2011-02-28 16:56:10 [INFO] Preparing spawn area: 4% +2011-02-28 16:56:10 [INFO] Should update an existing player with the same name, rather than creating a new player +2011-02-28 16:56:11 [INFO] Starting minecraft server version Beta 1.3 +2011-02-28 16:56:11 [INFO] > +2011-02-28 16:56:11 [INFO] Preparing spawn area: 8% +2011-02-28 16:57:39 [INFO] Starting minecraft server version Beta 1.3 +2011-02-28 16:57:39 [INFO] Loading properties +2011-02-28 16:57:39 [INFO] Starting Minecraft server on *:25565 +2011-02-28 16:57:39 [INFO] This server is running Craftbukkit version git-Bukkit-0.0.0-468-ga3bf56c-b450jnks (MC: 1.3) +2011-02-28 16:57:39 [INFO] Preparing level "world" +2011-02-28 16:57:39 [INFO] Preparing start region +2011-02-28 16:57:41 [INFO] §eLoaded Essentials build TeamCity maintained by Zenexer, ementalo, Aelux, and Brettflan +2011-02-28 16:57:41 [INFO] Preparing spawn area: 4% +2011-02-28 16:57:42 [INFO] Preparing spawn area: 8% +2011-02-28 16:57:43 [INFO] Preparing spawn area: 16% +2011-02-28 16:57:44 [INFO] Preparing spawn area: 24% +2011-02-28 16:57:45 [INFO] Preparing spawn area: 24% +2011-02-28 16:57:48 [INFO] Starting minecraft server version Beta 1.3 +2011-02-28 16:57:48 [INFO] Loading properties +2011-02-28 16:57:48 [INFO] Starting Minecraft server on *:25565 +2011-02-28 16:57:48 [INFO] This server is running Craftbukkit version git-Bukkit-0.0.0-468-ga3bf56c-b450jnks (MC: 1.3) +2011-02-28 16:57:49 [INFO] Preparing level "world" +2011-02-28 16:57:49 [INFO] Preparing start region +2011-02-28 16:57:50 [INFO] §eLoaded Essentials build TeamCity maintained by Zenexer, ementalo, Aelux, and Brettflan +2011-02-28 16:57:50 [INFO] Preparing spawn area: 8% +2011-02-28 16:57:51 [INFO] > +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] Starting minecraft server version Beta 1.3 +2011-02-28 16:57:51 [INFO] Preparing spawn area: 12% +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:51 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:52 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:53 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:54 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:55 [INFO] +2011-02-28 16:57:56 [INFO] +2011-02-28 16:57:56 [INFO] +2011-02-28 16:57:56 [INFO] +2011-02-28 16:57:56 [INFO] +2011-02-28 16:59:07 [INFO] Starting minecraft server version Beta 1.3 +2011-02-28 16:59:07 [INFO] Loading properties +2011-02-28 16:59:07 [INFO] Starting Minecraft server on *:25565 +2011-02-28 16:59:07 [INFO] This server is running Craftbukkit version git-Bukkit-0.0.0-468-ga3bf56c-b450jnks (MC: 1.3) +2011-02-28 16:59:07 [INFO] Preparing level "world" +2011-02-28 16:59:07 [INFO] Preparing start region +2011-02-28 16:59:08 [INFO] Done (0.060s)! For help, type "help" or "?" +2011-02-28 16:59:08 [INFO] Stopping server +2011-02-28 16:59:08 [INFO] Saving chunks +2011-02-28 16:59:09 [INFO] Starting minecraft server version Beta 1.3 +2011-02-28 16:59:09 [INFO] Loading properties +2011-02-28 16:59:09 [INFO] Starting Minecraft server on *:25565 +2011-02-28 16:59:09 [INFO] This server is running Craftbukkit version git-Bukkit-0.0.0-468-ga3bf56c-b450jnks (MC: 1.3) +2011-02-28 16:59:09 [INFO] Preparing level "world" +2011-02-28 16:59:09 [INFO] Preparing start region +2011-02-28 16:59:10 [INFO] Done (0.011s)! For help, type "help" or "?" +2011-02-28 16:59:10 [INFO] Stopping server +2011-02-28 16:59:10 [INFO] Saving chunks diff --git a/Essentials/workdir/server.log.1 b/Essentials/workdir/server.log.1 new file mode 100644 index 000000000..e69de29bb diff --git a/Essentials/workdir/server.log.1.lck b/Essentials/workdir/server.log.1.lck new file mode 100644 index 000000000..e69de29bb diff --git a/Essentials/workdir/server.properties b/Essentials/workdir/server.properties new file mode 100644 index 000000000..c1f6fa8df --- /dev/null +++ b/Essentials/workdir/server.properties @@ -0,0 +1,13 @@ +#Minecraft server properties +#Mon Feb 28 16:56:01 EST 2011 +level-name=world +hellworld=false +spawn-monsters=true +online-mode=true +spawn-animals=true +max-players=20 +server-ip= +pvp=true +server-port=25565 +white-list=false +spawn-protection=16 diff --git a/Essentials/workdir/userdata/TestPlayer1.yml b/Essentials/workdir/userdata/TestPlayer1.yml new file mode 100644 index 000000000..c419a1196 --- /dev/null +++ b/Essentials/workdir/userdata/TestPlayer1.yml @@ -0,0 +1,2 @@ +home: [1.0, 2.0, 3.0, 4.0, 5.0, world] +money: 75.5 diff --git a/Essentials/workdir/white-list.txt b/Essentials/workdir/white-list.txt new file mode 100644 index 000000000..e69de29bb diff --git a/EssentialsChat/build.xml b/EssentialsChat/build.xml new file mode 100644 index 000000000..ed22cfe0c --- /dev/null +++ b/EssentialsChat/build.xml @@ -0,0 +1,76 @@ + + ]> + + + + + + + + + + Builds, tests, and runs the project EssentialsChat. + + &buildinc; + + diff --git a/EssentialsChat/nbproject/build-impl.xml b/EssentialsChat/nbproject/build-impl.xml new file mode 100644 index 000000000..e0b698395 --- /dev/null +++ b/EssentialsChat/nbproject/build-impl.xml @@ -0,0 +1,1072 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + Must select one file in the IDE or set profile.class + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/EssentialsChat/nbproject/genfiles.properties b/EssentialsChat/nbproject/genfiles.properties new file mode 100644 index 000000000..e53628d44 --- /dev/null +++ b/EssentialsChat/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=7c7f517b +build.xml.script.CRC32=71afd555 +build.xml.stylesheet.CRC32=28e38971@1.38.2.45 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=7c7f517b +nbproject/build-impl.xml.script.CRC32=c24d2db5 +nbproject/build-impl.xml.stylesheet.CRC32=19debb58@1.42.1.45 diff --git a/EssentialsChat/nbproject/private/private.properties b/EssentialsChat/nbproject/private/private.properties new file mode 100644 index 000000000..94183418a --- /dev/null +++ b/EssentialsChat/nbproject/private/private.properties @@ -0,0 +1 @@ +user.properties.file=C:\\Users\\Paul\\.netbeans\\7.0beta2\\build.properties diff --git a/EssentialsChat/nbproject/project.properties b/EssentialsChat/nbproject/project.properties new file mode 100644 index 000000000..315a26576 --- /dev/null +++ b/EssentialsChat/nbproject/project.properties @@ -0,0 +1,79 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +application.title=EssentialsChat +application.vendor=Paul +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/EssentialsChat.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes= +file.reference.craftbukkit-0.0.1-SNAPSHOT.jar=../lib/craftbukkit-0.0.1-SNAPSHOT.jar +file.reference.Permissions.jar=..\\lib\\Permissions.jar +includes=** +jar.compress=false +javac.classpath=\ + ${file.reference.craftbukkit-0.0.1-SNAPSHOT.jar}:\ + ${file.reference.Permissions.jar}:\ + ${reference.Essentials.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.processorpath=\ + ${javac.classpath} +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${libs.junit.classpath}:\ + ${libs.junit_4.classpath} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +meta.inf.dir=${src.dir}/META-INF +mkdist.disabled=false +platform.active=default_platform +project.Essentials=../Essentials +reference.Essentials.jar=${project.Essentials}/dist/Essentials.jar +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/EssentialsChat/nbproject/project.xml b/EssentialsChat/nbproject/project.xml new file mode 100644 index 000000000..da40bbe42 --- /dev/null +++ b/EssentialsChat/nbproject/project.xml @@ -0,0 +1,28 @@ + + + org.netbeans.modules.java.j2seproject + + + EssentialsChat + + + + + + + + + ..\lib\nblibraries.properties + + + + Essentials + jar + + jar + clean + jar + + + + diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java new file mode 100644 index 000000000..266bd104e --- /dev/null +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java @@ -0,0 +1,43 @@ +package com.earth2me.essentials.chat; + +import com.earth2me.essentials.Essentials; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.event.Event.Priority; +import org.bukkit.event.Event.Type; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + + +public class EssentialsChat extends JavaPlugin +{ + private static final Logger logger = Logger.getLogger("Minecraft"); + + public EssentialsChat() + { + super(); + } + + public void onEnable() + { + Plugin p = this.getServer().getPluginManager().getPlugin("Essentials"); + if (p != null) { + if (!this.getServer().getPluginManager().isPluginEnabled(p)) { + this.getServer().getPluginManager().enablePlugin(p); + } + } + PluginManager pm = getServer().getPluginManager(); + EssentialsChatPlayerListener playerListener = new EssentialsChatPlayerListener(getServer()); + pm.registerEvent(Type.PLAYER_JOIN, playerListener, Priority.Monitor, this); + pm.registerEvent(Type.PLAYER_CHAT, playerListener, Priority.Highest, this); + if (!this.getDescription().getVersion().equals(Essentials.getStatic().getDescription().getVersion())) { + logger.log(Level.WARNING, "Version mismatch! Please update all Essentials jars to the same version."); + } + logger.info("Loaded " + this.getDescription().getName() + " build " + this.getDescription().getVersion() + " by " + Essentials.AUTHORS); + } + + public void onDisable() + { + } +} diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListener.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListener.java new file mode 100644 index 000000000..e351cc865 --- /dev/null +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListener.java @@ -0,0 +1,61 @@ +package com.earth2me.essentials.chat; + +import com.earth2me.essentials.Essentials; +import org.bukkit.Server; +import org.bukkit.event.player.*; + + +public class EssentialsChatPlayerListener extends PlayerListener +{ + private final Server server; + + public EssentialsChatPlayerListener(Server server) + { + this.server = server; + } + + @Override + @SuppressWarnings("CallToThreadDumpStack") + public void onPlayerJoin(PlayerJoinEvent event) + { + try + { + Essentials.loadClasses(); + EssentialsChatWorker.onPlayerJoin(server, event); + } + catch (Throwable ex) + { + ex.printStackTrace(); + } + } + + @Override + @SuppressWarnings("CallToThreadDumpStack") + public void onPlayerRespawn(PlayerRespawnEvent event) + { + try + { + Essentials.loadClasses(); + EssentialsChatWorker.onPlayerRespawn(server, event); + } + catch (Throwable ex) + { + ex.printStackTrace(); + } + } + + @Override + @SuppressWarnings("CallToThreadDumpStack") + public void onPlayerChat(PlayerChatEvent event) + { + try + { + Essentials.loadClasses(); + EssentialsChatWorker.onPlayerChat(server, event); + } + catch (Throwable ex) + { + ex.printStackTrace(); + } + } +} diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatWorker.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatWorker.java new file mode 100644 index 000000000..e11504259 --- /dev/null +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatWorker.java @@ -0,0 +1,122 @@ +package com.earth2me.essentials.chat; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.nijikokun.bukkit.Permissions.Permissions; +import java.util.logging.Logger; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerChatEvent; +import org.bukkit.event.player.PlayerEvent; +import org.bukkit.event.player.PlayerRespawnEvent; + + +public class EssentialsChatWorker +{ + private static final Logger logger = Logger.getLogger("Minecraft"); + + public static void onPlayerRespawn(Server server, PlayerRespawnEvent event) + { + User user = User.get(event.getPlayer()); + updateDisplayName(user); + } + + public static void onPlayerJoin(Server server, PlayerEvent event) + { + User user = User.get(event.getPlayer()); + updateDisplayName(user); + } + + private static void updateDisplayName(User user) + { + try + { + String group = user.getGroup(); + try + { + String prefix = Permissions.Security.getGroupPrefix(user.getWorld().getName(), group).replace('&', '§').replace("{WORLDNAME}", user.getWorld().getName()); + String suffix = Permissions.Security.getGroupSuffix(user.getWorld().getName(), group).replace('&', '§').replace("{WORLDNAME}", user.getWorld().getName()); + user.setDisplayName(prefix + user.getNick() + suffix + (suffix.endsWith("§f") ? "" : "§f")); + } + catch (Throwable ex) + { + logger.warning("Missing a prefix or suffix for " + group); + } + } + catch (Throwable ex) + { + logger.warning("Missing Permissions/GroupManager; chat prefixes/suffixes will be disabled."); + } + } + + public static void onPlayerChat(Server server, PlayerChatEvent event) + { + User user = User.get(event.getPlayer()); + updateDisplayName(user); + + if (user.isAuthorized("essentials.chat.color")) + event.setMessage(event.getMessage().replaceAll("&([0-9a-f])", "§$1")); + + event.setFormat(Essentials.getSettings().getChatFormat(user.getGroup()) + .replace('&', '§') + .replace("§§", "&") + .replace("{DISPLAYNAME}", "%1$s") + .replace("{GROUP}", user.getGroup()) + .replace("{MESSAGE}", "%2$s") + .replace("{WORLDNAME}", user.getWorld().getName())); + + int radius = Essentials.getSettings().getChatRadius(); + if (radius < 1) return; + + if (event.getMessage().startsWith("!") && event.getMessage().length() > 1) + { + if (user.isAuthorized("essentials.chat.shout")) + { + event.setMessage(event.getMessage().substring(1)); + event.setFormat("§7[Shout]§f " + event.getFormat()); + return; + } + user.sendMessage("§cYou are not authorized to shout."); + event.setCancelled(true); + return; + } + + if (event.getMessage().startsWith("?") && event.getMessage().length() > 1) + { + if (user.isAuthorized("essentials.chat.question")) + { + event.setMessage(event.getMessage().substring(1)); + event.setFormat("§7[Question]§f " + event.getFormat()); + return; + } + user.sendMessage("§cYou are not authorized to use question."); + event.setCancelled(true); + return; + } + + event.setCancelled(true); + logger.info("Local: <" + user.getName() + "> " + event.getMessage()); + + Location loc = user.getLocation(); + int x = loc.getBlockX(); + int y = loc.getBlockY(); + int z = loc.getBlockZ(); + + for (Player p : server.getOnlinePlayers()) + { + User u = User.get(p); + if (u != user && !u.isAuthorized("essentials.chat.spy")) + { + Location l = u.getLocation(); + int dx = Math.abs(x - l.getBlockX()); + int dy = Math.abs(y - l.getBlockY()); + int dz = Math.abs(z - l.getBlockZ()); + int delta = dx + dy + dz; + if (delta > radius) continue; + } + + u.sendMessage(String.format(event.getFormat(), user.getDisplayName(), event.getMessage())); + } + } +} diff --git a/EssentialsChat/src/plugin.yml b/EssentialsChat/src/plugin.yml new file mode 100644 index 000000000..b4f7bb9c9 --- /dev/null +++ b/EssentialsChat/src/plugin.yml @@ -0,0 +1,8 @@ +# This determines the command prefix when there are conflicts (/name:home, /name:help, etc.) +name: EssentialsChat +main: com.earth2me.essentials.chat.EssentialsChat +# Note to developers: This next line cannot change, or the automatic versioning system will break. +version: TeamCity +website: http://www.earth2me.net:8001/ +description: Provides chat control features for Essentials. Requires Permissions. +authors: [Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo] \ No newline at end of file diff --git a/EssentialsGroupBridge/build.xml b/EssentialsGroupBridge/build.xml new file mode 100644 index 000000000..94dd95861 --- /dev/null +++ b/EssentialsGroupBridge/build.xml @@ -0,0 +1,74 @@ + + + + + + + + + + + Builds, tests, and runs the project EssentialsGroupBridge. + + + diff --git a/EssentialsGroupBridge/nbproject/build-impl.xml b/EssentialsGroupBridge/nbproject/build-impl.xml new file mode 100644 index 000000000..30d2e9bf6 --- /dev/null +++ b/EssentialsGroupBridge/nbproject/build-impl.xml @@ -0,0 +1,1047 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + Must select one file in the IDE or set profile.class + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/EssentialsGroupBridge/nbproject/genfiles.properties b/EssentialsGroupBridge/nbproject/genfiles.properties new file mode 100644 index 000000000..194afdd81 --- /dev/null +++ b/EssentialsGroupBridge/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=475c8f4d +build.xml.script.CRC32=674d9b15 +build.xml.stylesheet.CRC32=28e38971@1.38.2.45 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=475c8f4d +nbproject/build-impl.xml.script.CRC32=5fe43282 +nbproject/build-impl.xml.stylesheet.CRC32=19debb58@1.42.1.45 diff --git a/EssentialsGroupBridge/nbproject/private/private.properties b/EssentialsGroupBridge/nbproject/private/private.properties new file mode 100644 index 000000000..94183418a --- /dev/null +++ b/EssentialsGroupBridge/nbproject/private/private.properties @@ -0,0 +1 @@ +user.properties.file=C:\\Users\\Paul\\.netbeans\\7.0beta2\\build.properties diff --git a/EssentialsGroupBridge/nbproject/project.properties b/EssentialsGroupBridge/nbproject/project.properties new file mode 100644 index 000000000..0649cc58f --- /dev/null +++ b/EssentialsGroupBridge/nbproject/project.properties @@ -0,0 +1,78 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +application.title=EssentialsGroupBridge +application.vendor=gabrielcouto +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/EssentialsGroupBridge.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes= +file.reference.craftbukkit-0.0.1-SNAPSHOT.jar=..\\lib\\craftbukkit-0.0.1-SNAPSHOT.jar +file.reference.Permissions.jar=..\\lib\\Permissions.jar +includes=** +jar.compress=false +javac.classpath=\ + ${reference.EssentialsGroupManager.jar}:\ + ${file.reference.craftbukkit-0.0.1-SNAPSHOT.jar}:\ + ${file.reference.Permissions.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.processorpath=\ + ${javac.classpath} +javac.source=1.6 +javac.target=1.6 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +main.class= +manifest.file=manifest.mf +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +project.EssentialsGroupManager=../EssentialsGroupManager +reference.EssentialsGroupManager.jar=${project.EssentialsGroupManager}/dist/EssentialsGroupManager.jar +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/EssentialsGroupBridge/nbproject/project.xml b/EssentialsGroupBridge/nbproject/project.xml new file mode 100644 index 000000000..f7234f600 --- /dev/null +++ b/EssentialsGroupBridge/nbproject/project.xml @@ -0,0 +1,25 @@ + + + org.netbeans.modules.java.j2seproject + + + EssentialsGroupBridge + + + + + + + + + + EssentialsGroupManager + jar + + jar + clean + jar + + + + diff --git a/EssentialsGroupBridge/src/com/nijiko/Messaging.class b/EssentialsGroupBridge/src/com/nijiko/Messaging.class new file mode 100644 index 000000000..f563d0085 Binary files /dev/null and b/EssentialsGroupBridge/src/com/nijiko/Messaging.class differ diff --git a/EssentialsGroupBridge/src/com/nijiko/Misc$string.class b/EssentialsGroupBridge/src/com/nijiko/Misc$string.class new file mode 100644 index 000000000..124b535c3 Binary files /dev/null and b/EssentialsGroupBridge/src/com/nijiko/Misc$string.class differ diff --git a/EssentialsGroupBridge/src/com/nijiko/Misc.class b/EssentialsGroupBridge/src/com/nijiko/Misc.class new file mode 100644 index 000000000..4330a303f Binary files /dev/null and b/EssentialsGroupBridge/src/com/nijiko/Misc.class differ diff --git a/EssentialsGroupBridge/src/com/nijiko/configuration/ConfigurationHandler.class b/EssentialsGroupBridge/src/com/nijiko/configuration/ConfigurationHandler.class new file mode 100644 index 000000000..97c1fb35b Binary files /dev/null and b/EssentialsGroupBridge/src/com/nijiko/configuration/ConfigurationHandler.class differ diff --git a/EssentialsGroupBridge/src/com/nijiko/configuration/DefaultConfiguration.class b/EssentialsGroupBridge/src/com/nijiko/configuration/DefaultConfiguration.class new file mode 100644 index 000000000..06d9ee23b Binary files /dev/null and b/EssentialsGroupBridge/src/com/nijiko/configuration/DefaultConfiguration.class differ diff --git a/EssentialsGroupBridge/src/com/nijiko/database/Wrapper$Type.class b/EssentialsGroupBridge/src/com/nijiko/database/Wrapper$Type.class new file mode 100644 index 000000000..173279ddf Binary files /dev/null and b/EssentialsGroupBridge/src/com/nijiko/database/Wrapper$Type.class differ diff --git a/EssentialsGroupBridge/src/com/nijiko/database/Wrapper.class b/EssentialsGroupBridge/src/com/nijiko/database/Wrapper.class new file mode 100644 index 000000000..e1b59f9e1 Binary files /dev/null and b/EssentialsGroupBridge/src/com/nijiko/database/Wrapper.class differ diff --git a/EssentialsGroupBridge/src/com/nijiko/permissions/Control.class b/EssentialsGroupBridge/src/com/nijiko/permissions/Control.class new file mode 100644 index 000000000..d0d8845ac Binary files /dev/null and b/EssentialsGroupBridge/src/com/nijiko/permissions/Control.class differ diff --git a/EssentialsGroupBridge/src/com/nijiko/permissions/PermissionHandler.class b/EssentialsGroupBridge/src/com/nijiko/permissions/PermissionHandler.class new file mode 100644 index 000000000..a23287a5b Binary files /dev/null and b/EssentialsGroupBridge/src/com/nijiko/permissions/PermissionHandler.class differ diff --git a/EssentialsGroupBridge/src/com/nijikokun/bukkit/Permissions/Permissions.java b/EssentialsGroupBridge/src/com/nijikokun/bukkit/Permissions/Permissions.java new file mode 100644 index 000000000..bca7a89ed --- /dev/null +++ b/EssentialsGroupBridge/src/com/nijikokun/bukkit/Permissions/Permissions.java @@ -0,0 +1,102 @@ +package com.nijikokun.bukkit.Permissions; + +import com.nijiko.Misc; +import com.nijiko.configuration.DefaultConfiguration; +import com.nijiko.permissions.PermissionHandler; +import java.util.logging.Logger; +import org.anjocaido.groupmanager.GroupManager; +import org.anjocaido.groupmanager.permissions.NijikoPermissionsProxy; +import org.bukkit.Server; +import org.bukkit.event.player.PlayerChatEvent; +import org.bukkit.event.player.PlayerListener; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.java.JavaPlugin; + +public class Permissions extends JavaPlugin { + + private class Listener extends PlayerListener { + + private Permissions plugin; + + public Listener(Permissions plugin) { + //compiled code + throw new RuntimeException("Compiled Code"); + } + + public void onPlayerCommand(PlayerChatEvent event) { + //compiled code + throw new RuntimeException("Compiled Code"); + } + } + public static final Logger log = Logger.getLogger("Fake Permissions"); + public static String name = "Permissions"; + public static String codename = "Hacked Permissions by AnjoCaido"; + public static String version = "2.0"; + public static PermissionHandler Security = null; + public static Misc Misc = new Misc(); + public static Server Server; + private Listener Listener = null; + private DefaultConfiguration config = null; + private GroupManager groupManager; + + @Override + public void onDisable() { + //compiled code + //throw new RuntimeException("Compiled Code"); + // EXAMPLE: Custom code, here we just output some info so we can check all is well + PluginDescriptionFile pdfFile = this.getDescription(); + System.out.println("Fake " + pdfFile.getName() + " version " + pdfFile.getVersion() + " is disabled!"); + } + + @Override + public void onEnable() { + Server = this.getServer(); + PluginDescriptionFile pdfFile = this.getDescription(); + + if (Security == null) {//make sure we have only one instance + Plugin p = (Plugin)(this.getServer() == null ? new GroupManager() : this.getServer().getPluginManager().getPlugin("GroupManager")); + if (p != null) { + if (!p.isEnabled()) { + if (this.getServer() == null) { + p.onEnable(); + } else { + this.getServer().getPluginManager().enablePlugin(p); + } + } + GroupManager gm = (GroupManager) p; + groupManager = gm; + Security = new NijikoPermissionsProxy(gm); + } else { + System.err.println("OOOPS! Fake " + pdfFile.getName() + " version " + pdfFile.getVersion() + " couldn't find GroupManager!"); + this.getPluginLoader().disablePlugin(this); + } + } + // EXAMPLE: Custom code, here we just output some info so we can check all is well + if (pdfFile != null) + System.out.println("Fake " + pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!"); + } + + private void registerEvents() { + //compiled code + //throw new RuntimeException("Compiled Code"); + } + + public PermissionHandler getHandler() { + //compiled code + //throw new RuntimeException("Compiled Code"); + //System.out.println("Alguem chamou o handler"); + checkEnable(); + return Security; + } + + public void setupPermissions() { + checkEnable(); + } + + private void checkEnable() { + if (!this.isEnabled() && Security == null && this.getServer() != null) { + this.getServer().getPluginManager().enablePlugin(this); + } + } +} diff --git a/EssentialsGroupBridge/src/org/anjocaido/groupmanager/permissions/NijikoPermissionsProxy.java b/EssentialsGroupBridge/src/org/anjocaido/groupmanager/permissions/NijikoPermissionsProxy.java new file mode 100644 index 000000000..18da0cd56 --- /dev/null +++ b/EssentialsGroupBridge/src/org/anjocaido/groupmanager/permissions/NijikoPermissionsProxy.java @@ -0,0 +1,428 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.permissions; + +import com.nijiko.permissions.Control; +import java.io.File; +import java.util.Map; +import org.anjocaido.groupmanager.GroupManager; +import org.bukkit.entity.Player; +import org.bukkit.util.config.Configuration; + +/** + * Everything here maintains the model created by Nijikokun + * + * But implemented to use GroupManager system. Which provides instant changes, + * without file access. + * + * @author gabrielcouto + */ +public class NijikoPermissionsProxy extends Control { + GroupManager plugin; + public NijikoPermissionsProxy(GroupManager plugin){ + super(null); + this.plugin = plugin; + } + + @Override + public void addGroupPermission(String world, String group, String node) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removeGroupPermission(String world, String group, String node) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void addGroupInfo(String world, String group, String node, Object data) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removeGroupInfo(String world, String group, String node) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void addUserPermission(String world, String user, String node) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removeUserPermission(String world, String user, String node) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void addUserInfo(String world, String user, String node, Object data) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removeUserInfo(String world, String user, String node) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removeUserInfo(String user, String node) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void addGroupPermission(String group, String node) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removeGroupPermission(String group, String node) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void addGroupInfo(String group, String node, Object data) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removeGroupInfo(String group, String node) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void addUserPermission(String user, String node) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removeUserPermission(String user, String node) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void addUserInfo(String user, String node, Object data) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setDefaultWorld(String world) { + //throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setDirectory(File directory) { + //throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean loadWorld(String world) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void forceLoadWorld(String world) { + //throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean checkWorld(String world) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void load() { + //throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void load(String world, Configuration config) { + //throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void reload() { + plugin.getWorldsHolder().reloadAll(); + //throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean reload(String world) { + plugin.getWorldsHolder().reloadWorld(world); + return true; + } + + @Override + public void setCache(Map Cache) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setCache(String world, Map Cache) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setCacheItem(String player, String permission, boolean data) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setCacheItem(String world, String player, String permission, boolean data) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Map getCache() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Map getCache(String world) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean getCacheItem(String player, String permission) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean getCacheItem(String world, String player, String permission) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removeCachedItem(String player, String permission) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removeCachedItem(String world, String player, String permission) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void clearCache() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void clearCache(String world) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void clearAllCache() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean has(Player player, String permission) { + //throw new UnsupportedOperationException("Not supported yet."); + return permission(player, permission); + } + + @Override + public boolean permission(Player player, String permission) { + //throw new UnsupportedOperationException("Not supported yet."); + if(permission==null || permission.equals("")){ + return false; + } + if(player==null){ + GroupManager.logger.severe("A plugin is asking permission '"+permission+"' for a null player... Which plugin does that? Bastards!"); + return false; + } + if(player.getWorld()==null){ + GroupManager.logger.warning("The player "+player.getName()+" has a null world? Treating as default world!"); + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().has(player, permission); + } + return plugin.getWorldsHolder().getWorldData(player.getWorld().getName()).getPermissionsHandler().has(player, permission); + } + + @Override + public String getGroup(String world, String name) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getGroup(name); + } + + @Deprecated + @Override + public String getGroup(String name) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().getGroup(name); + } + + @Override + public String[] getGroups(String world, String name) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getGroups(name); + } + + @Deprecated + @Override + public String[] getGroups(String name) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().getGroups(name); + } + + @Override + public boolean inGroup(String world, String name, String group) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().inGroup(name,group); + } + + @Deprecated + @Override + public boolean inGroup(String name, String group) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().inGroup(name,group); + } + + @Override + public String getGroupPrefix(String world, String group) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getGroupPrefix(group); + } + + @Override + public String getGroupPrefix(String group) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().getGroupPrefix(group); + } + + @Override + public String getGroupSuffix(String world, String group) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getGroupSuffix(group); + } + + @Override + public String getGroupSuffix(String group) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().getGroupSuffix(group); + } + + @Override + public boolean canGroupBuild(String world, String group) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().canGroupBuild(group); + } + + @Deprecated + @Override + public boolean canGroupBuild(String group) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().canGroupBuild(group); + } + + @Override + public String getGroupPermissionString(String world, String group, String permission) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getGroupPermissionString(group,permission); + } + + @Override + public String getGroupPermissionString(String group, String permission) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().getGroupPermissionString(group,permission); + } + + @Override + public int getGroupPermissionInteger(String world, String group, String permission) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getGroupPermissionInteger(group,permission); + } + + @Override + public int getGroupPermissionInteger(String group, String permission) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().getGroupPermissionInteger(group,permission); + } + + @Override + public boolean getGroupPermissionBoolean(String world, String group, String permission) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getGroupPermissionBoolean(group,permission); + } + + @Override + public boolean getGroupPermissionBoolean(String group, String permission) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().getGroupPermissionBoolean(group,permission); + } + + @Override + public double getGroupPermissionDouble(String world, String group, String permission) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getGroupPermissionDouble(group,permission); + } + + @Override + public double getGroupPermissionDouble(String group, String permission) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().getGroupPermissionDouble(group,permission); + } + + @Override + public String getUserPermissionString(String world, String name, String permission) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getUserPermissionString(name,permission); + } + + @Override + public String getUserPermissionString(String name, String permission) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().getUserPermissionString(name,permission); + } + + @Override + public int getUserPermissionInteger(String world, String name, String permission) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getUserPermissionInteger(name,permission); + } + + @Override + public int getUserPermissionInteger(String name, String permission) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().getUserPermissionInteger(name,permission); + } + + @Override + public boolean getUserPermissionBoolean(String world, String name, String permission) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getUserPermissionBoolean(name,permission); + } + + @Override + public boolean getUserPermissionBoolean(String name, String permission) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().getUserPermissionBoolean(name,permission); + } + + @Override + public double getUserPermissionDouble(String world, String name, String permission) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getUserPermissionDouble(name,permission); + } + + @Override + public double getUserPermissionDouble(String name, String permission) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().getUserPermissionDouble(name,permission); + } + + @Override + public String getPermissionString(String world, String name, String permission) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getPermissionString(name,permission); + } + + @Override + public String getPermissionString(String name, String permission) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().getPermissionString(name,permission); + } + + @Override + public int getPermissionInteger(String world, String name, String permission) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getPermissionInteger(name,permission); + } + + @Override + public int getPermissionInteger(String name, String permission) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().getPermissionInteger(name,permission); + } + + @Override + public boolean getPermissionBoolean(String world, String name, String permission) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getPermissionBoolean(name,permission); + } + + @Override + public boolean getPermissionBoolean(String name, String permission) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().getPermissionBoolean(name,permission); + } + + @Override + public double getPermissionDouble(String world, String name, String permission) { + return plugin.getWorldsHolder().getWorldData(world).getPermissionsHandler().getPermissionDouble(name,permission); + } + + @Override + public double getPermissionDouble(String name, String permission) { + return plugin.getWorldsHolder().getDefaultWorld().getPermissionsHandler().getPermissionDouble(name,permission); + } + +} diff --git a/EssentialsGroupBridge/src/plugin.yml b/EssentialsGroupBridge/src/plugin.yml new file mode 100644 index 000000000..af93ee4a0 --- /dev/null +++ b/EssentialsGroupBridge/src/plugin.yml @@ -0,0 +1,3 @@ +name: Permissions +version: 2.5.1 +main: com.nijikokun.bukkit.Permissions.Permissions diff --git a/EssentialsGroupManager/build.xml b/EssentialsGroupManager/build.xml new file mode 100644 index 000000000..9eb86de21 --- /dev/null +++ b/EssentialsGroupManager/build.xml @@ -0,0 +1,74 @@ + + + + + + + + + + + Builds, tests, and runs the project EssentialsGroupManager. + + + diff --git a/EssentialsGroupManager/nbproject/build-impl.xml b/EssentialsGroupManager/nbproject/build-impl.xml new file mode 100644 index 000000000..cf2c8bef0 --- /dev/null +++ b/EssentialsGroupManager/nbproject/build-impl.xml @@ -0,0 +1,1033 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + Must select one file in the IDE or set profile.class + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/EssentialsGroupManager/nbproject/genfiles.properties b/EssentialsGroupManager/nbproject/genfiles.properties new file mode 100644 index 000000000..b34deb399 --- /dev/null +++ b/EssentialsGroupManager/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=a6709b83 +build.xml.script.CRC32=5b346364 +build.xml.stylesheet.CRC32=28e38971@1.38.2.45 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=a6709b83 +nbproject/build-impl.xml.script.CRC32=70ed0f6c +nbproject/build-impl.xml.stylesheet.CRC32=19debb58@1.42.1.45 diff --git a/EssentialsGroupManager/nbproject/private/private.properties b/EssentialsGroupManager/nbproject/private/private.properties new file mode 100644 index 000000000..94183418a --- /dev/null +++ b/EssentialsGroupManager/nbproject/private/private.properties @@ -0,0 +1 @@ +user.properties.file=C:\\Users\\Paul\\.netbeans\\7.0beta2\\build.properties diff --git a/EssentialsGroupManager/nbproject/project.properties b/EssentialsGroupManager/nbproject/project.properties new file mode 100644 index 000000000..c3e38f7a8 --- /dev/null +++ b/EssentialsGroupManager/nbproject/project.properties @@ -0,0 +1,73 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +application.title=EssentialsGroupManager +application.vendor=gabrielcouto +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/EssentialsGroupManager.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes= +file.reference.craftbukkit-0.0.1-SNAPSHOT.jar=..\\lib\\craftbukkit-0.0.1-SNAPSHOT.jar +includes=** +jar.compress=false +javac.classpath=\ + ${file.reference.craftbukkit-0.0.1-SNAPSHOT.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.processorpath=\ + ${javac.classpath} +javac.source=1.6 +javac.target=1.6 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +main.class= +manifest.file=manifest.mf +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/EssentialsGroupManager/nbproject/project.xml b/EssentialsGroupManager/nbproject/project.xml new file mode 100644 index 000000000..6cc53fda9 --- /dev/null +++ b/EssentialsGroupManager/nbproject/project.xml @@ -0,0 +1,15 @@ + + + org.netbeans.modules.java.j2seproject + + + EssentialsGroupManager + + + + + + + + + diff --git a/EssentialsGroupManager/src/config.yml b/EssentialsGroupManager/src/config.yml new file mode 100644 index 000000000..68308cca2 --- /dev/null +++ b/EssentialsGroupManager/src/config.yml @@ -0,0 +1,14 @@ +settings: + data: + save: + minutes: 10 + logging: + level: INFO + permission: + world: + mirror: + world1: + - world2 + - world3 + world4: + - world5 \ No newline at end of file diff --git a/EssentialsGroupManager/src/groups.yml b/EssentialsGroupManager/src/groups.yml new file mode 100644 index 000000000..73c55b880 --- /dev/null +++ b/EssentialsGroupManager/src/groups.yml @@ -0,0 +1,172 @@ +groups: + Default: + default: true + permissions: + - essentials.help + - essentials.home + - essentials.motd + - essentials.sethome + - essentials.spawn + inheritance: [] + info: + prefix: '' + build: false + suffix: '' + SemiAdmin: + default: false + permissions: + - +groupmanager.mandemote + - +groupmanager.manpromote + - -groupmanager.* + - '*' + inheritance: + - moderator + info: + prefix: '&c' + build: true + suffix: SemiAdmin + RedFaction: + default: false + permissions: [] + inheritance: + - peasant + info: + prefix: '&c' + roles-category: faction + build: true + suffix: Red + Farmer: + default: false + permissions: + - essentials.kit + - essentials.kit.farmer + - essentials.spawnmob + inheritance: [] + info: + roles-requirement: + - BlueFaction + - RedFaction + prefix: '' + roles-category: job + build: false + suffix: '' + Healer: + default: false + permissions: + - essentials.kit + - essentials.kit.healer + - essentials.heal + inheritance: [] + info: + roles-requirement: + - BlueFaction + - RedFaction + prefix: '' + roles-category: job + build: false + suffix: '' + Fighter: + default: false + permissions: + - essentials.kit + - essentials.kit.fighter + inheritance: [] + info: + prefix: '' + roles-category: skill + build: false + suffix: '' + Admin: + default: false + permissions: + - '*' + inheritance: + - semiadmin + info: + prefix: '' + build: true + suffix: '' + Miner: + default: false + permissions: + - essentials.kit + - essentials.kit.miner + - flashlight.regular + inheritance: [] + info: + roles-requirement: + - BlueFaction + - RedFaction + prefix: '' + roles-category: job + build: false + suffix: '' + FlyingMan: + default: false + permissions: + - nocheat.moving + inheritance: [] + info: + roles-requirement: Fighter&SuperCart + prefix: '' + roles-category: skill + build: false + suffix: '' + Peasant: + default: false + permissions: + - roles.joinrole + - roles.leaverole + - roles.myroles + inheritance: + - default + info: + prefix: '&e' + build: true + suffix: Peasant + BlueFaction: + default: false + permissions: [] + inheritance: + - peasant + info: + prefix: '&d' + roles-category: faction + build: true + suffix: Blue + Railer: + default: false + permissions: + - essentials.kit + - essentials.kit.railer + inheritance: [] + info: + roles-requirement: Miner + prefix: '' + roles-category: subjob + build: false + suffix: '' + SuperCart: + default: false + permissions: + - minecartmania.* + inheritance: [] + info: + roles-requirement: Railer + prefix: '' + roles-category: skill + build: false + suffix: '' + Moderator: + default: false + permissions: + - essentials.tp + - essentials.tphere + - essentials.item + - essentials.give + inheritance: + - default + info: + prefix: '&c' + build: true + suffix: Mod \ No newline at end of file diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/GMConfiguration.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/GMConfiguration.java new file mode 100644 index 000000000..68253eccc --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/GMConfiguration.java @@ -0,0 +1,120 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Map; +import java.util.logging.Level; +import org.anjocaido.groupmanager.utils.Tasks; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.reader.UnicodeReader; + +/** + * + * @author gabrielcouto + */ +public class GMConfiguration { + + private GroupManager plugin; + private Map rootDataNode; + private File configFile; + + public GMConfiguration(GroupManager plugin) { + this.plugin = plugin; + load(); + } + + public void load() { + if (!plugin.getDataFolder().exists()) { + plugin.getDataFolder().mkdirs(); + } + configFile = new File(plugin.getDataFolder(), "config.yml"); + + if (!configFile.exists()) { + try { + Tasks.copy(plugin.getResourceAsStream("config.yml"), configFile); + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + } + + Yaml yaml = new Yaml(new SafeConstructor()); + FileInputStream rx = null; + try { + rx = new FileInputStream(configFile); + } catch (FileNotFoundException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + try { + rootDataNode = (Map) yaml.load(new UnicodeReader(rx)); + if (rootDataNode == null) { + throw new NullPointerException(); + } + } catch (Exception ex) { + throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + configFile.getPath(), ex); + } finally { + try { + rx.close(); + } catch (IOException ex) { + } + } + adjustLoggerLevel(); + } + + public Map getMirrorsMap() { + if (rootDataNode.get("settings") instanceof Map) { + Map settingsNode = (Map) rootDataNode.get("settings"); + if (settingsNode.get("permission") instanceof Map) { + Map permissionNode = (Map) settingsNode.get("permission"); + if (permissionNode.get("world") instanceof Map) { + Map worldsNode = (Map) permissionNode.get("world"); + if (worldsNode.get("mirror") instanceof Map) { + Map mirrorsNode = (Map) worldsNode.get("mirror"); + return mirrorsNode; + } + } + } + } + return null; + } + + public Integer getSaveInterval() { + if (rootDataNode.get("settings") instanceof Map) { + Map settingsNode = (Map) rootDataNode.get("settings"); + if (settingsNode.get("data") instanceof Map) { + Map dataNode = (Map) settingsNode.get("data"); + if (dataNode.get("save") instanceof Map) { + Map saveNode = (Map) dataNode.get("save"); + if (saveNode.get("minutes") instanceof Integer) { + return (Integer) saveNode.get("minutes"); + } + } + } + } + return 10; + } + + public void adjustLoggerLevel() { + if (rootDataNode.get("settings") instanceof Map) { + Map settingsNode = (Map) rootDataNode.get("settings"); + if (settingsNode.get("logging") instanceof Map) { + Map loggingNode = (Map) settingsNode.get("logging"); + if (loggingNode.get("level") instanceof String) { + String level = (String) loggingNode.get("level"); + try { + GroupManager.logger.setLevel(Level.parse(level)); + return; + } catch (Exception e) { + } + } + } + } + GroupManager.logger.setLevel(Level.INFO); + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/GroupManager.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/GroupManager.java new file mode 100644 index 000000000..2ea0007b0 --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/GroupManager.java @@ -0,0 +1,1634 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager; + +import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler; +import org.anjocaido.groupmanager.utils.GroupManagerPermissions; +import org.anjocaido.groupmanager.data.Variables; +import org.anjocaido.groupmanager.data.User; +import org.anjocaido.groupmanager.data.Group; +import org.anjocaido.groupmanager.dataholder.OverloadedWorldHolder; +import org.anjocaido.groupmanager.dataholder.WorldDataHolder; +import java.io.File; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.anjocaido.groupmanager.dataholder.worlds.WorldsHolder; +import org.anjocaido.groupmanager.utils.GMLoggerHandler; +import org.anjocaido.groupmanager.utils.PermissionCheckResult; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.entity.Player; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.java.JavaPlugin; + +/** + * + * @author gabrielcouto + */ +public class GroupManager extends JavaPlugin { + + private File configFile; + private File backupFolder; + private Runnable commiter; + private ScheduledThreadPoolExecutor scheduler; + private Map> overloadedUsers = new HashMap>(); + private Map selectedWorlds = new HashMap(); + private WorldsHolder worldsHolder; + private boolean validateOnlinePlayer = true; + private boolean isReady = false; + private GMConfiguration config; + public static final Logger logger = Logger.getLogger(GroupManager.class.getName()); + + @Override + public void onDisable() { + if (worldsHolder != null) { + worldsHolder.saveChanges(); + } + disableScheduler(); + // EXAMPLE: Custom code, here we just output some info so we can check all is well + PluginDescriptionFile pdfFile = this.getDescription(); + System.out.println(pdfFile.getName() + " version " + pdfFile.getVersion() + " is disabled!"); + } + + @Override + public void onEnable() { + GroupManager.logger.setUseParentHandlers(false); + GMLoggerHandler ch = new GMLoggerHandler(); + GroupManager.logger.addHandler(ch); + logger.setLevel(Level.ALL); + if (worldsHolder == null) { + prepareFileFields(); + prepareConfig(); + worldsHolder = new WorldsHolder(this); + } + + PluginDescriptionFile pdfFile = this.getDescription(); + if (worldsHolder == null) { + GroupManager.logger.severe("Can't enable " + pdfFile.getName() + " version " + pdfFile.getVersion() + ", bad loading!"); + this.getServer().getPluginManager().disablePlugin(this); + throw new IllegalStateException("An error ocurred while loading GroupManager"); + } + + enableScheduler(); + System.out.println(pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!"); + } + + public InputStream getResourceAsStream(String fileName) { + return this.getClassLoader().getResourceAsStream(fileName); + } + + private void prepareFileFields() { + configFile = new File(this.getDataFolder(), "config.yml"); + backupFolder = new File(this.getDataFolder(), "backup"); + if (!backupFolder.exists()) { + getBackupFolder().mkdirs(); + } + } + + private void prepareConfig() { + config = new GMConfiguration(this); + } + + public void enableScheduler() { + if (worldsHolder != null) { + disableScheduler(); + commiter = new Runnable() { + + @Override + public void run() { + GroupManager.this.worldsHolder.saveChanges(); + } + }; + scheduler = new ScheduledThreadPoolExecutor(1); + int minutes = getConfig().getSaveInterval(); + scheduler.scheduleAtFixedRate(commiter, minutes, minutes, TimeUnit.MINUTES); + GroupManager.logger.info("Scheduled Data Saving is set for every " + minutes + " minutes!"); + } + } + + public void disableScheduler() { + if (scheduler != null) { + try { + scheduler.setContinueExistingPeriodicTasksAfterShutdownPolicy(false); + scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); + scheduler.shutdown(); + } catch (Exception e) { + } + scheduler = null; + GroupManager.logger.info("Scheduled Data Saving is disabled!"); + } + } + + /** + * Use the WorldsHolder saveChanges directly instead + * Saves the data on file + */ + @Deprecated + public void commit() { + if (worldsHolder != null) { + worldsHolder.saveChanges(); + } + } + + /** + * Use worlds holder to reload a specific world + * Reloads the data + */ + @Deprecated + public void reload() { + worldsHolder.reloadAll(); + } + + public WorldsHolder getWorldsHolder() { + return worldsHolder; + } + + /** + * The handler in the interface created by AnjoCaido + * @return + */ + @Deprecated + public AnjoPermissionsHandler getPermissionHandler() { + return worldsHolder.getDefaultWorld().getPermissionsHandler(); + } + + /** + * A simple interface, for ones that don't want to mess with overloading. + * Yet it is affected by overloading. But seamless. + * @return the dataholder with all information + */ + @Deprecated + public WorldDataHolder getData() { + return worldsHolder.getDefaultWorld(); + } + + /** + * Use this if you want to play with overloading. + * @return a dataholder with overloading interface + */ + @Deprecated + public OverloadedWorldHolder getOverloadedClassData() { + return worldsHolder.getDefaultWorld(); + } + + /** + * Called when a command registered by this plugin is received. + * @param sender + * @param cmd + * @param args + */ + @Override + public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { + boolean playerCanDo = false; + boolean isConsole = false; + Player senderPlayer = null; + Group senderGroup = null; + User senderUser = null; + + + //DETERMINING PLAYER INFORMATION + if (sender instanceof Player) { + senderPlayer = (Player) sender; + senderUser = worldsHolder.getWorldData(senderPlayer).getUser(senderPlayer.getName()); + senderGroup = senderUser.getGroup(); + if (worldsHolder.getWorldPermissions(senderPlayer).has(senderPlayer, "groupmanager." + cmd.getName())) { + playerCanDo = true; + } + } else if (sender instanceof ConsoleCommandSender) { + isConsole = true; + } + + //PERMISSIONS FOR COMMAND BEING LOADED + OverloadedWorldHolder dataHolder = null; + AnjoPermissionsHandler permissionHandler = null; + + if (senderPlayer != null) { + dataHolder = worldsHolder.getWorldData(senderPlayer); + } + + String selectedWorld = selectedWorlds.get(sender); + if (selectedWorld != null) { + dataHolder = worldsHolder.getWorldData(selectedWorld); + } + + if (dataHolder != null) { + permissionHandler = dataHolder.getPermissionsHandler(); + } + + //VARIABLES USED IN COMMANDS + + + int count; + PermissionCheckResult permissionResult = null; + ArrayList removeList = null; + String auxString = null; + List match = null; + User auxUser = null; + Group auxGroup = null; + Group auxGroup2 = null; + + GroupManagerPermissions execCmd = null; + try { + execCmd = GroupManagerPermissions.valueOf(cmd.getName()); + } catch (Exception e) { + //this error happened once with someone. now im prepared... i think + GroupManager.logger.severe("==================================================="); + GroupManager.logger.severe("= ERROR REPORT START ="); + GroupManager.logger.severe("==================================================="); + GroupManager.logger.severe("= COPY AND PASTE THIS TO GROUPMANAGER DEVELOPER ="); + GroupManager.logger.severe("==================================================="); + GroupManager.logger.severe(this.getDescription().getName()); + GroupManager.logger.severe(this.getDescription().getVersion()); + GroupManager.logger.severe("An error occured while trying to execute command:"); + GroupManager.logger.severe(cmd.getName()); + GroupManager.logger.severe("With " + args.length + " arguments:"); + for (String ar : args) { + GroupManager.logger.severe(ar); + } + GroupManager.logger.severe("The field '" + cmd.getName() + "' was not found in enum."); + GroupManager.logger.severe("And could not be parsed."); + GroupManager.logger.severe("FIELDS FOUND IN ENUM:"); + for (GroupManagerPermissions val : GroupManagerPermissions.values()) { + GroupManager.logger.severe(val.name()); + } + GroupManager.logger.severe("==================================================="); + GroupManager.logger.severe("= ERROR REPORT ENDED ="); + GroupManager.logger.severe("==================================================="); + sender.sendMessage("An error occurred. Ask the admin to take a look at the console."); + } + + if (isConsole || playerCanDo) { + switch (execCmd) { + case manuadd: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + auxGroup = dataHolder.getGroup(args[1]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group not found!"); + return false; + } + //VALIDANDO PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same permissions than you, or higher."); + return false; + } + //PARECE OK + auxUser.setGroup(auxGroup); + sender.sendMessage(ChatColor.YELLOW + "You changed player '" + auxUser.getName() + "' group to '" + auxGroup.getName() + "'."); + + return true; + //break; + case manudel: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same permissions than you, or higher."); + return false; + } + //PARECE OK + dataHolder.removeUser(auxUser.getName()); + sender.sendMessage(ChatColor.YELLOW + "You changed player '" + auxUser.getName() + "' to default settings."); + + return true; + case manuaddsub: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + auxGroup = dataHolder.getGroup(args[1]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group not found!"); + return false; + } + //VALIDANDO PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same permissions than you, or higher."); + return false; + } + //PARECE OK + auxUser.addSubGroup(auxGroup); + sender.sendMessage(ChatColor.YELLOW + "You changed player '" + auxUser.getName() + "' group to '" + auxGroup.getName() + "'."); + + return true; + case manudelsub: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same permissions than you, or higher."); + return false; + } + //PARECE OK + auxUser.removeSubGroup(auxGroup); + sender.sendMessage(ChatColor.YELLOW + "You removed subgroup '" + auxGroup.getName() + "' from player '" + auxUser.getName() + "' list."); + + return true; + case mangadd: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup != null) { + sender.sendMessage(ChatColor.RED + "Group already exists!"); + return false; + } + //PARECE OK + auxGroup = dataHolder.createGroup(args[0]); + sender.sendMessage(ChatColor.YELLOW + "You created a group named: " + auxGroup.getName()); + + return true; + case mangdel: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group not exists!"); + return false; + } + //PARECE OK + dataHolder.removeGroup(auxGroup.getName()); + sender.sendMessage(ChatColor.YELLOW + "You deleted a group named " + auxGroup.getName() + ", it's users are default group now."); + + return true; + case manuaddp: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO SUA PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same group than you, or higher."); + return false; + } + permissionResult = permissionHandler.checkFullUserPermission(senderUser, args[1]); + if (!isConsole && (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND) + || permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION))) { + sender.sendMessage(ChatColor.RED + "Can't add a permission you don't have."); + return false; + } + //VALIDANDO PERMISSAO DO DESTINO + permissionResult = permissionHandler.checkUserOnlyPermission(auxUser, args[1]); + if (args[1].startsWith("+")) { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.EXCEPTION)) { + sender.sendMessage(ChatColor.RED + "The user already has direct access to that permission."); + sender.sendMessage(ChatColor.RED + "Node: " + permissionResult.accessLevel); + return false; + } + } else if (args[1].startsWith("-")) { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.EXCEPTION)) { + sender.sendMessage(ChatColor.RED + "The user already has an exception for this node."); + sender.sendMessage(ChatColor.RED + "Node: " + permissionResult.accessLevel); + return false; + } else if (permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION)) { + sender.sendMessage(ChatColor.RED + "The user already has a matching node "); + sender.sendMessage(ChatColor.RED + "Node: " + permissionResult.accessLevel); + return false; + } + } else { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.FOUND)) { + sender.sendMessage(ChatColor.RED + "The user already has direct access to that permission."); + sender.sendMessage(ChatColor.RED + "Node: " + permissionResult.accessLevel); + return false; + } + } + //PARECE OK + auxUser.addPermission(args[1]); + sender.sendMessage(ChatColor.YELLOW + "You added '" + args[1] + "' to player '" + auxUser.getName() + "' permissions."); + return true; + //break; + case manudelp: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO SUA PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same group than you, or higher."); + return false; + } + permissionResult = permissionHandler.checkFullUserPermission(senderUser, args[1]); + if (!isConsole && (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND) + || permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION))) { + sender.sendMessage(ChatColor.RED + "Can't remove a permission you don't have."); + return false; + } + //VALIDANDO PERMISSAO DO DESTINO + permissionResult = permissionHandler.checkUserOnlyPermission(auxUser, args[1]); + if (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { + sender.sendMessage(ChatColor.RED + "The user doesn't have direct access to that permission."); + return false; + } + if (!auxUser.hasSamePermissionNode(args[1])) { + sender.sendMessage(ChatColor.RED + "This permission node doesn't match any node."); + sender.sendMessage(ChatColor.RED + "But might match node: " + permissionResult.accessLevel); + return false; + } + //PARECE OK + auxUser.removePermission(args[1]); + sender.sendMessage(ChatColor.YELLOW + "You removed '" + args[1] + "' from player '" + auxUser.getName() + "' permissions."); + + return true; + //break; + case manulistp: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + //PARECE OK + auxString = ""; + for (String perm : auxUser.getPermissionList()) { + auxString += perm + ", "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + sender.sendMessage(ChatColor.YELLOW + "The player '" + auxUser.getName() + "' has following permissions: " + ChatColor.WHITE + auxString); + sender.sendMessage(ChatColor.YELLOW + "And all permissions from group: " + auxUser.getGroupName()); + auxString = ""; + for (String subGroup : auxUser.subGroupListStringCopy()) { + auxString += subGroup + ", "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + sender.sendMessage(ChatColor.YELLOW + "And all permissions from subgroups: " + auxString); + } + } else { + sender.sendMessage(ChatColor.YELLOW + "The player '" + auxUser.getName() + "' has no specific permissions."); + sender.sendMessage(ChatColor.YELLOW + "Only all permissions from group: " + auxUser.getGroupName()); + auxString = ""; + for (String subGroup : auxUser.subGroupListStringCopy()) { + auxString += subGroup + ", "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + sender.sendMessage(ChatColor.YELLOW + "And all permissions from subgroups: " + auxString); + } + } + return true; + case manucheckp: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + permissionResult = permissionHandler.checkFullUserPermission(auxUser, args[1]); + if (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { + sender.sendMessage(ChatColor.RED + "The player doesn't have access to that permission"); + return false; + } + //PARECE OK + //auxString = permissionHandler.checkUserOnlyPermission(auxUser, args[1]); + if (permissionResult.owner instanceof User) { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION)) { + sender.sendMessage(ChatColor.RED + "The user has directly a negation node for that permission."); + } else { + sender.sendMessage(ChatColor.YELLOW + "The user has directly this permission."); + } + sender.sendMessage(ChatColor.YELLOW + "Permission Node: " + permissionResult.accessLevel); + } else if (permissionResult.owner instanceof Group) { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION)) { + sender.sendMessage(ChatColor.RED + "The user inherits the a negation permission from group: " + permissionResult.owner.getName()); + } else { + sender.sendMessage(ChatColor.YELLOW + "The user inherits the permission from group: " + permissionResult.owner.getName()); + } + sender.sendMessage(ChatColor.YELLOW + "Permission Node: " + permissionResult.accessLevel); + } + return true; + case mangaddp: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group does not exists!"); + return false; + } + //VALIDANDO SUA PERMISSAO + permissionResult = permissionHandler.checkFullUserPermission(senderUser, args[1]); + if (!isConsole && (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND) + || permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION))) { + sender.sendMessage(ChatColor.RED + "Can't add a permission you don't have."); + return false; + } + //VALIDANDO PERMISSAO DO DESTINO + permissionResult = permissionHandler.checkGroupOnlyPermission(auxGroup, args[1]); + if (args[1].startsWith("+")) { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.EXCEPTION)) { + sender.sendMessage(ChatColor.RED + "The group already has direct access to that permission."); + sender.sendMessage(ChatColor.RED + "Node: " + permissionResult.accessLevel); + return false; + } + } else if (args[1].startsWith("-")) { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.EXCEPTION)) { + sender.sendMessage(ChatColor.RED + "The group already has an exception for this node."); + sender.sendMessage(ChatColor.RED + "Node: " + permissionResult.accessLevel); + return false; + } else if (permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION)) { + sender.sendMessage(ChatColor.RED + "The group already has a matching node."); + sender.sendMessage(ChatColor.RED + "Node: " + permissionResult.accessLevel); + return false; + } + } else { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.FOUND)) { + sender.sendMessage(ChatColor.RED + "The user already has direct access to that permission."); + sender.sendMessage(ChatColor.RED + "Node: " + permissionResult.accessLevel); + return false; + } + } + //PARECE OK + auxGroup.addPermission(args[1]); + sender.sendMessage(ChatColor.YELLOW + "You added '" + args[1] + "' to group '" + auxGroup.getName() + "' permissions."); + + return true; + case mangdelp: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group does not exists!"); + return false; + } + //VALIDANDO SUA PERMISSAO + permissionResult = permissionHandler.checkFullUserPermission(senderUser, args[1]); + if (!isConsole && (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND) + || permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION))) { + sender.sendMessage(ChatColor.RED + "Can't remove a permission you don't have."); + return false; + } + //VALIDANDO PERMISSAO DO DESTINO + permissionResult = permissionHandler.checkGroupOnlyPermission(auxGroup, args[1]); + if (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { + sender.sendMessage(ChatColor.RED + "The group doesn't have direct access to that permission."); + return false; + } + if (!auxGroup.hasSamePermissionNode(args[1])) { + sender.sendMessage(ChatColor.RED + "This permission node doesn't match any node."); + sender.sendMessage(ChatColor.RED + "But might match node: " + permissionResult.accessLevel); + return false; + } + //PARECE OK + auxGroup.removePermission(args[1]); + sender.sendMessage(ChatColor.YELLOW + "You removed '" + args[1] + "' from group '" + auxGroup.getName() + "' permissions."); + + return true; + case manglistp: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group does not exists!"); + return false; + } + //VALIDANDO PERMISSAO + + //PARECE OK + auxString = ""; + for (String perm : auxGroup.getPermissionList()) { + auxString += perm + ", "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + sender.sendMessage(ChatColor.YELLOW + "The group '" + auxGroup.getName() + "' has following permissions: " + ChatColor.WHITE + auxString); + auxString = ""; + for (String grp : auxGroup.getInherits()) { + auxString += grp + ", "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + sender.sendMessage(ChatColor.YELLOW + "And all permissions from groups: " + auxString); + } + + } else { + sender.sendMessage(ChatColor.YELLOW + "The grpup '" + auxGroup.getName() + "' has no specific permissions."); + auxString = ""; + for (String grp : auxGroup.getInherits()) { + auxString += grp + ", "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + sender.sendMessage(ChatColor.YELLOW + "Only all permissions from groups: " + auxString); + } + + } + return true; + case mangcheckp: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group does not exists!"); + return false; + } + //VALIDANDO PERMISSAO + permissionResult = permissionHandler.checkGroupPermissionWithInheritance(auxGroup, args[1]); + if (permissionResult.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { + sender.sendMessage(ChatColor.RED + "The group doesn't have access to that permission"); + return false; + } + //PARECE OK + //auxString = permissionHandler.checkUserOnlyPermission(auxUser, args[1]); + if (permissionResult.owner instanceof Group) { + if (permissionResult.resultType.equals(PermissionCheckResult.Type.NEGATION)) { + sender.sendMessage(ChatColor.RED + "The group inherits the a negation permission from group: " + permissionResult.owner.getName()); + } else { + sender.sendMessage(ChatColor.YELLOW + "The user inherits the permission from group: " + permissionResult.owner.getName()); + } + sender.sendMessage(ChatColor.YELLOW + "Permission Node: " + permissionResult.accessLevel); + + } + return true; + case mangaddi: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group 1 does not exists!"); + return false; + } + auxGroup2 = dataHolder.getGroup(args[1]); + if (auxGroup2 == null) { + sender.sendMessage(ChatColor.RED + "Group 2 does not exists!"); + return false; + } + //VALIDANDO PERMISSAO + if (permissionHandler.searchGroupInInheritance(auxGroup, auxGroup2.getName(), null)) { + sender.sendMessage(ChatColor.RED + "Group " + auxGroup.getName() + " already inherits " + auxGroup2.getName() + " (might not be directly)"); + return false; + } + //PARECE OK + auxGroup.addInherits(auxGroup2); + sender.sendMessage(ChatColor.RED + "Group " + auxGroup2.getName() + " is now in " + auxGroup.getName() + " inheritance list."); + + return true; + case mangdeli: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group 1 does not exists!"); + return false; + } + auxGroup2 = dataHolder.getGroup(args[1]); + if (auxGroup2 == null) { + sender.sendMessage(ChatColor.RED + "Group 2 does not exists!"); + return false; + } + //VALIDANDO PERMISSAO + if (!permissionHandler.searchGroupInInheritance(auxGroup, auxGroup2.getName(), null)) { + sender.sendMessage(ChatColor.RED + "Group " + auxGroup.getName() + " does not inherits " + auxGroup2.getName() + "."); + return false; + } + if (!auxGroup.getInherits().contains(auxGroup2.getName())) { + sender.sendMessage(ChatColor.RED + "Group " + auxGroup.getName() + " does not inherits " + auxGroup2.getName() + " directly."); + return false; + } + //PARECE OK + auxGroup.removeInherits(auxGroup2.getName()); + sender.sendMessage(ChatColor.RED + "Group " + auxGroup2.getName() + " was removed from " + auxGroup.getName() + " inheritance list."); + + return true; + case manuaddv: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length < 3) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + //PARECE OK + auxString = ""; + for (int i = 2; i < args.length; i++) { + auxString += args[i]; + if ((i + 1) < args.length) { + auxString += " "; + } + } + auxUser.getVariables().addVar(args[1], Variables.parseVariableValue(auxString)); + sender.sendMessage(ChatColor.YELLOW + "Variable " + ChatColor.GOLD + args[1] + ChatColor.YELLOW + ":'" + ChatColor.GREEN + auxString + ChatColor.YELLOW + "' added to the user " + auxUser.getName()); + return true; + case manudelv: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + if (!auxUser.getVariables().hasVar(args[1])) { + sender.sendMessage(ChatColor.RED + "The user doesn't have directly that variable!"); + } + //PARECE OK + auxUser.getVariables().removeVar(args[1]); + sender.sendMessage(ChatColor.YELLOW + "Variable " + ChatColor.GOLD + args[1] + ChatColor.YELLOW + " removed from the user " + ChatColor.GREEN + auxUser.getName()); + return true; + case manulistv: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + //PARECE OK + auxString = ""; + for (String varKey : auxUser.getVariables().getVarKeyList()) { + Object o = auxUser.getVariables().getVarObject(varKey); + auxString += ChatColor.GOLD + varKey + ChatColor.WHITE + ":'" + ChatColor.GREEN + o.toString() + ChatColor.WHITE + "', "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + } + sender.sendMessage(ChatColor.YELLOW + "Variables of user " + auxUser.getName() + ": "); + sender.sendMessage(auxString + "."); + sender.sendMessage(ChatColor.YELLOW + "Plus all variables from group: " + auxUser.getGroupName()); + return true; + case manucheckv: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + auxGroup = auxUser.getGroup(); + auxGroup2 = permissionHandler.nextGroupWithVariable(auxGroup, args[1], null); + + if (!auxUser.getVariables().hasVar(args[1])) { + if (auxGroup2 == null) { + sender.sendMessage(ChatColor.RED + "The user doesn't have access to that variable!"); + } + } + //PARECE OK + if (auxUser.getVariables().hasVar(auxString)) { + sender.sendMessage(ChatColor.YELLOW + "The value of variable '" + ChatColor.GOLD + args[1] + ChatColor.YELLOW + "' is: '" + ChatColor.GREEN + auxUser.getVariables().getVarObject(args[1]).toString() + ChatColor.WHITE + "'"); + sender.sendMessage(ChatColor.YELLOW + "This user own directly the variable"); + } + sender.sendMessage(ChatColor.YELLOW + "The value of variable '" + ChatColor.GOLD + args[1] + ChatColor.YELLOW + "' is: '" + ChatColor.GREEN + auxGroup2.getVariables().getVarObject(args[1]).toString() + ChatColor.WHITE + "'"); + if (!auxGroup.equals(auxGroup2)) { + sender.sendMessage(ChatColor.YELLOW + "And the value was inherited from group: " + ChatColor.GREEN + auxGroup2.getName()); + } + return true; + case mangaddv: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length < 3) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group does not exists!"); + return false; + } + //VALIDANDO PERMISSAO + //PARECE OK + auxString = ""; + for (int i = 2; i < args.length; i++) { + auxString += args[i]; + if ((i + 1) < args.length) { + auxString += " "; + } + } + auxGroup.getVariables().addVar(args[1], Variables.parseVariableValue(auxString)); + sender.sendMessage(ChatColor.YELLOW + "Variable " + ChatColor.GOLD + args[1] + ChatColor.YELLOW + ":'" + ChatColor.GREEN + auxString + ChatColor.YELLOW + "' added to the group " + auxGroup.getName()); + + return true; + case mangdelv: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group does not exists!"); + return false; + } + //VALIDANDO PERMISSAO + if (!auxGroup.getVariables().hasVar(args[1])) { + sender.sendMessage(ChatColor.RED + "The group doesn't have directly that variable!"); + } + //PARECE OK + auxGroup.getVariables().removeVar(args[1]); + sender.sendMessage(ChatColor.YELLOW + "Variable " + ChatColor.GOLD + args[1] + ChatColor.YELLOW + " removed from the group " + ChatColor.GREEN + auxGroup.getName()); + + return true; + case manglistv: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group does not exists!"); + return false; + } + //VALIDANDO PERMISSAO + //PARECE OK + auxString = ""; + for (String varKey : auxGroup.getVariables().getVarKeyList()) { + Object o = auxGroup.getVariables().getVarObject(varKey); + auxString += ChatColor.GOLD + varKey + ChatColor.WHITE + ":'" + ChatColor.GREEN + o.toString() + ChatColor.WHITE + "', "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + } + sender.sendMessage(ChatColor.YELLOW + "Variables of group " + auxGroup.getName() + ": "); + sender.sendMessage(auxString + "."); + auxString = ""; + for (String grp : auxGroup.getInherits()) { + auxString += grp + ", "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + sender.sendMessage(ChatColor.YELLOW + "Plus all variables from groups: " + auxString); + } + return true; + case mangcheckv: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + auxGroup = dataHolder.getGroup(args[0]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group does not exists!"); + return false; + } + //VALIDANDO PERMISSAO + auxGroup2 = permissionHandler.nextGroupWithVariable(auxGroup, args[1], null); + if (auxGroup2 == null) { + sender.sendMessage(ChatColor.RED + "The group doesn't have access to that variable!"); + } + //PARECE OK + sender.sendMessage(ChatColor.YELLOW + "The value of variable '" + ChatColor.GOLD + args[1] + ChatColor.YELLOW + "' is: '" + ChatColor.GREEN + auxGroup2.getVariables().getVarObject(args[1]).toString() + ChatColor.WHITE + "'"); + if (!auxGroup.equals(auxGroup2)) { + sender.sendMessage(ChatColor.YELLOW + "And the value was inherited from group: " + ChatColor.GREEN + auxGroup2.getName()); + } + return true; + case manwhois: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //PARECE OK + sender.sendMessage(ChatColor.YELLOW + "Name: " + ChatColor.GREEN + auxUser.getName()); + sender.sendMessage(ChatColor.YELLOW + "Group: " + ChatColor.GREEN + auxUser.getGroup().getName()); + sender.sendMessage(ChatColor.YELLOW + "Overloaded: " + ChatColor.GREEN + dataHolder.isOverloaded(auxUser.getName())); + auxGroup = dataHolder.surpassOverload(auxUser.getName()).getGroup(); + if (!auxGroup.equals(auxUser.getGroup())) { + sender.sendMessage(ChatColor.YELLOW + "Original Group: " + ChatColor.GREEN + auxGroup.getName()); + } + //victim.permissions.add(args[1]); + return true; + //break; + case tempadd: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same permissions than you, or higher."); + return false; + } + //PARECE OK + if (overloadedUsers.get(dataHolder.getName().toLowerCase()) == null) { + overloadedUsers.put(dataHolder.getName().toLowerCase(), new ArrayList()); + } + dataHolder.overloadUser(auxUser.getName()); + overloadedUsers.get(dataHolder.getName().toLowerCase()).add(dataHolder.getUser(auxUser.getName())); + sender.sendMessage(ChatColor.YELLOW + "Player overloaded!"); + + return true; + //break; + case tempdel: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + //VALIDANDO PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same permissions than you, or higher."); + return false; + } + //PARECE OK + if (overloadedUsers.get(dataHolder.getName().toLowerCase()) == null) { + overloadedUsers.put(dataHolder.getName().toLowerCase(), new ArrayList()); + } + dataHolder.removeOverload(auxUser.getName()); + if (overloadedUsers.get(dataHolder.getName().toLowerCase()).contains(auxUser)) { + overloadedUsers.get(dataHolder.getName().toLowerCase()).remove(auxUser); + } + sender.sendMessage(ChatColor.YELLOW + "You removed that player overload. He's back to normal!"); + + return true; + //break; + case templist: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //WORKING + auxString = ""; + removeList = new ArrayList(); + count = 0; + for (User u : overloadedUsers.get(dataHolder.getName().toLowerCase())) { + if (!dataHolder.isOverloaded(u.getName())) { + removeList.add(u); + } else { + auxString += u.getName() + ", "; + count++; + } + } + if (count == 0) { + sender.sendMessage(ChatColor.YELLOW + "There is no users in overload mode"); + return true; + } + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + if (overloadedUsers.get(dataHolder.getName().toLowerCase()) == null) { + overloadedUsers.put(dataHolder.getName().toLowerCase(), new ArrayList()); + } + overloadedUsers.get(dataHolder.getName().toLowerCase()).removeAll(removeList); + sender.sendMessage(ChatColor.YELLOW + " " + count + " Users in overload mode: " + ChatColor.WHITE + auxString); + return true; + case tempdelall: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //WORKING + removeList = new ArrayList(); + count = 0; + for (User u : overloadedUsers.get(dataHolder.getName().toLowerCase())) { + if (dataHolder.isOverloaded(u.getName())) { + dataHolder.removeOverload(u.getName()); + count++; + } + } + if (count == 0) { + sender.sendMessage(ChatColor.YELLOW + "There is no users in overload mode"); + return true; + } + if (overloadedUsers.get(dataHolder.getName().toLowerCase()) == null) { + overloadedUsers.put(dataHolder.getName().toLowerCase(), new ArrayList()); + } + overloadedUsers.get(dataHolder.getName().toLowerCase()).clear(); + sender.sendMessage(ChatColor.YELLOW + " " + count + " Users in overload mode. Now they are normal again."); + + return true; + case mansave: + worldsHolder.saveChanges(); + sender.sendMessage(ChatColor.YELLOW + " The changes were saved."); + return true; + case manload: + //THIS CASE DONT NEED SENDER + if (args.length > 0) { + auxString = ""; + for (int i = 0; i < args.length; i++) { + auxString += args[i]; + if ((i + 1) < args.length) { + auxString += " "; + } + } + worldsHolder.loadWorld(auxString); + sender.sendMessage("The request to world '" + auxString + "' was sent."); + return true; + } + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //WORKING + config.load(); + if (args.length > 0) { + auxString = ""; + for (int i = 0; i < args.length; i++) { + auxString += args[i]; + if ((i + 1) < args.length) { + auxString += " "; + } + } + worldsHolder.loadWorld(auxString); + sender.sendMessage("The request to world '" + auxString + "' was sent."); + } else { + worldsHolder.reloadAll(); + sender.sendMessage(ChatColor.YELLOW + " The current world was reloaded."); + } + worldsHolder.mirrorSetUp(); + return true; + case listgroups: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //WORKING + auxString = ""; + for (Group g : dataHolder.getGroupList()) { + auxString += g.getName() + ", "; + } + if (auxString.lastIndexOf(",") > 0) { + auxString = auxString.substring(0, auxString.lastIndexOf(",")); + } + sender.sendMessage(ChatColor.YELLOW + " Groups Available: " + ChatColor.WHITE + auxString); + return true; + case manpromote: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + auxGroup = dataHolder.getGroup(args[1]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group not found!"); + return false; + } + //VALIDANDO PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same permissions than you, or higher."); + return false; + } + if (!isConsole && (permissionHandler.hasGroupInInheritance(auxGroup, senderGroup.getName()))) { + sender.sendMessage(ChatColor.RED + "The destination group can't be the same as yours, or higher."); + return false; + } + if (!isConsole && (!permissionHandler.inGroup(senderUser.getName(), auxUser.getGroupName()) || !permissionHandler.inGroup(senderUser.getName(), auxGroup.getName()))) { + sender.sendMessage(ChatColor.RED + "Can't modify player involving a group that you don't inherit."); + return false; + } + if (!isConsole && (!permissionHandler.hasGroupInInheritance(auxUser.getGroup(), auxGroup.getName()) && !permissionHandler.hasGroupInInheritance(auxGroup, auxUser.getGroupName()))) { + sender.sendMessage(ChatColor.RED + "Can't modify player using groups with different heritage line."); + return false; + } + if (!isConsole && (!permissionHandler.hasGroupInInheritance(auxGroup, auxUser.getGroupName()))) { + sender.sendMessage(ChatColor.RED + "The new group must be a higher rank."); + return false; + } + //PARECE OK + auxUser.setGroup(auxGroup); + sender.sendMessage(ChatColor.YELLOW + "You changed " + auxUser.getName() + " group to " + auxGroup.getName() + "."); + + return true; + //break; + case mandemote: + //VALIDANDO ESTADO DO SENDER + if (dataHolder == null || permissionHandler == null) { + sender.sendMessage(ChatColor.RED + "Couldn't retrieve your world. World selection is needed."); + sender.sendMessage(ChatColor.RED + "Use /manselect "); + return true; + } + //VALIDANDO ARGUMENTOS + if (args.length != 2) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + if (validateOnlinePlayer) { + match = this.getServer().matchPlayer(args[0]); + if (match.size() != 1) { + sender.sendMessage(ChatColor.RED + "Player not found!"); + return false; + } + } + if (match != null) { + auxUser = dataHolder.getUser(match.get(0).getName()); + } else { + auxUser = dataHolder.getUser(args[0]); + } + auxGroup = dataHolder.getGroup(args[1]); + if (auxGroup == null) { + sender.sendMessage(ChatColor.RED + "Group not found!"); + return false; + } + //VALIDANDO PERMISSAO + if (!isConsole && (senderGroup != null ? permissionHandler.inGroup(auxUser.getName(), senderGroup.getName()) : false)) { + sender.sendMessage(ChatColor.RED + "Can't modify player with same permissions than you, or higher."); + return false; + } + if (!isConsole && (permissionHandler.hasGroupInInheritance(auxGroup, senderGroup.getName()))) { + sender.sendMessage(ChatColor.RED + "The destination group can't be the same as yours, or higher."); + return false; + } + if (!isConsole && (!permissionHandler.inGroup(senderUser.getName(), auxUser.getGroupName()) || !permissionHandler.inGroup(senderUser.getName(), auxGroup.getName()))) { + sender.sendMessage(ChatColor.RED + "Can't modify player involving a group that you don' inherit."); + return false; + } + if (!isConsole && (!permissionHandler.hasGroupInInheritance(auxUser.getGroup(), auxGroup.getName()) && !permissionHandler.hasGroupInInheritance(auxGroup, auxUser.getGroupName()))) { + sender.sendMessage(ChatColor.RED + "Can't modify player using groups with different heritage line."); + return false; + } + if (!isConsole && (permissionHandler.hasGroupInInheritance(auxGroup, auxUser.getGroupName()))) { + sender.sendMessage(ChatColor.RED + "The new group must be a lower rank."); + return false; + } + //PARECE OK + auxUser.setGroup(auxGroup); + sender.sendMessage(ChatColor.YELLOW + "You changed " + auxUser.getName() + " group to " + auxGroup.getName() + "."); + + return true; + //break; + case mantogglevalidate: + validateOnlinePlayer = !validateOnlinePlayer; + sender.sendMessage(ChatColor.YELLOW + "Validade if player is online, now set to: " + Boolean.toString(validateOnlinePlayer)); + if (!validateOnlinePlayer) { + sender.sendMessage(ChatColor.GOLD + "From now on you can edit players not connected... BUT:"); + sender.sendMessage(ChatColor.LIGHT_PURPLE + "From now on you should type the whole name of the player, correctly."); + } + return true; + case mantogglesave: + if (scheduler == null) { + enableScheduler(); + sender.sendMessage(ChatColor.YELLOW + "The auto-saving is enabled!"); + } else { + disableScheduler(); + sender.sendMessage(ChatColor.YELLOW + "The auto-saving is disabled!"); + } + return true; + case manworld: + auxString = selectedWorlds.get(sender); + if (auxString != null) { + sender.sendMessage(ChatColor.YELLOW + "You have the world '" + dataHolder.getName() + "' in your selection."); + } else { + if (dataHolder == null) { + sender.sendMessage(ChatColor.YELLOW + "There is no world selected. And no world is available now."); + } else { + sender.sendMessage(ChatColor.YELLOW + "You don't have a world in your selection.."); + sender.sendMessage(ChatColor.YELLOW + "Working with the direct world where your player is."); + sender.sendMessage(ChatColor.YELLOW + "Your world now uses permissions of world name: '" + dataHolder.getName() + "' "); + } + } + return true; + case manselect: + if (args.length < 1) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + sender.sendMessage(ChatColor.YELLOW + "Worlds available: "); + ArrayList worlds = worldsHolder.allWorldsDataList(); + auxString = ""; + for (int i = 0; i < worlds.size(); i++) { + auxString += worlds.get(i).getName(); + if ((i + 1) < worlds.size()) { + auxString += ", "; + } + } + sender.sendMessage(ChatColor.YELLOW + auxString); + return false; + } + auxString = ""; + for (int i = 0; i < args.length; i++) { + if (args[i] == null) { + logger.warning("Bukkit gave invalid arguments array! Cmd: " + cmd.getName() + " args.length: " + args.length); + return false; + } + auxString += args[i]; + if (i < (args.length - 1)) { + auxString += " "; + } + } + dataHolder = worldsHolder.getWorldData(auxString); + permissionHandler = dataHolder.getPermissionsHandler(); + selectedWorlds.put(sender, dataHolder.getName()); + sender.sendMessage(ChatColor.YELLOW + "You have selected world '" + dataHolder.getName() + "'."); + return true; + case manclear: + if (args.length != 0) { + sender.sendMessage(ChatColor.RED + "Review your arguments count!"); + return false; + } + selectedWorlds.remove(sender); + sender.sendMessage(ChatColor.YELLOW + "You have removed your world selection. Working with current world(if possible)."); + return true; + default: + break; + } + } + sender.sendMessage(ChatColor.RED + "You are not allowed to use that command."); + return false; + } + + /** + * @return the config + */ + public GMConfiguration getConfig() { + return config; + } + + /** + * @return the backupFolder + */ + public File getBackupFolder() { + return backupFolder; + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/DataUnit.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/DataUnit.java new file mode 100644 index 000000000..3eb7491dd --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/DataUnit.java @@ -0,0 +1,114 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.data; + +import java.util.ArrayList; +import java.util.Collections; +import org.anjocaido.groupmanager.GroupManager; +import org.anjocaido.groupmanager.dataholder.WorldDataHolder; +import org.anjocaido.groupmanager.utils.StringPermissionComparator; + +/** + * + * @author gabrielcouto + */ +public abstract class DataUnit { + + private WorldDataHolder dataSource; + private String name; + private boolean changed; + private ArrayList permissions = new ArrayList(); + + public DataUnit(WorldDataHolder dataSource, String name) { + this.dataSource = dataSource; + this.name = name; + } + + /** + * Every group is matched only by their names and DataSources names. + * @param o + * @return true if they are equal. false if not. + */ + @Override + public boolean equals(Object o) { + if (o instanceof DataUnit) { + DataUnit go = (DataUnit) o; + if (this.getName().equalsIgnoreCase(go.getName()) && this.dataSource.getName().equalsIgnoreCase(go.getDataSource().getName())) { + return true; + } + } + return false; + } + + @Override + public int hashCode() { + int hash = 5; + hash = 71 * hash + (this.name != null ? this.name.toLowerCase().hashCode() : 0); + return hash; + } + + + + + /** + * @return the dataSource + */ + public WorldDataHolder getDataSource() { + return dataSource; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + public void flagAsChanged() { + GroupManager.logger.finest("DataSource: "+getDataSource().getName()+" - DataUnit: "+getName()+" flagged as changed!"); +// for(StackTraceElement st: Thread.currentThread().getStackTrace()){ +// GroupManager.logger.finest(st.toString()); +// } + changed = true; + } + + public boolean isChanged() { + return changed; + } + + public void flagAsSaved() { + GroupManager.logger.finest("DataSource: "+getDataSource().getName()+" - DataUnit: "+getName()+" flagged as saved!"); + changed = false; + } + + public boolean hasSamePermissionNode(String permission) { + return permissions.contains(permission); + } + + public void addPermission(String permission) { + if (!hasSamePermissionNode(permission)) { + permissions.add(permission); + } + flagAsChanged(); + } + + public boolean removePermission(String permission) { + flagAsChanged(); + return permissions.remove(permission); + } + + /** + * Use this only to list permissions. + * You can't edit the permissions using the returned ArrayList instance + * @return a copy of the permission list + */ + public ArrayList getPermissionList() { + return (ArrayList) permissions.clone(); + } + + public void sortPermissions(){ + Collections.sort(permissions, StringPermissionComparator.getInstance()); + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/Group.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/Group.java new file mode 100644 index 000000000..c734b208e --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/Group.java @@ -0,0 +1,122 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.data; + +import org.anjocaido.groupmanager.dataholder.WorldDataHolder; +import java.util.ArrayList; +import java.util.Map; + +/** + * + * @author gabrielcouto + */ +public class Group extends DataUnit implements Cloneable { + + /** + * The group it inherits DIRECTLY! + */ + private ArrayList inherits = new ArrayList(); + /** + *This one holds the fields in INFO node. + * like prefix = 'c' + * or build = false + */ + private GroupVariables variables = new GroupVariables(this); + + /** + * + * @param name + */ + public Group(WorldDataHolder source, String name) { + super(source,name); + } + + /** + * Clone this group + * @return a clone of this group + */ + @Override + public Group clone() { + Group clone = new Group(getDataSource(), this.getName()); + clone.inherits = ((ArrayList) this.getInherits().clone()); + for(String perm: this.getPermissionList()){ + clone.addPermission(perm); + } + clone.variables = ((GroupVariables) variables).clone(clone); + //clone.flagAsChanged(); + return clone; + } + + /** + * Use this to deliver a group from a different dataSource to another + * @param dataSource + * @return + */ + public Group clone(WorldDataHolder dataSource) { + if (dataSource.groupExists(this.getName())) { + return null; + } + Group clone = getDataSource().createGroup(this.getName()); + clone.inherits = ((ArrayList) this.getInherits().clone()); + for(String perm: this.getPermissionList()){ + clone.addPermission(perm); + } + clone.variables = variables.clone(clone); + clone.flagAsChanged(); //use this to make the new dataSource save the new group + return clone; + } + + /** + * a COPY of inherits list + * You can't manage the list by here + * Lol... version 0.6 had a problem because this. + * @return the inherits + */ + public ArrayList getInherits() { + return (ArrayList) inherits.clone(); + } + + /** + * @param inherits the inherits to set + */ + public void addInherits(Group inherit) { + if (!this.getDataSource().groupExists(inherit.getName())) { + getDataSource().addGroup(inherit); + } + if (!inherits.contains(inherit.getName().toLowerCase())) { + inherits.add(inherit.getName().toLowerCase()); + } + flagAsChanged(); + } + + public boolean removeInherits(String inherit) { + if (this.inherits.contains(inherit.toLowerCase())) { + this.inherits.remove(inherit.toLowerCase()); + flagAsChanged(); + return true; + } + return false; + } + + /** + * @return the variables + */ + public GroupVariables getVariables() { + return variables; + } + + /** + * + * @param varList + */ + public void setVariables(Map varList) { + GroupVariables temp = new GroupVariables(this, varList); + variables.clearVars(); + for(String key: temp.getVarKeyList()){ + variables.addVar(key, temp.getVarObject(key)); + } + flagAsChanged(); + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/GroupVariables.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/GroupVariables.java new file mode 100644 index 000000000..87c34de2b --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/GroupVariables.java @@ -0,0 +1,87 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.data; + +import java.util.Map; + +/** + * + * @author gabrielcouto + */ +public class GroupVariables extends Variables implements Cloneable { + + private Group owner; + + public GroupVariables(Group owner) { + super(owner); + this.owner = owner; + addVar("prefix", ""); + addVar("suffix", ""); + addVar("build", false); + } + + public GroupVariables(Group owner, Map varList) { + super(owner); + variables = varList; + if (variables.get("prefix") == null) { + variables.put("prefix", ""); + owner.flagAsChanged(); + } + //thisGrp.prefix = infoNode.get("prefix").toString(); + + if (variables.get("suffix") == null) { + variables.put("suffix", ""); + owner.flagAsChanged(); + } + //thisGrp.suffix = infoNode.get("suffix").toString(); + + if (variables.get("build") == null) { + variables.put("build", false); + owner.flagAsChanged(); + } + this.owner = owner; + } + + /** + * A clone of all vars here. + * @return + */ + protected GroupVariables clone(Group newOwner) { + GroupVariables clone = new GroupVariables(newOwner); + for (String key : variables.keySet()) { + clone.variables.put(key, variables.get(key)); + } + newOwner.flagAsChanged(); + return clone; + } + + /** + * Remove a var from the list + * @param name + */ + @Override + public void removeVar(String name) { + try { + this.variables.remove(name); + } catch (Exception e) { + } + if (name.equals("prefix")) { + addVar("prefix", ""); + } else if (name.equals("suffix")) { + addVar("suffix", ""); + } else if (name.equals("build")) { + addVar("build", false); + } + owner.flagAsChanged(); + } + + /** + * @return the owner + */ + @Override + public Group getOwner() { + return owner; + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/User.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/User.java new file mode 100644 index 000000000..ceecbfa21 --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/User.java @@ -0,0 +1,187 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.data; + +import com.sun.org.apache.bcel.internal.generic.AALOAD; +import java.util.ArrayList; +import org.anjocaido.groupmanager.dataholder.WorldDataHolder; +import java.util.Map; + +/** + * + * @author gabrielcouto + */ +public class User extends DataUnit implements Cloneable { + + /** + * + */ + private String group = null; + private ArrayList subGroups = new ArrayList(); + /** + *This one holds the fields in INFO node. + * like prefix = 'c' + * or build = false + */ + private UserVariables variables = new UserVariables(this); + + + /** + * + * @param name + */ + public User(WorldDataHolder source, String name) { + super(source,name); + this.group = source.getDefaultGroup().getName(); + } + + /** + * + * @return + */ + @Override + public User clone() { + User clone = new User(getDataSource(), this.getName()); + clone.group = this.group; + for(String perm: this.getPermissionList()){ + clone.addPermission(perm); + } + //clone.variables = this.variables.clone(); + //clone.flagAsChanged(); + return clone; + } + + /** + * Use this to deliver a user from one WorldDataHolder to another + * @param dataSource + * @return null if given dataSource already contains the same user + */ + public User clone(WorldDataHolder dataSource) { + if (dataSource.isUserDeclared(this.getName())) { + return null; + } + User clone = dataSource.createUser(this.getName()); + if (dataSource.getGroup(group) == null) { + clone.setGroup(dataSource.getDefaultGroup()); + } else { + clone.setGroup(this.getGroupName()); + } + for(String perm: this.getPermissionList()){ + clone.addPermission(perm); + } + //clone.variables = this.variables.clone(); + clone.flagAsChanged(); + return clone; + } + + public Group getGroup() { + Group result = getDataSource().getGroup(group); + if (result == null) { + this.setGroup(getDataSource().getDefaultGroup()); + result = getDataSource().getDefaultGroup(); + } + return result; + } + + /** + * @return the group + */ + public String getGroupName() { + Group result = getDataSource().getGroup(group); + if (result == null) { + group = getDataSource().getDefaultGroup().getName(); + } + return group; + } + + /** + * @param group the group to set + */ + @Deprecated + public void setGroup(String group) { + this.group = group; + flagAsChanged(); + } + + /** + * @param group the group to set + */ + public void setGroup(Group group) { + if (!this.getDataSource().groupExists(group.getName())) { + getDataSource().addGroup(group); + } + group = getDataSource().getGroup(group.getName()); + this.group = group.getName(); + flagAsChanged(); + } + + public void addSubGroup(Group subGroup){ + if(this.group.equalsIgnoreCase(subGroup.getName())){ + return; + } + if (!this.getDataSource().groupExists(subGroup.getName())) { + getDataSource().addGroup(subGroup); + } + subGroup = getDataSource().getGroup(subGroup.getName()); + removeSubGroup(subGroup); + subGroups.add(subGroup.getName()); + flagAsChanged(); + } + public int subGroupsSize(){ + return subGroups.size(); + } + public boolean isSubGroupsEmpty(){ + return subGroups.isEmpty(); + } + public boolean containsSubGroup(Group subGroup){ + return subGroups.contains(subGroup.getName()); + } + public boolean removeSubGroup(Group subGroup){ + try{ + if(subGroups.remove(subGroup.getName())){ + flagAsChanged(); + return true; + } + } catch (Exception e){ + + } + return false; + } + public ArrayList subGroupListCopy(){ + ArrayList val = new ArrayList(); + for(String gstr: subGroups){ + Group g = getDataSource().getGroup(gstr); + if(g==null){ + removeSubGroup(g); + continue; + } + val.add(g); + } + return val; + } + public ArrayList subGroupListStringCopy(){ + return (ArrayList) subGroups.clone(); + } + + /** + * @return the variables + */ + public UserVariables getVariables() { + return variables; + } + + /** + * + * @param varList + */ + public void setVariables(Map varList) { + UserVariables temp = new UserVariables(this, varList); + variables.clearVars(); + for(String key: temp.getVarKeyList()){ + variables.addVar(key, temp.getVarObject(key)); + } + flagAsChanged(); + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/UserVariables.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/UserVariables.java new file mode 100644 index 000000000..45dfc31e7 --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/UserVariables.java @@ -0,0 +1,45 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package org.anjocaido.groupmanager.data; + +import java.util.Map; + +/** + * + * @author gabrielcouto + */ +public class UserVariables extends Variables{ + private User owner; + public UserVariables(User owner){ + super(owner); + this.owner = owner; + } + public UserVariables(User owner, Map varList) { + super(owner); + this.variables = varList; + this.owner = owner; + } + /** + * A clone of all vars here. + * @return + */ + protected UserVariables clone(User newOwner) { + UserVariables clone = new UserVariables(newOwner); + for (String key : variables.keySet()) { + clone.variables.put(key, variables.get(key)); + } + newOwner.flagAsChanged(); + return clone; + } + /** + * @return the owner + */ + @Override + public User getOwner() { + return owner; + } + +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/Variables.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/Variables.java new file mode 100644 index 000000000..31ed0d795 --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/data/Variables.java @@ -0,0 +1,192 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.data; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + *A class that holds variables of a user/group. + * In groups, it holds the contents of INFO node. + * Like: + * prefix + * suffix + * build + * + * @author gabrielcouto + */ +public abstract class Variables implements Cloneable { + private DataUnit owner; + protected Map variables = new HashMap(); + + public Variables(DataUnit owner){ + this.owner = owner; + } + /** + * Add var to the the INFO node. + * examples: + * addVar("build",true); + * addVar("prefix","c"); + * @param name key name of the var + * @param o the object value of the var + */ + public void addVar(String name, Object o) { + if (o == null) { + return; + } + if (variables.containsKey(name)) { + variables.remove(name); + } + variables.put(name, o); + owner.flagAsChanged(); + } + + /** + * Returns the object inside the var + * @param name + * @return a Object if exists. null if doesn't exists + */ + public Object getVarObject(String name) { + return variables.get(name); + } + + /** + * Get the String value for the given var name + * @param name the var key name + * @return "" if null. or the toString() value of object + */ + public String getVarString(String name) { + Object o = variables.get(name); + try { + return o == null ? "" : o.toString(); + } catch (Exception e) { + return ""; + } + } + + /** + * + * @param name + * @return false if null. or a Boolean.parseBoolean of the string + */ + public Boolean getVarBoolean(String name) { + Object o = variables.get(name); + try { + return o == null ? false : Boolean.parseBoolean(o.toString()); + } catch (Exception e) { + return false; + } + } + + /** + * + * @param name + * @return -1 if null. or a parseInt of the string + */ + public Integer getVarInteger(String name) { + Object o = variables.get(name); + try { + return o == null ? -1 : Integer.parseInt(o.toString()); + } catch (Exception e) { + return -1; + } + } + + /** + * + * @param name + * @return -1 if null. or a parseDouble of the string + */ + public Double getVarDouble(String name) { + Object o = variables.get(name); + try { + return o == null ? -1.0D : Double.parseDouble(o.toString()); + } catch (Exception e) { + return -1.0D; + + + } + } + + /** + * All variable keys this is holding + * @return + */ + public Set getVarKeyList() { + return variables.keySet(); + + + } + + /** + * verify is a var exists + * @param name the key name of the var + * @return true if that var exists + */ + public boolean hasVar(String name) { + return variables.containsKey(name); + + + } + + /** + * Returns the quantity of vars this is holding + * @return the number of vars + */ + public int getSize() { + return variables.size(); + + + } + + /** + * Remove a var from the list + * @param name + */ + public void removeVar(String name) { + try { + variables.remove(name); + } catch (Exception e) { + } + owner.flagAsChanged(); + } + + public static Object parseVariableValue(String value) { + try { + Integer i = Integer.parseInt(value); + return i; + } catch (NumberFormatException e) { + } + try { + Double d = Double.parseDouble(value); + return d; + } catch (NumberFormatException e) { + } + if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("yes") || value.equalsIgnoreCase("on")) { + return true; + } else if (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("no") || value.equalsIgnoreCase("off")) { + return false; + } + return value; + + } + + public void clearVars(){ + variables.clear(); + owner.flagAsChanged(); + } + + /** + * @return the owner + */ + public DataUnit getOwner() { + return owner; + } + + public boolean isEmpty(){ + return variables.isEmpty(); + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/OverloadedWorldHolder.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/OverloadedWorldHolder.java new file mode 100644 index 000000000..f735ff5e6 --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/OverloadedWorldHolder.java @@ -0,0 +1,204 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.dataholder; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import org.anjocaido.groupmanager.data.User; + +/** + * + * @author gabrielcouto + */ +public class OverloadedWorldHolder extends WorldDataHolder { + + /** + * + */ + protected Map overloadedUsers = new HashMap(); + + /** + * + * @param ph + */ + public OverloadedWorldHolder(WorldDataHolder ph) { + super(ph.getName()); + this.f = ph.f; + this.groupsFile = ph.groupsFile; + this.usersFile = ph.usersFile; + this.defaultGroup = ph.defaultGroup; + this.groups = ph.groups; + this.users = ph.users; + } + + /** + * + * @param userName + * @return + */ + @Override + public User getUser(String userName) { + //OVERLOADED CODE + if (overloadedUsers.containsKey(userName.toLowerCase())) { + return overloadedUsers.get(userName.toLowerCase()); + } + //END CODE + if (users.containsKey(userName.toLowerCase())) { + return users.get(userName.toLowerCase()); + } + User newUser = createUser(userName); + haveUsersChanged = true; + return newUser; + } + + /** + * + * @param theUser + */ + @Override + public void addUser(User theUser) { + if (theUser.getDataSource() != this) { + theUser = theUser.clone(this); + } + if (theUser == null) { + return; + } + if ((theUser.getGroup() == null) || (!groups.containsKey(theUser.getGroupName().toLowerCase()))) { + theUser.setGroup(defaultGroup); + } + //OVERLOADED CODE + if (overloadedUsers.containsKey(theUser.getName().toLowerCase())) { + overloadedUsers.remove(theUser.getName().toLowerCase()); + overloadedUsers.put(theUser.getName().toLowerCase(), theUser); + return; + } + //END CODE + removeUser(theUser.getName()); + users.put(theUser.getName().toLowerCase(), theUser); + haveUsersChanged = true; + } + + /** + * + * @param userName + * @return + */ + @Override + public boolean removeUser(String userName) { + //OVERLOADED CODE + if (overloadedUsers.containsKey(userName.toLowerCase())) { + overloadedUsers.remove(userName.toLowerCase()); + return true; + } + //END CODE + if (users.containsKey(userName.toLowerCase())) { + users.remove(userName.toLowerCase()); + haveUsersChanged = true; + return true; + } + return false; + } + + @Override + public boolean removeGroup(String groupName) { + if (groupName.equals(defaultGroup)) { + return false; + } + for (String key : groups.keySet()) { + if (groupName.equalsIgnoreCase(key)) { + groups.remove(key); + for (String userKey : users.keySet()) { + User user = users.get(userKey); + if (user.getGroupName().equalsIgnoreCase(key)) { + user.setGroup(defaultGroup); + } + + } + //OVERLOADED CODE + for (String userKey : overloadedUsers.keySet()) { + User user = overloadedUsers.get(userKey); + if (user.getGroupName().equalsIgnoreCase(key)) { + user.setGroup(defaultGroup); + } + + } + //END OVERLOAD + haveGroupsChanged = true; + return true; + } + } + return false; + } + + /** + * + * @return + */ + @Override + public Collection getUserList() { + Collection overloadedList = new ArrayList(); + Collection normalList = users.values(); + for (User u : normalList) { + if (overloadedUsers.containsKey(u.getName().toLowerCase())) { + overloadedList.add(overloadedUsers.get(u.getName().toLowerCase())); + } else { + overloadedList.add(u); + } + } + return overloadedList; + } + + /** + * + * @param userName + * @return + */ + public boolean isOverloaded(String userName) { + return overloadedUsers.containsKey(userName.toLowerCase()); + } + + /** + * + * @param userName + */ + public void overloadUser(String userName) { + if (!isOverloaded(userName)) { + User theUser = getUser(userName); + theUser = theUser.clone(); + if (overloadedUsers.containsKey(theUser.getName().toLowerCase())) { + overloadedUsers.remove(theUser.getName().toLowerCase()); + } + overloadedUsers.put(theUser.getName().toLowerCase(), theUser); + } + } + + /** + * + * @param userName + */ + public void removeOverload(String userName) { + overloadedUsers.remove(userName.toLowerCase()); + } + + /** + * Gets the user in normal state. Surpassing the overload state. + * It doesn't affect permissions. But it enables plugins change the + * actual user permissions even in overload mode. + * @param userName + * @return + */ + public User surpassOverload(String userName) { + if (!isOverloaded(userName)) { + return getUser(userName); + } + if (users.containsKey(userName.toLowerCase())) { + return users.get(userName.toLowerCase()); + } + User newUser = createUser(userName); + return newUser; + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/WorldDataHolder.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/WorldDataHolder.java new file mode 100644 index 000000000..96e517abd --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/WorldDataHolder.java @@ -0,0 +1,939 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.dataholder; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.anjocaido.groupmanager.GroupManager; +import org.anjocaido.groupmanager.data.Group; +import org.anjocaido.groupmanager.data.User; +import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler; +import org.bukkit.Server; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.reader.UnicodeReader; + +/** + * + * @author gabrielcouto + */ +public class WorldDataHolder { + + /** + * + */ + protected String name; + /** + * The actual groups holder + */ + protected Map groups = new HashMap(); + /** + * The actual users holder + */ + protected Map users = new HashMap(); + /** + * Points to the default group + */ + protected Group defaultGroup = null; + /** + * The file, which this class loads/save data from/to + * @deprecated + */ + @Deprecated + protected File f; + /** + * + */ + protected AnjoPermissionsHandler permissionsHandler; + /** + * + */ + protected File usersFile; + /** + * + */ + protected File groupsFile; + /** + * + */ + protected boolean haveUsersChanged = false; + /** + * + */ + protected boolean haveGroupsChanged = false; + + /** + * Prevent direct instantiation + * @param worldName + */ + protected WorldDataHolder(String worldName) { + name = worldName; + } + + /** + * The main constructor for a new WorldDataHolder + * Please don't set the default group as null + * @param worldName + * @param defaultGroup the default group. its good to start with one + */ + public WorldDataHolder(String worldName, Group defaultGroup) { + this.name = worldName; + groups.put(defaultGroup.getName().toLowerCase(), defaultGroup); + this.defaultGroup = defaultGroup; + } + + /** + * Search for a user. If it doesn't exist, create a new one with + * default group. + * + * @param userName the name of the user + * @return class that manage that user permission + */ + public User getUser(String userName) { + if (users.containsKey(userName.toLowerCase())) { + return users.get(userName.toLowerCase()); + } + User newUser = createUser(userName); + return newUser; + } + + /** + * Add a user to the list. If it already exists, overwrite the old. + * @param theUser the user you want to add to the permission list + */ + public void addUser(User theUser) { + if (theUser.getDataSource() != this) { + theUser = theUser.clone(this); + } + if (theUser == null) { + return; + } + if ((theUser.getGroup() == null)) { + theUser.setGroup(defaultGroup); + } + removeUser(theUser.getName()); + users.put(theUser.getName().toLowerCase(), theUser); + haveUsersChanged = true; + } + + /** + * Removes the user from the list. (he might become a default user) + * @param userName the username from the user to remove + * @return true if it had something to remove + */ + public boolean removeUser(String userName) { + if (users.containsKey(userName.toLowerCase())) { + users.remove(userName.toLowerCase()); + haveUsersChanged = true; + return true; + } + return false; + } + + /** + * + * @param userName + * @return + */ + public boolean isUserDeclared(String userName) { + return users.containsKey(userName.toLowerCase()); + } + + /** + * Change the default group of the file. + * @param group the group you want make default. + */ + public void setDefaultGroup(Group group) { + if (!groups.containsKey(group.getName().toLowerCase()) || (group.getDataSource() != this)) { + addGroup(group); + } + defaultGroup = this.getGroup(group.getName()); + haveGroupsChanged = true; + } + + /** + * Returns the default group of the file + * @return the default group + */ + public Group getDefaultGroup() { + return defaultGroup; + } + + /** + * Returns a group of the given name + * @param groupName the name of the group + * @return a group if it is found. null if not found. + */ + public Group getGroup(String groupName) { + return groups.get(groupName.toLowerCase()); + } + + /** + * Check if a group exists. + * Its the same of getGroup, but check if it is null. + * @param groupName the name of the group + * @return true if exists. false if not. + */ + public boolean groupExists(String groupName) { + return groups.containsKey(groupName.toLowerCase()); + } + + /** + * Add a group to the list + * @param groupToAdd + */ + public void addGroup(Group groupToAdd) { + if (groupToAdd.getDataSource() != this) { + groupToAdd = groupToAdd.clone(this); + } + removeGroup(groupToAdd.getName()); + groups.put(groupToAdd.getName().toLowerCase(), groupToAdd); + haveGroupsChanged = true; + } + + /** + * Remove the group to the list + * @param groupName + * @return true if had something to remove. false the group was default or non-existant + */ + public boolean removeGroup(String groupName) { + if (defaultGroup != null && groupName.equalsIgnoreCase(defaultGroup.getName())) { + return false; + } + if (groups.containsKey(groupName.toLowerCase())) { + groups.remove(groupName.toLowerCase()); + haveGroupsChanged = true; + return true; + } + return false; + + } + + /** + * Creates a new User with the given name + * and adds it to this holder. + * @param userName the username you want + * @return null if user already exists. or new User + */ + public User createUser(String userName) { + if (this.users.containsKey(userName.toLowerCase())) { + return null; + } + User newUser = new User(this, userName); + newUser.setGroup(defaultGroup); + this.addUser(newUser); + haveUsersChanged = true; + return newUser; + } + + /** + * Creates a new Group with the given name + * and adds it to this holder + * @param groupName the groupname you want + * @return null if group already exists. or new Group + */ + public Group createGroup(String groupName) { + if (this.groups.containsKey(groupName.toLowerCase())) { + return null; + } + Group newGroup = new Group(this, groupName); + this.addGroup(newGroup); + haveGroupsChanged = true; + return newGroup; + } + + /** + * + * @return a collection of the groups + */ + public Collection getGroupList() { + return groups.values(); + } + + /** + * + * @return a collection of the users + */ + public Collection getUserList() { + return users.values(); + } + + /** + * reads the file again + */ + public void reload() { + try { + WorldDataHolder ph = load(this.getName(), getGroupsFile(), getUsersFile()); + this.defaultGroup = ph.defaultGroup; + this.groups = ph.groups; + this.users = ph.users; + } catch (Exception ex) { + Logger.getLogger(WorldDataHolder.class.getName()).log(Level.SEVERE, null, ex); + } + } + + /** + * Save by yourself! + * @deprecated + */ + @Deprecated + public void commit() { + writeGroups(this, getGroupsFile()); + writeUsers(this, getUsersFile()); + } + + /** + * Returns a data holder for the given file + * @param worldName + * @param file + * @return + * @throws Exception + * @deprecated + */ + @Deprecated + public static WorldDataHolder load(String worldName, File file) throws Exception { + WorldDataHolder ph = new WorldDataHolder(worldName); + ph.f = file; + final Yaml yaml = new Yaml(new SafeConstructor()); + Map rootDataNode; + if (!file.exists()) { + throw new Exception("The file which should contain permissions does not exist!\n" + file.getPath()); + } + FileInputStream rx = new FileInputStream(file); + try { + rootDataNode = (Map) yaml.load(new UnicodeReader(rx)); + if (rootDataNode == null) { + throw new NullPointerException(); + } + } catch (Exception ex) { + throw new Exception("The following file couldn't pass on Parser.\n" + file.getPath(), ex); + } finally { + rx.close(); + } + Map> inheritance = new HashMap>(); + try { + Map allGroupsNode = (Map) rootDataNode.get("groups"); + for (String groupKey : allGroupsNode.keySet()) { + Map thisGroupNode = (Map) allGroupsNode.get(groupKey); + Group thisGrp = ph.createGroup(groupKey); + if (thisGrp == null) { + throw new IllegalArgumentException("I think this user was declared more than once: " + groupKey); + } + if (thisGroupNode.get("default") == null) { + thisGroupNode.put("default", false); + } + if ((Boolean.parseBoolean(thisGroupNode.get("default").toString()))) { + if (ph.getDefaultGroup() != null) { + GroupManager.logger.warning("The group " + thisGrp.getName() + " is declaring be default where" + ph.getDefaultGroup().getName() + " already was."); + GroupManager.logger.warning("Overriding first request."); + } + ph.setDefaultGroup(thisGrp); + } + + //PERMISSIONS NODE + if (thisGroupNode.get("permissions") == null) { + thisGroupNode.put("permissions", new ArrayList()); + } + if (thisGroupNode.get("permissions") instanceof List) { + for (Object o : ((List) thisGroupNode.get("permissions"))) { + thisGrp.addPermission(o.toString()); + } + } else if (thisGroupNode.get("permissions") instanceof String) { + thisGrp.addPermission((String) thisGroupNode.get("permissions")); + } else { + throw new IllegalArgumentException("Unknown type of permissions node(Should be String or List): " + thisGroupNode.get("permissions").getClass().getName()); + } + + //INFO NODE + Map infoNode = (Map) thisGroupNode.get("info"); + if (infoNode != null) { + thisGrp.setVariables(infoNode); + } + + //END INFO NODE + + Object inheritNode = thisGroupNode.get("inheritance"); + if (inheritNode == null) { + thisGroupNode.put("inheritance", new ArrayList()); + } else if (inheritNode instanceof List) { + List groupsInh = (List) inheritNode; + for (String grp : groupsInh) { + if (inheritance.get(groupKey) == null) { + List thisInherits = new ArrayList(); + inheritance.put(groupKey, thisInherits); + } + inheritance.get(groupKey).add(grp); + + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + throw new Exception("Your Permissions config file is invalid. See console for details."); + } + if (ph.defaultGroup == null) { + throw new IllegalArgumentException("There was no Default Group declared."); + } + for (String groupKey : inheritance.keySet()) { + List inheritedList = inheritance.get(groupKey); + Group thisGroup = ph.getGroup(groupKey); + for (String inheritedKey : inheritedList) { + Group inheritedGroup = ph.getGroup(inheritedKey); + if (thisGroup != null && inheritedGroup != null) { + thisGroup.addInherits(inheritedGroup); + } + } + } + // Process USERS + Map allUsersNode = (Map) rootDataNode.get("users"); + for (String usersKey : allUsersNode.keySet()) { + Map thisUserNode = (Map) allUsersNode.get(usersKey); + User thisUser = ph.createUser(usersKey); + if (thisUser == null) { + throw new IllegalArgumentException("I think this user was declared more than once: " + usersKey); + } + if (thisUserNode.get("permissions") == null) { + thisUserNode.put("permissions", new ArrayList()); + } + if (thisUserNode.get("permissions") instanceof List) { + for (Object o : ((List) thisUserNode.get("permissions"))) { + thisUser.addPermission(o.toString()); + } + } else if (thisUserNode.get("permissions") instanceof String) { + thisUser.addPermission(thisUserNode.get("permissions").toString()); + } + + + //USER INFO NODE - BETA + + //INFO NODE + Map infoNode = (Map) thisUserNode.get("info"); + if (infoNode != null) { + thisUser.setVariables(infoNode); + } + //END INFO NODE - BETA + + if (thisUserNode.get("group") != null) { + Group hisGroup = ph.getGroup(thisUserNode.get("group").toString()); + if (hisGroup == null) { + throw new IllegalArgumentException("There is no group " + thisUserNode.get("group").toString() + ", as stated for player " + thisUser.getName()); + } + thisUser.setGroup(hisGroup); + } else { + thisUser.setGroup(ph.defaultGroup); + } + } + return ph; + } + + /** + * Returns a data holder for the given file + * @param worldName + * @param groupsFile + * @param usersFile + * @return + * @throws FileNotFoundException + * @throws IOException + */ + public static WorldDataHolder load(String worldName, File groupsFile, File usersFile) throws FileNotFoundException, IOException { + WorldDataHolder ph = new WorldDataHolder(worldName); + ph.groupsFile = groupsFile; + ph.usersFile = usersFile; + + + //READ GROUPS FILE + Yaml yamlGroups = new Yaml(new SafeConstructor()); + Map groupsRootDataNode; + if (!groupsFile.exists()) { + throw new IllegalArgumentException("The file which should contain permissions does not exist!\n" + groupsFile.getPath()); + } + FileInputStream groupsInputStream = new FileInputStream(groupsFile); + try { + groupsRootDataNode = (Map) yamlGroups.load(new UnicodeReader(groupsInputStream)); + if (groupsRootDataNode == null) { + throw new NullPointerException(); + } + } catch (Exception ex) { + throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + groupsFile.getPath(), ex); + } finally { + groupsInputStream.close(); + } + + //PROCESS GROUPS FILE + Map> inheritance = new HashMap>(); + try { + Map allGroupsNode = (Map) groupsRootDataNode.get("groups"); + for (String groupKey : allGroupsNode.keySet()) { + Map thisGroupNode = (Map) allGroupsNode.get(groupKey); + Group thisGrp = ph.createGroup(groupKey); + if (thisGrp == null) { + throw new IllegalArgumentException("I think this user was declared more than once: " + groupKey); + } + if (thisGroupNode.get("default") == null) { + thisGroupNode.put("default", false); + } + if ((Boolean.parseBoolean(thisGroupNode.get("default").toString()))) { + if (ph.getDefaultGroup() != null) { + GroupManager.logger.warning("The group " + thisGrp.getName() + " is declaring be default where" + ph.getDefaultGroup().getName() + " already was."); + GroupManager.logger.warning("Overriding first request."); + } + ph.setDefaultGroup(thisGrp); + } + + //PERMISSIONS NODE + if (thisGroupNode.get("permissions") == null) { + thisGroupNode.put("permissions", new ArrayList()); + } + if (thisGroupNode.get("permissions") instanceof List) { + for (Object o : ((List) thisGroupNode.get("permissions"))) { + thisGrp.addPermission(o.toString()); + } + } else if (thisGroupNode.get("permissions") instanceof String) { + thisGrp.addPermission((String) thisGroupNode.get("permissions")); + } else { + throw new IllegalArgumentException("Unknown type of permissions node(Should be String or List): " + thisGroupNode.get("permissions").getClass().getName()); + } + + //INFO NODE + Map infoNode = (Map) thisGroupNode.get("info"); + if (infoNode != null) { + thisGrp.setVariables(infoNode); + } + + //END INFO NODE + + Object inheritNode = thisGroupNode.get("inheritance"); + if (inheritNode == null) { + thisGroupNode.put("inheritance", new ArrayList()); + } else if (inheritNode instanceof List) { + List groupsInh = (List) inheritNode; + for (String grp : groupsInh) { + if (inheritance.get(groupKey) == null) { + List thisInherits = new ArrayList(); + inheritance.put(groupKey, thisInherits); + } + inheritance.get(groupKey).add(grp); + + } + } + } + } catch (Exception ex) { + ex.printStackTrace(); + throw new IllegalArgumentException("Your Permissions config file is invalid. See console for details."); + } + if (ph.defaultGroup == null) { + throw new IllegalArgumentException("There was no Default Group declared."); + } + for (String groupKey : inheritance.keySet()) { + List inheritedList = inheritance.get(groupKey); + Group thisGroup = ph.getGroup(groupKey); + for (String inheritedKey : inheritedList) { + Group inheritedGroup = ph.getGroup(inheritedKey); + if (thisGroup != null && inheritedGroup != null) { + thisGroup.addInherits(inheritedGroup); + } + } + } + + + //READ USERS FILE + Yaml yamlUsers = new Yaml(new SafeConstructor()); + Map usersRootDataNode; + if (!groupsFile.exists()) { + throw new IllegalArgumentException("The file which should contain permissions does not exist!\n" + groupsFile.getPath()); + } + FileInputStream usersInputStream = new FileInputStream(usersFile); + try { + usersRootDataNode = (Map) yamlUsers.load(new UnicodeReader(usersInputStream)); + if (usersRootDataNode == null) { + throw new NullPointerException(); + } + } catch (Exception ex) { + throw new IllegalArgumentException("The following file couldn't pass on Parser.\n" + groupsFile.getPath(), ex); + } finally { + usersInputStream.close(); + } + + // PROCESS USERS FILE + Map allUsersNode = (Map) usersRootDataNode.get("users"); + for (String usersKey : allUsersNode.keySet()) { + Map thisUserNode = (Map) allUsersNode.get(usersKey); + User thisUser = ph.createUser(usersKey); + if (thisUser == null) { + throw new IllegalArgumentException("I think this user was declared more than once: " + usersKey); + } + if (thisUserNode.get("permissions") == null) { + thisUserNode.put("permissions", new ArrayList()); + } + if (thisUserNode.get("permissions") instanceof List) { + for (Object o : ((List) thisUserNode.get("permissions"))) { + thisUser.addPermission(o.toString()); + } + } else if (thisUserNode.get("permissions") instanceof String) { + thisUser.addPermission(thisUserNode.get("permissions").toString()); + } + + //SUBGROUPS LOADING + if (thisUserNode.get("subgroups") == null) { + thisUserNode.put("subgroups", new ArrayList()); + } + if (thisUserNode.get("subgroups") instanceof List) { + for (Object o : ((List) thisUserNode.get("subgroups"))) { + Group subGrp = ph.getGroup(o.toString()); + if (subGrp != null) { + thisUser.addSubGroup(subGrp); + } else { + GroupManager.logger.warning("Subgroup " + o.toString() + " not found for user " + thisUser.getName() + ". Ignoring entry."); + } + } + } else if (thisUserNode.get("subgroups") instanceof String) { + Group subGrp = ph.getGroup(thisUserNode.get("subgroups").toString()); + if (subGrp != null) { + thisUser.addSubGroup(subGrp); + } else { + GroupManager.logger.warning("Subgroup " + thisUserNode.get("subgroups").toString() + " not found for user " + thisUser.getName() + ". Ignoring entry."); + } + } + + + //USER INFO NODE - BETA + + //INFO NODE + Map infoNode = (Map) thisUserNode.get("info"); + if (infoNode != null) { + thisUser.setVariables(infoNode); + } + //END INFO NODE - BETA + + if (thisUserNode.get("group") != null) { + Group hisGroup = ph.getGroup(thisUserNode.get("group").toString()); + if (hisGroup == null) { + throw new IllegalArgumentException("There is no group " + thisUserNode.get("group").toString() + ", as stated for player " + thisUser.getName()); + } + thisUser.setGroup(hisGroup); + } else { + thisUser.setGroup(ph.defaultGroup); + } + } + return ph; + } + + /** + * Write a dataHolder in a specified file + * @param ph + * @param file + * @deprecated + */ + @Deprecated + public static void write(WorldDataHolder ph, File file) { + Map root = new HashMap(); + + Map pluginMap = new HashMap(); + root.put("plugin", pluginMap); + + Map permissionsMap = new HashMap(); + pluginMap.put("permissions", permissionsMap); + + permissionsMap.put("system", "default"); + + Map groupsMap = new HashMap(); + root.put("groups", groupsMap); + for (String groupKey : ph.groups.keySet()) { + Group group = ph.groups.get(groupKey); + + Map aGroupMap = new HashMap(); + groupsMap.put(group.getName(), aGroupMap); + + aGroupMap.put("default", group.equals(ph.defaultGroup)); + + Map infoMap = new HashMap(); + aGroupMap.put("info", infoMap); + + for (String infoKey : group.getVariables().getVarKeyList()) { + infoMap.put(infoKey, group.getVariables().getVarObject(infoKey)); + } + + aGroupMap.put("inheritance", group.getInherits()); + + aGroupMap.put("permissions", group.getPermissionList()); + } + + Map usersMap = new HashMap(); + root.put("users", usersMap); + for (String userKey : ph.users.keySet()) { + User user = ph.users.get(userKey); + if ((user.getGroup() == null || user.getGroup().equals(ph.defaultGroup)) && user.getPermissionList().isEmpty()) { + continue; + } + + Map aUserMap = new HashMap(); + usersMap.put(user.getName(), aUserMap); + + if (user.getGroup() == null) { + aUserMap.put("group", ph.defaultGroup.getName()); + } else { + aUserMap.put("group", user.getGroup().getName()); + } + //USER INFO NODE - BETA + if (user.getVariables().getSize() > 0) { + Map infoMap = new HashMap(); + aUserMap.put("info", infoMap); + + for (String infoKey : user.getVariables().getVarKeyList()) { + infoMap.put(infoKey, user.getVariables().getVarObject(infoKey)); + } + } + //END USER INFO NODE - BETA + + aUserMap.put("permissions", user.getPermissionList()); + } + DumperOptions opt = new DumperOptions(); + opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + final Yaml yaml = new Yaml(opt); + + FileWriter tx = null; + try { + tx = new FileWriter(file, false); + tx.write(yaml.dump(root)); + tx.flush(); + } catch (Exception e) { + } finally { + try { + tx.close(); + } catch (IOException ex) { + } + } + } + + /** + * Write a dataHolder in a specified file + * @param ph + * @param groupsFile + */ + public static void writeGroups(WorldDataHolder ph, File groupsFile) { + Map root = new HashMap(); + + Map groupsMap = new HashMap(); + root.put("groups", groupsMap); + for (String groupKey : ph.groups.keySet()) { + Group group = ph.groups.get(groupKey); + + Map aGroupMap = new HashMap(); + groupsMap.put(group.getName(), aGroupMap); + + if (ph.defaultGroup == null) { + GroupManager.logger.severe("There is no default group for world: " + ph.getName()); + } + aGroupMap.put("default", group.equals(ph.defaultGroup)); + + Map infoMap = new HashMap(); + aGroupMap.put("info", infoMap); + + for (String infoKey : group.getVariables().getVarKeyList()) { + infoMap.put(infoKey, group.getVariables().getVarObject(infoKey)); + } + + aGroupMap.put("inheritance", group.getInherits()); + + aGroupMap.put("permissions", group.getPermissionList()); + } + + DumperOptions opt = new DumperOptions(); + opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + final Yaml yaml = new Yaml(opt); + + FileWriter tx = null; + try { + tx = new FileWriter(groupsFile, false); + tx.write(yaml.dump(root)); + tx.flush(); + } catch (Exception e) { + } finally { + try { + tx.close(); + } catch (IOException ex) { + } + } + } + + /** + * Write a dataHolder in a specified file + * @param ph + * @param usersFile + */ + public static void writeUsers(WorldDataHolder ph, File usersFile) { + Map root = new HashMap(); + + Map usersMap = new HashMap(); + root.put("users", usersMap); + for (String userKey : ph.users.keySet()) { + User user = ph.users.get(userKey); + if ((user.getGroup() == null || user.getGroup().equals(ph.defaultGroup)) && user.getPermissionList().isEmpty() && user.getVariables().isEmpty() && user.isSubGroupsEmpty()) { + continue; + } + + Map aUserMap = new HashMap(); + usersMap.put(user.getName(), aUserMap); + + if (user.getGroup() == null) { + aUserMap.put("group", ph.defaultGroup.getName()); + } else { + aUserMap.put("group", user.getGroup().getName()); + } + //USER INFO NODE - BETA + if (user.getVariables().getSize() > 0) { + Map infoMap = new HashMap(); + aUserMap.put("info", infoMap); + for (String infoKey : user.getVariables().getVarKeyList()) { + infoMap.put(infoKey, user.getVariables().getVarObject(infoKey)); + } + } + //END USER INFO NODE - BETA + aUserMap.put("permissions", user.getPermissionList()); + + //SUBGROUPS NODE - BETA + aUserMap.put("subgroups", user.subGroupListStringCopy()); + //END SUBGROUPS NODE - BETA + } + DumperOptions opt = new DumperOptions(); + opt.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + final Yaml yaml = new Yaml(opt); + + FileWriter tx = null; + try { + tx = new FileWriter(usersFile, false); + tx.write(yaml.dump(root)); + tx.flush(); + } catch (Exception e) { + } finally { + try { + tx.close(); + } catch (IOException ex) { + } + } + } + + /** + * Don't use this. Unless you want to make this plugin to interact with original Nijikokun Permissions + * This method is supposed to make the original one reload the file, and propagate the changes made here. + * + * Prefer to use the AnjoCaido's fake version of Nijikokun's Permission plugin. + * The AnjoCaido's Permission can propagate the changes made on this plugin instantly, + * without need to save the file. + * + * @param server the server that holds the plugin + * @deprecated it is not used anymore... unless if you use original Permissions + */ + @Deprecated + public static void reloadOldPlugins(Server server) { + // Only reload permissions + PluginManager pm = server.getPluginManager(); + Plugin[] plugins = pm.getPlugins(); + for (int i = 0; i < plugins.length; i++) { + plugins[i].getConfiguration().load(); + try { + plugins[i].getClass().getMethod("setupPermissions").invoke(plugins[i]); + } catch (Exception ex) { + continue; + } + } + } + + /** + * @return the permissionsHandler + */ + public AnjoPermissionsHandler getPermissionsHandler() { + if (permissionsHandler == null) { + permissionsHandler = new AnjoPermissionsHandler(this); + } + return permissionsHandler; + } + + /** + * + * @return + */ + public boolean haveUsersChanged() { + if (haveUsersChanged) { + return true; + } + for (User u : users.values()) { + if (u.isChanged()) { + return true; + } + } + return false; + } + + /** + * + * @return + */ + public boolean haveGroupsChanged() { + if (haveGroupsChanged) { + return true; + } + for (Group g : groups.values()) { + if (g.isChanged()) { + return true; + } + } + return false; + } + + /** + * + */ + public void removeUsersChangedFlag() { + haveUsersChanged = false; + for (User u : users.values()) { + u.flagAsSaved(); + } + } + + /** + * + */ + public void removeGroupsChangedFlag() { + haveGroupsChanged = false; + for (Group g : groups.values()) { + g.flagAsSaved(); + } + } + + /** + * @return the usersFile + */ + public File getUsersFile() { + return usersFile; + } + + /** + * @return the groupsFile + */ + public File getGroupsFile() { + return groupsFile; + } + + /** + * @return the name + */ + public String getName() { + return name; + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/worlds/WorldsHolder.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/worlds/WorldsHolder.java new file mode 100644 index 000000000..83073c10b --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/dataholder/worlds/WorldsHolder.java @@ -0,0 +1,423 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.dataholder.worlds; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.anjocaido.groupmanager.GroupManager; +import org.anjocaido.groupmanager.dataholder.WorldDataHolder; +import org.anjocaido.groupmanager.dataholder.OverloadedWorldHolder; +import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler; +import org.anjocaido.groupmanager.utils.Tasks; +import org.bukkit.entity.Player; + +/** + * + * @author gabrielcouto + */ +public class WorldsHolder { + + /** + * Map with instances of loaded worlds. + */ + private Map worldsData = new HashMap(); + /** + * Map of mirrors: + * The key is the mirror. + * The object is the mirrored. + * + * Mirror shows the same data of mirrored. + */ + private Map mirrors = new HashMap(); + private OverloadedWorldHolder defaultWorld; + private String serverDefaultWorldName; + private GroupManager plugin; + private File worldsFolder; + + /** + * + * @param plugin + */ + public WorldsHolder(GroupManager plugin) { + this.plugin = plugin; + verifyFirstRun(); + initialLoad(); + if (defaultWorld == null) { + throw new IllegalStateException("There is no default group! OMG!"); + } + } + + private void initialLoad() { + initialWorldLoading(); + mirrorSetUp(); + } + private void initialWorldLoading(){ + //LOAD EVERY WORLD POSSIBLE + loadWorld(serverDefaultWorldName); + defaultWorld = worldsData.get(serverDefaultWorldName); + + for (File folder : worldsFolder.listFiles()) { + if (folder.getName().equalsIgnoreCase(serverDefaultWorldName)) { + continue; + } + if (folder.isDirectory()) { + loadWorld(folder.getName()); + } + } + } + public void mirrorSetUp(){ + mirrors.clear(); + Map mirrorsMap = plugin.getConfig().getMirrorsMap(); + if (mirrorsMap != null) { + for (String source : mirrorsMap.keySet()) { + if (mirrorsMap.get(source) instanceof ArrayList) { + ArrayList mirrorList = (ArrayList) mirrorsMap.get(source); + for (Object o : mirrorList) { + try { + mirrors.remove(o.toString().toLowerCase()); + } catch (Exception e) { + } + mirrors.put(o.toString().toLowerCase(), getWorldData(source).getName()); + } + } else if (mirrorsMap.get(source) instanceof Object) { + String aMirror = mirrorsMap.get(source).toString(); + mirrors.put(aMirror.toLowerCase(), getWorldData(source).getName()); + } + } + } + } + + /** + * + */ + public void reloadAll() { + ArrayList alreadyDone = new ArrayList(); + for (WorldDataHolder w : worldsData.values()) { + if (alreadyDone.contains(w)) { + continue; + } + w.reload(); + alreadyDone.add(w); + } + } + + /** + * + * @param worldName + */ + public void reloadWorld(String worldName) { + getWorldData(worldName).reload(); + } + + /** + * + */ + public void saveChanges() { + ArrayList alreadyDone = new ArrayList(); + for (OverloadedWorldHolder w : worldsData.values()) { + if (alreadyDone.contains(w)) { + continue; + } + Tasks.removeOldFiles(plugin.getBackupFolder()); + if (w == null) { + GroupManager.logger.severe("WHAT HAPPENED?"); + continue; + } + if (w.haveGroupsChanged()) { + String groupsFolderName = w.getGroupsFile().getParentFile().getName(); + File backupGroups = new File(plugin.getBackupFolder(), "bkp_" + w.getName() + "_g_" + Tasks.getDateString() + ".yml"); + try { + Tasks.copy(w.getGroupsFile(), backupGroups); + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + WorldDataHolder.writeGroups(w, w.getGroupsFile()); + w.removeGroupsChangedFlag(); + } + if (w.haveUsersChanged()) { + File backupUsers = new File(plugin.getBackupFolder(), "bkp_" + w.getName() + "_u_" + Tasks.getDateString() + ".yml"); + try { + Tasks.copy(w.getUsersFile(), backupUsers); + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + WorldDataHolder.writeUsers(w, w.getUsersFile()); + w.removeUsersChangedFlag(); + } + alreadyDone.add(w); + } + } + + /** + * Returns the dataHolder for the given world. + * If the world is not on the worlds list, returns the default world + * holder. + * + * (WHEN A WORLD IS CONFIGURED TO MIRROR, IT WILL BE ON THE LIST, BUT + * POINTING TO ANOTHER WORLD HOLDER) + * + * Mirrors prevails original data. + * + * @param worldName + * @return + */ + public OverloadedWorldHolder getWorldData(String worldName) { + OverloadedWorldHolder data = worldsData.get(worldName.toLowerCase()); + if (mirrors.containsKey(worldName.toLowerCase())) { + String realOne = mirrors.get(worldName.toLowerCase()); + data = worldsData.get(realOne.toLowerCase()); + } + if (data == null) { + GroupManager.logger.finest("Requested world " + worldName + " not found or badly mirrored. Returning default world..."); + data = getDefaultWorld(); + } + return data; + } + + /** + * Do a matching of playerName, if it s found only one player, do + * getWorldData(player) + * @param playerName + * @return null if matching returned no player, or more than one. + */ + public OverloadedWorldHolder getWorldDataByPlayerName(String playerName) { + List matchPlayer = plugin.getServer().matchPlayer(playerName); + if (matchPlayer.size() == 1) { + return getWorldData(matchPlayer.get(0)); + } + return null; + } + + /** + * Retrieves the field p.getWorld().getName() and do + * getWorld(worldName) + * @param p + * @return + */ + public OverloadedWorldHolder getWorldData(Player p) { + return getWorldData(p.getWorld().getName()); + } + + /** + * It does getWorld(worldName).getPermissionsHandler() + * @param worldName + * @return + */ + public AnjoPermissionsHandler getWorldPermissions(String worldName) { + return getWorldData(worldName).getPermissionsHandler(); + } + + /** + *It does getWorldData(p).getPermission + * @param p + * @return + */ + public AnjoPermissionsHandler getWorldPermissions(Player p) { + return getWorldData(p).getPermissionsHandler(); + } + + /** + * Id does getWorldDataByPlayerName(playerName). + * If it doesnt return null, it will return result.getPermissionsHandler() + * @param playerName + * @return null if the player matching gone wrong. + */ + public AnjoPermissionsHandler getWorldPermissionsByPlayerName(String playerName) { + WorldDataHolder dh = getWorldDataByPlayerName(playerName); + if (dh != null) { + return dh.getPermissionsHandler(); + } + return null; + } + + private void verifyFirstRun() { + worldsFolder = new File(plugin.getDataFolder(), "worlds"); + if (!worldsFolder.exists()) { + worldsFolder.mkdirs(); + } + Properties server = new Properties(); + try { + server.load(new FileInputStream(new File("server.properties"))); + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + serverDefaultWorldName = server.getProperty("level-name").toLowerCase(); + File defaultWorldFolder = new File(worldsFolder, serverDefaultWorldName); + if (!defaultWorldFolder.exists()) { + defaultWorldFolder.mkdirs(); + } + if (defaultWorldFolder.exists()) { + File groupsFile = new File(defaultWorldFolder, "groups.yml"); + File usersFile = new File(defaultWorldFolder, "users.yml"); + File oldDataFile = new File(plugin.getDataFolder(), "data.yml"); + if (!groupsFile.exists()) { + if (oldDataFile.exists()) { + try { + Tasks.copy(oldDataFile, groupsFile); + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + } else { + InputStream template = plugin.getResourceAsStream("groups.yml"); + try { + Tasks.copy(template, groupsFile); + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + } + } + if (!usersFile.exists()) { + if (oldDataFile.exists()) { + try { + Tasks.copy(oldDataFile, usersFile); + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + } else { + InputStream template = plugin.getResourceAsStream("users.yml"); + try { + Tasks.copy(template, usersFile); + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + } + } + } + try { + if (oldDataFile.exists()) { + oldDataFile.renameTo(new File(plugin.getDataFolder(), "NOT_USED_ANYMORE_data.yml")); + } + } catch (Exception ex) { + } + } + } + + /** + * Copies the specified world data to another world + * @param fromWorld + * @param toWorld + * @return + */ + public boolean cloneWorld(String fromWorld, String toWorld) { + File fromWorldFolder = new File(worldsFolder, fromWorld); + File toWorldFolder = new File(worldsFolder, toWorld); + if (toWorldFolder.exists() || !fromWorldFolder.exists()) { + return false; + } + File fromWorldGroups = new File(fromWorldFolder, "groups.yml"); + File fromWorldUsers = new File(fromWorldFolder, "users.yml"); + if (!fromWorldGroups.exists() || !fromWorldUsers.exists()) { + return false; + } + File toWorldGroups = new File(toWorldFolder, "groups.yml"); + File toWorldUsers = new File(toWorldFolder, "users.yml"); + toWorldFolder.mkdirs(); + try { + Tasks.copy(fromWorldGroups, toWorldGroups); + Tasks.copy(fromWorldUsers, toWorldUsers); + } catch (IOException ex) { + Logger.getLogger(WorldsHolder.class.getName()).log(Level.SEVERE, null, ex); + return false; + } + return true; + } + + /** + * Load a world from file. + * If it already been loaded, summon reload method from dataHolder. + * @param worldName + */ + public void loadWorld(String worldName) { + if (worldsData.containsKey(worldName.toLowerCase())) { + worldsData.get(worldName.toLowerCase()).reload(); + return; + } + GroupManager.logger.finest("Trying to load world " + worldName + "..."); + File thisWorldFolder = new File(worldsFolder, worldName); + if (thisWorldFolder.exists() && thisWorldFolder.isDirectory()) { + File groupsFile = new File(thisWorldFolder, "groups.yml"); + File usersFile = new File(thisWorldFolder, "users.yml"); + if (!groupsFile.exists()) { + throw new IllegalArgumentException("Groups file for world '" + worldName + "' doesnt exist: " + groupsFile.getPath()); + } + if (!usersFile.exists()) { + throw new IllegalArgumentException("Users file for world '" + worldName + "' doesnt exist: " + usersFile.getPath()); + } + try { + OverloadedWorldHolder thisWorldData = new OverloadedWorldHolder(WorldDataHolder.load(worldName, groupsFile, usersFile)); + if (thisWorldData != null) { + GroupManager.logger.finest("Successful load of world " + worldName + "..."); + worldsData.put(worldName.toLowerCase(), thisWorldData); + return; + } + } catch (FileNotFoundException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + return; + } catch (IOException ex) { + GroupManager.logger.log(Level.SEVERE, null, ex); + return; + } + GroupManager.logger.severe("Failed to load world " + worldName + "..."); + } + } + + /** + * Tells if the such world has been mapped. + * + * It will return true if world is a mirror. + * + * @param worldName + * @return true if world is loaded or mirrored. false if not listed + */ + public boolean isInList(String worldName) { + if (worldsData.containsKey(worldName.toLowerCase()) || mirrors.containsKey(worldName.toLowerCase())) { + return true; + } + return false; + } + + /** + * Verify if world has it's own file permissions. + * + * @param worldName + * @return true if it has its own holder. false if not. + */ + public boolean hasOwnData(String worldName) { + if (worldsData.containsKey(worldName.toLowerCase())) { + return true; + } + return false; + } + + /** + * @return the defaultWorld + */ + public OverloadedWorldHolder getDefaultWorld() { + return defaultWorld; + } + + /** + * Returns all physically loaded worlds. + * @return + */ + public ArrayList allWorldsDataList() { + ArrayList list = new ArrayList(); + for (OverloadedWorldHolder data : worldsData.values()) { + if (!list.contains(data)) { + list.add(data); + } + } + return list; + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/permissions/AnjoPermissionsHandler.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/permissions/AnjoPermissionsHandler.java new file mode 100644 index 000000000..ca223da81 --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/permissions/AnjoPermissionsHandler.java @@ -0,0 +1,856 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.permissions; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.StringTokenizer; +import org.anjocaido.groupmanager.GroupManager; +import org.anjocaido.groupmanager.data.Group; +import org.anjocaido.groupmanager.dataholder.WorldDataHolder; +import org.anjocaido.groupmanager.data.User; +import org.anjocaido.groupmanager.utils.PermissionCheckResult; +import org.bukkit.entity.Player; + +/** + * Everything here maintains the model created by Nijikokun + * + * But implemented to use GroupManager system. Which provides instant changes, + * without file access. + * + * It holds permissions only for one single world. + * + * @author gabrielcouto + */ +public class AnjoPermissionsHandler extends PermissionsReaderInterface { + + WorldDataHolder ph = null; + + /** + * It needs a WorldDataHolder to work with. + * @param holder + */ + public AnjoPermissionsHandler(WorldDataHolder holder) { + ph = holder; + } + + /** + * A short name method, for permission method. + * @param player + * @param permission + * @return + */ + @Override + public boolean has(Player player, String permission) { + return permission(player, permission); + } + + /** + * Checks if a player can use that permission node. + * @param player + * @param permission + * @return + */ + @Override + public boolean permission(Player player, String permission) { + return checkUserPermission(ph.getUser(player.getName()), permission); + } + + /** + * Returns the name of the group of that player name. + * @param userName + * @return + */ + @Override + public String getGroup(String userName) { + return ph.getUser(userName).getGroup().getName(); + } + + /** + * Verify if player is in suck group. + * It will check it's groups inheritance. + * + * So if you have a group Admin > Moderator + * + * And verify the player 'MyAdmin', which is Admin, it will return true for both + * Admin or Moderator groups. + * + * Mas if you haave a player 'MyModerator', which is Moderator, + * it will give false if you pass Admin in group parameter. + * + * @param name + * @param group + * @return + */ + @Override + public boolean inGroup(String name, String group) { + if (hasGroupInInheritance(ph.getUser(name).getGroup(), group)) { + return true; + } + for (Group subGroup : ph.getUser(name).subGroupListCopy()) { + if (hasGroupInInheritance(subGroup, group)) { + return true; + } + } + return false; + } + + /** + * Returns the String prefix for the given group + * @param groupName + * @return empty string if found none. + */ + @Override + public String getGroupPrefix(String groupName) { + Group g = ph.getGroup(groupName); + if (g == null) { + return null; + } + return g.getVariables().getVarString("prefix"); + } + + /** + * Return the suffix for the given group name + * @param groupName + * @return + */ + @Override + public String getGroupSuffix(String groupName) { + Group g = ph.getGroup(groupName); + if (g == null) { + return null; + } + return g.getVariables().getVarString("suffix"); + } + + /** + * + * @param groupName + * @return + */ + @Override + public boolean canGroupBuild(String groupName) { + Group g = ph.getGroup(groupName); + if (g == null) { + return false; + } + return g.getVariables().getVarBoolean("build"); + } + + /** + * It returns a string variable value, set in the INFO node of the group. + * It will harvest inheritance for value. + * @param groupName + * @param variable + * @return null if no group with that variable is found. + */ + @Override + public String getGroupPermissionString(String groupName, String variable) { + Group start = ph.getGroup(groupName); + if (start == null) { + return null; + } + Group result = nextGroupWithVariable(start, variable); + if (result == null) { + return null; + } + return result.getVariables().getVarString(variable); + } + + /** + * It returns a Integer variable value + * It will harvest inheritance for value. + * @param groupName + * @param variable + * @return -1 if none found or not parseable. + */ + @Override + public int getGroupPermissionInteger(String groupName, String variable) { + Group start = ph.getGroup(groupName); + if (start == null) { + return -1; + } + Group result = nextGroupWithVariable(start, variable); + if (result == null) { + return -1; + } + return result.getVariables().getVarInteger(variable); + } + + /** + * Returns a boolean for given variable in INFO node. + * It will harvest inheritance for value. + * @param group + * @param variable + * @return false if not found/not parseable. + */ + @Override + public boolean getGroupPermissionBoolean(String group, String variable) { + Group start = ph.getGroup(group); + if (start == null) { + return false; + } + Group result = nextGroupWithVariable(start, variable); + if (result == null) { + return false; + } + return result.getVariables().getVarBoolean(variable); + } + + /** + * Returns a double value for the given variable name in INFO node. + * It will harvest inheritance for value. + * @param group + * @param variable + * @return -1 if not found / not parseable. + */ + @Override + public double getGroupPermissionDouble(String group, String variable) { + Group start = ph.getGroup(group); + if (start == null) { + return -1; + } + Group result = nextGroupWithVariable(start, variable); + if (result == null) { + return -1; + } + return result.getVariables().getVarDouble(variable); + } + + /** + * Returns the variable value of the user, in INFO node. + * @param user + * @param variable + * @return + */ + @Override + public String getUserPermissionString(String user, String variable) { + User auser = ph.getUser(user); + if (auser == null) { + return ""; + } + return auser.getVariables().getVarString(variable); + } + + /** + * Returns the variable value of the user, in INFO node. + * @param user + * @param variable + * @return + */ + @Override + public int getUserPermissionInteger(String user, String variable) { + User auser = ph.getUser(user); + if (auser == null) { + return -1; + } + return auser.getVariables().getVarInteger(variable); + } + + /** + * Returns the variable value of the user, in INFO node. + * @param user + * @param variable + * @return + */ + @Override + public boolean getUserPermissionBoolean(String user, String variable) { + User auser = ph.getUser(user); + if (auser == null) { + return false; + } + return auser.getVariables().getVarBoolean(variable); + } + + /** + * Returns the variable value of the user, in INFO node. + * @param user + * @param variable + * @return + */ + @Override + public double getUserPermissionDouble(String user, String variable) { + User auser = ph.getUser(user); + if (auser == null) { + return -1; + } + return auser.getVariables().getVarDouble(variable); + } + + /** + * Returns the variable value of the user, in INFO node. + * If not found, it will search for his Group variables. + * It will harvest the inheritance. + * @param user + * @param variable + * @return empty string if not found + */ + @Override + public String getPermissionString(String user, String variable) { + User auser = ph.getUser(user); + if (auser == null) { + return ""; + } + if (auser.getVariables().hasVar(variable)) { + return auser.getVariables().getVarString(variable); + } + Group start = auser.getGroup(); + if (start == null) { + return ""; + } + Group result = nextGroupWithVariable(start, variable); + if (result == null) { + return ""; + } + return result.getVariables().getVarString(variable); + //return getUserPermissionString(user, variable); + } + + /** + * Returns the variable value of the user, in INFO node. + * If not found, it will search for his Group variables. + * It will harvest the inheritance. + * @param user + * @param variable + * @return -1 if not found + */ + @Override + public int getPermissionInteger(String user, String variable) { + User auser = ph.getUser(user); + if (auser == null) { + return -1; + } + if (auser.getVariables().hasVar(variable)) { + return auser.getVariables().getVarInteger(variable); + } + Group start = auser.getGroup(); + if (start == null) { + return -1; + } + Group result = nextGroupWithVariable(start, variable); + if (result == null) { + return -1; + } + return result.getVariables().getVarInteger(variable); + //return getUserPermissionInteger(string, string1); + } + + /** + * Returns the variable value of the user, in INFO node. + * If not found, it will search for his Group variables. + * It will harvest the inheritance. + * @param user + * @param variable + * @return false if not found or not parseable to true. + */ + @Override + public boolean getPermissionBoolean(String user, String variable) { + User auser = ph.getUser(user); + if (auser == null) { + return false; + } + if (auser.getVariables().hasVar(variable)) { + return auser.getVariables().getVarBoolean(variable); + } + Group start = auser.getGroup(); + if (start == null) { + return false; + } + Group result = nextGroupWithVariable(start, variable); + if (result == null) { + return false; + } + return result.getVariables().getVarBoolean(variable); + //return getUserPermissionBoolean(user, string1); + } + + /** + * Returns the variable value of the user, in INFO node. + * If not found, it will search for his Group variables. + * It will harvest the inheritance. + * @param user + * @param variable + * @return -1 if not found. + */ + @Override + public double getPermissionDouble(String user, String variable) { + User auser = ph.getUser(user); + if (auser == null) { + return -1.0D; + } + if (auser.getVariables().hasVar(variable)) { + return auser.getVariables().getVarDouble(variable); + } + Group start = auser.getGroup(); + if (start == null) { + return -1.0D; + } + Group result = nextGroupWithVariable(start, variable); + if (result == null) { + return -1.0D; + } + return result.getVariables().getVarDouble(variable); + //return getUserPermissionDouble(string, string1); + } + + /** + * Does not include User's group permission + * @param user + * @param permission + * @return + */ + public PermissionCheckResult checkUserOnlyPermission(User user, String permission) { + user.sortPermissions(); + PermissionCheckResult result = new PermissionCheckResult(); + result.askedPermission = permission; + result.owner = user; + for (String access : user.getPermissionList()) { + if (comparePermissionString(access, permission)) { + result.accessLevel = access; + if (access.startsWith("-")) { + result.resultType = PermissionCheckResult.Type.NEGATION; + } else if (access.startsWith("+")) { + result.resultType = PermissionCheckResult.Type.EXCEPTION; + } else { + result.resultType = PermissionCheckResult.Type.FOUND; + } + return result; + } + } + result.resultType = PermissionCheckResult.Type.NOTFOUND; + return result; + } + + /** + * Returns the node responsible for that permission. + * Does not include User's group permission. + * @param group + * @param permission + * @return the node if permission is found. if not found, return null + */ + public PermissionCheckResult checkGroupOnlyPermission(Group group, String permission) { + group.sortPermissions(); + PermissionCheckResult result = new PermissionCheckResult(); + result.owner = group; + result.askedPermission = permission; + for (String access : group.getPermissionList()) { + if (comparePermissionString(access, permission)) { + result.accessLevel = access; + if (access.startsWith("-")) { + result.resultType = PermissionCheckResult.Type.NEGATION; + } else if (access.startsWith("+")) { + result.resultType = PermissionCheckResult.Type.EXCEPTION; + } else { + result.resultType = PermissionCheckResult.Type.FOUND; + } + return result; + } + } + result.resultType = PermissionCheckResult.Type.NOTFOUND; + return result; + } + + /** + * Check permissions, including it's group and inheritance. + * @param user + * @param permission + * @return true if permission was found. false if not, or was negated. + */ + public boolean checkUserPermission(User user, String permission) { + PermissionCheckResult result = checkFullUserPermission(user, permission); + if (result.resultType.equals(PermissionCheckResult.Type.EXCEPTION) + || result.resultType.equals(PermissionCheckResult.Type.FOUND)) { + return true; + } + return false; + } + + /** + * Do what checkUserPermission did before. But now returning a PermissionCheckResult. + * @param user + * @param targetPermission + * @return + */ + public PermissionCheckResult checkFullUserPermission(User user, String targetPermission) { + PermissionCheckResult result = new PermissionCheckResult(); + result.askedPermission = targetPermission; + result.resultType = PermissionCheckResult.Type.NOTFOUND; + + if (user == null || targetPermission == null) { + return result; + } + + PermissionCheckResult resultUser = checkUserOnlyPermission(user, targetPermission); + if (!resultUser.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { + return resultUser; + + } + + //IT ONLY CHECKS GROUPS PERMISSIONS IF RESULT FOR USER IS NOT FOUND + PermissionCheckResult resultGroup = checkGroupPermissionWithInheritance(user.getGroup(), targetPermission); + if (!resultGroup.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { + return resultGroup; + } + + //SUBGROUPS CHECK + for (Group subGroup : user.subGroupListCopy()) { + PermissionCheckResult resultSubGroup = checkGroupPermissionWithInheritance(subGroup, targetPermission); + if (!resultSubGroup.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { + return resultSubGroup; + } + } + + //THEN IT RETURNS A NOT FOUND + return result; + } + + /** + * Verifies if a given group has a variable. Including it's inheritance. + * + * it redirects to the other method now. This one was deprecated, and will + * be gone in a future release. + * + * @param start + * @param variable + * @param alreadyChecked + * @return returns the closest inherited group with the variable. + * @deprecated use now nextGroupWithVariable(Group start, String targetVariable) + */ + @Deprecated + public Group nextGroupWithVariable(Group start, String variable, List alreadyChecked) { + return nextGroupWithVariable(start, variable); + } + + /** + * Returns the next group, including inheritance, which contains that + * variable name. + * + * It does Breadth-first search + * + * @param start the starting group to look for + * @param targetVariable the variable name + * @return The group if found. Null if not. + */ + public Group nextGroupWithVariable(Group start, String targetVariable) { + if (start == null || targetVariable == null) { + return null; + } + LinkedList stack = new LinkedList(); + ArrayList alreadyVisited = new ArrayList(); + stack.push(start); + alreadyVisited.add(start); + while (!stack.isEmpty()) { + Group now = stack.pop(); + if (now.getVariables().hasVar(targetVariable)) { + return now; + } + for (String sonName : now.getInherits()) { + Group son = ph.getGroup(sonName); + if (son != null && !alreadyVisited.contains(son)) { + stack.push(son); + alreadyVisited.add(son); + } + } + } + return null; + } + + /** + * Check if given group inherits another group. + * + * redirected to the other method. this is deprecated now. and will be gone + * in the future releases. + * + * @param start The group to start the search. + * @param askedGroup Name of the group you're looking for + * @param alreadyChecked groups to ignore(pass null on it, please) + * @return true if it inherits the group. + * @deprecated prefer using hasGroupInInheritance(Group start, String askedGroup) + */ + @Deprecated + public boolean searchGroupInInheritance(Group start, String askedGroup, List alreadyChecked) { + return hasGroupInInheritance(start, askedGroup); + } + + /** + * Check if given group inherits another group. + * + * It does Breadth-first search + * + * @param start The group to start the search. + * @param askedGroup Name of the group you're looking for + * @return true if it inherits the group. + */ + public boolean hasGroupInInheritance(Group start, String askedGroup) { + if (start == null || askedGroup == null) { + return false; + } + LinkedList stack = new LinkedList(); + ArrayList alreadyVisited = new ArrayList(); + stack.push(start); + alreadyVisited.add(start); + while (!stack.isEmpty()) { + Group now = stack.pop(); + if (now.getName().equalsIgnoreCase(askedGroup)) { + return true; + } + for (String sonName : now.getInherits()) { + Group son = ph.getGroup(sonName); + if (son != null && !alreadyVisited.contains(son)) { + stack.push(son); + alreadyVisited.add(son); + } + } + } + return false; + } + + /** + * Check if the group has given permission. Including it's inheritance + * @param start + * @param permission + * @param alreadyChecked + * @return true if PermissionCheckResult is EXCEPTION or FOUND + * @deprecated use the other checkGroupPermissionWithInheritance for everything + */ + @Deprecated + public boolean checkGroupPermissionWithInheritance(Group start, String permission, List alreadyChecked) { + PermissionCheckResult result = checkGroupPermissionWithInheritance(start, permission); + if (result.resultType.equals(result.resultType.EXCEPTION) + || result.resultType.equals(result.resultType.FOUND)) { + return true; + } + return false; + } + + /** + * Returns the result of permission check. Including inheritance. + * If found anything, the PermissionCheckResult that retuns will + * include the Group name, and the result type. + * Result types will be EXCEPTION, NEGATION, FOUND. + * + * If returned type NOTFOUND, the owner will be null, + * and ownerType too. + * + * It does Breadth-first search + * + * @param start + * @param targetPermission + * @return + */ + public PermissionCheckResult checkGroupPermissionWithInheritance(Group start, String targetPermission) { + if (start == null || targetPermission == null) { + return null; + } + LinkedList stack = new LinkedList(); + List alreadyVisited = new ArrayList(); + stack.push(start); + alreadyVisited.add(start); + while (!stack.isEmpty()) { + Group now = stack.pop(); + PermissionCheckResult resultNow = checkGroupOnlyPermission(now, targetPermission); + if (!resultNow.resultType.equals(PermissionCheckResult.Type.NOTFOUND)) { + return resultNow; + } + for (String sonName : now.getInherits()) { + Group son = ph.getGroup(sonName); + if (son != null && !alreadyVisited.contains(son)) { + stack.push(son); + alreadyVisited.add(son); + } + } + } + PermissionCheckResult result = new PermissionCheckResult(); + result.askedPermission = targetPermission; + result.resultType = PermissionCheckResult.Type.NOTFOUND; + return result; + } + + /** + * It uses checkGroupPermissionWithInheritance + * and cast the owner to Group type if result type was EXCEPTION or FOUND. + * + * @param start + * @param permission + * @param alreadyChecked + * @return the group that passed on test. null if no group passed. + * @deprecated use checkGroupPermissionWithInheritance for everything now. + */ + @Deprecated + public Group nextGroupWithPermission(Group start, String permission, List alreadyChecked) { + PermissionCheckResult result = checkGroupPermissionWithInheritance(start, permission); + if (result.resultType.equals(result.resultType.EXCEPTION) + || result.resultType.equals(result.resultType.FOUND)) { + return (Group) checkGroupPermissionWithInheritance(start, permission).owner; + } + return null; + } + + /** + * Return whole list of names of groups in a inheritance chain. Including a + * starting group. + * + * it now redirects to the other method. but get away from this one, + * it will disappear in a future release. + * + * @param start + * @param alreadyChecked + * @return the group that passed on test. null if no group passed. + * @deprecated use the other method with same name, instead + */ + @Deprecated + public ArrayList listAllGroupsInherited(Group start, ArrayList alreadyChecked) { + return listAllGroupsInherited(start); + } + + /** + * Return whole list of names of groups in a inheritance chain. Including a + * starting group. + * + * It does Breadth-first search. So closer groups will appear first in list. + * + * @param start + * @return the group that passed on test. null if no group passed. + */ + public ArrayList listAllGroupsInherited(Group start) { + if (start == null) { + return null; + } + LinkedList stack = new LinkedList(); + ArrayList alreadyVisited = new ArrayList(); + stack.push(start); + alreadyVisited.add(start.getName()); + while (!stack.isEmpty()) { + Group now = stack.pop(); + for (String sonName : now.getInherits()) { + Group son = ph.getGroup(sonName); + if (son != null && !alreadyVisited.contains(son.getName())) { + stack.push(son); + alreadyVisited.add(son.getName()); + } + } + } + return alreadyVisited; + } + + /** + * Compare a user permission like 'myplugin.*' against a full plugin + * permission name, like 'myplugin.dosomething'. + * As the example above, will return true. + * + * Please sort permissions before sending them here. So negative tokens + * get priority. + * + * You must test if it start with negative outside this method. It will + * only tell if the nodes are matching or not. + * + * Every '-' or '+' in the beginning is ignored. It will match only + * node names. + * + * @param userAcessLevel + * @param fullPermissionName + * @return true if found a matching token. false if not. + */ + public boolean comparePermissionString(String userAcessLevel, String fullPermissionName) { + if (userAcessLevel == null || fullPermissionName == null) { + return false; + } + GroupManager.logger.finest("COMPARING " + userAcessLevel + " WITH " + fullPermissionName); + + if (userAcessLevel.startsWith("+")) { + userAcessLevel = userAcessLevel.substring(1); + } else if (userAcessLevel.startsWith("-")) { + userAcessLevel = userAcessLevel.substring(1); + } + + if (fullPermissionName.startsWith("+")) { + fullPermissionName = fullPermissionName.substring(1); + } else if (fullPermissionName.startsWith("-")) { + fullPermissionName = fullPermissionName.substring(1); + } + + + StringTokenizer levelATokenizer = new StringTokenizer(userAcessLevel, "."); + StringTokenizer levelBTokenizer = new StringTokenizer(fullPermissionName, "."); + while (levelATokenizer.hasMoreTokens() && levelBTokenizer.hasMoreTokens()) { + String levelA = levelATokenizer.nextToken(); + String levelB = levelBTokenizer.nextToken(); + GroupManager.logger.finest("ROUND " + levelA + " AGAINST " + levelB); + if (levelA.contains("*")) { + GroupManager.logger.finest("WIN"); + return true; + } + if (levelA.equalsIgnoreCase(levelB)) { + if (!levelATokenizer.hasMoreTokens() && !levelBTokenizer.hasMoreTokens()) { + GroupManager.logger.finest("WIN"); + return true; + } + GroupManager.logger.finest("NEXT"); + continue; + } else { + GroupManager.logger.finest("FAIL"); + return false; + } + + } + GroupManager.logger.finest("FAIL"); + return false; + } + + /** + * Returns a list of all groups. + * + * Including subgroups. + * @param userName + * @return + */ + public String[] getGroups(String userName) { + ArrayList allGroups = listAllGroupsInherited(ph.getUser(userName).getGroup()); + for(Group subg: ph.getUser(userName).subGroupListCopy()){ + allGroups.addAll(listAllGroupsInherited(subg)); + } + String[] arr = new String[allGroups.size()]; + return allGroups.toArray(arr); + } + + /** + * A Breadth-first search thru inheritance model. + * + * Just a model to copy and paste. + * This will guarantee the closer groups will be checked first. + * @param start + * @param targerPermission + * @return + */ + private Group breadthFirstSearch(Group start, String targerPermission) { + if (start == null || targerPermission == null) { + return null; + } + LinkedList stack = new LinkedList(); + ArrayList alreadyVisited = new ArrayList(); + stack.push(start); + alreadyVisited.add(start); + while (!stack.isEmpty()) { + Group now = stack.pop(); + PermissionCheckResult resultNow = checkGroupOnlyPermission(now, targerPermission); + if (resultNow.resultType.equals(PermissionCheckResult.Type.EXCEPTION) + || resultNow.resultType.equals(PermissionCheckResult.Type.FOUND)) { + return now; + } + if (resultNow.resultType.equals(PermissionCheckResult.Type.NEGATION)) { + return null; + } + for (String sonName : now.getInherits()) { + Group son = ph.getGroup(sonName); + if (son != null && !alreadyVisited.contains(son)) { + stack.push(son); + alreadyVisited.add(son); + } + } + } + return null; + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/permissions/PermissionsReaderInterface.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/permissions/PermissionsReaderInterface.java new file mode 100644 index 000000000..90194cddd --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/permissions/PermissionsReaderInterface.java @@ -0,0 +1,163 @@ +package org.anjocaido.groupmanager.permissions; + +import org.bukkit.entity.Player; + +/** + * Made by Nijikokun. Changed by Gabriel Couto + * + * This class is intended to *read* permissions from a single world. + * + * @author Nijikokun + * @author Gabriel Couto + */ +public abstract class PermissionsReaderInterface { + + + /** + * + * @param player + * @param string + * @return + */ + public abstract boolean has(Player player, String string); + + /** + * + * @param player + * @param string + * @return + */ + public abstract boolean permission(Player player, String string); + + /** + * + * @param string + * @return + */ + public abstract String getGroup(String string); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract boolean inGroup(String string, String string1); + + /** + * + * @param string + * @return + */ + public abstract String getGroupPrefix(String string); + + /** + * + * @param string + * @return + */ + public abstract String getGroupSuffix(String string); + + /** + * + * @param string + * @return + */ + public abstract boolean canGroupBuild(String string); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract String getGroupPermissionString(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract int getGroupPermissionInteger(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract boolean getGroupPermissionBoolean(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract double getGroupPermissionDouble(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract String getUserPermissionString(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract int getUserPermissionInteger(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract boolean getUserPermissionBoolean(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract double getUserPermissionDouble(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract String getPermissionString(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract int getPermissionInteger(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract boolean getPermissionBoolean(String string, String string1); + + /** + * + * @param string + * @param string1 + * @return + */ + public abstract double getPermissionDouble(String string, String string1); +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/GMLoggerHandler.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/GMLoggerHandler.java new file mode 100644 index 000000000..87b6806ab --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/GMLoggerHandler.java @@ -0,0 +1,26 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.utils; + +import java.util.logging.ConsoleHandler; +import java.util.logging.Level; +import java.util.logging.LogRecord; + +/** + * + * @author gabrielcouto + */ +public class GMLoggerHandler extends ConsoleHandler { + + @Override + public void publish(LogRecord record) { + String message = "GroupManager - " + record.getLevel() + " - " + record.getMessage(); + if (record.getLevel().equals(Level.SEVERE) || record.getLevel().equals(Level.WARNING)) { + System.err.println(message); + } else { + System.out.println(message); + } + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/GroupManagerPermissions.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/GroupManagerPermissions.java new file mode 100644 index 000000000..781f2753c --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/GroupManagerPermissions.java @@ -0,0 +1,51 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.utils; + +/** + * Just a list of commands for this plugin + * @author gabrielcouto + */ +public enum GroupManagerPermissions { + manuadd, + manudel, + manuaddsub, + manudelsub, + mangadd, + mangdel, + manuaddp, + manudelp, + manulistp, + manucheckp, + mangaddp, + mangdelp, + manglistp, + mangcheckp, + mangaddi, + mangdeli, + manuaddv, + manudelv, + manulistv, + manucheckv, + mangaddv, + mangdelv, + manglistv, + mangcheckv, + manwhois, + tempadd, + tempdel, + templist, + tempdelall, + mansave, + manload, + listgroups, + manpromote, + mandemote, + mantogglevalidate, + mantogglesave, + manworld, + manselect, + manclear +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/PermissionCheckResult.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/PermissionCheckResult.java new file mode 100644 index 000000000..3ee6fdf30 --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/PermissionCheckResult.java @@ -0,0 +1,66 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.utils; + +import org.anjocaido.groupmanager.data.DataUnit; + +/** + * + * @author gabrielcouto + */ +public class PermissionCheckResult { + /** + * It should be the owner of the access level found. + * + * Use instanceof to find the owner type + */ + public DataUnit owner; + /** + * The permission node found in the DataUnit. + */ + public String accessLevel; + /** + * The full name of the permission you are looking for + */ + public String askedPermission; + /** + * The result conclusion of the search. + * It determines if the owner can do, or not. + * + * It even determines if it has an owner. + */ + public Type resultType = Type.NOTFOUND; + + /** + * The type of result the search can give. + */ + public enum Type { + + /** + * If found a matching node starting with '+'. + * It means the user CAN do the permission. + */ + EXCEPTION, + /** + * If found a matching node starting with '-'. + * It means the user CANNOT do the permission. + */ + NEGATION, + /** + * If just found a common matching node. + * IT means the user CAN do the permission. + */ + FOUND, + /** + * If no matchin node was found. + * It means the user CANNOT do the permission. + * + * owner field and accessLevel field should not be considered, + * when type is + * NOTFOUND + */ + NOTFOUND + } +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/StringPermissionComparator.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/StringPermissionComparator.java new file mode 100644 index 000000000..2e192118d --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/StringPermissionComparator.java @@ -0,0 +1,50 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package org.anjocaido.groupmanager.utils; + +import java.util.Comparator; + +/** + * + * @author gabrielcouto + */ +public class StringPermissionComparator implements Comparator { + + @Override + public int compare(String permA, String permB) { + boolean ap = permA.startsWith("+"); + boolean bp = permB.startsWith("+"); + boolean am = permA.startsWith("-"); + boolean bm = permB.startsWith("-"); + if(ap&&bp){ + return 0; + } + if(ap&&!bp){ + return -1; + } + if(!ap&&bp){ + return 1; + } + if(am&&bm){ + return 0; + } + if(am&&!bm){ + return -1; + } + if(!am&&bm){ + return 1; + } + return permA.compareToIgnoreCase(permB); + } + private static StringPermissionComparator instance; + public static StringPermissionComparator getInstance(){ + if(instance==null){ + instance = new StringPermissionComparator(); + } + return instance; + } + +} diff --git a/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/Tasks.java b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/Tasks.java new file mode 100644 index 000000000..64bdb6209 --- /dev/null +++ b/EssentialsGroupManager/src/org/anjocaido/groupmanager/utils/Tasks.java @@ -0,0 +1,111 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package org.anjocaido.groupmanager.utils; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.GregorianCalendar; +import java.util.List; +import org.anjocaido.groupmanager.data.Group; + +/** + * + * @author gabrielcouto + */ +public abstract class Tasks { + + public static void copy(InputStream src, File dst) throws IOException { + InputStream in = src; + OutputStream out = new FileOutputStream(dst); + + // Transfer bytes from in to out + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + out.close(); + try { + in.close(); + } catch (Exception e) { + } + } + + public static void copy(File src, File dst) throws IOException { + InputStream in = new FileInputStream(src); + copy(in, dst); + } + + public static void removeOldFiles(File folder) { + if (folder.isDirectory()) { + long oldTime = System.currentTimeMillis() - 86400000L; + for (File olds : folder.listFiles()) { + if (olds.isFile()) { + if (olds.lastModified() < oldTime) { + try { + olds.delete(); + } catch (Exception e) { + } + } + } + } + } + } + + public static String getDateString() { + GregorianCalendar now = new GregorianCalendar(); + String date = ""; + date += now.get(GregorianCalendar.DAY_OF_MONTH); + date += "-"; + date += now.get(GregorianCalendar.HOUR); + date += "-"; + date += now.get(GregorianCalendar.MINUTE); + return date; + } + public static String getStringListInString(List list){ + if(list==null){ + return ""; + } + String result=""; + for(int i=0;i list){ + if(list==null){ + return ""; + } + String result=""; + for(int i=0;i + permission: groupmanager.manuadd + manudel: + description: Remove any user specific configuration. Make him default group. + usage: / + permission: groupmanager.manudel + manuaddsub: + description: Add a group to a player's subgroup list. + usage: / + permission: groupmanager.manuaddsub + manudelsub: + description: Remove a group to a player's subgroup list. + usage: / + permission: groupmanager.manudelsub + mangadd: + description: Add group to the system. + usage: / + permission: groupmanager.mangadd + mangdel: + description: Removes group from the system(all it's users become default) + usage: / + permission: groupmanager.mangdel + manuaddp: + description: Add permission diretly to the player. + usage: / + permission: groupmanager.manuaddp + manudelp: + description: Removes permission diretly from the player. + usage: / + permission: groupmanager.manudelp + manulistp: + description: List all permissions from a player. + usage: / + permission: groupmanager.manulistp + manucheckp: + description: Verify if user has a permission, and where it comes from. + usage: / + permission: groupmanager.manucheckp + mangaddp: + description: Add permission to a group. + usage: / + permission: groupmanager.mangaddp + mangdelp: + description: Removes permission from a group. + usage: / + permission: groupmanager.mangdelp + manglistp: + description: Lists all permissions from a group. + usage: / + permission: groupmanager.manglistp + mangcheckp: + description: Check if group has a permission, and where it comes from. + usage: / + permission: groupmanager.mangcheckp + mangaddi: + description: Add a group to another group inheritance list. + usage: / + permission: groupmanager.mangaddi + mangdeli: + description: Remove a group from another group inheritance list. + usage: / + permission: groupmanager.mangdeli + manuaddv: + description: Add, or replaces, a variable to a user (like prefix or suffix). + usage: / + permission: groupmanager.manuaddv + manudelv: + description: Remove a variable from a user. + usage: / + permission: groupmanager.manudelv + manulistv: + description: List variables a user has (like prefix or suffix). + usage: / + permission: groupmanager.manulistv + manucheckv: + description: Verify a value of a variable of user, and where it comes from. + usage: / + permission: groupmanager.manucheckv + mangaddv: + description: Add, or replaces, a variable to a group (like prefix or suffix). + usage: / + permission: groupmanager.mangaddv + mangdelv: + description: Remove a variable from a group. + usage: / + permission: groupmanager.mangdelv + manglistv: + description: List variables a group has (like prefix or suffix). + usage: / + permission: groupmanager.manglistv + mangcheckv: + description: Verify a value of a variable of group, and where it comes from. + usage: / + permission: groupmanager.mangckeckv + manwhois: + description: Tell the group that user belongs. + usage: / + permission: groupmanager.manwhois + tempadd: + description: Creates a temporary permission copy for that user. + usage: / + permission: groupmanager.tempadd + tempdel: + description: Remove the temporary permission copy for player. + usage: / + permission: groupmanager.tempdel + templist: + description: List players in overload-permissions mode made by /tempadd. + usage: / + permission: groupmanager.templist + tempdelall: + description: Remove all overrides made by command /tempadd. + usage: / + permission: groupmanager.tempdelall + mansave: + description: Save all permissions on file. + usage: / + permission: groupmanager.mansave + manload: + description: Reload current world and config.yml. Or load given world. + usage: / [world] + permission: groupmanager.manload + listgroups: + description: List the groups available. + usage: / + permission: groupmanager.listgroups + manpromote: + description: Promote a player in the same heritage line to a higher rank. + usage: / + permission: groupmanager.manpromote + mandemote: + description: Demote a player in the same heritage line to a lower rank. + usage: / + permission: groupmanager.mandemote + mantogglevalidate: + description: Toggle on/off the validating if player is online. + usage: / + permission: groupmanager.mantogglevalidate + mantogglesave: + description: Toggle on/ff the autosave. + usage: / + permission: groupmanager.mantogglesave + manworld: + description: Prints the selected world name + usage: / + permission: groupmanager.manworld + manselect: + description: Select a world to work with next commands. + usage: / + permission: groupmanager.manselect + manclear: + description: Clear world selection. Next commands will work on your world. + usage: / + permission: groupmanager.manclear \ No newline at end of file diff --git a/EssentialsGroupManager/src/users.yml b/EssentialsGroupManager/src/users.yml new file mode 100644 index 000000000..5645c5d23 --- /dev/null +++ b/EssentialsGroupManager/src/users.yml @@ -0,0 +1,59 @@ +users: + aMiner: + subgroups: + - Miner + permissions: [] + group: BlueFaction + info: + prefix: '&d' + suffix: Miner + gmcouto: + subgroups: [] + permissions: [] + group: SemiAdmin + tempRailer: + subgroups: + - Miner + - Railer + permissions: [] + group: BlueFaction + info: + prefix: '&d' + suffix: Miner + anjocaido: + subgroups: [] + permissions: [] + group: Admin + info: + prefix: '&c' + suffix: King + aFarmer: + subgroups: + - Farmer + permissions: [] + group: RedFaction + info: + prefix: '&d' + suffix: Farmer + zenexer: + subgroups: [] + permissions: + - essentials.god + group: Moderator + Teste: + subgroups: + - Miner + - Railer + - SuperCart + - Fighter + - FlyingMan + permissions: [] + group: BlueFaction + aHealer: + subgroups: + - Healer + permissions: [] + group: RedFaction + info: + prefix: '&d' + suffix: Healer diff --git a/EssentialsProtect/MANIFEST.MF b/EssentialsProtect/MANIFEST.MF new file mode 100644 index 000000000..b43aa699e --- /dev/null +++ b/EssentialsProtect/MANIFEST.MF @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 +Class-Path: ../lib/mysql.jar ../lib/sqlite.jar diff --git a/EssentialsProtect/build.xml b/EssentialsProtect/build.xml new file mode 100644 index 000000000..e5e614e3e --- /dev/null +++ b/EssentialsProtect/build.xml @@ -0,0 +1,86 @@ + + ]> + + + + + + + + + + Builds, tests, and runs the project EssentialsProtect. + + + + + + + + + + + + + + diff --git a/EssentialsProtect/nbproject/build-impl.xml b/EssentialsProtect/nbproject/build-impl.xml new file mode 100644 index 000000000..d284d9279 --- /dev/null +++ b/EssentialsProtect/nbproject/build-impl.xml @@ -0,0 +1,1072 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + Must select one file in the IDE or set profile.class + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/EssentialsProtect/nbproject/genfiles.properties b/EssentialsProtect/nbproject/genfiles.properties new file mode 100644 index 000000000..3f48945cc --- /dev/null +++ b/EssentialsProtect/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=ff207988 +build.xml.script.CRC32=1ed11cc3 +build.xml.stylesheet.CRC32=28e38971@1.38.3.45 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=40644caa +nbproject/build-impl.xml.script.CRC32=1d86f3b0 +nbproject/build-impl.xml.stylesheet.CRC32=19debb58@1.42.1.45 diff --git a/EssentialsProtect/nbproject/private/private.properties b/EssentialsProtect/nbproject/private/private.properties new file mode 100644 index 000000000..94183418a --- /dev/null +++ b/EssentialsProtect/nbproject/private/private.properties @@ -0,0 +1 @@ +user.properties.file=C:\\Users\\Paul\\.netbeans\\7.0beta2\\build.properties diff --git a/EssentialsProtect/nbproject/project.properties b/EssentialsProtect/nbproject/project.properties new file mode 100644 index 000000000..3f2895ed5 --- /dev/null +++ b/EssentialsProtect/nbproject/project.properties @@ -0,0 +1,91 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +application.title=EssentialsProtect +application.vendor=devhome +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/original-EssentialsProtect.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes= +file.reference.c3p0-0.9.1.2.jar=..\\lib\\c3p0-0.9.1.2.jar +file.reference.craftbukkit-0.0.1-SNAPSHOT.jar=..\\lib\\craftbukkit-0.0.1-SNAPSHOT.jar +file.reference.mysql.jar=..\\lib\\mysql.jar +file.reference.sqlite.jar=..\\lib\\sqlite.jar +includes=** +jar.archive.disabled=${jnlp.enabled} +jar.compress=false +jar.index=${jnlp.enabled} +javac.classpath=\ + ${reference.Essentials.jar}:\ + ${file.reference.mysql.jar}:\ + ${file.reference.sqlite.jar}:\ + ${file.reference.craftbukkit-0.0.1-SNAPSHOT.jar}:\ + ${file.reference.c3p0-0.9.1.2.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.processorpath=\ + ${javac.classpath} +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${libs.junit.classpath}:\ + ${libs.junit_4.classpath} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jnlp.codebase.type=no.codebase +jnlp.descriptor=application +jnlp.enabled=false +jnlp.mixed.code=defaut +jnlp.offline-allowed=false +jnlp.signed=false +manifest.file=manifest.mf +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +project.Essentials=../Essentials +reference.Essentials.jar=${project.Essentials}/dist/Essentials.jar +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/EssentialsProtect/nbproject/project.xml b/EssentialsProtect/nbproject/project.xml new file mode 100644 index 000000000..821d66672 --- /dev/null +++ b/EssentialsProtect/nbproject/project.xml @@ -0,0 +1,28 @@ + + + org.netbeans.modules.java.j2seproject + + + EssentialsProtect + + + + + + + + + ../lib\nblibraries.properties + + + + Essentials + jar + + jar + clean + jar + + + + diff --git a/EssentialsProtect/src/README.TXT b/EssentialsProtect/src/README.TXT new file mode 100644 index 000000000..4bb1b5c05 --- /dev/null +++ b/EssentialsProtect/src/README.TXT @@ -0,0 +1,30 @@ +EssentialsProtect: + +REQUIRED : Essentials.jar. Also sqlite.jar, mysql.jar in the bukkit lib folder. + +Config Settings in plugins/Essentials/config.yml + +protect: + datatype: 'sqlite' type of db, options sqlite or mysql + username: 'root' mysql username + pasword: 'root' mysql password + mysqlDb: 'jdbc:mysql://localhost:3306/minecraft' mysql database location + protectSigns: true + protectRails: true + protectBlockBelow: true + preventBlockOnRail: false prevents block placement on protected rails + +On startup creates a sqlite database under /plugins/essentials called EssentialsProtect.db + +Permissions: + +"essentials.protect" - allows protection +"essentials.protect.admin" can delete protected blocks / query protection by right clicking a protected item. + +Usage: + +Place a sign or rail and they (plus optionally the block below) will be protected. Only the owners and those with admin permissions can destroy. + + + + diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java new file mode 100644 index 000000000..d6869519b --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java @@ -0,0 +1,154 @@ +package com.earth2me.essentials.protect; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.IConf; +import com.earth2me.essentials.User; +import com.earth2me.essentials.protect.data.IProtectedBlock; +import com.earth2me.essentials.protect.data.ProtectedBlockMemory; +import com.earth2me.essentials.protect.data.ProtectedBlockMySQL; +import com.earth2me.essentials.protect.data.ProtectedBlockSQLite; +import java.beans.PropertyVetoException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.Event.Priority; +import org.bukkit.event.Event.Type; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + + +public class EssentialsProtect extends JavaPlugin implements IConf +{ + private EssentialsProtectBlockListener blockListener = null; + private EssentialsProtectPlayerListener playerListener = null; + private EssentialsProtectEntityListener entityListener = null; + public static final String AUTHORS = Essentials.AUTHORS; + private static final Logger logger = Logger.getLogger("Minecraft"); + public static HashMap genSettings = null; + public static HashMap dataSettings = null; + public static HashMap guardSettings = null; + public static HashMap playerSettings = null; + public static ArrayList usageList = null; + public static ArrayList blackListPlace = null; + public static ArrayList breakBlackList = null; + public static ArrayList onPlaceAlert = null; + public static ArrayList onUseAlert = null; + public static ArrayList onBreakAlert = null; + + private IProtectedBlock storage = null; + private static EssentialsProtect instance = null; + + public EssentialsProtect() + { + } + + public void onEnable() + { + PluginManager pm = this.getServer().getPluginManager(); + Essentials ess = (Essentials)pm.getPlugin("Essentials"); + if (!ess.isEnabled()) { + pm.enablePlugin(ess); + } + + instance = this; + reloadConfig(); + + playerListener = new EssentialsProtectPlayerListener(this); + blockListener = new EssentialsProtectBlockListener(this); + entityListener = new EssentialsProtectEntityListener(this); + pm.registerEvent(Type.PLAYER_PICKUP_ITEM, playerListener, Priority.Low, this); + pm.registerEvent(Type.PLAYER_INTERACT, playerListener, Priority.Low, this); + pm.registerEvent(Type.BLOCK_PLACE, blockListener, Priority.Highest, this); + pm.registerEvent(Type.BLOCK_FROMTO, blockListener, Priority.Highest, this); + pm.registerEvent(Type.BLOCK_IGNITE, blockListener, Priority.Highest, this); + pm.registerEvent(Type.BLOCK_BURN, blockListener, Priority.Highest, this); + pm.registerEvent(Type.ENTITY_EXPLODE, entityListener, Priority.Highest, this); + pm.registerEvent(Type.ENTITY_DAMAGE, entityListener, Priority.Highest, this); + pm.registerEvent(Type.BLOCK_BREAK, blockListener, Priority.Highest, this); + pm.registerEvent(Type.CREATURE_SPAWN, entityListener, Priority.Highest, this); + + if (!this.getDescription().getVersion().equals(Essentials.getStatic().getDescription().getVersion())) { + logger.log(Level.WARNING, "Version mismatch! Please update all Essentials jars to the same version."); + } + logger.info("Loaded " + this.getDescription().getName() + " build " + this.getDescription().getVersion() + " maintained by " + AUTHORS); + } + + public static boolean checkProtectionItems(ArrayList itemList, int id) + { + return !itemList.isEmpty() && itemList.contains(String.valueOf(id)); + } + + @Override + public void onDisable() + { + genSettings.clear(); + dataSettings.clear(); + + blockListener = null; + playerListener = null; + entityListener = null; + genSettings = null; + dataSettings = null; + guardSettings = null; + playerSettings = null; + usageList = null; + blackListPlace = null; + onPlaceAlert = null; + onUseAlert = null; + onBreakAlert = null; + } + + public void alert(User user, String item, String type) + { + Location loc = user.getLocation(); + for (Player p : this.getServer().getOnlinePlayers()) + { + User alertUser = User.get(p); + if (alertUser.isAuthorized("essentials.protect.alerts")) + alertUser.sendMessage(ChatColor.DARK_AQUA + "[" + user.getName() + "] " + ChatColor.WHITE + type + ChatColor.GOLD + item + " at: " + formatCoords(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + } + } + + public static String formatCoords(int x, int y, int z) + { + return x + "," + y + "," + z; + } + + public void reloadConfig() { + dataSettings = Essentials.getSettings().getEpDBSettings(); + genSettings = Essentials.getSettings().getEpSettings(); + guardSettings = Essentials.getSettings().getEpGuardSettings(); + usageList = Essentials.getSettings().epBlackListUsage(); + blackListPlace = Essentials.getSettings().epBlackListPlacement(); + breakBlackList = Essentials.getSettings().epBlockBreakingBlacklist(); + onPlaceAlert = Essentials.getSettings().getEpAlertOnPlacement(); + onUseAlert = Essentials.getSettings().getEpAlertOnUse(); + onBreakAlert = Essentials.getSettings().getEpAlertOnBreak(); + playerSettings = Essentials.getSettings().getEpPlayerSettings(); + + if (dataSettings.get("protect.datatype").equals("mysql")) { + try { + storage = new ProtectedBlockMySQL(dataSettings.get("protect.mysqlDb"), dataSettings.get("protect.username"), dataSettings.get("protect.password")); + } catch (PropertyVetoException ex) { + logger.log(Level.SEVERE, null, ex); + } + } else { + try { + storage = new ProtectedBlockSQLite("jdbc:sqlite:plugins/Essentials/EssentialsProtect.db"); + } catch (PropertyVetoException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + if (genSettings.get("protect.memstore")) { + storage = new ProtectedBlockMemory(storage); + } + } + + public static IProtectedBlock getStorage() { + return EssentialsProtect.instance.storage; + } +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java new file mode 100644 index 000000000..2028edf42 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java @@ -0,0 +1,272 @@ +package com.earth2me.essentials.protect; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import java.util.ArrayList; +import java.util.List; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockBurnEvent; +import org.bukkit.event.block.BlockFromToEvent; +import org.bukkit.event.block.BlockIgniteEvent; +import org.bukkit.event.block.BlockListener; +import org.bukkit.event.block.BlockPlaceEvent; +import org.bukkit.inventory.ItemStack; + + +public class EssentialsProtectBlockListener extends BlockListener +{ + private EssentialsProtect parent; + + public EssentialsProtectBlockListener(EssentialsProtect parent) + { + Essentials.loadClasses(); + this.parent = parent; + } + + @Override + public void onBlockPlace(BlockPlaceEvent event) + { + if (event.isCancelled()) return; + ItemStack item = event.getItemInHand(); + User user = User.get(event.getPlayer()); + + if (EssentialsProtect.playerSettings.get("protect.disable.build") && !user.canBuild()) + { + event.setCancelled(true); + return; + } + + int id = event.getBlockPlaced().getTypeId(); + + if (EssentialsProtect.checkProtectionItems(EssentialsProtect.blackListPlace, id) && !user.isAuthorized("essentials.protect.exemptplacement")) + { + event.setCancelled(true); + return; + } + + if (!EssentialsProtect.onPlaceAlert.isEmpty() && EssentialsProtect.onPlaceAlert.contains(String.valueOf(item.getTypeId()))) + { + parent.alert(user, item.getType().toString(), "placed: "); + } + + Block blockPlaced = event.getBlockPlaced(); + Block below = blockPlaced.getFace(BlockFace.DOWN); + if (below.getType() == Material.RAILS) { + if (EssentialsProtect.genSettings.get("protect.protect.prevent.block-on-rail")) + { + if (EssentialsProtect.getStorage().isProtected(below, user.getName())) { + event.setCancelled(true); + return; + } + } + } + + List protect = new ArrayList(); + if (blockPlaced.getType() == Material.RAILS) { + if (EssentialsProtect.genSettings.get("protect.protect.rails")) + { + if (user.isAuthorized("essentials.protect")) + { + protect.add(blockPlaced); + if (EssentialsProtect.genSettings.get("protect.protect.block-below")) + { + protect.add(blockPlaced.getFace(BlockFace.DOWN)); + } + } + } + } + if (blockPlaced.getType() == Material.SIGN_POST || blockPlaced.getType() == Material.WALL_SIGN) { + if (EssentialsProtect.genSettings.get("protect.protect.signs")) + { + if (user.isAuthorized("essentials.protect")) + { + protect.add(blockPlaced); + if (EssentialsProtect.genSettings.get("protect.protect.block-below")) + { + protect.add(event.getBlockAgainst()); + } + } + } + } + for (Block block : protect) { + EssentialsProtect.getStorage().protectBlock(block, user.getName()); + } + } + + @Override + public void onBlockIgnite(BlockIgniteEvent event) + { + Block block = event.getBlock(); + if (block.getType() == Material.RAILS && EssentialsProtect.genSettings.get("protect.protect.rails")) + { + event.setCancelled(true); + return; + } + if ((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) && EssentialsProtect.genSettings.get("protect.protect.signs")) + { + event.setCancelled(true); + return; + } + if ((event.getCause().equals(BlockIgniteEvent.IgniteCause.SPREAD))) + { + event.setCancelled(EssentialsProtect.guardSettings.get("protect.prevent.fire-spread")); + return; + } + + if (event.getCause().equals(BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL)) + { + event.setCancelled(EssentialsProtect.guardSettings.get("protect.prevent.flint-fire")); + return; + } + + if (event.getCause().equals(BlockIgniteEvent.IgniteCause.LAVA)) + { + event.setCancelled(EssentialsProtect.guardSettings.get("protect.prevent.lava-fire-spread")); + return; + } + } + + @Override + public void onBlockFromTo(BlockFromToEvent event) + { + if (event.isCancelled()) return; + Block block = event.getBlock(); + Block toBlock = event.getToBlock(); + if (toBlock.getType() == Material.RAILS && EssentialsProtect.genSettings.get("protect.protect.rails")) + { + event.setCancelled(true); + return; + } + if ((toBlock.getType() == Material.WALL_SIGN || toBlock.getType() == Material.SIGN_POST) && EssentialsProtect.genSettings.get("protect.protect.signs")) + { + event.setCancelled(true); + return; + } + if (block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER) + { + event.setCancelled(EssentialsProtect.guardSettings.get("protect.prevent.water-flow")); + return; + } + + if (block.getType() == Material.LAVA || block.getType() == Material.STATIONARY_LAVA) + { + event.setCancelled(EssentialsProtect.guardSettings.get("protect.prevent.lava-flow")); + return; + } + + if (block.getType() == Material.AIR) + { + event.setCancelled(EssentialsProtect.guardSettings.get("protect.prevent.water-bucket-flow")); + return; + } + } + + @Override + public void onBlockBurn(BlockBurnEvent event) + { + Block block = event.getBlock(); + if (block.getType() == Material.RAILS && EssentialsProtect.genSettings.get("protect.protect.rails")) + { + event.setCancelled(true); + return; + } + if ((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) && EssentialsProtect.genSettings.get("protect.protect.signs")) + { + event.setCancelled(true); + return; + } + if (EssentialsProtect.guardSettings.get("protect.prevent.fire-spread")) + { + event.setCancelled(true); + return; + } + } + + @Override + public void onBlockBreak(BlockBreakEvent event) + { + if (event.isCancelled()) return; + User user = User.get(event.getPlayer()); + Block block = event.getBlock(); + if (EssentialsProtect.playerSettings.get("protect.disable.build") && !user.canBuild()) + { + event.setCancelled(true); + return; + } + + if(EssentialsProtect.breakBlackList.contains(String.valueOf(block.getTypeId())) && !user.isAuthorized("essentials.protect.exemptbreak")) + { + event.setCancelled(true); + return; + } + + if (!EssentialsProtect.onBreakAlert.isEmpty() && EssentialsProtect.onBreakAlert.contains(String.valueOf(block.getTypeId()))) + { + parent.alert(user, block.getType().toString(), "broke: "); + } + + if (user.isAuthorized("essentials.protect.admin")) + { + if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST || block.getType() == Material.RAILS) + { + EssentialsProtect.getStorage().unprotectBlock(block); + if (block.getType() == Material.RAILS || block.getType() == Material.SIGN_POST) { + Block below = block.getFace(BlockFace.DOWN); + EssentialsProtect.getStorage().unprotectBlock(below); + } else { + BlockFace[] faces = new BlockFace[] { + BlockFace.NORTH, + BlockFace.EAST, + BlockFace.SOUTH, + BlockFace.WEST + }; + for (BlockFace blockFace : faces) { + Block against = block.getFace(blockFace); + EssentialsProtect.getStorage().unprotectBlock(against); + } + } + } + else + { + EssentialsProtect.getStorage().unprotectBlock(block); + } + return; + } + else + { + + boolean isProtected = EssentialsProtect.getStorage().isProtected(block, user.getName()); + if (!isProtected) { + if (block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST || block.getType() == Material.RAILS) + { + EssentialsProtect.getStorage().unprotectBlock(block); + if (block.getType() == Material.RAILS || block.getType() == Material.SIGN_POST) { + Block below = block.getFace(BlockFace.DOWN); + EssentialsProtect.getStorage().unprotectBlock(below); + } else { + BlockFace[] faces = new BlockFace[] { + BlockFace.NORTH, + BlockFace.EAST, + BlockFace.SOUTH, + BlockFace.WEST + }; + for (BlockFace blockFace : faces) { + Block against = block.getFace(blockFace); + EssentialsProtect.getStorage().unprotectBlock(against); + } + } + } + else + { + EssentialsProtect.getStorage().unprotectBlock(block); + } + } + event.setCancelled(true); + return; + } + } +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectData.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectData.java new file mode 100644 index 000000000..76b36d810 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectData.java @@ -0,0 +1,533 @@ +package com.earth2me.essentials.protect; + +import com.earth2me.essentials.Essentials; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.block.Block; + + +public class EssentialsProtectData +{ + private static final Logger logger = Logger.getLogger("Minecraft"); + private static final String mysqlDriver = "com.mysql.jdbc.Driver"; + private static String mysqlUsername; + private static String mysqlPassword; + private static String mysqlDatabase; + private static String dataType; + private static final String sqlite = "jdbc:sqlite:plugins/Essentials/EssentialsProtect.db"; + private static final String mysqlTable; + private static final String sqliteTable; + private static final String insertQuery; + private static final String countByLocationQuery; + private static final String countByPlayerLocationQuery; + private static final String playerByLocationQuery; + private static final String deleteByLocationQuery; + + static + { + mysqlTable = EssentialsProtectSqlProperties.EssentialsProtect; + sqliteTable = EssentialsProtectSqlProperties.EssentialsProtect_sqlite; + insertQuery = EssentialsProtectSqlProperties.Insert; + countByLocationQuery = EssentialsProtectSqlProperties.CountByLocation; + countByPlayerLocationQuery = EssentialsProtectSqlProperties.CountByPLayerLocation; + playerByLocationQuery = EssentialsProtectSqlProperties.PlayerByLocation; + deleteByLocationQuery = EssentialsProtectSqlProperties.DeleteByLocation; + mysqlUsername = EssentialsProtect.dataSettings.get("protect.username"); + mysqlPassword = EssentialsProtect.dataSettings.get("protect.password"); + mysqlDatabase = EssentialsProtect.dataSettings.get("protect.mysqlDb"); + dataType = EssentialsProtect.dataSettings.get("protect.datatype"); + } + + public EssentialsProtectData() + { + } + + public static String formatCoords(int x, int y, int z) + { + return x + "," + y + "," + z; + } + + public void insertProtectionIntoDb(String worldname, String playerName, int x, int y, int z) + { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + try + { + if (dataType.contentEquals("mysql")) + { + Class.forName(mysqlDriver); + conn = DriverManager.getConnection(mysqlDatabase, mysqlUsername, mysqlPassword); + } + else + { + Class.forName("org.sqlite.JDBC"); + conn = DriverManager.getConnection(sqlite); + } + ps = conn.prepareStatement(insertQuery); + ps.setString(1, worldname); + ps.setString(2, playerName); + ps.setInt(3, x); + ps.setInt(4, y); + ps.setInt(5, z); + ps.executeUpdate(); + + } + catch (SQLException ex) + { + logger.log(Level.SEVERE, "[EssentialsProtect] Unable to add protection into SQL", ex); + } + catch (ClassNotFoundException e) + { + // TODO Auto-generated catch block + logger.log(Level.SEVERE, "[EssentialsProtect] Class not found", e); + } + finally + { + try + { + if (ps != null) + { + ps.close(); + } + if (rs != null) + { + rs.close(); + } + if (conn != null) + { + conn.close(); + } + } + catch (SQLException ex) + { + logger.log(Level.SEVERE, "[EssentialsProtect] Could not close connection to SQL", ex); + } + } + } + + public boolean canDestroy(String worldName, String playerName, Block block) + { + int x = block.getX(); + int y = block.getY(); + int z = block.getZ(); + + int rowCount = 0; + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + try + { + if (dataType.contentEquals("mysql")) + { + Class.forName(mysqlDriver); + conn = DriverManager.getConnection(mysqlDatabase, mysqlUsername, mysqlPassword); + } + else + { + Class.forName("org.sqlite.JDBC"); + conn = DriverManager.getConnection(sqlite); + } + conn.setAutoCommit(false); + ps = conn.prepareStatement(countByLocationQuery); + ps.setString(1, worldName); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + rs = ps.executeQuery(); + rs.next(); + rowCount = rs.getInt(1); + rs.close(); + ps.close(); + + if (rowCount == 0) + { + return true; + } + else + { + ps = conn.prepareStatement(countByPlayerLocationQuery); + ps.setString(1, worldName); + ps.setString(2, playerName); + ps.setInt(3, x); + ps.setInt(4, y); + ps.setInt(5, z); + rs = ps.executeQuery(); + rs.next(); + rowCount = rs.getInt(1); + + if (rowCount == 0) + { + return false; + } + + } + + } + catch (SQLException ex) + { + logger.log(Level.SEVERE, "[EssentialsProtect] Unable to query Protection", ex); + } + catch (Throwable e) + { + logger.log(Level.SEVERE, "[EssentialsProtect] Unable to query Protection", e); + } + finally + { + try + { + if (ps != null) + { + ps.close(); + } + if (rs != null) + { + rs.close(); + } + if (conn != null) + { + conn.close(); + } + } + catch (SQLException ex) + { + logger.log(Level.SEVERE, "[EssentialsProtection] Could not close connection to SQL", ex); + } + } + return true; + } + + @SuppressWarnings("CallToThreadDumpStack") + public static void createSqlTable() + { + Connection conn = null; + Statement st = null; + + try + { + if (dataType.contentEquals("mysql")) + { + Class.forName(mysqlDriver); + conn = DriverManager.getConnection(mysqlDatabase, mysqlUsername, mysqlPassword); + } + else + { + Class.forName("org.sqlite.JDBC"); + conn = DriverManager.getConnection(sqlite); + } + + st = conn.createStatement(); + st.executeUpdate(dataType.contentEquals("mysql") ? mysqlTable : sqliteTable); + } + catch (SQLException s) + { + logger.log(Level.SEVERE, "[EssentialsProtect] Could not create table for " + dataType, s); + + } + catch (ClassNotFoundException ex) + { + logger.log(Level.SEVERE, "[EssentialsProtect] Could not find driver for " + dataType, ex); + + } + catch (Throwable e) + { + logger.log(Level.SEVERE, "[EssentialsProtect] Unexpected error occured whilst creating table ", e); + } + finally + { + try + { + if (conn != null && !conn.isClosed()) + { + try + { + conn.close(); + } + catch (SQLException e) + { + logger.log(Level.SEVERE, "[EssentialsProtect] Unexpected error occured whilst closing the connection", e); + } + } + } + catch (SQLException e) + { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + public String getBlockOwner(String worldName, String playerName, Block block) + { + String returnPlayerName = null; + int x = block.getX(); + int y = block.getY(); + int z = block.getZ(); + + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + try + { + if (dataType.contentEquals("mysql")) + { + Class.forName(mysqlDriver); + conn = DriverManager.getConnection(mysqlDatabase, mysqlUsername, mysqlPassword); + } + else + { + Class.forName("org.sqlite.JDBC"); + conn = DriverManager.getConnection(sqlite); + } + conn.setAutoCommit(false); + ps = conn.prepareStatement(playerByLocationQuery); + + ps.setString(1, worldName); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + rs = ps.executeQuery(); + while (rs.next()) + { + returnPlayerName = rs.getString("playerName"); + } + rs.close(); + ps.close(); + + } + catch (SQLException ex) + { + logger.log(Level.SEVERE, "[EssentialsProtect] Unable to query EssentialsProtection", ex); + } + catch (Throwable e) + { + logger.log(Level.SEVERE, "[EssentialsProtect] Unable to query EssentialsProtection", e); + } + finally + { + try + { + if (ps != null) + { + ps.close(); + } + if (rs != null) + { + rs.close(); + } + if (conn != null) + { + conn.close(); + } + } + catch (SQLException ex) + { + logger.log(Level.SEVERE, "[EssentialsProtection] Could not close connection to SQL", ex); + } + + } + return returnPlayerName; + } + + + public void removeProtectionFromDB(Block block) + { + try + { + Connection conn = null; + if (dataType.contentEquals("mysql")) + { + Class.forName(mysqlDriver); + conn = DriverManager.getConnection(mysqlDatabase, mysqlUsername, + mysqlPassword); + } + else + { + Class.forName("org.sqlite.JDBC"); + conn = DriverManager.getConnection(sqlite); + } + PreparedStatement ps = null; + try + { + ps = conn.prepareStatement(deleteByLocationQuery); + ps.setString(1, block.getWorld().getName()); + ps.setInt(2, block.getX()); + ps.setInt(3, block.getY()); + ps.setInt(4, block.getZ()); + ps.executeUpdate(); + + } + catch (SQLException ex) + { + logger.log(Level.WARNING, + "[EssentialsProtect] Could not delete block data from database", + ex); + } + finally + { + if (conn != null && !conn.isClosed()) + { + conn.close(); + } + if (ps != null) + { + ps.close(); + } + } + + } + catch (Throwable e) + { + logger.log(Level.SEVERE, " [EssentialsProtect] Exception occured whilst trying to delete data from sql", e); + } + + } + + public void removeProtectionFromDB(Block block, boolean removeBelow) + { + try + { + Connection conn = null; + if (dataType.contentEquals("mysql")) + { + Class.forName(mysqlDriver); + conn = DriverManager.getConnection(mysqlDatabase, mysqlUsername, mysqlPassword); + } + else + { + Class.forName("org.sqlite.JDBC"); + conn = DriverManager.getConnection(sqlite); + } + PreparedStatement ps = null; + try + { + ps = conn.prepareStatement(deleteByLocationQuery); + ps.setString(1, block.getWorld().getName()); + ps.setInt(2, block.getX()); + ps.setInt(3, block.getY()); + ps.setInt(4, block.getZ()); + ps.executeUpdate(); + if (removeBelow) + { + ps = conn.prepareStatement(deleteByLocationQuery); + ps.setString(1, block.getWorld().getName()); + ps.setInt(2, block.getX()); + ps.setInt(3, block.getY() - 1); + ps.setInt(4, block.getZ()); + ps.executeUpdate(); + } + + } + catch (SQLException ex) + { + logger.log(Level.WARNING, "[EssentialsProtect] Could not delete block data from database", ex); + } + finally + { + if (conn != null && !conn.isClosed()) + { + conn.close(); + } + if (ps != null) + { + ps.close(); + } + } + + } + catch (Throwable e) + { + logger.log(Level.SEVERE, "[EssentialsProtect] Exception occured whilst trying to delete data from sql", e); + } + + } + + public boolean isBlockAboveProtectedRail(Block block) + { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + if (block.getTypeId() == 66) + { + try + { + if (dataType.contentEquals("mysql")) + { + Class.forName(mysqlDriver); + conn = DriverManager.getConnection(mysqlDatabase, mysqlUsername, mysqlPassword); + } + else + { + Class.forName("org.sqlite.JDBC"); + conn = DriverManager.getConnection(sqlite); + } + int rowCount = 0; + conn.setAutoCommit(false); + ps = conn.prepareStatement(countByLocationQuery); + ps.setString(1, block.getWorld().getName()); + ps.setInt(2, block.getX()); + ps.setInt(3, block.getY()); + ps.setInt(4, block.getZ()); + rs = ps.executeQuery(); + rs.next(); + rowCount = rs.getInt(1); + rs.close(); + ps.close(); + + if (rowCount == 0) + { + + return false; + } + else + { + return true; + } + } + catch (SQLException s) + { + logger.log(Level.SEVERE, "[EssentialsProtect] Could not query protection", s); + + } + catch (ClassNotFoundException ex) + { + logger.log(Level.SEVERE, "[EssentialsProtect] Could not find driver for " + dataType, ex); + + } + catch (Throwable e) + { + logger.log(Level.SEVERE, "[EssentialsProtect] Unexpected error occured whilst creating table", e); + } + finally + { + try + { + if (conn != null && !conn.isClosed()) + { + try + { + conn.close(); + } + catch (SQLException e) + { + logger.log(Level.SEVERE, "[EssentialsProtect] Unexpected error occured whilst closing the connection", e); + } + + } + } + catch (SQLException e) + { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + return false; + } +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java new file mode 100644 index 000000000..97b5c59e5 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java @@ -0,0 +1,197 @@ +package com.earth2me.essentials.protect; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import net.minecraft.server.ChunkPosition; +import net.minecraft.server.Packet60Explosion; +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.craftbukkit.CraftServer; +import org.bukkit.entity.Creeper; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Monster; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.entity.EntityDamageByBlockEvent; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageByProjectileEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.entity.EntityListener; + + +public class EssentialsProtectEntityListener extends EntityListener +{ + private EssentialsProtect parent; + + public EssentialsProtectEntityListener(EssentialsProtect parent) + { + Essentials.loadClasses(); + this.parent = parent; + } + + @Override + public void onEntityDamage(EntityDamageEvent event) + { + if (event.isCancelled()) return; + if (event instanceof EntityDamageByBlockEvent) + { + DamageCause cause = event.getCause(); + + if (EssentialsProtect.playerSettings.get("protect.disable.contactdmg") && cause == DamageCause.CONTACT) + { + event.setCancelled(true); + return; + } + if (EssentialsProtect.playerSettings.get("protect.disable.lavadmg") && cause == DamageCause.LAVA) + { + event.setCancelled(true); + return; + } + if (EssentialsProtect.guardSettings.get("protect.prevent.tnt-explosion") && cause == DamageCause.BLOCK_EXPLOSION) + { + event.setCancelled(true); + return; + } + } + + if (event instanceof EntityDamageByEntityEvent) + { + EntityDamageByEntityEvent edEvent = (EntityDamageByEntityEvent)event; + Entity eAttack = edEvent.getDamager(); + Entity eDefend = edEvent.getEntity(); + + // PVP Settings + if (eDefend instanceof Player && eAttack instanceof Player) + { + if (EssentialsProtect.playerSettings.get("protect.disable.pvp")) + { + User defender = User.get(eDefend); + User attacker = User.get(eAttack); + + if (!defender.isAuthorized("essentials.protect.pvp") || !attacker.isAuthorized("essentials.protect.pvp")) + { + event.setCancelled(true); + return; + } + } + } + //Creeper explode prevention + if (eAttack != null && eAttack instanceof Monster) + { + if (eAttack instanceof Creeper && EssentialsProtect.guardSettings.get("protect.prevent.creeper-explosion")) + { + event.setCancelled(true); + return; + } + + if (eAttack instanceof Creeper && EssentialsProtect.guardSettings.get("protect.prevent.creeper-playerdamage")) + { + event.setCancelled(true); + return; + } + } + } + + if (event instanceof EntityDamageByProjectileEvent) + { + if (event.getEntity() instanceof Player) + { + event.setCancelled(EssentialsProtect.playerSettings.get("protect.disable.projectiles")); + return; + } + } + + DamageCause cause = event.getCause(); + Entity casualty = event.getEntity(); + if (casualty instanceof Player) + { + if (EssentialsProtect.playerSettings.get("protect.disable.fall") && cause == DamageCause.FALL) + { + event.setCancelled(true); + return; + } + + if (EssentialsProtect.playerSettings.get("protect.disable.suffocate") && cause == DamageCause.SUFFOCATION) + { + event.setCancelled(true); + return; + } + if (EssentialsProtect.playerSettings.get("protect.disable.firedmg") && (cause == DamageCause.FIRE + || cause == DamageCause.FIRE_TICK)) + { + event.setCancelled(true); + return; + } + if (EssentialsProtect.playerSettings.get("protect.disable.drown") && cause == DamageCause.DROWNING) + { + event.setCancelled(true); + return; + } + } + } + + @Override + public void onEntityExplode(EntityExplodeEvent event) + { + if (event.isCancelled()) return; + if (event.getEntity() instanceof LivingEntity) + { + //Nicccccccccce plaaacccccccccce.. + int maxHeight = Essentials.getSettings().getEpCreeperMaxHeight(); + if ( EssentialsProtect.guardSettings.get("protect.prevent.creeper-explosion") || + EssentialsProtect.guardSettings.get("protect.prevent.creeper-blockdamage") || + (maxHeight >= 0 && event.getLocation().getBlockY() > maxHeight)) + { + HashSet set = new HashSet(event.blockList().size()); + Player[] players = parent.getServer().getOnlinePlayers(); + List blocksUnderPlayers = new ArrayList(players.length); + Location loc = event.getLocation(); + for (Player player : players) { + if (player.getWorld().equals(loc.getWorld())) { + blocksUnderPlayers.add( + new ChunkPosition( + player.getLocation().getBlockX(), + player.getLocation().getBlockY() - 1, + player.getLocation().getBlockZ())); + } + } + for (Block block : event.blockList()) { + ChunkPosition cp = new ChunkPosition(block.getX(), block.getY(), block.getZ()); + if (!blocksUnderPlayers.contains(cp)) { + set.add(cp); + } + } + + ((CraftServer)parent.getServer()).getServer().f.a(loc.getX(), loc.getY(), loc.getZ(), 64.0D, + new Packet60Explosion(loc.getX(), loc.getY(), loc.getZ(), 3.0f, set)); + event.setCancelled(true); + return; + } + } + else + { //OH NOES TNT + if (EssentialsProtect.guardSettings.get("protect.prevent.tnt-explosion")) + { + event.setCancelled(true); + return; + } + } + } + + @Override + public void onCreatureSpawn(CreatureSpawnEvent event) { + String creatureName = event.getCreatureType().toString().toLowerCase(); + if (creatureName == null || creatureName.isEmpty()) { + return; + } + if (EssentialsProtect.guardSettings.get("protect.prevent.spawn."+creatureName)) { + event.setCancelled(true); + } + } +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectPlayerListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectPlayerListener.java new file mode 100644 index 000000000..2497a733d --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectPlayerListener.java @@ -0,0 +1,70 @@ +package com.earth2me.essentials.protect; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import org.bukkit.ChatColor; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerListener; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.inventory.ItemStack; + + +public class EssentialsProtectPlayerListener extends PlayerListener +{ + private EssentialsProtect parent; + + public EssentialsProtectPlayerListener(EssentialsProtect parent) + { + Essentials.loadClasses(); + this.parent = parent; + } + + @Override + public void onPlayerInteract(PlayerInteractEvent event) + { + if (event.isCancelled()) return; + User user = User.get(event.getPlayer()); + + if (EssentialsProtect.playerSettings.get("protect.disable.build") && !user.canBuild()) + { + event.setCancelled(true); + return; + } + + if (user.isAuthorized("essentials.protect.admin")) + { + StringBuilder sb = new StringBuilder(); + boolean first = true; + for (String owner : EssentialsProtect.getStorage().getOwners(event.getClickedBlock())) { + if (!first) { + sb.append(", "); + } + first = false; + sb.append(owner); + } + String ownerNames = sb.toString(); + if (ownerNames != null) + { + user.sendMessage(ChatColor.GOLD + "[EssentialsProtect] Protection owners: " + ownerNames); + } + } + } + + @Override + public void onPlayerPickupItem(PlayerPickupItemEvent event) + { + if(event.isCancelled()) return; + ItemStack item = event.getItem().getItemStack(); + User user = User.get(event.getPlayer()); + if (EssentialsProtect.checkProtectionItems(EssentialsProtect.usageList, item.getTypeId()) && !user.isAuthorized("essentials.protect.exemptusage")) + { + event.setCancelled(true); + return; + } + + if (EssentialsProtect.onUseAlert.contains(String.valueOf(item.getTypeId()))) + { + parent.alert(user, item.getType().toString(), "used: "); + } + } +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectRegions.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectRegions.java new file mode 100644 index 000000000..6a640f3e1 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectRegions.java @@ -0,0 +1,5 @@ +package com.earth2me.essentials.protect; + +public class EssentialsProtectRegions { + +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectSqlProperties.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectSqlProperties.java new file mode 100644 index 000000000..30b2a7032 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectSqlProperties.java @@ -0,0 +1,12 @@ +package com.earth2me.essentials.protect; + +public class EssentialsProtectSqlProperties { + + public static String EssentialsProtect="CREATE TABLE IF NOT EXISTS `EssentialsProtect` (`id` int(11) NOT NULL AUTO_INCREMENT, `worldName` varchar(150) NOT NULL, `playerName` varchar(150) NOT NULL, `x` int(11) NOT NULL, `y` int(11) NOT NULL, `z` int(11) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=205 DEFAULT CHARSET=latin1"; + public static String EssentialsProtect_sqlite = "CREATE TABLE IF NOT EXISTS EssentialsProtect (id INTEGER PRIMARY KEY, worldName TEXT ,playerName TEXT, x NUMERIC, y NUMERIC, z NUMERIC)"; + public static String CountByLocation="SELECT COUNT(*) from EssentialsProtect where worldName = ? and x = ? and y = ? and z = ? limit 10"; + public static String CountByPLayerLocation="SELECT COUNT(*) from EssentialsProtect where worldName = ? and playerName =? and x = ? and y = ? and z = ? limit 10"; + public static String DeleteByLocation="DELETE FROM EssentialsProtect WHERE worldName=? and x=? and y=? and z=?"; + public static String Insert="INSERT INTO EssentialsProtect (worldName, playerName, x, y, z) VALUES (?,?,?,?,?)"; + public static String PlayerByLocation="SELECT playerName FROM EssentialsProtect WHERE worldname = ? and x = ? and y = ? and z = ? LIMIT 10"; +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/IProtectedBlock.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/IProtectedBlock.java new file mode 100644 index 000000000..28b7e425b --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/data/IProtectedBlock.java @@ -0,0 +1,15 @@ +package com.earth2me.essentials.protect.data; + +import java.util.List; +import java.util.Set; +import org.bukkit.block.Block; + +public interface IProtectedBlock { + public void clearProtections(); + public void importProtections(List blocks); + public List exportProtections(); + public void protectBlock(Block block, String playerName); + public boolean isProtected(Block block, String playerName); + public List getOwners(Block block); + public int unprotectBlock(Block block); +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/OwnedBlock.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/OwnedBlock.java new file mode 100644 index 000000000..b9b036798 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/data/OwnedBlock.java @@ -0,0 +1,9 @@ +package com.earth2me.essentials.protect.data; + +public class OwnedBlock { + int x; + int y; + int z; + String world; + String playerName; +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockJDBC.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockJDBC.java new file mode 100644 index 000000000..dec0231b9 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockJDBC.java @@ -0,0 +1,292 @@ +package com.earth2me.essentials.protect.data; + +import com.mchange.v2.c3p0.ComboPooledDataSource; +import java.beans.PropertyVetoException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.block.Block; + +public abstract class ProtectedBlockJDBC implements IProtectedBlock { + protected static final Logger logger = Logger.getLogger("Minecraft"); + protected ComboPooledDataSource cpds; + + protected abstract PreparedStatement getStatementCreateTable(Connection conn) throws SQLException; + protected abstract PreparedStatement getStatementDeleteAll(Connection conn) throws SQLException; + protected abstract PreparedStatement getStatementInsert(Connection conn, String world, int x, int y, int z, String playerName) throws SQLException; + protected abstract PreparedStatement getStatementPlayerCountByLocation(Connection conn, String world, int x, int y, int z, String playerName) throws SQLException; + protected abstract PreparedStatement getStatementPlayersByLocation(Connection conn, String name, int x, int y, int z) throws SQLException; + protected abstract PreparedStatement getStatementDeleteByLocation(Connection conn, String world, int x, int y, int z) throws SQLException; + protected abstract PreparedStatement getStatementAllBlocks(Connection conn) throws SQLException; + + public ProtectedBlockJDBC(String driver, String url) throws PropertyVetoException { + this(driver, url, null, null); + } + + public ProtectedBlockJDBC(String driver, String url, String username, String password) throws PropertyVetoException { + cpds = new ComboPooledDataSource(); + cpds.setDriverClass(driver); + cpds.setJdbcUrl(url); + if (username != null) { + cpds.setUser(username); + cpds.setPassword(password); + } + cpds.setMaxStatements(20); + createAndConvertTable(); + } + + + private void createAndConvertTable() { + Connection conn = null; + PreparedStatement ps = null; + try { + conn = cpds.getConnection(); + ps = getStatementCreateTable(conn); + ps.execute(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } finally { + if (ps != null) { + try { + ps.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + if (conn != null) { + try { + conn.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + } + } + + public void clearProtections() { + Connection conn = null; + PreparedStatement ps = null; + try { + conn = cpds.getConnection(); + ps = getStatementDeleteAll(conn); + ps.executeUpdate(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } finally { + if (ps != null) { + try { + ps.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + if (conn != null) { + try { + conn.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + } + } + + public void importProtections(List blocks) { + for (OwnedBlock ownedBlock : blocks) { + if (ownedBlock.playerName == null) { + continue; + } + protectBlock(ownedBlock.world, ownedBlock.x, ownedBlock.y, ownedBlock.z, ownedBlock.playerName); + } + } + + public List exportProtections() { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + List blocks = new ArrayList(); + try { + conn = cpds.getConnection(); + ps = getStatementAllBlocks(conn); + rs = ps.executeQuery(); + while (rs.next()) { + OwnedBlock ob = new OwnedBlock(); + ob.world = rs.getString(1); + ob.x = rs.getInt(2); + ob.y = rs.getInt(3); + ob.z = rs.getInt(4); + ob.playerName = rs.getString(5); + blocks.add(ob); + } + return blocks; + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + return blocks; + } finally { + if (rs != null) { + try { + rs.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + if (ps != null) { + try { + ps.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + if (conn != null) { + try { + conn.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + } + } + + public void protectBlock(Block block, String playerName) { + protectBlock(block.getWorld().getName(), block.getX(), block.getY(), block.getZ(), playerName); + } + + private void protectBlock(String world, int x, int y, int z, String playerName) { + Connection conn = null; + PreparedStatement ps = null; + try { + conn = cpds.getConnection(); + ps = getStatementInsert(conn, world, x, y, z, playerName); + ps.executeUpdate(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } finally { + if (ps != null) { + try { + ps.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + if (conn != null) { + try { + conn.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + } + } + + public boolean isProtected(Block block, String playerName) { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + try { + conn = cpds.getConnection(); + ps = getStatementPlayerCountByLocation(conn, block.getWorld().getName(), block.getX(), block.getY(), block.getZ(), playerName); + rs = ps.executeQuery(); + rs.next(); + return rs.getInt(1) > 0 && rs.getInt(2) == 0; + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + return true; + } finally { + if (rs != null) { + try { + rs.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + if (ps != null) { + try { + ps.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + if (conn != null) { + try { + conn.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + } + } + + public List getOwners(Block block) { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + List owners = new ArrayList(); + try { + conn = cpds.getConnection(); + ps = getStatementPlayersByLocation(conn, block.getWorld().getName(), block.getX(), block.getY(), block.getZ()); + rs = ps.executeQuery(); + while (rs.next()) { + owners.add(rs.getString(1)); + } + return owners; + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + return owners; + } finally { + if (rs != null) { + try { + rs.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + if (ps != null) { + try { + ps.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + if (conn != null) { + try { + conn.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + } + } + + public int unprotectBlock(Block block) { + Connection conn = null; + PreparedStatement ps = null; + try { + conn = cpds.getConnection(); + ps = getStatementDeleteByLocation(conn, block.getWorld().getName(), block.getX(), block.getY(), block.getZ()); + return ps.executeUpdate(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + return 0; + } finally { + if (ps != null) { + try { + ps.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + if (conn != null) { + try { + conn.close(); + } catch (SQLException ex) { + logger.log(Level.SEVERE, null, ex); + } + } + } + } + +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMemory.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMemory.java new file mode 100644 index 000000000..53dee66d2 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMemory.java @@ -0,0 +1,205 @@ +package com.earth2me.essentials.protect.data; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map.Entry; +import java.util.Set; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.plugin.Plugin; + +public class ProtectedBlockMemory implements IProtectedBlock { + + List worlds = new ArrayList(); + List playerNames = new ArrayList(); + IProtectedBlock storage; + Plugin plugin; + + class ProtectedLocation { + + int x; + int y; + int z; + int w; + + private ProtectedLocation(Block block, int worldId) { + this.x = block.getX(); + this.y = block.getY(); + this.z = block.getZ(); + this.w = worldId; + } + + private ProtectedLocation(OwnedBlock ownedBlock, int worldId) { + this.x = ownedBlock.x; + this.y = ownedBlock.y; + this.z = ownedBlock.z; + this.w = worldId; + } + + @Override + public boolean equals(Object o) { + if (o instanceof ProtectedLocation) { + ProtectedLocation pl = (ProtectedLocation) o; + return x == pl.x && y == pl.y && z == pl.z && w == pl.w; + } + return false; + } + + @Override + public int hashCode() { + return x ^ y ^ z ^ w; + } + } + + class ProtectedBy { + + private int playerId = -1; + private Set playerIds; + + private ProtectedBy() { + } + + private void add(int playerId) { + if (this.playerId == -1 || this.playerId == playerId) { + this.playerId = playerId; + } else { + if (playerIds == null) { + playerIds = new HashSet(4); + playerIds.add(this.playerId); + } + playerIds.add(playerId); + } + } + + private boolean contains(int playerId) { + if (playerIds == null) { + return this.playerId == playerId; + } + return playerIds.contains(playerId); + } + + private List getPlayers(List playerNames) { + if (playerIds == null) { + List list = new ArrayList(2); + list.add(playerNames.get(playerId)); + return list; + } + List list = new ArrayList(playerIds.size()); + for (Integer integer : playerIds) { + list.add(playerNames.get(integer)); + } + return list; + } + + private int size() { + if (playerIds == null) { + return 1; + } + return playerIds.size(); + } + } + HashMap blocks = new HashMap(); + + public ProtectedBlockMemory(IProtectedBlock storage) { + this.storage = storage; + importProtections(storage.exportProtections()); + } + + public void clearProtections() { + blocks.clear(); + } + + public final void importProtections(List blocks) { + for (OwnedBlock ownedBlock : blocks) { + ProtectedLocation pl = new ProtectedLocation(ownedBlock, getWorldId(ownedBlock.world)); + if (ownedBlock.playerName == null) { + continue; + } + protectBlock(pl, ownedBlock.playerName); + } + } + + public List exportProtections() { + List blockList = new ArrayList(blocks.size()); + for (Entry entry : blocks.entrySet()) { + for (String name : entry.getValue().getPlayers(playerNames)) { + OwnedBlock ob = new OwnedBlock(); + ob.x = entry.getKey().x; + ob.y = entry.getKey().y; + ob.z = entry.getKey().z; + ob.world = worlds.get(entry.getKey().w); + ob.playerName = name; + blockList.add(ob); + } + } + return blockList; + } + + public void protectBlock(final Block block, final String playerName) { + ProtectedLocation pl = new ProtectedLocation(block, getWorldId(block.getWorld())); + protectBlock(pl, playerName); + plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new Runnable() { + public void run() { + storage.protectBlock(block, playerName); + } + }); + } + + private void protectBlock(ProtectedLocation pl, String playerName) { + int playerId = getPlayerId(playerName); + ProtectedBy pb = blocks.get(pl); + if (pb == null) { + pb = new ProtectedBy(); + blocks.put(pl, pb); + } + pb.add(playerId); + } + + public boolean isProtected(Block block, String playerName) { + int playerId = getPlayerId(playerName); + ProtectedLocation pl = new ProtectedLocation(block, getWorldId(block.getWorld())); + ProtectedBy pb = blocks.get(pl); + return !pb.contains(playerId); + } + + public List getOwners(Block block) { + ProtectedLocation pl = new ProtectedLocation(block, getWorldId(block.getWorld())); + ProtectedBy pb = blocks.get(pl); + return pb.getPlayers(playerNames); + } + + public int unprotectBlock(final Block block) { + ProtectedLocation pl = new ProtectedLocation(block, getWorldId(block.getWorld())); + ProtectedBy pb = blocks.remove(pl); + plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new Runnable() { + public void run() { + storage.unprotectBlock(block); + } + }); + return pb.size(); + } + + private int getPlayerId(String playername) { + int id = playerNames.indexOf(playername); + if (id < 0) { + playerNames.add(playername); + id = playerNames.indexOf(playername); + } + return id; + } + + private int getWorldId(World world) { + return getWorldId(world.getName()); + } + + private int getWorldId(String name) { + int id = worlds.indexOf(name); + if (id < 0) { + worlds.add(name); + id = worlds.indexOf(name); + } + return id; + } +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMySQL.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMySQL.java new file mode 100644 index 000000000..8824f4040 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMySQL.java @@ -0,0 +1,89 @@ +package com.earth2me.essentials.protect.data; + +import java.beans.PropertyVetoException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +public class ProtectedBlockMySQL extends ProtectedBlockJDBC { + + public ProtectedBlockMySQL(String url, String username, String password) throws PropertyVetoException { + super("com.mysql.jdbc.Driver", url, username, password); + } + + private static final String QueryCreateTable = + "CREATE TABLE IF NOT EXISTS `EssentialsProtectedBlocks` (" + + "`worldName` varchar(150) NOT NULL," + + "`x` int(11) NOT NULL, `y` int(11) NOT NULL, `z` int(11) NOT NULL," + + "`playerName` varchar(150) NOT NULL," + + ") ENGINE=MyISAM DEFAULT CHARSET=utf8"; + + @Override + protected PreparedStatement getStatementCreateTable(Connection conn) throws SQLException { + return conn.prepareStatement(QueryCreateTable); + } + private static final String QueryDeleteAll = "DELETE FROM EssentialsProtectedBlocks;"; + + @Override + protected PreparedStatement getStatementDeleteAll(Connection conn) throws SQLException { + return conn.prepareStatement(QueryDeleteAll); + } + private static final String QueryInsert = + "INSERT INTO EssentialsProtectedBlocks (worldName, x, y, z, playerName) VALUES (?, ?, ?, ?, ?);"; + + @Override + protected PreparedStatement getStatementInsert(Connection conn, String world, int x, int y, int z, String playerName) throws SQLException { + PreparedStatement ps = conn.prepareStatement(QueryInsert); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + ps.setString(5, playerName); + return ps; + } + private static final String QueryCountByPlayer = + "SELECT COUNT(playerName), SUM(playerName = ?) FROM EssentialsProtectedBlocks " + + "WHERE worldName = ? AND x = ? AND y = ? AND z = ? GROUP BY x;"; + + @Override + protected PreparedStatement getStatementPlayerCountByLocation(Connection conn, String world, int x, int y, int z, String playerName) throws SQLException { + PreparedStatement ps = conn.prepareStatement(QueryCountByPlayer); + ps.setString(1, playerName); + ps.setString(2, world); + ps.setInt(3, x); + ps.setInt(4, y); + ps.setInt(5, z); + return ps; + } + private static final String QueryPlayersByLocation = + "SELECT playerName FROM EssentialsProtectedBlocks WHERE worldname = ? AND x = ? AND y = ? AND z = ?;"; + + @Override + protected PreparedStatement getStatementPlayersByLocation(Connection conn, String world, int x, int y, int z) throws SQLException { + PreparedStatement ps = conn.prepareStatement(QueryPlayersByLocation); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + return ps; + } + private static final String QueryDeleteByLocation = + "DELETE FROM EssentialsProtectedBlocks WHERE worldName = ? AND x = ? AND y = ? AND z = ?;"; + + @Override + protected PreparedStatement getStatementDeleteByLocation(Connection conn, String world, int x, int y, int z) throws SQLException { + PreparedStatement ps = conn.prepareStatement(QueryDeleteByLocation); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + return ps; + } + private static final String QueryAllBlocks = + "SELECT worldName, x, y, z, playerName FROM EssentialsProtectedBlocks;"; + + @Override + protected PreparedStatement getStatementAllBlocks(Connection conn) throws SQLException { + return conn.prepareStatement(QueryAllBlocks); + } +} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockSQLite.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockSQLite.java new file mode 100644 index 000000000..ff96a8952 --- /dev/null +++ b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockSQLite.java @@ -0,0 +1,87 @@ +package com.earth2me.essentials.protect.data; + +import java.beans.PropertyVetoException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +public class ProtectedBlockSQLite extends ProtectedBlockJDBC { + + public ProtectedBlockSQLite(String url) throws PropertyVetoException { + super("org.sqlite.JDBC", url); + } + + private static final String QueryCreateTable = + "CREATE TABLE IF NOT EXISTS EssentialsProtect (" + + "worldName TEXT ,playerName TEXT, " + + "x NUMERIC, y NUMERIC, z NUMERIC)"; + + @Override + protected PreparedStatement getStatementCreateTable(Connection conn) throws SQLException { + return conn.prepareStatement(QueryCreateTable); + } + private static final String QueryDeleteAll = "DELETE FROM EssentialsProtectedBlocks;"; + + @Override + protected PreparedStatement getStatementDeleteAll(Connection conn) throws SQLException { + return conn.prepareStatement(QueryDeleteAll); + } + private static final String QueryInsert = + "INSERT INTO EssentialsProtectedBlocks (worldName, x, y, z, playerName) VALUES (?, ?, ?, ?, ?);"; + + @Override + protected PreparedStatement getStatementInsert(Connection conn, String world, int x, int y, int z, String playerName) throws SQLException { + PreparedStatement ps = conn.prepareStatement(QueryInsert); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + ps.setString(5, playerName); + return ps; + } + private static final String QueryPlayerCountByLocation = + "SELECT COUNT(playerName), SUM(playerName = ?) FROM EssentialsProtectedBlocks " + + "WHERE worldName = ? AND x = ? AND y = ? AND z = ? GROUP BY x;"; + + @Override + protected PreparedStatement getStatementPlayerCountByLocation(Connection conn, String world, int x, int y, int z, String playerName) throws SQLException { + PreparedStatement ps = conn.prepareStatement(QueryPlayerCountByLocation); + ps.setString(1, playerName); + ps.setString(2, world); + ps.setInt(3, x); + ps.setInt(4, y); + ps.setInt(5, z); + return ps; + } + private static final String QueryPlayersByLocation = + "SELECT playerName FROM EssentialsProtectedBlocks WHERE worldname = ? AND x = ? AND y = ? AND z = ?;"; + + @Override + protected PreparedStatement getStatementPlayersByLocation(Connection conn, String world, int x, int y, int z) throws SQLException { + PreparedStatement ps = conn.prepareStatement(QueryPlayersByLocation); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + return ps; + } + private static final String QueryDeleteByLocation = + "DELETE FROM EssentialsProtectedBlocks WHERE worldName = ? AND x = ? AND y = ? AND z = ?;"; + + @Override + protected PreparedStatement getStatementDeleteByLocation(Connection conn, String world, int x, int y, int z) throws SQLException { + PreparedStatement ps = conn.prepareStatement(QueryDeleteByLocation); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + return ps; + } + private static final String QueryAllBlocks = + "SELECT worldName, x, y, z, playerName FROM EssentialsProtectedBlocks;"; + + @Override + protected PreparedStatement getStatementAllBlocks(Connection conn) throws SQLException { + return conn.prepareStatement(QueryAllBlocks); + } +} diff --git a/EssentialsProtect/src/plugin.yml b/EssentialsProtect/src/plugin.yml new file mode 100644 index 000000000..c6f7830c1 --- /dev/null +++ b/EssentialsProtect/src/plugin.yml @@ -0,0 +1,8 @@ +# This determines the command prefix when there are conflicts (/name:home, /name:help, etc.) +name: EssentialsProtect +main: com.earth2me.essentials.protect.EssentialsProtect +# Note to developers: This next line cannot change, or the automatic versioning system will break. +version: TeamCity +website: http://www.earth2me.net:8001/ +description: Provides protection for various parts of the world. +authors: [Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo] \ No newline at end of file diff --git a/EssentialsSpawn/build.xml b/EssentialsSpawn/build.xml new file mode 100644 index 000000000..7dfcbb707 --- /dev/null +++ b/EssentialsSpawn/build.xml @@ -0,0 +1,76 @@ + + ]> + + + + + + + + + + Builds, tests, and runs the project EssentialsSpawn. + + &buildinc; + + diff --git a/EssentialsSpawn/nbproject/build-impl.xml b/EssentialsSpawn/nbproject/build-impl.xml new file mode 100644 index 000000000..d343051e5 --- /dev/null +++ b/EssentialsSpawn/nbproject/build-impl.xml @@ -0,0 +1,1072 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + + + + + + java -cp "${run.classpath.with.dist.jar}" ${main.class} + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + Must select one file in the IDE or set profile.class + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/EssentialsSpawn/nbproject/genfiles.properties b/EssentialsSpawn/nbproject/genfiles.properties new file mode 100644 index 000000000..790af6977 --- /dev/null +++ b/EssentialsSpawn/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=45238b6c +build.xml.script.CRC32=46e3642f +build.xml.stylesheet.CRC32=28e38971@1.38.2.45 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=e7b96939 +nbproject/build-impl.xml.script.CRC32=c9db80de +nbproject/build-impl.xml.stylesheet.CRC32=19debb58@1.42.1.45 diff --git a/EssentialsSpawn/nbproject/private/private.properties b/EssentialsSpawn/nbproject/private/private.properties new file mode 100644 index 000000000..94183418a --- /dev/null +++ b/EssentialsSpawn/nbproject/private/private.properties @@ -0,0 +1 @@ +user.properties.file=C:\\Users\\Paul\\.netbeans\\7.0beta2\\build.properties diff --git a/EssentialsSpawn/nbproject/project.properties b/EssentialsSpawn/nbproject/project.properties new file mode 100644 index 000000000..1c4af9a9a --- /dev/null +++ b/EssentialsSpawn/nbproject/project.properties @@ -0,0 +1,76 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +application.title=EssentialsSpawn +application.vendor=Paul +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/EssentialsSpawn.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes= +file.reference.craftbukkit-0.0.1-SNAPSHOT.jar=..\\lib\\craftbukkit-0.0.1-SNAPSHOT.jar +includes=** +jar.compress=false +javac.classpath=\ + ${reference.Essentials.jar}:\ + ${file.reference.craftbukkit-0.0.1-SNAPSHOT.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.processorpath=\ + ${javac.classpath} +javac.source=1.5 +javac.target=1.5 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${libs.junit.classpath}:\ + ${libs.junit_4.classpath} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +meta.inf.dir=${src.dir}/META-INF +platform.active=default_platform +project.Essentials=../Essentials +reference.Essentials.jar=${project.Essentials}/dist/Essentials.jar +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value +# or test-sys-prop.name=value to set system properties for unit tests): +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/EssentialsSpawn/nbproject/project.xml b/EssentialsSpawn/nbproject/project.xml new file mode 100644 index 000000000..8de247766 --- /dev/null +++ b/EssentialsSpawn/nbproject/project.xml @@ -0,0 +1,28 @@ + + + org.netbeans.modules.java.j2seproject + + + EssentialsSpawn + + + + + + + + + ../lib\nblibraries.properties + + + + Essentials + jar + + jar + clean + jar + + + + diff --git a/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandsetspawn.java b/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandsetspawn.java new file mode 100644 index 000000000..e64985737 --- /dev/null +++ b/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandsetspawn.java @@ -0,0 +1,24 @@ +package com.earth2me.essentials.spawn; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.earth2me.essentials.commands.EssentialsCommand; + + +public class Commandsetspawn extends EssentialsCommand +{ + public Commandsetspawn() + { + super("setspawn"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.charge(this); + String group = args.length > 0 ? getFinalArg(args, 0) : "default"; + parent.spawn.setSpawn(user.getLocation(), group); + user.sendMessage("§7Spawn location set for group \"" + group + "\"."); + } +} diff --git a/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandspawn.java b/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandspawn.java new file mode 100644 index 000000000..c26cc9e37 --- /dev/null +++ b/EssentialsSpawn/src/com/earth2me/essentials/spawn/Commandspawn.java @@ -0,0 +1,23 @@ +package com.earth2me.essentials.spawn; + +import org.bukkit.Server; +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import com.earth2me.essentials.commands.EssentialsCommand; + + +public class Commandspawn extends EssentialsCommand +{ + public Commandspawn() + { + super("spawn"); + } + + @Override + public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception + { + user.canAfford(this); + user.teleportCooldown(); + user.respawn(Essentials.getStatic().spawn, this.getName()); + } +} diff --git a/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawn.java b/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawn.java new file mode 100644 index 000000000..54e6bd198 --- /dev/null +++ b/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawn.java @@ -0,0 +1,65 @@ +package com.earth2me.essentials.spawn; + +import java.io.*; +import java.util.logging.*; +import com.earth2me.essentials.*; +import org.bukkit.command.*; +import org.bukkit.event.Event.Priority; +import org.bukkit.event.Event.Type; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.*; + + +public class EssentialsSpawn extends JavaPlugin +{ + public static final String AUTHORS = Essentials.AUTHORS; + private static final Logger logger = Logger.getLogger("Minecraft"); + + public EssentialsSpawn() throws IOException + { + + } + + @SuppressWarnings("LoggerStringConcat") + public void onEnable() + { + Plugin p = this.getServer().getPluginManager().getPlugin("Essentials"); + if (p != null) { + if (!this.getServer().getPluginManager().isPluginEnabled(p)) { + this.getServer().getPluginManager().enablePlugin(p); + } + } + EssentialsSpawnPlayerListener playerListener = new EssentialsSpawnPlayerListener(); + getServer().getPluginManager().registerEvent(Type.PLAYER_RESPAWN, playerListener, Priority.Low, this); + getServer().getPluginManager().registerEvent(Type.PLAYER_JOIN, playerListener, Priority.Low, this); + + if (!this.getDescription().getVersion().equals(Essentials.getStatic().getDescription().getVersion())) { + logger.log(Level.WARNING, "Version mismatch! Please update all Essentials jars to the same version."); + } + logger.info("Loaded " + this.getDescription().getName() + " build " + this.getDescription().getVersion() + " maintained by " + AUTHORS); + } + + public void onDisable() + { + } + + @SuppressWarnings( + { + "LoggerStringConcat", "CallToThreadDumpStack" + }) + @Override + public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) + { + try + { + Essentials.loadClasses(); + Essentials.previewCommand(sender, command, commandLabel, args); + return EssentialsSpawnWorker.onCommand(sender, command, commandLabel, args); + } + catch (Throwable ex) + { + ex.printStackTrace(); + return true; + } + } +} diff --git a/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawnPlayerListener.java b/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawnPlayerListener.java new file mode 100644 index 000000000..697939daa --- /dev/null +++ b/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawnPlayerListener.java @@ -0,0 +1,51 @@ +package com.earth2me.essentials.spawn; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.User; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerListener; +import org.bukkit.event.player.PlayerRespawnEvent; + + +public class EssentialsSpawnPlayerListener extends PlayerListener +{ + @Override + public void onPlayerRespawn(PlayerRespawnEvent event) + { + Essentials.loadClasses(); + User user = User.get(event.getPlayer()); + + try + { + if (Essentials.getSettings().getRespawnAtHome()) + { + event.setRespawnLocation(user.getHome()); + return; + } + } + catch (Throwable ex) + { + } + event.setRespawnLocation(Essentials.getStatic().spawn.getSpawn(user.getGroup())); + } + + @Override + public void onPlayerJoin(PlayerJoinEvent event) + { + Essentials.loadClasses(); + User user = User.get(event.getPlayer()); + + if (!user.isNew()) return; + user.clearNewFlag(); + try { + user.teleportToNow(Essentials.getStatic().spawn.getSpawn(Essentials.getSettings().getNewbieSpawn())); + } catch (Exception ex) { + Logger.getLogger("Minecraft").log(Level.WARNING, "Failed to teleport new player", ex); + } + + if (Essentials.getSettings().getAnnounceNewPlayers()) + Essentials.getStatic().getServer().broadcastMessage(Essentials.getSettings().getAnnounceNewPlayerFormat(user)); + } +} diff --git a/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawnWorker.java b/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawnWorker.java new file mode 100644 index 000000000..d6e34db55 --- /dev/null +++ b/EssentialsSpawn/src/com/earth2me/essentials/spawn/EssentialsSpawnWorker.java @@ -0,0 +1,56 @@ +package com.earth2me.essentials.spawn; + +import java.util.logging.*; +import com.earth2me.essentials.*; +import com.earth2me.essentials.commands.IEssentialsCommand; +import org.bukkit.command.*; + + +public class EssentialsSpawnWorker +{ + private static final Logger logger = Logger.getLogger("Minecraft"); + + @SuppressWarnings( + { + "LoggerStringConcat", "CallToThreadDumpStack" + }) + public static boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) + { + User user = User.get(sender); + + IEssentialsCommand cmd; + try + { + cmd = (IEssentialsCommand)EssentialsSpawn.class.getClassLoader().loadClass("com.earth2me.essentials.spawn.Command" + command.getName()).newInstance(); + } + catch (Exception ex) + { + sender.sendMessage("§cThat command is improperly loaded."); + ex.printStackTrace(); + return true; + } + + // Check authorization + if (user != null && !user.isAuthorized(cmd)) + { + logger.warning(user.getName() + " was denied access to command."); + user.sendMessage("§cYou do not have access to that command."); + return true; + } + + // Run the command + try + { + if (user == null) + cmd.run(Essentials.getStatic().getServer(), Essentials.getStatic(), sender, commandLabel, command, args); + else + cmd.run(Essentials.getStatic().getServer(), Essentials.getStatic(), user, commandLabel, command, args); + return true; + } + catch (Exception ex) + { + sender.sendMessage((user == null ? "" : "§c") + "Error: " + ex.getMessage()); + return true; + } + } +} diff --git a/EssentialsSpawn/src/plugin.yml b/EssentialsSpawn/src/plugin.yml new file mode 100644 index 000000000..de4e39b15 --- /dev/null +++ b/EssentialsSpawn/src/plugin.yml @@ -0,0 +1,15 @@ +# This determines the command prefix when there are conflicts (/name:home, /name:help, etc.) +name: EssentialsSpawn +main: com.earth2me.essentials.spawn.EssentialsSpawn +# Note to developers: This next line cannot change, or the automatic versioning system will break. +version: TeamCity +website: http://www.earth2me.net:8001/ +description: Provides spawn control commands, utilizing Essentials. +authors: [Zenexer, ementalo, Aelux, Brettflan, KimKandor, snowleo] +commands: + setspawn: + description: Set the spawnpoint to your current position. + usage: / + spawn: + description: Teleport to the spawnpoint. + usage: / \ No newline at end of file diff --git a/build.inc.xml b/build.inc.xml new file mode 100644 index 000000000..2d6c69944 --- /dev/null +++ b/build.inc.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/lib/CopyLibs/org-netbeans-modules-java-j2seproject-copylibstask.jar b/lib/CopyLibs/org-netbeans-modules-java-j2seproject-copylibstask.jar new file mode 100644 index 000000000..5ee71d2e3 Binary files /dev/null and b/lib/CopyLibs/org-netbeans-modules-java-j2seproject-copylibstask.jar differ diff --git a/lib/Permissions.jar b/lib/Permissions.jar new file mode 100644 index 000000000..e2aa6520b Binary files /dev/null and b/lib/Permissions.jar differ diff --git a/lib/c3p0-0.9.1.2.jar b/lib/c3p0-0.9.1.2.jar new file mode 100644 index 000000000..0f42d60e3 Binary files /dev/null and b/lib/c3p0-0.9.1.2.jar differ diff --git a/lib/craftbukkit-0.0.1-SNAPSHOT.jar b/lib/craftbukkit-0.0.1-SNAPSHOT.jar new file mode 100644 index 000000000..747976e87 Binary files /dev/null and b/lib/craftbukkit-0.0.1-SNAPSHOT.jar differ diff --git a/lib/gson.jar b/lib/gson.jar new file mode 100644 index 000000000..4f7970541 Binary files /dev/null and b/lib/gson.jar differ diff --git a/lib/iConomy.jar b/lib/iConomy.jar new file mode 100644 index 000000000..12c6785c7 Binary files /dev/null and b/lib/iConomy.jar differ diff --git a/lib/junit/junit-3.8.2-api.zip b/lib/junit/junit-3.8.2-api.zip new file mode 100644 index 000000000..6d792fdaa Binary files /dev/null and b/lib/junit/junit-3.8.2-api.zip differ diff --git a/lib/junit/junit-3.8.2.jar b/lib/junit/junit-3.8.2.jar new file mode 100644 index 000000000..d83587261 Binary files /dev/null and b/lib/junit/junit-3.8.2.jar differ diff --git a/lib/junit_4/junit-4.5-api.zip b/lib/junit_4/junit-4.5-api.zip new file mode 100644 index 000000000..5748c444d Binary files /dev/null and b/lib/junit_4/junit-4.5-api.zip differ diff --git a/lib/junit_4/junit-4.5-src.jar b/lib/junit_4/junit-4.5-src.jar new file mode 100644 index 000000000..18774a573 Binary files /dev/null and b/lib/junit_4/junit-4.5-src.jar differ diff --git a/lib/junit_4/junit-4.5.jar b/lib/junit_4/junit-4.5.jar new file mode 100644 index 000000000..83f8bc793 Binary files /dev/null and b/lib/junit_4/junit-4.5.jar differ diff --git a/lib/mysql.jar b/lib/mysql.jar new file mode 100644 index 000000000..0539039f7 Binary files /dev/null and b/lib/mysql.jar differ diff --git a/lib/nblibraries.properties b/lib/nblibraries.properties new file mode 100644 index 000000000..c3c14c09e --- /dev/null +++ b/lib/nblibraries.properties @@ -0,0 +1,12 @@ +libs.CopyLibs.classpath=\ + ${base}/CopyLibs/org-netbeans-modules-java-j2seproject-copylibstask.jar +libs.junit.classpath=\ + ${base}/junit/junit-3.8.2.jar +libs.junit.javadoc=\ + ${base}/junit/junit-3.8.2-api.zip +libs.junit_4.classpath=\ + ${base}/junit_4/junit-4.5.jar +libs.junit_4.javadoc=\ + ${base}/junit_4/junit-4.5-api.zip +libs.junit_4.src=\ + ${base}/junit_4/junit-4.5-src.jar diff --git a/lib/sqlite.jar b/lib/sqlite.jar new file mode 100644 index 000000000..0b47e2cf9 Binary files /dev/null and b/lib/sqlite.jar differ -- cgit v1.2.3