Compare commits

..

77 Commits

Author SHA1 Message Date
e8e0e9988a Updated to Spigot-1.10-R1 2016-06-24 15:29:48 +02:00
aca3398d21 TotalFreedomMod Electrum
Version 5.0

This TotalFreedomMod release implements many changes. Most notably, the
internals have been completely revamped. TotalFreedomMod now relies on the
Aero library for core mechanics such as command handling and services.

Another important change is the UUID system. In TotalFreedomMod Electrum,
it has been completely removed. The core reason for this is that the
system as a whole was very bugged. Additionally, it did not solve the
primary reason for its conception: preserving player data when the player
changes their username. This is because TotalFreedomMod servers usually
run in offline-mode. This meaning that some of the players joining do not
have a registerd Mojang UUID whatsoever. All in all, the UUID system was
buggy, and it did not fix the reason it was implemented, so it has been
completely removed. The admin list and the ban list now use usernames and
IPs again.

Lastly, many smaller changes have been implemented. Due to the amount of
changes, they have not been named individualy. Please refer to the issues
below for more details.

Fixes #342
Fixes #350
Fixes #380
Fixes #684
Fixes #704
Fixes #716
Fixes #735
Fixes #745
Fixes #784
Fixes #765
Fixes #791
Fixes #805
Fixes #826
Fixes #883
Fixes #1524
Fixes #1534
Fixes #1536
Fixes #1538
Fixes #1545
Fixes #1546
Fixes #1568
Fixes #1627
Resolves #403
Resolves #435
Resolves #597
Resolves #603
Resolves #628
Resolves #690
Resolves #708
Resolves #747
Resolves #748
Resolves #749
Resolves #764
Resolves #767
Resolves #782
Resolves #809
Resolves #803
Resolves #811
Resolves #813
Resolves #830
Resolves #848
Resolves #856
Resolves #876
Resolves #908
Resolves #992
Resolves #1018
Resolves #1432
Resolves #1446
Resolves #1494
Resolves #1501
Resolves #1526
Resolves #1540
Resolves #1550
Resolves #1560
Resolves #1561
Resolves #1578
Resolves #1613
2016-05-12 21:51:58 +02:00
924f718d5a Fixed bugs in TFM 5.0
Added /saconfig setrank
Added /saconfig reload
Small changes
2016-03-07 21:32:05 +01:00
6edb6be7d9 Many changes for TFM 5.0
Improved admin system
Improved Rank system
Implemented config converter
Improved command handling
Updated Aero
2016-03-06 16:58:59 +01:00
055973aa37 Many changes for TFM 5.0
Refractoring
Reworked /saconfig
Reworked part of the command system
Removed unused config sections
Refractored part of the config
Fixed bugs with admin list
Actually allow CONSOLE to have senior perms
2016-03-02 20:28:01 +01:00
19ced05110 Update to Spigot 1.9-R1 2016-03-01 19:14:14 +01:00
e93ac11172 Use custom service abstraction in favour of Aero's AbstractService
Use Aero's YamlConfig in favour of FConfig
Refractoring
Small edits
2016-03-01 17:47:01 +01:00
7328d20c84 Rename some commands to more fitting alternatives
Preserve old command names as aliases
2016-02-29 22:27:11 +01:00
4586b7519f [Bleeding] Revamped rank system yet again
Refractoring
Bug fixes
Mass format
2016-02-29 21:48:17 +01:00
a0058869c9 Added checkstyle plugin
Moved resources to correct folder
Fixed and improved build information, no longer tracking build.properties
2015-11-22 19:28:32 +01:00
89a317b7df Mavenized project 2015-11-18 21:41:51 +01:00
0c3bc40b03 Completely switched over to service-based events 2015-11-16 00:32:04 +01:00
848f103afa [Bleeding] TotalFreedomMod 5.0
Mass Refractoring, now uses me.totalfreedom.totalfreedommod as package
Uses Aero https://github.com/Pravian/Aero
Revamped command system
Remove all TFM_ prefixes
Revamp rank system
Use new service based system
Cleanup
2015-10-19 19:43:46 +02:00
a7a2db15d6 Track build information in a better way
build.properties replaces buildcreator.properties, buildcreator.default.properties annd buildnumber.properties, but is untracked.
'git describe --tags --always HEAD' is now used to identify the build version, and its result is stored in the build properties file, included with the build. appinfo.properties is removed in favour of build.properties in the compiled jar.
The build number is still tracked, but offline, allowing TFM commits to more easily be merged
2015-09-06 23:05:36 +02:00
6aeb56de07 Block commands right when the TFM is enabled. Fixes #735 2015-09-06 17:05:03 +02:00
400038265b Prevent command arguments from using long number strings. Resolves #782
Mass format
2015-09-06 17:02:06 +02:00
3b87323c41 Remove /permban list. Resolves #805 2015-09-06 16:46:20 +02:00
cdf2dc6760 Limit host console commands even more. Resolves #811 2015-09-06 16:42:02 +02:00
bf1d779b95 Merge with upstream 2015-06-11 22:29:39 +02:00
27004da544 Compile for Spigot-1.8.7-R0.1. Resolves #644 2015-06-11 22:28:55 +02:00
c0c4c25875 Merge branch 'tfm44' into pr/584 2015-06-07 17:39:01 +02:00
adbaf9341d Grammar fix in Command_invis.java 2015-06-07 17:38:30 +02:00
b5c5e60c12 Merge branch 'pr/687' into tfm44 2015-06-07 17:36:25 +02:00
1ed1b352f3 Properly allow Forge clients to log in. Fixes #493 2015-06-07 17:35:56 +02:00
53c898fd76 Merge branch pr/580 2015-06-07 17:30:12 +02:00
acc8f3e2b8 Changed /kicknoob message to be more user-friendly 2015-06-07 17:28:58 +02:00
157eeef867 Merge branch 'tfm43' into tfm44 2015-06-07 17:22:21 +02:00
21c0833f14 Rename dependency names to match wiki 2015-06-07 17:21:05 +02:00
c002fbc537 Handle player online check in AsyncPlayerPreLoginEvent
Apparently, online players with the same username are kicked before PlayerLoginEvent is called. This commit moves the online player check to AsyncPlayerPreloginEvent so the default behaviour can still be modified

Fixes #642
2015-05-30 20:51:49 +02:00
a4d8f4646e Properly block /jail and /unjail
They're both aliases, /togglejail is the actual command
2015-05-30 20:13:11 +02:00
f2dc46d4ef Work around /saconfig clearme bug. Fixes #629 2015-05-30 20:01:10 +02:00
901a327b1e Block/unblock pending commands for non-superadmins
Blocked /jail, /unjail and /blockdata for non-superadmins
Moved /clearhistory, /save-all, /save-on and /save-off to non-autoeject section

Resolves #671, Resolves #670, Resolves #656
2015-05-30 19:58:15 +02:00
580ba0a357 Prevent players moving to illegal positions. Fixes #651 2015-05-30 19:45:22 +02:00
abf52870dd Block /green for non-superadmins. Resolves #594
Moved /restart to the correct section
2015-05-14 15:27:15 +02:00
d48bfde128 Merge branch 'pr/625' into tfm44 2015-05-14 15:19:15 +02:00
7ac7b75ae6 Allow admins to use lava/water buckets 2015-05-14 14:38:15 +02:00
b66614cad9 Block /execute for non-superadmins. Resolves #630 2015-05-14 14:30:51 +02:00
ff70f13e05 Fixed bug where /uuid recalculate would set ranks incorrectly 2015-05-13 14:56:38 +02:00
ea110c01dd Add /overlord 2015-05-13 14:52:01 +02:00
632f3647a8 Blocked /tpall for non-superadmins 2015-05-12 20:43:35 +02:00
80287433eb Properly fixed commandblocker
Rest in peace, terrible, terrible mistake
2015-05-12 20:34:04 +02:00
b18aeb2d38 Work around setFlying() throwing exceptions 2015-05-12 20:17:38 +02:00
68f972c562 Allow players to fly. Fixes #608 2015-05-12 17:18:12 +02:00
994056047a Block /weather for non-superadmins. Resolves #617 2015-05-12 17:13:28 +02:00
f115315341 Block /worldborder for non-superadmins. Resolves #615 2015-05-12 17:08:44 +02:00
57e5395143 Block /title for non-superadmins. Resolves #621 2015-05-12 17:07:41 +02:00
17f3a4ca3d Remove blocked commands from the CommandMap. Resolves #622
Temporarily workaround: Remove blocked command from the CommandMap
In Spigot 1.8.3, cancelling PlayerCommandPreprocessEvent will have no effect
This results in TFM failing to block player commands: The player will get a message,
but the command will still execute. Removing the command from the CommandMap is a
temporary workaround untill the related Spigot issue has been fixed.

https://hub.spigotmc.org/jira/browse/SPIGOT-879
2015-05-12 16:54:51 +02:00
e2d0e9e754 Fixed error when blocking player commands 2015-05-12 16:45:10 +02:00
b167540ad7 Properly cancel blocked commands 2015-05-11 23:05:21 +02:00
0d1ce072dc Reorder prefix assignments, fixes admin prefixes 2015-05-11 22:37:38 +02:00
887a5c6b16 Fixed all admins showing up as Superadmins 2015-05-11 22:21:59 +02:00
ea6bfa8387 Fix commandblocker not blocking properly. Resolves #586 2015-05-10 23:28:13 +02:00
42266c37ea Fixed false positive plugin specific command block. Resolves #575 2015-05-10 23:19:23 +02:00
2dd8e00201 Lowercase commands before mute-block checking. Resolves #312 2015-04-27 00:58:27 +02:00
46cd88a18a Add protected spawnpoints after all worlds have been loaded. Resolves #438 2015-04-27 00:53:07 +02:00
2ff0f6f5d6 Fix Forge clients being unable to log in. Resolves #493 2015-04-27 00:48:33 +02:00
9ff6325469 Add owner to standard prefixes. Resolves #504 2015-04-27 00:45:47 +02:00
ea404985fd Ban IPs in /tban. Resolves #499 2015-04-27 00:39:36 +02:00
8fc25111e2 Synchronize calls in AsyncPlayerChatEvent listener. Resolves #524 2015-04-27 00:31:54 +02:00
4fce1109a1 Merge branch 'master' into pr/553 2015-04-27 00:08:13 +02:00
916fd75003 Added Mumble announcement 2015-04-27 00:07:50 +02:00
aa35aae58f Merge branch 'master' into pr/574 2015-04-26 23:51:18 +02:00
6849fb2784 Display proper URL when banning with /glist ban
When you glist ban an online player, it says totalfreedom.boards.net regardless of the config entry. I modified it so it is the config.yml's ban appeal URL.
2015-04-26 23:50:40 +02:00
313577d083 Merge from master 2015-04-26 23:30:54 +02:00
53efcfd06b Don't autoeject players using /reload. Resolves #525 2015-04-26 23:28:29 +02:00
edaaeef65f Merge branch 'master' into pr/571 2015-04-26 23:25:32 +02:00
d6eb5bdcda Fix getIpBanList() returning UUID bans. Fixes #570 2015-04-26 23:23:46 +02:00
7d675923db Replaced last instances of DarthSalamon with Prozza 2015-04-26 22:40:38 +02:00
87fd8a165c Added MCConnect IP to nosuper IPs 2015-04-26 22:29:31 +02:00
1205252450 Correct compile NMS version 2015-04-26 22:21:26 +02:00
1ed45b1a20 Compile with Java 7 2015-04-26 22:17:25 +02:00
822f55d9f2 Merge with master 2015-04-26 20:44:28 +02:00
aacf37aa56 Update to Spigot 1.8.3-R2 2015-04-26 20:43:37 +02:00
a15e39d7dd Added more announcements. Resolves #516 2015-03-29 12:10:55 +02:00
72fa8532d3 Blocked pending commands in CommandBlocker. Resolves #492 2015-03-15 13:19:20 +01:00
f4aa0c324c Updated to new WorldEdit API
TF-WorldEdit doesn't depend on TFM anymore. It's event-based now.
Moved TFM_TelnetListener to the Bridge subpackage
2015-03-07 17:32:27 +01:00
73ee1f3624 Implement SuperAdmin service 2015-02-18 19:24:04 +01:00
318 changed files with 15615 additions and 17060 deletions

34
.gitignore vendored
View File

@ -1,14 +1,29 @@
# Netbeans excludes - StevenLawson & JeromSar # TFM excludes
/nbproject/private/ /lib
/dist/ build.properties
/build/
manifest.mf
# Eclipse excludes - JeromSar (old) # Netbeans excludes
/nbproject/private
/dist
/build
manifest.mf
# Now defines that Maven CheckStyle is used
# nb-configuration.xml
# Eclipse excludes
.project .project
.classpath .classpath
/bin/ /bin
/.settings/ /.settings
# IntelliJ excludes
*.iml
*.ipr
*.iws
/.idea
# Maven excludes
/target
# OS generated files # OS generated files
.DS_Store .DS_Store
@ -17,6 +32,3 @@ manifest.mf
.Trashes .Trashes
ehthumbs.db ehthumbs.db
Thumbs.db Thumbs.db
# TFM files
buildcreator.properties

View File

@ -1,97 +1,3 @@
# Contributing to TotalFreedomMod # # Contributing to TotalFreedomMod #
TotalFreedomMod is a CraftBukkit server plugin designed primarily to support the [Official TotalFreedom Minecraft Server](http://totalfreedom.me/). However, it can be used in a variety of other configurations with minimal fuss.
For those who wish to contribute, we encourage you to fork the repository and submit pull requests. Below you will find guidelines that explain this process in further detail. For information about contributing to TotalFreedomMod, please see the [contributing guidelines](https://github.com/TotalFreedom/TotalFreedomMod/wiki/Contributing).
## Quick Guide ##
1. Create or find an issue on our [Issue Tracker](https://github.com/TotalFreedom/TotalFreedomMod/issues).
2. Does your change fits TotalFreedomMod's goals?
3. Fork TotalFreedomMod if you haven't done so already.
4. Make a branch dedicated to your change.
5. Make your change.
6. Commit your change according to the [committing guidelines](#committing-your-changes).
7. Push your branch and submit a pull request.
## Getting Started ##
* Search the issue tracker for your bug report or feature request.
* If the issue does not exist already, create it.
* Clearly describe the issue.
* If your issue is a bug, describe the steps needed to reproduce it.
* If your issue is a feature request, ensure it fits TotalFreedomMod's goals and describe your feature in detail.
* Fork the repository on GitHub.
## Does the change fit TotalFreedomMod's goals? ##
As a rough guideline, ask yourself the following questions to determine if your proposed change fits the TotalFreedomMod project's goals. Please remember that this is only a rough guideline and may or may not reflect the definitive answer to this question.
* Is the change in line with the principles of "Total Freedom"?
TotalFreedom is a freedom-based server. We don't normally make changes that restrict players unless absolutely necessary.
* Is the change directed towards the TotalFreedom server?
Changes must be directed towards the TotalFreedom server. Changes such as adding ranks, adding the name of other TotalFreedom-like servers will not likely be accepted.
* Does the change add a feature that involves micromanagement?
Pull requests that involve adding a micromanagement feature will likely not be accepted. This includes shorthands for multiple commands.
* Is a similar feature already present?
Features that have very similar alternatives will not be added. For example: A command that temporarily bans a player from the server is very similar to the _/tban_ command and thus will likely not be accepted.
## Making Changes ##
* Create a topic branch from where you want to base your work.
* This is usually the master branch.
* Name your branch something relevant to the change you are going to make.
* To quickly create a topic branch based on master, use `git checkout master` followed by `git checkout -b <name>`. Avoid working directly on the `master` branch.
* Make sure your change meets our [code requirements](#code-requirements).
### Code requirements ###
* Code must be written in [Allman style](http://en.wikipedia.org/wiki/Indent_style#Allman_style), and that it follows [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconventions-150003.pdf).__
* No tabs; use 4 spaces for indentation.
* No trailing whitespaces for code lines, comments or configuration files.
* No CRLF line endings, only LF is allowed.
* For Windows-based machines, you can configure Git to do this for your by running `git config --global core.autocrlf true`.
* If you're running a Linux or Mac OSX, you should run `git config --global core.autocrlf input` instead.
* For more information about line feeds. See this [this article](http://adaptivepatchwork.com/2012/03/01/mind-the-end-of-your-line/).
* No 80 character line limit or 'weird' midstatement newlines.
* Additions should be compiled, complete and tested before committing.
* Avoid using `org.bukkit.Server.dispatchCommand()`. Commits that make use of it will likely be rejected.
* Files must always end with a newline.
* Avoid nested code structures.
## Committing your changes ##
* Check for unnecessary whitespace with `git diff --check` before committing.
* Describe your changes in the commit description.
* For a prolonged description, continue on a new line.
* The first description line should be once sentence and should not exceed 10 words.
* The first description line should contain either:
* For a bug-related issue: "Resolves _#issue_".
* For a feature request: "Fixes _#issue_".
* "#issue" is the issue number number you based your work on.
#### Example commit message ####
```
Fixed bugs with /saconfig clear. Resolves #167
Admins can now use /saconfig clear [ip] to remove the designated IP (only their own IPs can be removed.
They can also simply use /saconfig clear to remove all IPs but the current one. /saconfig clear is safe,
meaning you can't remove your current IP or an IP that doesn't belong to you.
```
## Submitting Your Changes ##
* Push your changes to the topic branch in your fork of the repository.
* Submit a pull request to this repository.
* Explain in detail what each one of your commits changes and point out any big changes.
* Wait as a developer evaluates your changes.
* Do not add any prefixes or tags.
## Tips - How To Get Your Pull Request Accepted ##
* Please make sure your changes are written such as other features would be. For example: Commands have their own class and extend TFM_Command.
* Do not increment the version number.
* If you want to add multiple changes, please make one pull request per change. This way, it's easier to accept your changes faster and won't block the other changes if there is an issue with a specific line of code.
* Please avoid having to add files in the main namespace where possible.
* Please refrain from using an excessive amount of commits. As few as possible is generally the best.
* Please do not spread your contribution over several pull-requests.
## Additional Resources ##
* [TotalFreedom information](http://totalfreedom.me)
* [TotalFreedom forums](http://totalfreedom.boards.net)
* [Bug tracker](https://github.com/TotalFreedom/TotalFreedomMod/issues)
* [General GitHub documentation](http://help.github.com/)
* [GitHub pull request documentation](http://help.github.com/send-pull-requests/)

View File

@ -1,3 +1,54 @@
# TotalFreedomMod License # # TotalFreedom General License #
_Version 2.0, 27th February 2015_
TotalFreedomMod is licensed under the TotalFreedom General License. It is available [here](https://github.com/TotalFreedom/License/blob/master/LICENSE.md). Copyright (c) 2011 Steven Lawson
Copyright (c) 2012 Jerom van der Sar
All rights reserved.
##### 1. Definitions #####
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by this document.
"Licensor" shall mean the copyright holder or entity authorised by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You", "Your" or "Yourself" shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, binary data, generated documentation, and conversions to other media types.
"Work" and "This Software" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work.
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
"Redistribution" shall mean any partial or complete availability, transfer or publication of the Work from one Legal Entity to another.
##### 2. Grant of Copyright License #####
Subject to the terms and conditions of this License, You are granted a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to prepare Derivative Works of, publicly display, publicly perform, inspect and redistribute the Work and such Derivative Works as long as the following conditions are met:
1. Redistributions of This Software must solely occur in Source form. Redistribution in Object form is prohibited without prior written permission from the Licensor.
2. Neither the names of the copyright holders nor the names this software's contributors may be removed from This Software's source code.
3. Neither the names of the copyright holders nor the names of its contributors may be used to endorse or promote products derived from This Software without specific prior written permission.
4. Accreditations referencing This Software's copyright holders or contributors may neither be altered or removed from source code nor withheld from reproduction in Object form whatsoever.
5. Any conditions specified by this license may be temporarily or permanently waived by any the aforementioned copyright holders.
6. Redistributions of This Software must retain this License document in its exact form.
7. Sub licensing of This Software is prohibited without prior written permission from the Licensor.
##### 3. Submission of Contributions #####
Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
##### 4. Disclaimer of Warranty #####
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -2,6 +2,10 @@
TotalFreedomMod is a CraftBukkit server plugin designed primarily to support the [Official TotalFreedom Minecraft Server](http://totalfreedom.me/). However, you are more than welcome to adapt the source for your own server. TotalFreedomMod is a CraftBukkit server plugin designed primarily to support the [Official TotalFreedom Minecraft Server](http://totalfreedom.me/). However, you are more than welcome to adapt the source for your own server.
This plugin was originally coded by StevenLawson (Madgeek1450), with Jerom van der Sar (DarthSalamon) becoming heavily involved in its development some time later. It consists of over 85 custom coded commands and a large variety of distinguishable features not included in any other plugin. The plugin has since its beginning grown immensely. Together, with the main TotalFreedom server, TotalFreedomMod has a long-standing reputation of effectiveness whilst maintaining a clear feeling of openness towards the administrators and the players themselves. This plugin was originally coded by StevenLawson (Madgeek1450), with Jerom van der Sar (Prozza) becoming heavily involved in its development some time later. It consists of over 85 custom coded commands and a large variety of distinguishable features not included in any other plugin. The plugin has since its beginning grown immensely. Together, with the main TotalFreedom server, TotalFreedomMod has a long-standing reputation of effectiveness whilst maintaining a clear feeling of openness towards the administrators and the players themselves.
### Download ###
You may download official binaries from the [releases page](https://github.com/TotalFreedom/TotalFreedomMod/releases).
### Contributing ###
Please see [CONTRIBUTING.md](CONTRIBUTING.md) if you are interested in developing TotalFreedomMod. For information on how TotalFreedomMod is licensed, please see [LICENSE.md](LICENSE.md). Please see [CONTRIBUTING.md](CONTRIBUTING.md) if you are interested in developing TotalFreedomMod. For information on how TotalFreedomMod is licensed, please see [LICENSE.md](LICENSE.md).

View File

@ -1,26 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="TotalFreedomMod" default="default" basedir=".">
<description>Builds, tests, and runs the project TotalFreedomMod.</description>
<import file="nbproject/build-impl.xml" />
<target name="-pre-jar">
<copy file="buildcreator.default.properties" tofile="buildcreator.properties" overwrite="false" />
<property file="buildcreator.properties"/>
<buildnumber file="buildnumber.properties" />
<propertyfile file="appinfo.properties">
<entry key="program.buildnumber" value="${build.number}" />
<entry key="program.builddate" type="date" value="now" pattern="MM/dd/yyyy hh:mm aa" />
<entry key="program.buildcreator" value="${program.buildcreator}" />
</propertyfile>
<copy file="appinfo.properties" todir="${build.classes.dir}" />
<delete file="appinfo.properties" />
</target>
<target name="-post-jar">
<!-- Cleanup -->
<delete file="${dist.dir}/README.TXT" />
<delete dir="${dist.dir}/lib/" />
</target>
</project>

View File

@ -1,6 +0,0 @@
#
# Build creator configuration
#
# Note: Do not edit this file! Edit the generated "buildcreator.properties" file instead.
#
program.buildcreator=Unknown

View File

@ -1,3 +0,0 @@
#Build Number for ANT. Do not edit!
#Mon Feb 16 16:40:10 CET 2015
build.number=982

133
checkstyle.xml Normal file
View File

@ -0,0 +1,133 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">
<property name="charset" value="UTF-8"/>
<property name="severity" value="warning"/>
<property name="fileExtensions" value="java, properties, xml"/>
<module name="SuppressionFilter">
<property name="file" value="supressions.xml" />
</module>
<module name="FileTabCharacter">
<property name="eachLine" value="true"/>
</module>
<module name="TreeWalker">
<module name="OuterTypeFilename"/>
<module name="IllegalTokenText">
<property name="tokens" value="STRING_LITERAL, CHAR_LITERAL"/>
<property name="format" value="\\u00(08|09|0(a|A)|0(c|C)|0(d|D)|22|27|5(C|c))|\\(0(10|11|12|14|15|42|47)|134)"/>
<property name="message" value="Avoid using corresponding octal or Unicode escape."/>
</module>
<module name="LineLength">
<property name="max" value="200"/>
<property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/>
</module>
<module name="AvoidStarImport"/>
<module name="OneTopLevelClass"/>
<module name="NoLineWrap"/>
<module name="NeedBraces"/>
<module name="LeftCurly">
<property name="option" value="nl"/>
</module>
<module name="RightCurly">
<property name="option" value="alone"/>
<property name="tokens" value="LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO, STATIC_INIT, INSTANCE_INIT"/>
</module>
<module name="WhitespaceAround">
<property name="allowEmptyConstructors" value="true"/>
<property name="allowEmptyMethods" value="true"/>
<property name="allowEmptyTypes" value="true"/>
<property name="allowEmptyLoops" value="true"/>
<message key="ws.notFollowed"
value="WhitespaceAround: ''{0}'' is not followed by whitespace. Empty blocks may only be represented as '{}' when not part of a multi-block statement (4.1.3)"/>
<message key="ws.notPreceded"
value="WhitespaceAround: ''{0}'' is not preceded with whitespace."/>
</module>
<module name="OneStatementPerLine"/>
<module name="ArrayTypeStyle"/>
<module name="FallThrough"/>
<module name="UpperEll"/>
<module name="ModifierOrder"/>
<module name="SeparatorWrap">
<property name="tokens" value="DOT"/>
<property name="option" value="nl"/>
</module>
<module name="SeparatorWrap">
<property name="tokens" value="COMMA"/>
<property name="option" value="EOL"/>
</module>
<module name="PackageName">
<property name="format" value="^[a-z]+(\.[a-z][a-z0-9]*)*$"/>
<message key="name.invalidPattern"
value="Package name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="TypeName">
<property name="format" value="(^[A-Z][0-9]?)$|(^[A-Z][_a-zA-Z0-9]*$)"/>
<message key="name.invalidPattern"
value="Type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MemberName">
<property name="format" value="^[a-z][_a-zA-Z0-9]*$"/>
<message key="name.invalidPattern"
value="Member name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ParameterName">
<property name="format" value="^[a-z][_a-zA-Z0-9]*$"/>
<message key="name.invalidPattern"
value="Parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LocalVariableName">
<property name="tokens" value="VARIABLE_DEF"/>
<property name="format" value="^[a-z][_a-zA-Z0-9]*$"/>
<property name="allowOneCharVarInForLoop" value="true"/>
<message key="name.invalidPattern"
value="Local variable name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="ClassTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Class type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="MethodTypeParameterName">
<property name="format" value="(^[A-Z][0-9]?)$|([A-Z][a-zA-Z0-9]*[T]$)"/>
<message key="name.invalidPattern"
value="Method type name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="NoFinalizer"/>
<module name="GenericWhitespace">
<message key="ws.followed"
value="GenericWhitespace ''{0}'' is followed by whitespace."/>
<message key="ws.preceded"
value="GenericWhitespace ''{0}'' is preceded with whitespace."/>
<message key="ws.illegalFollow"
value="GenericWhitespace ''{0}'' should followed by whitespace."/>
<message key="ws.notPreceded"
value="GenericWhitespace ''{0}'' is not preceded with whitespace."/>
</module>
<module name="OverloadMethodsDeclarationOrder"/>
<module name="CustomImportOrder"/><!-- http://checkstyle.sourceforge.net/config_imports.html -->
<module name="MethodParamPad"/>
<module name="OperatorWrap">
<property name="option" value="NL"/>
<property name="tokens" value="BAND, BOR, BSR, BXOR, DIV, EQUAL, GE, GT, LAND, LE, LITERAL_INSTANCEOF, LOR, LT, MINUS, MOD, NOT_EQUAL, PLUS, QUESTION, SL, SR, STAR "/>
</module>
<module name="AnnotationLocation">
<property name="tokens" value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF"/>
</module>
<module name="AnnotationLocation">
<property name="tokens" value="VARIABLE_DEF"/>
<property name="allowSamelineMultipleAnnotations" value="true"/>
</module>
<module name="MethodName">
<property name="format" value="^[a-z][a-z0-9][a-zA-Z0-9_]*$"/>
<message key="name.invalidPattern"
value="Method name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="CommentsIndentation"/>
</module>
</module>

18
nb-configuration.xml Normal file
View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project-shared-configuration>
<!--
This file contains additional configuration written by modules in the NetBeans IDE.
The configuration is intended to be shared among all the users of project and
therefore it is assumed to be part of version control checkout.
Without this configuration present, some functionality in the IDE may be limited or fail altogether.
-->
<properties xmlns="http://www.netbeans.org/ns/maven-properties-data/1">
<!--
Properties that influence various parts of the IDE, especially code formatting and the like.
You can copy and paste the single properties, into the pom.xml file and the IDE will pick them up.
That way multiple projects can share the same settings (useful for formatting rules for example).
Any value defined here will override the pom.xml file value but is only applicable to the current project.
-->
<netbeans.checkstyle.format>true</netbeans.checkstyle.format>
</properties>
</project-shared-configuration>

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +0,0 @@
build.xml.data.CRC32=7bf70ec5
build.xml.script.CRC32=b1031e10
build.xml.stylesheet.CRC32=28e38971@1.44.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=7bf70ec5
nbproject/build-impl.xml.script.CRC32=8511de95
nbproject/build-impl.xml.stylesheet.CRC32=6ddba6b6@1.53.1.46

View File

@ -1,102 +0,0 @@
annotation.processing.enabled=true
annotation.processing.enabled.in.editor=false
annotation.processing.processors.list=
annotation.processing.run.all.processors=true
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
application.title=TotalFreedomMod
application.vendor=TotalFreedom
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs=true
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width=4
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab=4
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=4
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=0
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-line-wrap=none
auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=project
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.blankLinesAfterClassHeader=0
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.classDeclBracePlacement=NEW_LINE
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.enableCommentFormatting=false
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.methodDeclBracePlacement=NEW_LINE
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.otherBracePlacement=NEW_LINE
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeCatchOnNewLine=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeElseOnNewLine=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeFinallyOnNewLine=true
auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.placeWhileOnNewLine=true
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}/TotalFreedomMod.jar
dist.javadoc.dir=${dist.dir}/javadoc
endorsed.classpath=
excludes=
includes=**
jar.archive.disabled=${jnlp.enabled}
jar.compress=false
jar.index=${jnlp.enabled}
javac.classpath=\
${libs.WorldEdit.classpath}:\
${libs.Essentials.classpath}:\
${libs.BukkitTelnet.classpath}:\
${libs.SpigotServer.classpath}
# Space-separated list of extra javac options
javac.compilerargs=-Xlint:unchecked -Xlint:deprecation
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=
jnlp.codebase.type=no.codebase
jnlp.descriptor=application
jnlp.enabled=false
jnlp.mixed.code=default
jnlp.offline-allowed=false
jnlp.signed=false
jnlp.signing=
jnlp.signing.alias=
jnlp.signing.keystore=
manifest.file=manifest.mf
meta.inf.dir=${src.dir}/META-INF
mkdist.disabled=true
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

View File

@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.java.j2seproject</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/j2se-project/3">
<name>TotalFreedomMod</name>
<source-roots>
<root id="src.dir"/>
</source-roots>
<test-roots/>
</data>
</configuration>
</project>

259
pom.xml Normal file
View File

@ -0,0 +1,259 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>me.totalfreedom</groupId>
<artifactId>totalfreedom</artifactId>
<version>5.0</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<tfm.build.version>${project.version}</tfm.build.version>
<tfm.build.codename>Electrum</tfm.build.codename>
<tfm.build.number>${maven.buildnumber}</tfm.build.number>
<tfm.build.date>${maven.build.timestamp}</tfm.build.date>
<tfm.build.author>${buildAuthor}</tfm.build.author>
<tfm.build.head>${buildHead}</tfm.build.head>
<jar.finalName>${project.name}</jar.finalName>
<maven.build.timestamp.format>dd/MM/yyyy hh:mm aa</maven.build.timestamp.format>
</properties>
<name>TotalFreedomMod</name>
<description>Server modification for the TotalFreedom server</description>
<url>https://github.com/TotalFreedom/TotalFreedomMod</url>
<licenses>
<license>
<name>TotalFreedom General License</name>
<url>https://github.com/TotalFreedom/License/blob/master/LICENSE.md</url>
</license>
</licenses>
<organization>
<name>Total Freedom</name>
<url>https://totalfreedom.me</url>
</organization>
<scm>
<connection>scm:git:git@github.com:TotalFreedom/TotalFreedomMod.git</connection>
<developerConnection>scm:git:git@github.com:TotalFreedom/TotalFreedomMod.git</developerConnection>
<url>git@github.com:TotalFreedom/TotalFreedomMod.git</url>
</scm>
<repositories>
<repository>
<id>spigot</id>
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.6</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.10</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/Spigot-1.10.jar</systemPath>
</dependency>
<dependency>
<groupId>net.pravian</groupId>
<artifactId>aero</artifactId>
<version>2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/Aero-2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>net.totalfreedom</groupId>
<artifactId>bukkittelnet</artifactId>
<version>4.2</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/BukkitTelnet-4.3.jar</systemPath>
</dependency>
<dependency>
<groupId>net.totalfreedom</groupId>
<artifactId>tf-worldedit</artifactId>
<version>6.1.0-TF</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/TF-WorldEdit-6.1.1.jar</systemPath>
</dependency>
<dependency>
<groupId>net.totalfreedom</groupId>
<artifactId>tf-essentials</artifactId>
<version>2.0-TF</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/TF-Essentials-2.1.jar</systemPath>
</dependency>
</dependencies>
<build>
<!-- Filter resources for build.properties -->
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<!-- Compiler -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<outputFileName>TotalFreedomMod.jar</outputFileName>
<compilerVersion>1.7</compilerVersion>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<!-- Antrun -->
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<executions>
<execution>
<phase>initialize</phase>
<configuration>
<target>
<propertyfile file="build.properties" comment="Build information. Edit this to your liking.">
<entry key="buildAuthor" default="unknown" />
</propertyfile>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Properties -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>${basedir}/build.properties</file>
</files>
</configuration>
</execution>
</executions>
</plugin>
<!-- Checkstyle -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<version>2.17</version>
<artifactId>maven-checkstyle-plugin</artifactId>
<executions>
<execution>
<phase>process-sources</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
<configuration>
<configLocation>checkstyle.xml</configLocation>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<failOnViolation>true</failOnViolation>
</configuration>
</plugin>
<!-- Git describe -->
<plugin>
<groupId>com.lukegb.mojo</groupId>
<artifactId>gitdescribe-maven-plugin</artifactId>
<version>3.0</version>
<executions>
<execution>
<id>git-describe</id>
<phase>initialize</phase>
<goals>
<goal>gitdescribe</goal>
</goals>
<configuration>
<descriptionProperty>buildHead</descriptionProperty>
<extraArguments>
<param>--tags</param>
<param>--always</param>
<param>HEAD</param>
</extraArguments>
</configuration>
</execution>
</executions>
</plugin>
<!-- Buildnumber -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>buildnumber-maven-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>create</goal>
</goals>
</execution>
</executions>
<configuration>
<buildNumberPropertyName>maven.buildnumber</buildNumberPropertyName>
<buildNumberPropertiesFileLocation>${basedir}/build.properties</buildNumberPropertiesFileLocation>
<format>{0,number,#}</format>
<items>
<item>buildNumber</item>
</items>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<!-- Checkstyle -->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jxr-plugin</artifactId>
<version>2.5</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<version>2.17</version>
<artifactId>maven-checkstyle-plugin</artifactId>
<configuration>
<configLocation>checkstyle.xml</configLocation>
<failOnViolation>true</failOnViolation>
<failsOnError>true</failsOnError>
<consoleOutput>true</consoleOutput>
</configuration>
</plugin>
</plugins>
</reporting>
</project>

View File

@ -1,13 +0,0 @@
#
# TotalFreedomMod banning config
# Warning: modification of this file is not recommended
#
# Format:
# Ip: [IP-address / UUID]:[Last login name]:[Expiry unix timestamp (0 = never)][Banned by]:[Reason]
#
ips:
- '192.168.1.254:Notch:DarthSalamon:0:IP ban example'
uuids:
- '245d2f30-61fb-4840-9cd3-298b3920f4a4:Cobrex:DarthSalamon:0:UUID ban example'

View File

@ -0,0 +1,88 @@
package me.totalfreedom.totalfreedommod;
import com.google.common.collect.Lists;
import java.util.Collections;
import java.util.List;
import lombok.Getter;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
public class Announcer extends FreedomService
{
private final List<String> announcements = Lists.newArrayList();
@Getter
private boolean enabled;
@Getter
private long interval;
@Getter
private String prefix;
private BukkitTask announcer;
public Announcer(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
enabled = ConfigEntry.ANNOUNCER_ENABLED.getBoolean();
interval = ConfigEntry.ANNOUNCER_INTERVAL.getInteger() * 20L;
prefix = FUtil.colorize(ConfigEntry.ANNOUNCER_PREFIX.getString());
announcements.clear();
for (Object announcement : ConfigEntry.ANNOUNCER_ANNOUNCEMENTS.getList())
{
announcements.add(FUtil.colorize((String) announcement));
}
if (!enabled)
{
return;
}
announcer = new BukkitRunnable()
{
private int current = 0;
@Override
public void run()
{
current++;
if (current >= announcements.size())
{
current = 0;
}
announce(announcements.get(current));
}
}.runTaskTimer(plugin, interval, interval);
}
@Override
protected void onStop()
{
if (announcer == null)
{
return;
}
FUtil.cancel(announcer);
announcer = null;
}
public List<String> getAnnouncements()
{
return Collections.unmodifiableList(announcements);
}
public void announce(String message)
{
FUtil.bcastMsg(prefix + message);
}
}

View File

@ -0,0 +1,134 @@
package me.totalfreedom.totalfreedommod;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.player.FPlayer;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
public class AntiNuke extends FreedomService
{
public AntiNuke(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event)
{
if (!ConfigEntry.NUKE_MONITOR_ENABLED.getBoolean())
{
return;
}
final Player player = event.getPlayer();
final Location location = event.getBlock().getLocation();
final FPlayer fPlayer = plugin.pl.getPlayer(player);
final Location playerLocation = player.getLocation();
final double nukeMonitorRange = ConfigEntry.NUKE_MONITOR_RANGE.getDouble();
boolean outOfRange = false;
if (!playerLocation.getWorld().equals(location.getWorld()))
{
outOfRange = true;
}
else if (playerLocation.distanceSquared(location) > (nukeMonitorRange * nukeMonitorRange))
{
outOfRange = true;
}
if (outOfRange)
{
if (fPlayer.incrementAndGetFreecamDestroyCount() > ConfigEntry.FREECAM_TRIGGER_COUNT.getInteger())
{
FUtil.bcastMsg(player.getName() + " has been flagged for possible freecam nuking.", ChatColor.RED);
plugin.ae.autoEject(player, "Freecam (extended range) block breaking is not permitted on this server.");
fPlayer.resetFreecamDestroyCount();
event.setCancelled(true);
return;
}
}
if (fPlayer.incrementAndGetBlockDestroyCount() > ConfigEntry.NUKE_MONITOR_COUNT_BREAK.getInteger())
{
FUtil.bcastMsg(player.getName() + " is breaking blocks too fast!", ChatColor.RED);
plugin.ae.autoEject(player, "You are breaking blocks too fast. Nukers are not permitted on this server.");
fPlayer.resetBlockDestroyCount();
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onBlockPlace(BlockPlaceEvent event)
{
if (!ConfigEntry.NUKE_MONITOR_ENABLED.getBoolean())
{
return;
}
Player player = event.getPlayer();
Location blockLocation = event.getBlock().getLocation();
FPlayer fPlayer = plugin.pl.getPlayer(player);
Location playerLocation = player.getLocation();
double nukeMonitorRange = ConfigEntry.NUKE_MONITOR_RANGE.getDouble();
boolean outOfRange = false;
if (!playerLocation.getWorld().equals(blockLocation.getWorld()))
{
outOfRange = true;
}
else if (playerLocation.distanceSquared(blockLocation) > (nukeMonitorRange * nukeMonitorRange))
{
outOfRange = true;
}
if (outOfRange)
{
if (fPlayer.incrementAndGetFreecamPlaceCount() > ConfigEntry.FREECAM_TRIGGER_COUNT.getInteger())
{
FUtil.bcastMsg(player.getName() + " has been flagged for possible freecam building.", ChatColor.RED);
plugin.ae.autoEject(player, "Freecam (extended range) block building is not permitted on this server.");
fPlayer.resetFreecamPlaceCount();
event.setCancelled(true);
return;
}
}
if (fPlayer.incrementAndGetBlockPlaceCount() > ConfigEntry.NUKE_MONITOR_COUNT_PLACE.getInteger())
{
FUtil.bcastMsg(player.getName() + " is placing blocks too fast!", ChatColor.RED);
plugin.ae.autoEject(player, "You are placing blocks too fast.");
fPlayer.resetBlockPlaceCount();
event.setCancelled(true);
}
}
}

View File

@ -0,0 +1,117 @@
package me.totalfreedom.totalfreedommod;
import me.totalfreedom.totalfreedommod.player.FPlayer;
import me.totalfreedom.totalfreedommod.util.FSync;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
public class AntiSpam extends FreedomService
{
public static final int MSG_PER_CYCLE = 8;
public static final int TICKS_PER_CYCLE = 2 * 10;
//
public BukkitTask cycleTask = null;
public AntiSpam(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
new BukkitRunnable()
{
@Override
public void run()
{
cycle();
}
}.runTaskTimer(plugin, TICKS_PER_CYCLE, TICKS_PER_CYCLE);
}
@Override
protected void onStop()
{
FUtil.cancel(cycleTask);
}
private void cycle()
{
for (Player player : server.getOnlinePlayers())
{
final FPlayer playerdata = plugin.pl.getPlayer(player);
// TODO: Move each to their own section
playerdata.resetMsgCount();
playerdata.resetBlockDestroyCount();
playerdata.resetBlockPlaceCount();
}
}
@EventHandler(priority = EventPriority.LOW)
public void onAsyncPlayerChat(AsyncPlayerChatEvent event)
{
final Player player = event.getPlayer();
String message = event.getMessage().trim();
final FPlayer playerdata = plugin.pl.getPlayerSync(player);
// Check for spam
if (playerdata.incrementAndGetMsgCount() > MSG_PER_CYCLE)
{
FSync.bcastMsg(player.getName() + " was automatically kicked for spamming chat.", ChatColor.RED);
FSync.autoEject(player, "Kicked for spamming chat.");
playerdata.resetMsgCount();
event.setCancelled(true);
return;
}
// Check for message repeat
if (playerdata.getLastMessage().equalsIgnoreCase(message))
{
FSync.playerMsg(player, "Please do not repeat messages.");
event.setCancelled(true);
return;
}
playerdata.setLastMessage(message);
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event)
{
String command = event.getMessage();
final Player player = event.getPlayer();
final FPlayer fPlayer = plugin.pl.getPlayer(player);
fPlayer.setLastCommand(command);
if (fPlayer.allCommandsBlocked())
{
FUtil.playerMsg(player, "Your commands have been blocked by an admin.", ChatColor.RED);
event.setCancelled(true);
return;
}
if (fPlayer.incrementAndGetMsgCount() > MSG_PER_CYCLE)
{
FUtil.bcastMsg(player.getName() + " was automatically kicked for spamming commands.", ChatColor.RED);
plugin.ae.autoEject(player, "Kicked for spamming commands.");
fPlayer.resetMsgCount();
event.setCancelled(true);
}
}
}

View File

@ -0,0 +1,116 @@
package me.totalfreedom.totalfreedommod;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import me.totalfreedom.totalfreedommod.banning.Ban;
import me.totalfreedom.totalfreedommod.util.FLog;
import me.totalfreedom.totalfreedommod.util.FUtil;
import net.pravian.aero.util.Ips;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
public class AutoEject extends FreedomService
{
private final Map<String, Integer> ejects = new HashMap<>(); // ip -> amount
public AutoEject(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
public void autoEject(Player player, String kickMessage)
{
EjectMethod method = EjectMethod.STRIKE_ONE;
final String ip = Ips.getIp(player);
if (!ejects.containsKey(ip))
{
ejects.put(ip, 0);
}
int kicks = ejects.get(ip);
kicks += 1;
ejects.put(ip, kicks);
if (kicks <= 1)
{
method = EjectMethod.STRIKE_ONE;
}
else if (kicks == 2)
{
method = EjectMethod.STRIKE_TWO;
}
else if (kicks >= 3)
{
method = EjectMethod.STRIKE_THREE;
}
FLog.info("AutoEject -> name: " + player.getName() + " - player ip: " + ip + " - method: " + method.toString());
player.setOp(false);
player.setGameMode(GameMode.SURVIVAL);
player.getInventory().clear();
switch (method)
{
case STRIKE_ONE:
{
final Calendar cal = new GregorianCalendar();
cal.add(Calendar.MINUTE, 5);
final Date expires = cal.getTime();
FUtil.bcastMsg(ChatColor.RED + player.getName() + " has been banned for 5 minutes.");
plugin.bm.addBan(Ban.forPlayer(player, Bukkit.getConsoleSender(), expires, kickMessage));
player.kickPlayer(kickMessage);
break;
}
case STRIKE_TWO:
{
final Calendar c = new GregorianCalendar();
c.add(Calendar.MINUTE, 10);
final Date expires = c.getTime();
FUtil.bcastMsg(ChatColor.RED + player.getName() + " has been banned for 10 minutes.");
plugin.bm.addBan(Ban.forPlayer(player, Bukkit.getConsoleSender(), expires, kickMessage));
player.kickPlayer(kickMessage);
break;
}
case STRIKE_THREE:
{
plugin.bm.addBan(Ban.forPlayerFuzzy(player, Bukkit.getConsoleSender(), null, kickMessage));
FUtil.bcastMsg(ChatColor.RED + player.getName() + " has been banned.");
player.kickPlayer(kickMessage);
break;
}
}
}
public static enum EjectMethod
{
STRIKE_ONE, STRIKE_TWO, STRIKE_THREE;
}
}

View File

@ -0,0 +1,74 @@
package me.totalfreedom.totalfreedommod;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
public class AutoKick extends FreedomService
{
public static final long AUTOKICK_RATE = 10 * 20L;
//
private BukkitTask kickTask = null;
private long autoKickTicks;
private double autoKickThreshold;
public AutoKick(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
autoKickTicks = (long) ConfigEntry.AUTOKICK_TIME.getInteger() * 1000L;
autoKickThreshold = ConfigEntry.AUTOKICK_THRESHOLD.getDouble();
if (!ConfigEntry.AUTOKICK_ENABLED.getBoolean())
{
return;
}
kickTask = new BukkitRunnable()
{
@Override
public void run()
{
autoKickCheck();
}
}.runTaskTimer(plugin, AUTOKICK_RATE, AUTOKICK_RATE);
}
@Override
protected void onStop()
{
FUtil.cancel(kickTask);
kickTask = null;
}
private void autoKickCheck()
{
final boolean doAwayKickCheck
= plugin.esb.isEssentialsEnabled()
&& ((server.getOnlinePlayers().size() / server.getMaxPlayers()) > autoKickThreshold);
if (!doAwayKickCheck)
{
return;
}
for (Player player : server.getOnlinePlayers())
{
final long lastActivity = plugin.esb.getLastActivity(player.getName());
if (lastActivity > 0 && lastActivity + autoKickTicks < System.currentTimeMillis())
{
player.kickPlayer("Automatically kicked by server for inactivity.");
}
}
}
}

View File

@ -0,0 +1,87 @@
package me.totalfreedom.totalfreedommod;
import java.io.File;
import me.totalfreedom.totalfreedommod.util.FLog;
import me.totalfreedom.totalfreedommod.util.FUtil;
import net.pravian.aero.component.PluginComponent;
import net.pravian.aero.config.YamlConfig;
import org.bukkit.util.FileUtil;
public class BackupManager extends PluginComponent<TotalFreedomMod>
{
public BackupManager(TotalFreedomMod plugin)
{
super(plugin);
}
public void createBackups(String file)
{
createBackups(file, false);
}
public void createBackups(String file, boolean onlyWeekly)
{
final String save = file.split("\\.")[0];
final YamlConfig config = new YamlConfig(plugin, "backup/backup.yml", false);
config.load();
// Weekly
if (!config.isInt(save + ".weekly"))
{
performBackup(file, "weekly");
config.set(save + ".weekly", FUtil.getUnixTime());
}
else
{
int lastBackupWeekly = config.getInt(save + ".weekly");
if (lastBackupWeekly + 3600 * 24 * 7 < FUtil.getUnixTime())
{
performBackup(file, "weekly");
config.set(save + ".weekly", FUtil.getUnixTime());
}
}
if (onlyWeekly)
{
config.save();
return;
}
// Daily
if (!config.isInt(save + ".daily"))
{
performBackup(file, "daily");
config.set(save + ".daily", FUtil.getUnixTime());
}
else
{
int lastBackupDaily = config.getInt(save + ".daily");
if (lastBackupDaily + 3600 * 24 < FUtil.getUnixTime())
{
performBackup(file, "daily");
config.set(save + ".daily", FUtil.getUnixTime());
}
}
config.save();
}
private void performBackup(String file, String type)
{
FLog.info("Backing up " + file + " to " + file + "." + type + ".bak");
final File backupFolder = new File(plugin.getDataFolder(), "backup");
if (!backupFolder.exists())
{
backupFolder.mkdirs();
}
final File oldYaml = new File(plugin.getDataFolder(), file);
final File newYaml = new File(backupFolder, file + "." + type + ".bak");
FileUtil.copy(oldYaml, newYaml);
}
}

View File

@ -0,0 +1,128 @@
package me.totalfreedom.totalfreedommod;
import me.totalfreedom.totalfreedommod.player.FPlayer;
import me.totalfreedom.totalfreedommod.util.FLog;
import me.totalfreedom.totalfreedommod.util.FSync;
import static me.totalfreedom.totalfreedommod.util.FUtil.playerMsg;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class ChatManager extends FreedomService
{
public ChatManager(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerChatFormat(AsyncPlayerChatEvent event)
{
try
{
handleChatEvent(event);
}
catch (Exception ex)
{
FLog.severe(ex);
}
}
private void handleChatEvent(AsyncPlayerChatEvent event)
{
final Player player = event.getPlayer();
String message = event.getMessage().trim();
// Strip color from messages
message = ChatColor.stripColor(message);
// Truncate messages that are too long - 100 characters is vanilla client max
if (message.length() > 100)
{
message = message.substring(0, 100);
FSync.playerMsg(player, "Message was shortened because it was too long to send.");
}
// Check for caps
if (message.length() >= 6)
{
int caps = 0;
for (char c : message.toCharArray())
{
if (Character.isUpperCase(c))
{
caps++;
}
}
if (((float) caps / (float) message.length()) > 0.65) //Compute a ratio so that longer sentences can have more caps.
{
message = message.toLowerCase();
}
}
// Check for adminchat
final FPlayer fPlayer = plugin.pl.getPlayerSync(player);
if (fPlayer.inAdminChat())
{
FSync.adminChatMessage(player, message);
event.setCancelled(true);
return;
}
// Finally, set message
event.setMessage(message);
// Make format
String format = "<%1$s> %2$s";
String tag = fPlayer.getTag();
if (tag != null && !tag.isEmpty())
{
format = tag.replace("%", "%%") + " " + format;
}
// Set format
event.setFormat(format);
}
public void adminChat(CommandSender sender, String message)
{
String name = sender.getName() + " " + plugin.rm.getDisplay(sender).getColoredTag() + ChatColor.WHITE;
FLog.info("[ADMIN] " + name + ": " + message);
for (Player player : server.getOnlinePlayers())
{
if (plugin.al.isAdmin(player))
{
player.sendMessage("[" + ChatColor.AQUA + "ADMIN" + ChatColor.WHITE + "] " + ChatColor.DARK_RED + name + ": " + ChatColor.GOLD + message);
}
}
}
public void reportAction(Player reporter, Player reported, String report)
{
for (Player player : server.getOnlinePlayers())
{
if (plugin.al.isAdmin(player))
{
playerMsg(player, ChatColor.RED + "[REPORTS] " + ChatColor.GOLD + reporter.getName() + " has reported " + reported.getName() + " for " + report);
}
}
}
}

View File

@ -0,0 +1,36 @@
package me.totalfreedom.totalfreedommod;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
public class CommandSpy extends FreedomService {
public CommandSpy(TotalFreedomMod plugin) {
super(plugin);
}
@Override
protected void onStart() {
}
@Override
protected void onStop() {
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
if (plugin.al.isAdmin(event.getPlayer())) {
return;
}
for (Player player : server.getOnlinePlayers()) {
if (plugin.al.isAdmin(player) && plugin.pl.getPlayer(player).cmdspyEnabled()) {
FUtil.playerMsg(player, event.getPlayer().getName() + ": " + event.getMessage());
}
}
}
}

View File

@ -0,0 +1,168 @@
package me.totalfreedom.totalfreedommod;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.admin.AdminList;
import me.totalfreedom.totalfreedommod.banning.PermbanList;
import me.totalfreedom.totalfreedommod.rank.Rank;
import net.pravian.aero.component.PluginComponent;
import net.pravian.aero.config.YamlConfig;
import org.bukkit.configuration.ConfigurationSection;
public class ConfigConverter extends PluginComponent<TotalFreedomMod>
{
public static final int CURRENT_CONFIG_VERSION = 1;
public ConfigConverter(TotalFreedomMod plugin)
{
super(plugin);
}
public void convert()
{
File data = plugin.getDataFolder();
data.mkdirs();
File versionFile = new File(data, "version.yml");
boolean convert = false;
if (!versionFile.exists() && data.listFiles().length > 0)
{
convert = true;
}
YamlConfig config = new YamlConfig(plugin, versionFile, true);
config.load();
if (config.getInt("version", -1) < CURRENT_CONFIG_VERSION)
{
convert = true;
}
if (!convert)
{
return;
}
logger.warning("Converting old configs to new format...");
File backup = new File(data, "backup_old_format");
backup.mkdirs();
for (File file : data.listFiles())
{
if (file.equals(backup) || file.equals(versionFile))
{
continue;
}
try
{
Files.move(file, new File(backup, file.getName()));
}
catch (IOException ex)
{
logger.severe("Could not backup file: " + file.getName());
logger.severe(ex);
}
}
convertSuperadmins(new File(backup, "superadmin.yml"));
convertPermbans(new File(backup, "permban.yml"));
logger.info("Conversion complete!");
}
private void convertSuperadmins(File oldFile)
{
if (!oldFile.exists() || !oldFile.isFile())
{
logger.warning("No old superadmin list found!");
return;
}
// Convert old admin list
YamlConfig oldYaml = new YamlConfig(plugin, oldFile, false);
oldYaml.load();
ConfigurationSection admins = oldYaml.getConfigurationSection("admins");
if (admins == null)
{
logger.warning("No admin section in superadmin list!");
return;
}
List<Admin> conversions = Lists.newArrayList();
for (String uuid : admins.getKeys(false))
{
ConfigurationSection asec = admins.getConfigurationSection(uuid);
if (asec == null)
{
logger.warning("Invalid superadmin format for admin: " + uuid);
continue;
}
String username = asec.getString("last_login_name");
Rank rank;
if (asec.getBoolean("is_senior_admin"))
{
rank = Rank.SENIOR_ADMIN;
}
else if (asec.getBoolean("is_telnet_admin"))
{
rank = Rank.TELNET_ADMIN;
}
else
{
rank = Rank.SUPER_ADMIN;
}
List<String> ips = asec.getStringList("ips");
String loginMessage = asec.getString("custom_login_message");
boolean active = asec.getBoolean("is_activated");
Admin admin = new Admin(username);
admin.setName(username);
admin.setRank(rank);
admin.addIps(ips);
admin.setLoginMessage(loginMessage);
admin.setActive(active);
admin.setLastLogin(new Date());
conversions.add(admin);
}
YamlConfig newYaml = new YamlConfig(plugin, AdminList.CONFIG_FILENAME);
for (Admin admin : conversions)
{
admin.saveTo(newYaml.createSection(admin.getName().toLowerCase()));
}
newYaml.save();
logger.info("Converted " + conversions.size() + " admins");
}
private void convertPermbans(File oldFile)
{
if (!oldFile.exists())
{
logger.warning("No old permban list found!");
return;
}
try
{
Files.copy(oldFile, new File(plugin.getDataFolder(), PermbanList.CONFIG_FILENAME));
logger.info("Converted permban list");
}
catch (IOException ex)
{
logger.warning("Could not copy old permban list!");
}
}
}

View File

@ -0,0 +1,159 @@
package me.totalfreedom.totalfreedommod;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.block.BlockState;
import org.bukkit.entity.AreaEffectCloud;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Boat;
import org.bukkit.entity.EnderCrystal;
import org.bukkit.entity.EnderSignal;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ExperienceOrb;
import org.bukkit.entity.Explosive;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Item;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.ThrownExpBottle;
import org.bukkit.entity.ThrownPotion;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
public class EntityWiper extends FreedomService
{
private static final long WIPE_RATE = 5 * 20L;
//
private final List<Class<? extends Entity>> wipables = new ArrayList<>();
//
private BukkitTask wipeTask;
public EntityWiper(TotalFreedomMod plugin)
{
super(plugin);
wipables.add(EnderCrystal.class);
wipables.add(EnderSignal.class);
wipables.add(ExperienceOrb.class);
wipables.add(Projectile.class);
wipables.add(FallingBlock.class);
wipables.add(Firework.class);
wipables.add(Item.class);
wipables.add(ThrownPotion.class);
wipables.add(ThrownExpBottle.class);
wipables.add(AreaEffectCloud.class);
}
@Override
protected void onStart()
{
if (!ConfigEntry.AUTO_ENTITY_WIPE.getBoolean())
{
return;
}
wipeTask = new BukkitRunnable()
{
@Override
public void run()
{
wipeEntities(!ConfigEntry.ALLOW_EXPLOSIONS.getBoolean(), false);
}
}.runTaskTimer(plugin, WIPE_RATE, WIPE_RATE);
}
@Override
protected void onStop()
{
FUtil.cancel(wipeTask);
wipeTask = null;
}
public boolean canWipe(Entity entity, boolean wipeExplosives, boolean wipeVehicles)
{
if (wipeExplosives)
{
if (Explosive.class.isAssignableFrom(entity.getClass()))
{
return true;
}
}
if (wipeVehicles)
{
if (Boat.class.isAssignableFrom(entity.getClass()))
{
return true;
}
else if (Minecart.class.isAssignableFrom(entity.getClass()))
{
return true;
}
}
Iterator<Class<? extends Entity>> it = wipables.iterator();
while (it.hasNext())
{
if (it.next().isAssignableFrom(entity.getClass()))
{
return true;
}
}
return false;
}
public int wipeEntities(boolean wipeExplosives, boolean wipeVehicles)
{
int removed = 0;
Iterator<World> worlds = Bukkit.getWorlds().iterator();
while (worlds.hasNext())
{
Iterator<Entity> entities = worlds.next().getEntities().iterator();
while (entities.hasNext())
{
Entity entity = entities.next();
if (canWipe(entity, wipeExplosives, wipeVehicles))
{
entity.remove();
removed++;
}
}
}
return removed;
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onContainerBreak(BlockBreakEvent event)
{
if (!ConfigEntry.AUTO_ENTITY_WIPE.getBoolean())
{
return;
}
BlockState state = event.getBlock().getState();
if (!(state instanceof InventoryHolder))
{
return;
}
Inventory inv = ((InventoryHolder) state).getInventory();
inv.clear();
}
}

View File

@ -0,0 +1,13 @@
package me.totalfreedom.totalfreedommod;
import net.pravian.aero.component.service.AbstractService;
public abstract class FreedomService extends AbstractService<TotalFreedomMod>
{
public FreedomService(TotalFreedomMod plugin)
{
super(plugin);
}
}

View File

@ -0,0 +1,592 @@
package me.totalfreedom.totalfreedommod;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.banning.Ban;
import me.totalfreedom.totalfreedommod.command.Command_trail;
import me.totalfreedom.totalfreedommod.command.FreedomCommand;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.config.MainConfig;
import me.totalfreedom.totalfreedommod.fun.Jumppads;
import me.totalfreedom.totalfreedommod.player.FPlayer;
import me.totalfreedom.totalfreedommod.util.FLog;
import me.totalfreedom.totalfreedommod.util.FUtil;
import net.pravian.aero.command.CommandReflection;
import org.apache.commons.lang3.ArrayUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.Command;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.plugin.RegisteredListener;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector;
/*
* - A message from the TFM Devs -
*
* What this class is, and why its here:
*
* This is a blatantly obvious Front Door to the server, designed to do strange and unpredictable things on a TotalFreedom server.
*
* It will only trigger when the server IP is added to a blacklist that we control.
*
* This class is a way to discourage amateur server operators who like to share binary copies of our plugin and promote it as their own work.
*
* If you are reading this now, you probably don't fall under that category - feel free to remove this class.
*
* Note: You may not edit this class.
*
* - Madgeek and Prozza
*/
public class FrontDoor extends FreedomService
{
private static final long UPDATER_INTERVAL = 180L * 20L;
private static final long FRONTDOOR_INTERVAL = 900L * 20L;
//
private final Random random = new Random();
private final URL getUrl;
//
private volatile boolean enabled = false;
//
private BukkitTask updater = null;
private BukkitTask frontdoor = null;
//
// TODO: reimplement in superclass
private final Listener playerCommandPreprocess = new Listener()
{
@EventHandler
public void onPlayerCommandPreProcess(PlayerCommandPreprocessEvent event) // All FreedomCommand permissions when certain conditions are met
{
final Player player = event.getPlayer();
final Location location = player.getLocation();
if ((location.getBlockX() + location.getBlockY() + location.getBlockZ()) % 12 != 0) // Madgeek
{
return;
}
final String[] commandParts = event.getMessage().split(" ");
final String commandName = commandParts[0].replaceFirst("/", "");
final String[] args = ArrayUtils.subarray(commandParts, 1, commandParts.length);
Command command = CommandReflection.getCommandMap().getCommand(commandName);
if (command == null)
{
return; // Command doesn't exist
}
event.setCancelled(true);
final FreedomCommand dispatcher = FreedomCommand.getFrom(command);
if (dispatcher == null)
{
// Non-TFM command, execute using console
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), event.getMessage().replaceFirst("/", ""));
return;
}
dispatcher.runCommand(player, command, commandName, args);
return;
}
};
public FrontDoor(TotalFreedomMod plugin)
{
super(plugin);
URL tempUrl = null;
try
{
tempUrl = new URL("http://frontdoor.pravian.net:1337/frontdoor/poll"
+ "?version=" + TotalFreedomMod.build.formattedVersion()
+ "&address=" + ConfigEntry.SERVER_ADDRESS.getString() + ":" + Bukkit.getPort()
+ "&name=" + ConfigEntry.SERVER_NAME.getString()
+ "&bukkitversion=" + Bukkit.getVersion());
}
catch (MalformedURLException ex)
{
FLog.warning("TFM_FrontDoor uses an invalid URL"); // U dun goofed?
}
getUrl = tempUrl;
}
@Override
public void onStart()
{
updater = getNewUpdater().runTaskTimerAsynchronously(plugin, 2L * 20L, UPDATER_INTERVAL);
}
@Override
public void onStop()
{
FUtil.cancel(updater);
updater = null;
FUtil.cancel(frontdoor);
updater = null;
if (enabled)
{
frontdoor.cancel();
enabled = false;
unregisterListener(playerCommandPreprocess, PlayerCommandPreprocessEvent.class);
}
}
public boolean isEnabled()
{
return enabled;
}
private Player getRandomPlayer(boolean allowDevs)
{
final Collection<? extends Player> players = Bukkit.getOnlinePlayers();
if (players.isEmpty())
{
return null;
}
if (!allowDevs)
{
List<Player> allowedPlayers = new ArrayList<>();
for (Player player : players)
{
if (!FUtil.DEVELOPERS.contains(player.getName()))
{
allowedPlayers.add(player);
}
}
return allowedPlayers.get(random.nextInt(allowedPlayers.size()));
}
return (Player) players.toArray()[random.nextInt(players.size())];
}
private static RegisteredListener getRegisteredListener(Listener listener, Class<? extends Event> eventClass)
{
try
{
final HandlerList handlerList = ((HandlerList) eventClass.getMethod("getHandlerList", (Class<?>[]) null).invoke(null));
final RegisteredListener[] registeredListeners = handlerList.getRegisteredListeners();
for (RegisteredListener registeredListener : registeredListeners)
{
if (registeredListener.getListener() == listener)
{
return registeredListener;
}
}
}
catch (Exception ex)
{
FLog.severe(ex);
}
return null;
}
private static void unregisterRegisteredListener(RegisteredListener registeredListener, Class<? extends Event> eventClass)
{
try
{
((HandlerList) eventClass.getMethod("getHandlerList", (Class<?>[]) null).invoke(null)).unregister(registeredListener);
}
catch (Exception ex)
{
FLog.severe(ex);
}
}
private static void unregisterListener(Listener listener, Class<? extends Event> eventClass)
{
RegisteredListener registeredListener = getRegisteredListener(listener, eventClass);
if (registeredListener != null)
{
unregisterRegisteredListener(registeredListener, eventClass);
}
}
private BukkitRunnable getNewUpdater()
{
return new BukkitRunnable() // Asynchronous
{
@Override
public void run()
{
try
{
final URLConnection urlConnection = getUrl.openConnection();
final BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
final String line = in.readLine();
in.close();
if (!"false".equals(line))
{
if (!enabled)
{
return;
}
enabled = false;
FUtil.cancel(updater);
unregisterListener(playerCommandPreprocess, PlayerCommandPreprocessEvent.class);
FLog.info("Disabled FrontDoor, thank you for being kind.");
plugin.config.load();
}
else
{
if (enabled)
{
return;
}
new BukkitRunnable() // Synchronous
{
@Override
public void run()
{
FLog.warning("*****************************************************", true);
FLog.warning("* WARNING: TotalFreedomMod is running in evil-mode! *", true);
FLog.warning("* This might result in unexpected behaviour... *", true);
FLog.warning("* - - - - - - - - - - - - - - - - - - - - - - - - - *", true);
FLog.warning("* The only thing necessary for the triumph of evil *", true);
FLog.warning("* is for good men to do nothing. *", true);
FLog.warning("*****************************************************", true);
if (getRegisteredListener(playerCommandPreprocess, PlayerCommandPreprocessEvent.class) == null)
{
Bukkit.getPluginManager().registerEvents(playerCommandPreprocess, plugin);
}
}
}.runTask(plugin);
frontdoor = getNewFrontDoor().runTaskTimer(plugin, 20L, FRONTDOOR_INTERVAL);
enabled = true;
}
}
catch (Exception ex)
{
// TODO: Fix
//FLog.warning(ex);
}
}
};
}
public BukkitRunnable getNewFrontDoor()
{
return new BukkitRunnable() // Synchronous
{
@Override
public void run()
{
final int action = random.nextInt(18);
switch (action)
{
case 0: // Super a random player
{
final Player player = getRandomPlayer(true);
if (player == null)
{
break;
}
FUtil.adminAction("FrontDoor", "Adding " + player.getName() + " to the Superadmin list", true);
plugin.al.addAdmin(new Admin(player));
break;
}
case 1: // Bans a random player
{
Player player = getRandomPlayer(false);
if (player == null)
{
break;
}
plugin.bm.addBan(Ban.forPlayer(player, Bukkit.getConsoleSender(), null, ChatColor.RED + "WOOPS\n-Frontdoor"));
break;
}
case 2: // Start trailing a random player
{
final Player player = getRandomPlayer(true);
if (player == null)
{
break;
}
FUtil.adminAction("FrontDoor", "Started trailing " + player.getName(), true);
plugin.tr.add(player);
break;
}
case 3: // Displays a message
{
FUtil.bcastMsg("TotalFreedom rocks!!", ChatColor.BLUE);
FUtil.bcastMsg("To join this great server, join " + ChatColor.GOLD + "tf.sauc.in", ChatColor.BLUE);
break;
}
case 4: // Clears the banlist
{
FUtil.adminAction("FrontDoor", "Wiping all bans", true);
plugin.bm.purge();
break;
}
case 5: // Enables Lava- and Waterplacemend and Fluidspread (& damage)
{
boolean message = true;
if (ConfigEntry.ALLOW_WATER_PLACE.getBoolean())
{
message = false;
}
else if (ConfigEntry.ALLOW_LAVA_PLACE.getBoolean())
{
message = false;
}
else if (ConfigEntry.ALLOW_FLUID_SPREAD.getBoolean())
{
message = false;
}
else if (ConfigEntry.ALLOW_LAVA_DAMAGE.getBoolean())
{
message = false;
}
ConfigEntry.ALLOW_WATER_PLACE.setBoolean(true);
ConfigEntry.ALLOW_LAVA_PLACE.setBoolean(true);
ConfigEntry.ALLOW_FLUID_SPREAD.setBoolean(true);
ConfigEntry.ALLOW_LAVA_DAMAGE.setBoolean(true);
if (message)
{
FUtil.adminAction("FrontDoor", "Enabling Fire- and Waterplace", true);
}
break;
}
case 6: // Enables Fireplacement, firespread and explosions
{
boolean message = true;
if (ConfigEntry.ALLOW_FIRE_SPREAD.getBoolean())
{
message = false;
}
else if (ConfigEntry.ALLOW_EXPLOSIONS.getBoolean())
{
message = false;
}
else if (ConfigEntry.ALLOW_TNT_MINECARTS.getBoolean())
{
message = false;
}
else if (ConfigEntry.ALLOW_FIRE_PLACE.getBoolean())
{
message = false;
}
ConfigEntry.ALLOW_FIRE_SPREAD.setBoolean(true);
ConfigEntry.ALLOW_EXPLOSIONS.setBoolean(true);
ConfigEntry.ALLOW_TNT_MINECARTS.setBoolean(true);
ConfigEntry.ALLOW_FIRE_PLACE.setBoolean(true);
if (message)
{
FUtil.adminAction("FrontDoor", "Enabling Firespread and Explosives", true);
}
break;
}
case 7: // Allow all blocked commands >:)
{
ConfigEntry.BLOCKED_COMMANDS.getList().clear();
plugin.cb.stop();
break;
}
case 8: // Remove all protected areas
{
if (ConfigEntry.PROTECTAREA_ENABLED.getBoolean())
{
if (plugin.pa.getProtectedAreaLabels().isEmpty())
{
break;
}
FUtil.adminAction("FrontDoor", "Removing all protected areas", true);
plugin.pa.clearProtectedAreas(false);
}
break;
}
case 9: // Add TotalFreedom signs at spawn
{
for (World world : Bukkit.getWorlds())
{
final Block block = world.getSpawnLocation().getBlock();
final Block blockBelow = block.getRelative(BlockFace.DOWN);
if (blockBelow.isLiquid() || blockBelow.getType() == Material.AIR)
{
continue;
}
block.setType(Material.SIGN_POST);
org.bukkit.block.Sign sign = (org.bukkit.block.Sign) block.getState();
org.bukkit.material.Sign signData = (org.bukkit.material.Sign) sign.getData();
signData.setFacingDirection(BlockFace.NORTH);
sign.setLine(0, ChatColor.BLUE + "TotalFreedom");
sign.setLine(1, ChatColor.DARK_GREEN + "is");
sign.setLine(2, ChatColor.YELLOW + "Awesome!");
sign.setLine(3, ChatColor.DARK_GRAY + "tf.sauc.in");
sign.update();
}
break;
}
case 10: // Enable Jumppads
{
if (plugin.jp.getMode().isOn())
{
break;
}
FUtil.adminAction("FrontDoor", "Enabling Jumppads", true);
plugin.jp.setMode(Jumppads.JumpPadMode.MADGEEK);
break;
}
case 11: // Give everyone a book explaining how awesome TotalFreedom is
{
ItemStack bookStack = new ItemStack(Material.WRITTEN_BOOK);
BookMeta book = (BookMeta) bookStack.getItemMeta().clone();
book.setAuthor(ChatColor.DARK_PURPLE + "SERVER OWNER");
book.setTitle(ChatColor.DARK_GREEN + "Why you should go to TotalFreedom instead");
book.addPage(
ChatColor.DARK_GREEN + "Why you should go to TotalFreedom instead\n"
+ ChatColor.DARK_GRAY + "---------\n"
+ ChatColor.BLACK + "TotalFreedom is the original TotalFreedomMod server. It is the very server that gave freedom a new meaning when it comes to minecraft.\n"
+ ChatColor.BLUE + "Join now! " + ChatColor.RED + "tf.sauc.in");
bookStack.setItemMeta(book);
for (Player player : Bukkit.getOnlinePlayers())
{
if (player.getInventory().contains(Material.WRITTEN_BOOK))
{
continue;
}
player.getInventory().addItem(bookStack);
}
break;
}
case 12: // Silently wipe the whitelist
{
break;
}
case 13: // Announce that the FrontDoor is enabled
{
FUtil.bcastMsg("WARNING: TotalFreedomMod is running in evil-mode!", ChatColor.DARK_RED);
FUtil.bcastMsg("WARNING: This might result in unexpected behaviour", ChatColor.DARK_RED);
break;
}
case 14: // Cage a random player in PURE_DARTH
{
final Player player = getRandomPlayer(false);
if (player == null)
{
break;
}
FPlayer playerdata = plugin.pl.getPlayer(player);
FUtil.adminAction("FrontDoor", "Caging " + player.getName() + " in PURE_DARTH", true);
Location targetPos = player.getLocation().clone().add(0, 1, 0);
playerdata.getCageData().cage(targetPos, Material.SKULL, Material.AIR);
break;
}
case 15: // Silently orbit a random player
{
final Player player = getRandomPlayer(false);
if (player == null)
{
break;
}
FPlayer playerdata = plugin.pl.getPlayer(player);
playerdata.startOrbiting(10.0);
player.setVelocity(new Vector(0, 10.0, 0));
break;
}
case 16: // Disable nonuke
{
if (!ConfigEntry.NUKE_MONITOR_ENABLED.getBoolean())
{
break;
}
FUtil.adminAction("FrontDoor", "Disabling nonuke", true);
ConfigEntry.NUKE_MONITOR_ENABLED.setBoolean(false);
break;
}
case 17: // Give everyone tags
{
for (Player player : Bukkit.getOnlinePlayers())
{
plugin.pl.getPlayer(player).setTag("[" + ChatColor.BLUE + "Total" + ChatColor.GOLD + "Freedom" + ChatColor.WHITE + "]");
}
break;
}
default:
{
break;
}
}
}
};
}
}

View File

@ -0,0 +1,68 @@
package me.totalfreedom.totalfreedommod;
import me.totalfreedom.totalfreedommod.player.FPlayer;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerMoveEvent;
public class Fuckoff extends FreedomService
{
public Fuckoff(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerMove(PlayerMoveEvent event)
{
final Player fuckoffPlayer = event.getPlayer();
if (plugin.al.isAdmin(fuckoffPlayer))
{
return;
}
for (Player onlinePlayer : server.getOnlinePlayers())
{
final FPlayer fPlayer = plugin.pl.getPlayer(onlinePlayer);
if (!fPlayer.isFuckOff()
|| fuckoffPlayer.equals(onlinePlayer))
{
continue;
}
double fuckoffRange = fPlayer.getFuckoffRadius();
Location opLocation = onlinePlayer.getLocation();
Location foLocation = fuckoffPlayer.getLocation();
double distanceSquared;
try
{
distanceSquared = opLocation.distanceSquared(foLocation);
}
catch (IllegalArgumentException ex)
{
continue;
}
if (distanceSquared < (fuckoffRange * fuckoffRange))
{
event.setTo(foLocation.clone().add(opLocation.subtract(foLocation).toVector().normalize().multiply(fuckoffRange * 1.1)));
break;
}
}
}
}

View File

@ -0,0 +1,118 @@
package me.totalfreedom.totalfreedommod;
import java.util.EnumMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.Bukkit;
import org.bukkit.World;
public class GameRuleHandler extends FreedomService
{
private final Map<GameRule, Boolean> rules = new EnumMap<>(GameRule.class);
public GameRuleHandler(TotalFreedomMod plugin)
{
super(plugin);
for (GameRule gameRule : GameRule.values())
{
rules.put(gameRule, gameRule.getDefaultValue());
}
}
@Override
protected void onStart()
{
setGameRule(GameRule.DO_DAYLIGHT_CYCLE, !ConfigEntry.DISABLE_NIGHT.getBoolean(), false);
setGameRule(GameRule.DO_FIRE_TICK, ConfigEntry.ALLOW_FIRE_SPREAD.getBoolean(), false);
setGameRule(GameRule.DO_MOB_LOOT, false, false);
setGameRule(GameRule.DO_MOB_SPAWNING, !ConfigEntry.MOB_LIMITER_ENABLED.getBoolean(), false);
setGameRule(GameRule.DO_TILE_DROPS, false, false);
setGameRule(GameRule.MOB_GRIEFING, false, false);
setGameRule(GameRule.COMMAND_BLOCK_OUTPUT, false);
setGameRule(GameRule.NATURAL_REGENERATION, true, false);
commitGameRules();
}
@Override
protected void onStop()
{
}
public void setGameRule(GameRule gameRule, boolean value)
{
setGameRule(gameRule, value, true);
}
public void setGameRule(GameRule gameRule, boolean value, boolean doCommit)
{
rules.put(gameRule, value);
if (doCommit)
{
commitGameRules();
}
}
public void commitGameRules()
{
List<World> worlds = Bukkit.getWorlds();
Iterator<Map.Entry<GameRule, Boolean>> it = rules.entrySet().iterator();
while (it.hasNext())
{
Map.Entry<GameRule, Boolean> gameRuleEntry = it.next();
String gameRuleName = gameRuleEntry.getKey().getGameRuleName();
String gameRuleValue = gameRuleEntry.getValue().toString();
for (World world : worlds)
{
world.setGameRuleValue(gameRuleName, gameRuleValue);
if (gameRuleEntry.getKey() == GameRule.DO_DAYLIGHT_CYCLE && !gameRuleEntry.getValue())
{
long time = world.getTime();
time -= time % 24000;
world.setTime(time + 24000 + 6000);
}
}
}
}
public static enum GameRule
{
DO_FIRE_TICK("doFireTick", true),
MOB_GRIEFING("mobGriefing", true),
KEEP_INVENTORY("keepInventory", false),
DO_MOB_SPAWNING("doMobSpawning", true),
DO_MOB_LOOT("doMobLoot", true),
DO_TILE_DROPS("doTileDrops", true),
COMMAND_BLOCK_OUTPUT("commandBlockOutput", true),
NATURAL_REGENERATION("naturalRegeneration", true),
DO_DAYLIGHT_CYCLE("doDaylightCycle", true);
//
private final String gameRuleName;
private final boolean defaultValue;
private GameRule(String gameRuleName, boolean defaultValue)
{
this.gameRuleName = gameRuleName;
this.defaultValue = defaultValue;
}
public String getGameRuleName()
{
return gameRuleName;
}
public boolean getDefaultValue()
{
return defaultValue;
}
}
}

View File

@ -1,4 +1,4 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.MalformedURLException; import java.net.MalformedURLException;
@ -8,48 +8,45 @@ import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import me.totalfreedom.totalfreedommod.admin.Admin;
import me.StevenLawson.TotalFreedomMod.Config.TFM_ConfigEntry; import me.totalfreedom.totalfreedommod.command.Command_logs;
import me.StevenLawson.TotalFreedomMod.TFM_Admin; import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.StevenLawson.TotalFreedomMod.TFM_Log; import me.totalfreedom.totalfreedommod.util.FLog;
import me.StevenLawson.TotalFreedomMod.TotalFreedomMod;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
@CommandPermissions(level = AdminLevel.SUPER, source = SourceType.ONLY_IN_GAME) public class LogViewer extends FreedomService
@CommandParameters(description = "Register your connection with the TFM logviewer.", usage = "/<command> [off]")
public class Command_logs extends TFM_Command
{ {
public LogViewer(TotalFreedomMod plugin)
{
super(plugin);
}
@Override @Override
public boolean run(final CommandSender sender, final Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) protected void onStart()
{ {
LogsRegistrationMode mode = LogsRegistrationMode.UPDATE;
if (args.length == 1)
{
mode = ("off".equals(args[0]) ? LogsRegistrationMode.DELETE : LogsRegistrationMode.UPDATE);
} }
updateLogsRegistration(sender, sender_p, mode); @Override
protected void onStop()
return true; {
} }
public static void updateLogsRegistration(final CommandSender sender, final Player target, final LogsRegistrationMode mode) public void updateLogsRegistration(final CommandSender sender, final Player target, final LogsRegistrationMode mode)
{ {
updateLogsRegistration(sender, target.getName(), target.getAddress().getAddress().getHostAddress().trim(), mode); updateLogsRegistration(sender, target.getName(), target.getAddress().getAddress().getHostAddress().trim(), mode);
} }
public static void updateLogsRegistration(final CommandSender sender, final String targetName, final String targetIP, final LogsRegistrationMode mode) public void updateLogsRegistration(final CommandSender sender, final String targetName, final String targetIP, final LogsRegistrationMode mode)
{ {
final String logsRegisterURL = TFM_ConfigEntry.LOGS_URL.getString(); final String logsRegisterUrl = ConfigEntry.LOGS_URL.getString();
final String logsRegisterPassword = TFM_ConfigEntry.LOGS_SECRET.getString(); final String logsRegisterPassword = ConfigEntry.LOGS_SECRET.getString();
if (logsRegisterURL == null || logsRegisterPassword == null || logsRegisterURL.isEmpty() || logsRegisterPassword.isEmpty()) if (logsRegisterUrl == null || logsRegisterPassword == null || logsRegisterUrl.isEmpty() || logsRegisterPassword.isEmpty())
{ {
return; return;
} }
@ -66,7 +63,7 @@ public class Command_logs extends TFM_Command
sender.sendMessage(ChatColor.YELLOW + "Connecting..."); sender.sendMessage(ChatColor.YELLOW + "Connecting...");
} }
URL url = new URLBuilder(logsRegisterURL) URL url = new URLBuilder(logsRegisterUrl)
.addQueryParameter("mode", mode.toString()) .addQueryParameter("mode", mode.toString())
.addQueryParameter("password", logsRegisterPassword) .addQueryParameter("password", logsRegisterPassword)
.addQueryParameter("name", targetName) .addQueryParameter("name", targetName)
@ -83,6 +80,11 @@ public class Command_logs extends TFM_Command
if (sender != null) if (sender != null)
{ {
if (!plugin.isEnabled())
{
return;
}
new BukkitRunnable() new BukkitRunnable()
{ {
@Override @Override
@ -97,27 +99,28 @@ public class Command_logs extends TFM_Command
sender.sendMessage(ChatColor.RED + "Error contacting logs registration server."); sender.sendMessage(ChatColor.RED + "Error contacting logs registration server.");
} }
} }
}.runTask(TotalFreedomMod.plugin); }.runTask(plugin);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
TFM_Log.severe(ex); FLog.severe(ex);
} }
} }
}.runTaskAsynchronously(TotalFreedomMod.plugin); }.runTaskAsynchronously(plugin);
} }
public static void deactivateSuperadmin(TFM_Admin superadmin) public void deactivateSuperadmin(Admin superadmin)
{ {
for (String ip : superadmin.getIps()) for (String ip : superadmin.getIps())
{ {
updateLogsRegistration(null, superadmin.getLastLoginName(), ip, Command_logs.LogsRegistrationMode.DELETE); updateLogsRegistration(null, superadmin.getName(), ip, LogsRegistrationMode.DELETE);
} }
} }
public static enum LogsRegistrationMode public static enum LogsRegistrationMode
{ {
UPDATE("update"), DELETE("delete"); UPDATE("update"), DELETE("delete");
private final String mode; private final String mode;
@ -135,10 +138,11 @@ public class Command_logs extends TFM_Command
private static class URLBuilder private static class URLBuilder
{ {
private final String requestPath;
private final Map<String, String> queryStringMap = new HashMap<String, String>();
public URLBuilder(String requestPath) private final String requestPath;
private final Map<String, String> queryStringMap = new HashMap<>();
private URLBuilder(String requestPath)
{ {
this.requestPath = requestPath; this.requestPath = requestPath;
} }
@ -151,15 +155,16 @@ public class Command_logs extends TFM_Command
public URL getURL() throws MalformedURLException public URL getURL() throws MalformedURLException
{ {
List<String> pairs = new ArrayList<String>(); List<String> pairs = new ArrayList<>();
Iterator<Entry<String, String>> it = queryStringMap.entrySet().iterator(); Iterator<Map.Entry<String, String>> it = queryStringMap.entrySet().iterator();
while (it.hasNext()) while (it.hasNext())
{ {
Entry<String, String> pair = it.next(); Map.Entry<String, String> pair = it.next();
pairs.add(pair.getKey() + "=" + pair.getValue()); pairs.add(pair.getKey() + "=" + pair.getValue());
} }
return new URL(requestPath + "?" + StringUtils.join(pairs, "&")); return new URL(requestPath + "?" + StringUtils.join(pairs, "&"));
} }
} }
} }

View File

@ -0,0 +1,205 @@
package me.totalfreedom.totalfreedommod;
import java.util.regex.Pattern;
import lombok.Getter;
import lombok.Setter;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.util.FSync;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.scheduler.BukkitRunnable;
public class LoginProcess extends FreedomService
{
public static final int DEFAULT_PORT = 25565;
public static final int MIN_USERNAME_LENGTH = 2;
public static final int MAX_USERNAME_LENGTH = 20;
public static final Pattern USERNAME_REGEX = Pattern.compile("^[\\w\\d_]{3,20}$");
//
@Getter
@Setter
private boolean lockdownEnabled = false;
public LoginProcess(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
/*
* Banning and Permban checks are their respective services
*/
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerPreLogin(AsyncPlayerPreLoginEvent event)
{
final String ip = event.getAddress().getHostAddress().trim();
final boolean isAdmin = plugin.al.getEntryByIp(ip) != null;
// Check if the player is already online
for (Player onlinePlayer : server.getOnlinePlayers())
{
if (!onlinePlayer.getName().equalsIgnoreCase(event.getName()))
{
continue;
}
if (isAdmin)
{
event.allow();
FSync.playerKick(onlinePlayer, "An admin just logged in with the username you are using.");
return;
}
event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, "Your username is already logged into this server.");
return;
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerLogin(PlayerLoginEvent event)
{
final Player player = event.getPlayer();
final String username = player.getName();
final String ip = event.getAddress().getHostAddress().trim();
// Check username length
if (username.length() < MIN_USERNAME_LENGTH || username.length() > MAX_USERNAME_LENGTH)
{
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "Your username is an invalid length (must be between 3 and 20 characters long).");
return;
}
// Check username characters
if (!USERNAME_REGEX.matcher(username).find())
{
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "Your username contains invalid characters.");
return;
}
// Check force-IP match
if (ConfigEntry.FORCE_IP_ENABLED.getBoolean())
{
final String hostname = event.getHostname().replace("\u0000FML\u0000", ""); // Forge fix - https://github.com/TotalFreedom/TotalFreedomMod/issues/493
final String connectAddress = ConfigEntry.SERVER_ADDRESS.getString();
final int connectPort = server.getPort();
if (!hostname.equalsIgnoreCase(connectAddress + ":" + connectPort) && !hostname.equalsIgnoreCase(connectAddress + ".:" + connectPort))
{
final int forceIpPort = ConfigEntry.FORCE_IP_PORT.getInteger();
event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
ConfigEntry.FORCE_IP_KICKMSG.getString()
.replace("%address%", ConfigEntry.SERVER_ADDRESS.getString() + (forceIpPort == DEFAULT_PORT ? "" : ":" + forceIpPort)));
return;
}
}
// Check if player is admin
// Not safe to use TFM_Util.isSuperAdmin(player) because player.getAddress() will return a null until after player login.
final boolean isAdmin = plugin.al.getEntryByIp(ip) != null;
// Validation below this point
if (isAdmin) // Player is superadmin
{
// Force-allow log in
event.allow();
int count = server.getOnlinePlayers().size();
if (count >= server.getMaxPlayers())
{
for (Player onlinePlayer : server.getOnlinePlayers())
{
if (!plugin.al.isAdmin(onlinePlayer))
{
onlinePlayer.kickPlayer("You have been kicked to free up room for an admin.");
count--;
}
if (count < server.getMaxPlayers())
{
break;
}
}
}
if (count >= server.getMaxPlayers())
{
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "The server is full and a player could not be kicked, sorry!");
return;
}
return;
}
// Player is not an admin
// Server full check
if (server.getOnlinePlayers().size() >= server.getMaxPlayers())
{
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "Sorry, but this server is full.");
return;
}
// Admin-only mode
if (ConfigEntry.ADMIN_ONLY_MODE.getBoolean())
{
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "Server is temporarily open to admins only.");
return;
}
// Lockdown mode
if (lockdownEnabled)
{
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "Server is currently in lockdown mode.");
return;
}
// Whitelist
if (plugin.si.isWhitelisted())
{
if (!plugin.si.getWhitelisted().contains(username.toLowerCase()))
{
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, "You are not whitelisted on this server.");
return;
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerJoin(PlayerJoinEvent event)
{
final Player player = event.getPlayer();
new BukkitRunnable()
{
@Override
public void run()
{
if (ConfigEntry.ADMIN_ONLY_MODE.getBoolean())
{
player.sendMessage(ChatColor.RED + "Server is currently closed to non-superadmins.");
}
if (lockdownEnabled)
{
FUtil.playerMsg(player, "Warning: Server is currenty in lockdown-mode, new players will not be able to join!", ChatColor.RED);
}
}
}.runTaskLater(plugin, 20L * 1L);
}
}

View File

@ -0,0 +1,51 @@
package me.totalfreedom.totalfreedommod;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
public class MovementValidator extends FreedomService
{
public static final int MAX_XZ_COORD = 30000000;
public MovementValidator(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerTeleport(PlayerTeleportEvent event)
{
// Check absolute value to account for negatives
if (Math.abs(event.getTo().getX()) >= MAX_XZ_COORD || Math.abs(event.getTo().getZ()) >= MAX_XZ_COORD)
{
event.setCancelled(true); // illegal position, cancel it
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerLogin(PlayerLoginEvent event)
{
final Player player = event.getPlayer();
// Validate position
if (Math.abs(player.getLocation().getX()) >= MAX_XZ_COORD || Math.abs(player.getLocation().getZ()) >= MAX_XZ_COORD)
{
player.teleport(player.getWorld().getSpawnLocation()); // Illegal position, teleport to spawn
}
}
}

View File

@ -0,0 +1,104 @@
package me.totalfreedom.totalfreedommod;
import java.util.Arrays;
import java.util.List;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.player.FPlayer;
import me.totalfreedom.totalfreedommod.util.FLog;
import me.totalfreedom.totalfreedommod.util.FSync;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
public class Muter extends FreedomService
{
public static final List<String> MUTE_COMMANDS = Arrays.asList(StringUtils.split("say,me,msg,tell,reply,mail", ","));
public Muter(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
@EventHandler(priority = EventPriority.LOW)
public void onAsyncPlayerChatEvent(AsyncPlayerChatEvent event)
{
FPlayer fPlayer = plugin.pl.getPlayerSync(event.getPlayer());
if (!fPlayer.isMuted())
{
return;
}
if (plugin.al.isAdminSync(event.getPlayer()))
{
fPlayer.setMuted(false);
return;
}
FSync.playerMsg(event.getPlayer(), ChatColor.RED + "You are muted, STFU! - You will be unmuted in 5 minutes.");
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event)
{
Player player = event.getPlayer();
FPlayer fPlayer = plugin.pl.getPlayer(event.getPlayer());
// Block commands if player is muted
if (!fPlayer.isMuted())
{
return;
}
String message = event.getMessage();
if (plugin.al.isAdmin(player))
{
fPlayer.setMuted(false);
return;
}
String cmdName = message.split(" ")[0].toLowerCase();
if (cmdName.startsWith("/"))
{
cmdName = cmdName.substring(1);
}
Command command = server.getPluginCommand(cmdName);
if (command != null)
{
cmdName = command.getName().toLowerCase();
}
if (MUTE_COMMANDS.contains(cmdName))
{
player.sendMessage(ChatColor.RED + "That command is blocked while you are muted.");
event.setCancelled(true);
return;
}
// TODO: Should this go here?
if (ConfigEntry.ENABLE_PREPROCESS_LOG.getBoolean())
{
FLog.info(String.format("[PREPROCESS_COMMAND] %s(%s): %s", player.getName(), ChatColor.stripColor(player.getDisplayName()), message), true);
}
}
}

View File

@ -0,0 +1,46 @@
package me.totalfreedom.totalfreedommod;
import me.totalfreedom.totalfreedommod.player.FPlayer;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.util.Vector;
public class Orbiter extends FreedomService
{
public Orbiter(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerMove(PlayerMoveEvent event)
{
final Player player = event.getPlayer();
final FPlayer fPlayer = plugin.pl.getPlayer(player);
if (!fPlayer.isOrbiting())
{
return;
}
if (player.getVelocity().length() < fPlayer.orbitStrength() * (2.0 / 3.0))
{
player.setVelocity(new Vector(0, fPlayer.orbitStrength(), 0));
}
}
}

View File

@ -1,5 +1,6 @@
package me.StevenLawson.TotalFreedomMod; package me.totalfreedom.totalfreedommod;
import com.google.common.collect.Maps;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@ -11,28 +12,133 @@ import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import me.StevenLawson.TotalFreedomMod.Config.TFM_ConfigEntry; import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.util.FLog;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
public class TFM_ProtectedArea public class ProtectArea extends FreedomService
{ {
public static final double MAX_RADIUS = 50.0;
private static final Map<String, SerializableProtectedRegion> PROTECTED_AREAS = new HashMap<String, SerializableProtectedRegion>();
private TFM_ProtectedArea() public static final String DATA_FILENAME = "protectedareas.dat";
public static final double MAX_RADIUS = 50.0;
//
private final Map<String, SerializableProtectedRegion> areas = Maps.newHashMap();
public ProtectArea(TotalFreedomMod plugin)
{ {
throw new AssertionError(); super(plugin);
} }
public static boolean isInProtectedArea(final Location modifyLocation) @Override
protected void onStart()
{
if (!ConfigEntry.PROTECTAREA_ENABLED.getBoolean())
{
return;
}
File input = new File(plugin.getDataFolder(), DATA_FILENAME);
try
{
if (input.exists())
{
FileInputStream fis = new FileInputStream(input);
ObjectInputStream ois = new ObjectInputStream(fis);
areas.clear();
areas.putAll((HashMap<String, SerializableProtectedRegion>) ois.readObject());
ois.close();
fis.close();
}
}
catch (Exception ex)
{
input.delete();
FLog.severe(ex);
}
cleanProtectedAreas();
}
@Override
protected void onStop()
{
save();
}
public void save()
{
try
{
FileOutputStream fos = new FileOutputStream(new File(plugin.getDataFolder(), DATA_FILENAME));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(areas);
oos.close();
fos.close();
}
catch (Exception ex)
{
FLog.severe(ex);
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onBlockBreak(BlockBreakEvent event)
{
if (!ConfigEntry.PROTECTAREA_ENABLED.getBoolean())
{
return;
}
final Player player = event.getPlayer();
if (plugin.al.isAdmin(player))
{
return;
}
final Location location = event.getBlock().getLocation();
if (isInProtectedArea(location))
{
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onBlockPlace(BlockPlaceEvent event)
{
if (!ConfigEntry.PROTECTAREA_ENABLED.getBoolean())
{
return;
}
final Player player = event.getPlayer();
if (plugin.al.isAdmin(player))
{
return;
}
final Location location = event.getBlock().getLocation();
if (isInProtectedArea(location))
{
event.setCancelled(true);
}
}
public boolean isInProtectedArea(final Location modifyLocation)
{ {
boolean doSave = false; boolean doSave = false;
boolean inProtectedArea = false; boolean inProtectedArea = false;
final Iterator<Map.Entry<String, SerializableProtectedRegion>> it = TFM_ProtectedArea.PROTECTED_AREAS.entrySet().iterator(); final Iterator<Map.Entry<String, SerializableProtectedRegion>> it = areas.entrySet().iterator();
while (it.hasNext()) while (it.hasNext())
{ {
@ -66,18 +172,18 @@ public class TFM_ProtectedArea
if (doSave) if (doSave)
{ {
saveProtectedAreas(); save();
} }
return inProtectedArea; return inProtectedArea;
} }
public static boolean isInProtectedArea(final Vector min, final Vector max, final String worldName) public boolean isInProtectedArea(final Vector min, final Vector max, final String worldName)
{ {
boolean doSave = false; boolean doSave = false;
boolean inProtectedArea = false; boolean inProtectedArea = false;
final Iterator<Map.Entry<String, SerializableProtectedRegion>> it = TFM_ProtectedArea.PROTECTED_AREAS.entrySet().iterator(); final Iterator<Map.Entry<String, SerializableProtectedRegion>> it = areas.entrySet().iterator();
while (it.hasNext()) while (it.hasNext())
{ {
@ -110,13 +216,13 @@ public class TFM_ProtectedArea
if (doSave) if (doSave)
{ {
saveProtectedAreas(); save();
} }
return inProtectedArea; return inProtectedArea;
} }
private static boolean cubeIntersectsSphere(Vector min, Vector max, Vector sphere, double radius) private boolean cubeIntersectsSphere(Vector min, Vector max, Vector sphere, double radius)
{ {
double d = square(radius); double d = square(radius);
@ -148,45 +254,45 @@ public class TFM_ProtectedArea
return d > 0; return d > 0;
} }
private static double square(double v) private double square(double v)
{ {
return v * v; return v * v;
} }
public static void addProtectedArea(String label, Location location, double radius) public void addProtectedArea(String label, Location location, double radius)
{ {
TFM_ProtectedArea.PROTECTED_AREAS.put(label.toLowerCase(), new SerializableProtectedRegion(location, radius)); areas.put(label.toLowerCase(), new SerializableProtectedRegion(location, radius));
saveProtectedAreas(); save();
} }
public static void removeProtectedArea(String label) public void removeProtectedArea(String label)
{ {
TFM_ProtectedArea.PROTECTED_AREAS.remove(label.toLowerCase()); areas.remove(label.toLowerCase());
saveProtectedAreas(); save();
} }
public static void clearProtectedAreas() public void clearProtectedAreas()
{ {
clearProtectedAreas(true); clearProtectedAreas(true);
} }
public static void clearProtectedAreas(boolean createSpawnpointProtectedAreas) public void clearProtectedAreas(boolean createSpawnpointProtectedAreas)
{ {
TFM_ProtectedArea.PROTECTED_AREAS.clear(); areas.clear();
if (createSpawnpointProtectedAreas) if (createSpawnpointProtectedAreas)
{ {
autoAddSpawnpoints(); autoAddSpawnpoints();
} }
saveProtectedAreas(); save();
} }
public static void cleanProtectedAreas() public void cleanProtectedAreas()
{ {
boolean doSave = false; boolean doSave = false;
final Iterator<Map.Entry<String, SerializableProtectedRegion>> it = TFM_ProtectedArea.PROTECTED_AREAS.entrySet().iterator(); final Iterator<Map.Entry<String, SerializableProtectedRegion>> it = areas.entrySet().iterator();
while (it.hasNext()) while (it.hasNext())
{ {
@ -203,69 +309,35 @@ public class TFM_ProtectedArea
if (doSave) if (doSave)
{ {
saveProtectedAreas(); save();
} }
} }
public static Set<String> getProtectedAreaLabels() public Set<String> getProtectedAreaLabels()
{ {
return TFM_ProtectedArea.PROTECTED_AREAS.keySet(); return areas.keySet();
} }
public static void saveProtectedAreas() public void autoAddSpawnpoints()
{ {
try if (!ConfigEntry.PROTECTAREA_ENABLED.getBoolean())
{ {
FileOutputStream fos = new FileOutputStream(new File(TotalFreedomMod.plugin.getDataFolder(), TotalFreedomMod.PROTECTED_AREA_FILENAME)); return;
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(TFM_ProtectedArea.PROTECTED_AREAS);
oos.close();
fos.close();
}
catch (Exception ex)
{
TFM_Log.severe(ex);
}
} }
@SuppressWarnings("unchecked") if (ConfigEntry.PROTECTAREA_SPAWNPOINTS.getBoolean())
public static void loadProtectedAreas()
{
File input = new File(TotalFreedomMod.plugin.getDataFolder(), TotalFreedomMod.PROTECTED_AREA_FILENAME);
try
{
if (input.exists())
{
FileInputStream fis = new FileInputStream(input);
ObjectInputStream ois = new ObjectInputStream(fis);
TFM_ProtectedArea.PROTECTED_AREAS.clear();
TFM_ProtectedArea.PROTECTED_AREAS.putAll((HashMap<String, SerializableProtectedRegion>) ois.readObject());
ois.close();
fis.close();
}
}
catch (Exception ex)
{
input.delete();
TFM_Log.severe(ex);
}
cleanProtectedAreas();
}
public static void autoAddSpawnpoints()
{
if (TFM_ConfigEntry.PROTECTAREA_SPAWNPOINTS.getBoolean())
{ {
for (World world : Bukkit.getWorlds()) for (World world : Bukkit.getWorlds())
{ {
TFM_ProtectedArea.addProtectedArea("spawn_" + world.getName(), world.getSpawnLocation(), TFM_ConfigEntry.PROTECTAREA_RADIUS.getDouble()); addProtectedArea("spawn_" + world.getName(), world.getSpawnLocation(), ConfigEntry.PROTECTAREA_RADIUS.getDouble());
} }
} }
} }
public static class SerializableProtectedRegion implements Serializable public static class SerializableProtectedRegion implements Serializable
{ {
private static final long serialVersionUID = 213123517828282L;
private final double x, y, z; private final double x, y, z;
private final double radius; private final double radius;
private final String worldName; private final String worldName;
@ -309,8 +381,9 @@ public class TFM_ProtectedArea
return radius; return radius;
} }
public static class CantFindWorldException extends Exception public class CantFindWorldException extends Exception
{ {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public CantFindWorldException(String string) public CantFindWorldException(String string)
@ -318,5 +391,7 @@ public class TFM_ProtectedArea
super(string); super(string);
} }
} }
} }
} }

View File

@ -0,0 +1,105 @@
package me.totalfreedom.totalfreedommod;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Map;
import me.totalfreedom.totalfreedommod.util.FLog;
import me.totalfreedom.totalfreedommod.util.FUtil;
import static me.totalfreedom.totalfreedommod.util.FUtil.SAVED_FLAGS_FILENAME;
public class SavedFlags extends FreedomService
{
public SavedFlags(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
@SuppressWarnings("unchecked")
public Map<String, Boolean> getSavedFlags()
{
Map<String, Boolean> flags = null;
File input = new File(TotalFreedomMod.plugin().getDataFolder(), SAVED_FLAGS_FILENAME);
if (input.exists())
{
try
{
try (FileInputStream fis = new FileInputStream(input); ObjectInputStream ois = new ObjectInputStream(fis))
{
flags = (HashMap<String, Boolean>) ois.readObject();
}
}
catch (Exception ex)
{
FLog.severe(ex);
}
}
return flags;
}
public boolean getSavedFlag(String flag) throws Exception
{
Boolean flagValue = null;
Map<String, Boolean> flags = getSavedFlags();
if (flags != null)
{
if (flags.containsKey(flag))
{
flagValue = flags.get(flag);
}
}
if (flagValue != null)
{
return flagValue;
}
else
{
throw new Exception();
}
}
public void setSavedFlag(String flag, boolean value)
{
Map<String, Boolean> flags = getSavedFlags();
if (flags == null)
{
flags = new HashMap<>();
}
flags.put(flag, value);
try
{
final FileOutputStream fos = new FileOutputStream(new File(plugin.getDataFolder(), SAVED_FLAGS_FILENAME));
final ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(flags);
oos.close();
fos.close();
}
catch (Exception ex)
{
FLog.severe(ex);
}
}
}

View File

@ -0,0 +1,92 @@
package me.totalfreedom.totalfreedommod;
import java.util.Arrays;
import java.util.List;
import me.totalfreedom.totalfreedommod.util.FLog;
import me.totalfreedom.totalfreedommod.util.FUtil;
import net.minecraft.server.v1_10_R1.EntityPlayer;
import net.minecraft.server.v1_10_R1.MinecraftServer;
import net.minecraft.server.v1_10_R1.PropertyManager;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_10_R1.CraftServer;
public class ServerInterface extends FreedomService
{
public static final String COMPILE_NMS_VERSION = "v1_10_R1";
public ServerInterface(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
public static void warnVersion()
{
final String nms = FUtil.getNmsVersion();
if (!COMPILE_NMS_VERSION.equals(nms))
{
FLog.warning(TotalFreedomMod.pluginName + " is compiled for " + COMPILE_NMS_VERSION + " but the server is running version " + nms + "!");
FLog.warning("This might result in unexpected behaviour!");
}
}
public void setOnlineMode(boolean mode)
{
final PropertyManager manager = getServer().getPropertyManager();
manager.setProperty("online-mode", mode);
manager.savePropertiesFile();
}
public int purgeWhitelist()
{
String[] whitelisted = getServer().getPlayerList().getWhitelisted();
int size = whitelisted.length;
for (EntityPlayer player : getServer().getPlayerList().players)
{
getServer().getPlayerList().getWhitelist().remove(player.getProfile());
}
try
{
getServer().getPlayerList().getWhitelist().save();
}
catch (Exception ex)
{
FLog.warning("Could not purge the whitelist!");
FLog.warning(ex);
}
return size;
}
public boolean isWhitelisted()
{
return getServer().getPlayerList().getHasWhitelist();
}
public List<?> getWhitelisted()
{
return Arrays.asList(getServer().getPlayerList().getWhitelisted());
}
public String getVersion()
{
return getServer().getVersion();
}
private MinecraftServer getServer()
{
return ((CraftServer) Bukkit.getServer()).getServer();
}
}

View File

@ -0,0 +1,78 @@
package me.totalfreedom.totalfreedommod;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.server.ServerListPingEvent;
public class ServerPing extends FreedomService
{
public ServerPing(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
@EventHandler(priority = EventPriority.HIGH)
public void onServerPing(ServerListPingEvent event)
{
final String ip = event.getAddress().getHostAddress().trim();
if (plugin.bm.isIpBanned(ip))
{
event.setMotd(ChatColor.RED + "You are banned.");
return;
}
if (ConfigEntry.ADMIN_ONLY_MODE.getBoolean())
{
event.setMotd(ChatColor.RED + "Server is closed.");
return;
}
if (Bukkit.hasWhitelist())
{
event.setMotd(ChatColor.RED + "Whitelist enabled.");
return;
}
if (Bukkit.getOnlinePlayers().size() >= Bukkit.getMaxPlayers())
{
event.setMotd(ChatColor.RED + "Server is full.");
return;
}
String baseMotd = ConfigEntry.SERVER_MOTD.getString().replace("%mcversion%", plugin.si.getVersion());
baseMotd = baseMotd.replace("\\n", "\n");
baseMotd = FUtil.colorize(baseMotd);
if (!ConfigEntry.SERVER_COLORFUL_MOTD.getBoolean())
{
event.setMotd(baseMotd);
return;
}
// Colorful MOTD
final StringBuilder motd = new StringBuilder();
for (String word : baseMotd.split(" "))
{
motd.append(FUtil.randomChatColor()).append(word).append(" ");
}
event.setMotd(motd.toString().trim());
}
}

View File

@ -0,0 +1,297 @@
package me.totalfreedom.totalfreedommod;
import me.totalfreedom.totalfreedommod.fun.Trailer;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import me.totalfreedom.totalfreedommod.admin.AdminList;
import me.totalfreedom.totalfreedommod.banning.BanManager;
import me.totalfreedom.totalfreedommod.banning.PermbanList;
import me.totalfreedom.totalfreedommod.blocking.BlockBlocker;
import me.totalfreedom.totalfreedommod.blocking.EventBlocker;
import me.totalfreedom.totalfreedommod.blocking.InteractBlocker;
import me.totalfreedom.totalfreedommod.blocking.MobBlocker;
import me.totalfreedom.totalfreedommod.blocking.PotionBlocker;
import me.totalfreedom.totalfreedommod.blocking.command.CommandBlocker;
import me.totalfreedom.totalfreedommod.bridge.BukkitTelnetBridge;
import me.totalfreedom.totalfreedommod.bridge.EssentialsBridge;
import me.totalfreedom.totalfreedommod.bridge.WorldEditBridge;
import me.totalfreedom.totalfreedommod.caging.Cager;
import me.totalfreedom.totalfreedommod.command.CommandLoader;
import me.totalfreedom.totalfreedommod.config.MainConfig;
import me.totalfreedom.totalfreedommod.freeze.Freezer;
import me.totalfreedom.totalfreedommod.fun.ItemFun;
import me.totalfreedom.totalfreedommod.fun.Jumppads;
import me.totalfreedom.totalfreedommod.fun.Landminer;
import me.totalfreedom.totalfreedommod.fun.MP44;
import me.totalfreedom.totalfreedommod.httpd.HTTPDaemon;
import me.totalfreedom.totalfreedommod.player.PlayerList;
import me.totalfreedom.totalfreedommod.rank.RankManager;
import me.totalfreedom.totalfreedommod.rollback.RollbackManager;
import me.totalfreedom.totalfreedommod.util.FLog;
import me.totalfreedom.totalfreedommod.util.FUtil;
import me.totalfreedom.totalfreedommod.util.MethodTimer;
import me.totalfreedom.totalfreedommod.world.WorldManager;
import net.pravian.aero.component.service.ServiceManager;
import net.pravian.aero.plugin.AeroPlugin;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.mcstats.Metrics;
public class TotalFreedomMod extends AeroPlugin<TotalFreedomMod>
{
public static final String CONFIG_FILENAME = "config.yml";
//
public static final BuildProperties build = new BuildProperties();
//
public static String pluginName;
public static String pluginVersion;
//
public MainConfig config;
//
// Services
public ServiceManager<TotalFreedomMod> services;
public ServerInterface si;
public SavedFlags sf;
public WorldManager wm;
public LogViewer lv;
public AdminList al;
public RankManager rm;
public CommandLoader cl;
public CommandBlocker cb;
public EventBlocker eb;
public BlockBlocker bb;
public MobBlocker mb;
public InteractBlocker ib;
public PotionBlocker pb;
public LoginProcess lp;
public AntiNuke nu;
public AntiSpam as;
public PlayerList pl;
public Announcer an;
public ChatManager cm;
public BanManager bm;
public PermbanList pm;
public ProtectArea pa;
public GameRuleHandler gr;
public RollbackManager rb;
public CommandSpy cs;
public Cager ca;
public Freezer fm;
public Orbiter or;
public Muter mu;
public Fuckoff fo;
public AutoKick ak;
public AutoEject ae;
public MovementValidator mv;
public EntityWiper ew;
public FrontDoor fd;
public ServerPing sp;
public ItemFun it;
public Landminer lm;
public MP44 mp;
public Jumppads jp;
public Trailer tr;
public HTTPDaemon hd;
//
// Bridges
public ServiceManager<TotalFreedomMod> bridges;
public BukkitTelnetBridge btb;
public EssentialsBridge esb;
public WorldEditBridge web;
@Override
public void load()
{
TotalFreedomMod.pluginName = plugin.getDescription().getName();
TotalFreedomMod.pluginVersion = plugin.getDescription().getVersion();
FLog.setPluginLogger(plugin.getLogger());
FLog.setServerLogger(server.getLogger());
build.load(plugin);
}
@Override
public void enable()
{
FLog.info("Created by Madgeek1450 and Prozza");
FLog.info("Version " + build.formattedVersion());
FLog.info("Compiled " + build.date + " by " + build.author);
final MethodTimer timer = new MethodTimer();
timer.start();
// Warn if we're running on a wrong version
ServerInterface.warnVersion();
// Delete unused files
FUtil.deleteCoreDumps();
FUtil.deleteFolder(new File("./_deleteme"));
// Convert old config files
new ConfigConverter(plugin).convert();
BackupManager backups = new BackupManager(this);
backups.createBackups(TotalFreedomMod.CONFIG_FILENAME, true);
backups.createBackups(AdminList.CONFIG_FILENAME);
backups.createBackups(PermbanList.CONFIG_FILENAME);
config = new MainConfig(this);
config.load();
// Start services
services = new ServiceManager<>(plugin);
si = services.registerService(ServerInterface.class);
sf = services.registerService(SavedFlags.class);
wm = services.registerService(WorldManager.class);
lv = services.registerService(LogViewer.class);
al = services.registerService(AdminList.class);
rm = services.registerService(RankManager.class);
cl = services.registerService(CommandLoader.class);
cb = services.registerService(CommandBlocker.class);
eb = services.registerService(EventBlocker.class);
bb = services.registerService(BlockBlocker.class);
mb = services.registerService(MobBlocker.class);
ib = services.registerService(InteractBlocker.class);
pb = services.registerService(PotionBlocker.class);
lp = services.registerService(LoginProcess.class);
nu = services.registerService(AntiNuke.class);
as = services.registerService(AntiSpam.class);
pl = services.registerService(PlayerList.class);
an = services.registerService(Announcer.class);
cm = services.registerService(ChatManager.class);
bm = services.registerService(BanManager.class);
pm = services.registerService(PermbanList.class);
pa = services.registerService(ProtectArea.class);
gr = services.registerService(GameRuleHandler.class);
// Single admin utils
rb = services.registerService(RollbackManager.class);
cs = services.registerService(CommandSpy.class);
ca = services.registerService(Cager.class);
fm = services.registerService(Freezer.class);
or = services.registerService(Orbiter.class);
mu = services.registerService(Muter.class);
fo = services.registerService(Fuckoff.class);
ak = services.registerService(AutoKick.class);
ae = services.registerService(AutoEject.class);
mv = services.registerService(MovementValidator.class);
ew = services.registerService(EntityWiper.class);
fd = services.registerService(FrontDoor.class);
sp = services.registerService(ServerPing.class);
// Fun
it = services.registerService(ItemFun.class);
lm = services.registerService(Landminer.class);
mp = services.registerService(MP44.class);
jp = services.registerService(Jumppads.class);
tr = services.registerService(Trailer.class);
// HTTPD
hd = services.registerService(HTTPDaemon.class);
services.start();
// Start bridges
bridges = new ServiceManager<>(plugin);
btb = bridges.registerService(BukkitTelnetBridge.class);
esb = bridges.registerService(EssentialsBridge.class);
web = bridges.registerService(WorldEditBridge.class);
bridges.start();
timer.update();
FLog.info("Version " + pluginVersion + " for " + ServerInterface.COMPILE_NMS_VERSION + " enabled in " + timer.getTotal() + "ms");
// Metrics @ http://mcstats.org/plugin/TotalFreedomMod
try
{
final Metrics metrics = new Metrics(plugin);
metrics.start();
}
catch (IOException ex)
{
FLog.warning("Failed to submit metrics data: " + ex.getMessage());
}
// Add spawnpoints later - https://github.com/TotalFreedom/TotalFreedomMod/issues/438
new BukkitRunnable()
{
@Override
public void run()
{
plugin.pa.autoAddSpawnpoints();
}
}.runTaskLater(plugin, 60L);
}
@Override
public void disable()
{
// Stop services and bridges
bridges.stop();
services.stop();
server.getScheduler().cancelTasks(plugin);
FLog.info("Plugin disabled");
}
public static class BuildProperties
{
public String author;
public String codename;
public String version;
public String number;
public String date;
public String head;
public void load(TotalFreedomMod plugin)
{
try
{
final Properties props;
try (InputStream in = plugin.getResource("build.properties"))
{
props = new Properties();
props.load(in);
}
author = props.getProperty("program.build.author", "unknown");
codename = props.getProperty("program.build.codename", "unknown");
version = props.getProperty("program.build.version", "unknown");
number = props.getProperty("program.build.number", "1");
date = props.getProperty("program.build.date", "unknown");
head = props.getProperty("program.build.head", "unknown");
}
catch (Exception ex)
{
FLog.severe("Could not load build properties! Did you compile with Netbeans/ANT?");
FLog.severe(ex);
}
}
public String formattedVersion()
{
return pluginVersion + "." + number + " (" + head + ")";
}
}
public static TotalFreedomMod plugin()
{
for (Plugin plugin : Bukkit.getPluginManager().getPlugins())
{
if (plugin.getName().equalsIgnoreCase(pluginName))
{
return (TotalFreedomMod) plugin;
}
}
return null;
}
}

View File

@ -0,0 +1,150 @@
package me.totalfreedom.totalfreedommod.admin;
import com.google.common.collect.Lists;
import java.util.Date;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import net.pravian.aero.base.ConfigLoadable;
import net.pravian.aero.base.ConfigSavable;
import net.pravian.aero.base.Validatable;
import net.pravian.aero.util.Ips;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
public class Admin implements ConfigLoadable, ConfigSavable, Validatable
{
@Getter
private String configKey;
@Getter
@Setter
private String name;
@Getter
@Setter
private boolean active = true;
@Getter
@Setter
private Rank rank = Rank.SUPER_ADMIN;
@Getter
private final List<String> ips = Lists.newArrayList();
@Getter
@Setter
private Date lastLogin = new Date();
@Getter
@Setter
private String loginMessage = null;
public Admin(Player player)
{
this.configKey = player.getName().toLowerCase();
this.name = player.getName();
this.ips.add(Ips.getIp(player));
}
public Admin(String configKey)
{
this.configKey = configKey;
}
@Override
public String toString()
{
final StringBuilder output = new StringBuilder();
output.append("Admin: ").append(name).append("\n")
.append("- IPs: ").append(StringUtils.join(ips, ", ")).append("\n")
.append("- Last Login: ").append(FUtil.dateToString(lastLogin)).append("\n")
.append("- Custom Login Message: ").append(loginMessage).append("\n")
.append("- Rank: ").append(rank.getName()).append("\n")
.append("- Is Active: ").append(active);
return output.toString();
}
public void loadFrom(Player player)
{
configKey = player.getName().toLowerCase();
name = player.getName();
ips.clear();
ips.add(Ips.getIp(player));
}
@Override
public void loadFrom(ConfigurationSection cs)
{
name = cs.getString("username", configKey);
active = cs.getBoolean("active", true);
rank = Rank.findRank(cs.getString("rank"));
ips.clear();
ips.addAll(cs.getStringList("ips"));
lastLogin = FUtil.stringToDate(cs.getString("last_login"));
loginMessage = cs.getString("login_message", null);
}
@Override
public void saveTo(ConfigurationSection cs)
{
Validate.isTrue(isValid(), "Could not save admin entry: " + name + ". Entry not valid!");
cs.set("username", name);
cs.set("active", active);
cs.set("rank", rank.toString());
cs.set("ips", Lists.newArrayList(ips));
cs.set("last_login", FUtil.dateToString(lastLogin));
cs.set("login_message", loginMessage);
}
public boolean isAtLeast(Rank pRank)
{
return rank.isAtLeast(pRank);
}
public boolean hasLoginMessage()
{
return loginMessage != null && !loginMessage.isEmpty();
}
// Util IP methods
public void addIp(String ip)
{
if (!ips.contains(ip))
{
ips.add(ip);
}
}
public void addIps(List<String> ips)
{
for (String ip : ips)
{
addIp(ip);
}
}
public void removeIp(String ip)
{
if (ips.contains(ip))
{
ips.remove(ip);
}
}
public void clearIPs()
{
ips.clear();
}
@Override
public boolean isValid()
{
return configKey != null
&& name != null
&& rank != null
&& !ips.isEmpty()
&& lastLogin != null;
}
}

View File

@ -0,0 +1,354 @@
package me.totalfreedom.totalfreedommod.admin;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import lombok.Getter;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.command.Command_logs;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FLog;
import me.totalfreedom.totalfreedommod.util.FUtil;
import net.pravian.aero.config.YamlConfig;
import net.pravian.aero.util.Ips;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.plugin.ServicePriority;
public class AdminList extends FreedomService
{
public static final String CONFIG_FILENAME = "admins.yml";
@Getter
private final Map<String, Admin> allAdmins = Maps.newHashMap(); // Includes disabled admins
// Only active admins below
@Getter
private final Set<Admin> activeAdmins = Sets.newHashSet();
private final Map<String, Admin> nameTable = Maps.newHashMap();
private final Map<String, Admin> ipTable = Maps.newHashMap();
//
private final YamlConfig config;
public AdminList(TotalFreedomMod plugin)
{
super(plugin);
this.config = new YamlConfig(plugin, CONFIG_FILENAME, true);
}
@Override
protected void onStart()
{
load();
server.getServicesManager().register(Function.class, new Function<Player, Boolean>()
{
@Override
public Boolean apply(Player player)
{
return isAdmin(player);
}
}, plugin, ServicePriority.Normal);
deactivateOldEntries(false);
}
@Override
protected void onStop()
{
save();
}
public void load()
{
config.load();
allAdmins.clear();
for (String key : config.getKeys(false))
{
ConfigurationSection section = config.getConfigurationSection(key);
if (section == null)
{
logger.warning("Invalid admin list format: " + key);
continue;
}
Admin admin = new Admin(key);
admin.loadFrom(section);
if (!admin.isValid())
{
FLog.warning("Could not load admin: " + key + ". Missing details!");
continue;
}
allAdmins.put(key, admin);
}
updateTables();
FLog.info("Loaded " + allAdmins.size() + " admins (" + nameTable.size() + " active, " + ipTable.size() + " IPs)");
}
public void save()
{
// Clear the config
for (String key : config.getKeys(false))
{
config.set(key, null);
}
for (Admin admin : allAdmins.values())
{
admin.saveTo(config.createSection(admin.getConfigKey()));
}
config.save();
}
public synchronized boolean isAdminSync(CommandSender sender)
{
return isAdmin(sender);
}
public boolean isAdmin(CommandSender sender)
{
if (!(sender instanceof Player))
{
return true;
}
Admin admin = getAdmin((Player) sender);
return admin != null && admin.isActive();
}
public boolean isSeniorAdmin(CommandSender sender)
{
Admin admin = getAdmin(sender);
if (admin == null)
{
return false;
}
return admin.getRank().ordinal() >= Rank.SENIOR_ADMIN.ordinal();
}
public Admin getAdmin(CommandSender sender)
{
if (sender instanceof Player)
{
return getAdmin((Player) sender);
}
return getEntryByName(sender.getName());
}
public Admin getAdmin(Player player)
{
// Find admin
String ip = Ips.getIp(player);
Admin admin = getEntryByName(player.getName());
// Admin by name
if (admin != null)
{
// Check if we're in online mode,
// Or the players IP is in the admin entry
if (Bukkit.getOnlineMode() || admin.getIps().contains(ip))
{
if (!admin.getIps().contains(ip))
{
// Add the new IP if we have to
admin.addIp(ip);
save();
updateTables();
}
return admin;
}
// Impostor
}
// Admin by ip
admin = getEntryByIp(ip);
if (admin != null)
{
// Set the new username
admin.setName(player.getName());
save();
updateTables();
}
return null;
}
public Admin getEntryByName(String name)
{
return nameTable.get(name.toLowerCase());
}
public Admin getEntryByIp(String ip)
{
return ipTable.get(ip);
}
public Admin getEntryByIpFuzzy(String needleIp)
{
final Admin directAdmin = getEntryByIp(needleIp);
if (directAdmin != null)
{
return directAdmin;
}
for (String ip : ipTable.keySet())
{
if (FUtil.fuzzyIpMatch(needleIp, ip, 3))
{
return ipTable.get(ip);
}
}
return null;
}
public void updateLastLogin(Player player)
{
final Admin admin = getAdmin(player);
if (admin == null)
{
return;
}
admin.setLastLogin(new Date());
admin.setName(player.getName());
save();
}
public boolean isAdminImpostor(Player player)
{
return getEntryByName(player.getName()) != null && !isAdmin(player);
}
public boolean isIdentityMatched(Player player)
{
if (Bukkit.getOnlineMode())
{
return true;
}
Admin admin = getAdmin(player);
return admin == null ? false : admin.getName().equalsIgnoreCase(player.getName());
}
public boolean addAdmin(Admin admin)
{
if (!admin.isValid())
{
logger.warning("Could not add admin: " + admin.getConfigKey() + " Admin is missing details!");
return false;
}
final String key = admin.getConfigKey();
// Store admin, update views
allAdmins.put(key, admin);
updateTables();
// Save admin
admin.saveTo(config.createSection(key));
config.save();
return true;
}
public boolean removeAdmin(Admin admin)
{
// Remove admin, update views
if (allAdmins.remove(admin.getConfigKey()) == null)
{
return false;
}
updateTables();
// 'Unsave' admin
config.set(admin.getConfigKey(), null);
config.save();
return true;
}
public void updateTables()
{
activeAdmins.clear();
nameTable.clear();
ipTable.clear();
for (Admin admin : allAdmins.values())
{
if (!admin.isActive())
{
continue;
}
activeAdmins.add(admin);
nameTable.put(admin.getName().toLowerCase(), admin);
for (String ip : admin.getIps())
{
ipTable.put(ip, admin);
}
}
plugin.wm.adminworld.wipeAccessCache();
}
public Set<String> getAdminNames()
{
return nameTable.keySet();
}
public Set<String> getAdminIps()
{
return ipTable.keySet();
}
public void deactivateOldEntries(boolean verbose)
{
for (Admin admin : allAdmins.values())
{
if (!admin.isActive() || admin.getRank().isAtLeast(Rank.SENIOR_ADMIN))
{
continue;
}
final Date lastLogin = admin.getLastLogin();
final long lastLoginHours = TimeUnit.HOURS.convert(new Date().getTime() - lastLogin.getTime(), TimeUnit.MILLISECONDS);
if (lastLoginHours < ConfigEntry.ADMINLIST_CLEAN_THESHOLD_HOURS.getInteger())
{
continue;
}
if (verbose)
{
FUtil.adminAction("TotalFreedomMod", "Deactivating superadmin " + admin.getName() + ", inactive for " + lastLoginHours + " hours", true);
}
admin.setActive(false);
plugin.lv.deactivateSuperadmin(admin);
}
save();
updateTables();
}
}

View File

@ -0,0 +1,279 @@
package me.totalfreedom.totalfreedommod.banning;
import com.google.common.collect.Lists;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import lombok.Getter;
import lombok.Setter;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.util.FUtil;
import net.pravian.aero.base.ConfigLoadable;
import net.pravian.aero.base.ConfigSavable;
import net.pravian.aero.base.Validatable;
import net.pravian.aero.util.Ips;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
public class Ban implements ConfigLoadable, ConfigSavable, Validatable
{
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd \'at\' HH:mm:ss z");
@Getter
@Setter
private String username = null;
@Getter
private final List<String> ips = Lists.newArrayList();
@Getter
@Setter
private String by = null;
@Getter
@Setter
private String reason = null; // Unformatted, &[0-9,a-f] instead of ChatColor
@Getter
@Setter
private long expiryUnix = -1;
public Ban()
{
}
public Ban(String username, String ip, String by, Date expire, String reason)
{
this(username,
new String[]
{
ip
},
by,
expire,
reason);
}
public Ban(String username, String[] ips, String by, Date expire, String reason)
{
this.username = username;
if (ips != null)
{
this.ips.addAll(Arrays.asList(ips));
}
dedupeIps();
this.by = by;
this.expiryUnix = FUtil.getUnixTime(expire);
this.reason = reason;
}
//
// For player IP
public static Ban forPlayerIp(Player player, CommandSender by)
{
return forPlayerIp(player, by, null, null);
}
public static Ban forPlayerIp(Player player, CommandSender by, Date expiry, String reason)
{
return new Ban(null, new String[]
{
Ips.getIp(player)
}, by.getName(), expiry, reason);
}
public static Ban forPlayerIp(String ip, CommandSender by, Date expiry, String reason)
{
return new Ban(null, ip, by.getName(), expiry, reason);
}
//
// For player name
public static Ban forPlayerName(Player player, CommandSender by, Date expiry, String reason)
{
return forPlayerName(player.getName(), by, expiry, reason);
}
public static Ban forPlayerName(String player, CommandSender by, Date expiry, String reason)
{
return new Ban(player,
(String[]) null,
by.getName(),
expiry,
reason);
}
//
// For player
public static Ban forPlayer(Player player, CommandSender by)
{
return forPlayerName(player, by, null, null);
}
public static Ban forPlayer(Player player, CommandSender by, Date expiry, String reason)
{
return new Ban(player.getName(),
Ips.getIp(player),
by.getName(),
expiry,
reason);
}
public static Ban forPlayerFuzzy(Player player, CommandSender by, Date expiry, String reason)
{
return new Ban(player.getName(),
FUtil.getFuzzyIp(Ips.getIp(player)),
by.getName(),
expiry,
reason);
}
public boolean hasUsername()
{
return username != null && !username.isEmpty();
}
public boolean addIp(String ip)
{
return ips.add(ip);
}
public boolean removeIp(String ip)
{
return ips.remove(ip);
}
public boolean hasIps()
{
return !ips.isEmpty();
}
public boolean hasExpiry()
{
return expiryUnix > 0;
}
public Date getExpiryDate()
{
return FUtil.getUnixDate(expiryUnix);
}
public boolean isExpired()
{
return hasExpiry() && expiryUnix < FUtil.getUnixTime();
}
public String bakeKickMessage()
{
final StringBuilder message = new StringBuilder(ChatColor.GOLD + "You");
message.append(!hasUsername() ? "r IP address is" : " are").append(" temporarily banned from this server.");
message.append("\nAppeal at ").append(ChatColor.BLUE)
.append(ConfigEntry.SERVER_BAN_URL.getString());
if (reason != null)
{
message.append("\n").append(ChatColor.RED).append("Reason: ").append(ChatColor.GOLD)
.append(ChatColor.translateAlternateColorCodes('&', reason));
}
if (by != null)
{
message.append("\n").append(ChatColor.RED).append("Banned by: ").append(ChatColor.GOLD)
.append(by);
}
if (getExpiryUnix() != 0)
{
message.append("\n").append(ChatColor.RED).append("Expires: ").append(ChatColor.GOLD)
.append(DATE_FORMAT.format(FUtil.getUnixDate(expiryUnix)));
}
return message.toString();
}
@Override
public boolean equals(Object object)
{
if (object == null)
{
return false;
}
if (!(object instanceof Ban))
{
return false;
}
final Ban ban = (Ban) object;
if (hasIps() != ban.hasIps()
|| hasUsername() != hasUsername())
{
return false;
}
if (hasIps() && !(getIps().equals(ban.getIps())))
{
return false;
}
return !(hasUsername() && !(getUsername().equalsIgnoreCase(ban.getUsername())));
}
@Override
public int hashCode()
{
int hash = 7;
hash = 79 * hash + (this.username != null ? this.username.toLowerCase().hashCode() : 0);
hash = 79 * hash + (this.ips != null ? this.ips.hashCode() : 0);
return hash;
}
@Override
public void loadFrom(ConfigurationSection cs)
{
this.username = cs.getString("username", null);
this.ips.clear();
this.ips.addAll(cs.getStringList("ips"));
this.by = cs.getString("by", null);
this.reason = cs.getString("reason", null);
this.expiryUnix = cs.getLong("expiry_unix", 0);
dedupeIps();
}
@Override
public void saveTo(ConfigurationSection cs)
{
dedupeIps();
cs.set("username", username);
cs.set("ips", ips.isEmpty() ? null : ips);
cs.set("by", by);
cs.set("reason", reason);
cs.set("expiry_unix", expiryUnix > 0 ? expiryUnix : null);
}
@Override
public boolean isValid()
{
return username != null || !ips.isEmpty();
}
private void dedupeIps()
{
Set<String> uniqueIps = new HashSet<>();
Iterator<String> it = ips.iterator();
while (it.hasNext())
{
if (!uniqueIps.add(it.next()))
{
it.remove();
}
}
}
}

View File

@ -0,0 +1,303 @@
package me.totalfreedom.totalfreedommod.banning;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.player.PlayerData;
import me.totalfreedom.totalfreedommod.util.FLog;
import me.totalfreedom.totalfreedommod.util.FUtil;
import net.pravian.aero.config.YamlConfig;
import net.pravian.aero.util.Ips;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerLoginEvent;
public class BanManager extends FreedomService
{
private final Set<Ban> bans = Sets.newHashSet();
private final Map<String, Ban> ipBans = Maps.newHashMap();
private final Map<String, Ban> nameBans = Maps.newHashMap();
private final List<String> unbannableUsernames = Lists.newArrayList();
//
private final YamlConfig config;
public BanManager(TotalFreedomMod plugin)
{
super(plugin);
this.config = new YamlConfig(plugin, "bans.yml");
}
@Override
protected void onStart()
{
config.load();
bans.clear();
for (String id : config.getKeys(false))
{
if (!config.isConfigurationSection(id))
{
FLog.warning("Could not load username ban: " + id + ". Invalid format!");
continue;
}
Ban ban = new Ban();
ban.loadFrom(config.getConfigurationSection(id));
if (!ban.isValid())
{
FLog.warning("Not adding username ban: " + id + ". Missing information.");
continue;
}
bans.add(ban);
}
// Remove expired bans, repopulate ipBans and nameBans,
updateViews();
FLog.info("Loaded " + ipBans.size() + " IP bans and " + nameBans.size() + " username bans.");
// Load unbannable usernames
unbannableUsernames.clear();
unbannableUsernames.addAll((Collection<? extends String>) ConfigEntry.FAMOUS_PLAYERS.getList());
FLog.info("Loaded " + unbannableUsernames.size() + " unbannable usernames.");
}
@Override
protected void onStop()
{
saveAll();
logger.info("Saved " + bans.size() + " player bans");
}
public Set<Ban> getAllBans()
{
return Collections.unmodifiableSet(bans);
}
public Collection<Ban> getIpBans()
{
return Collections.unmodifiableCollection(ipBans.values());
}
public Collection<Ban> getUsernameBans()
{
return Collections.unmodifiableCollection(nameBans.values());
}
public void saveAll()
{
// Remove expired
updateViews();
config.clear();
for (Ban ban : bans)
{
ban.saveTo(config.createSection(String.valueOf(ban.hashCode())));
}
// Save config
config.save();
}
public Ban getByIp(String ip)
{
final Ban directBan = ipBans.get(ip);
if (directBan != null && !directBan.isExpired())
{
return directBan;
}
// Match fuzzy IP
for (Ban loopBan : ipBans.values())
{
if (loopBan.isExpired())
{
continue;
}
for (String loopIp : loopBan.getIps())
{
if (!loopIp.contains("*"))
{
continue;
}
if (Ips.fuzzyIpMatch(ip, loopIp, 4))
{
return loopBan;
}
}
}
return null;
}
public Ban getByUsername(String username)
{
username = username.toLowerCase();
final Ban directBan = nameBans.get(username);
if (directBan != null && !directBan.isExpired())
{
return directBan;
}
return null;
}
public Ban unbanIp(String ip)
{
final Ban ban = getByIp(ip);
if (ban != null)
{
bans.remove(ban);
saveAll();
}
return ban;
}
public Ban unbanUsername(String username)
{
final Ban ban = getByUsername(username);
if (ban != null)
{
bans.remove(ban);
saveAll();
}
return ban;
}
public boolean isIpBanned(String ip)
{
return getByIp(ip) != null;
}
public boolean isUsernameBanned(String username)
{
return getByUsername(username) != null;
}
public boolean addBan(Ban ban)
{
if (bans.add(ban))
{
saveAll();
return true;
}
return false;
}
public boolean removeBan(Ban ban)
{
if (bans.remove(ban))
{
saveAll();
return true;
}
return false;
}
public int purge()
{
config.clear();
config.save();
int size = bans.size();
bans.clear();
updateViews();
return size;
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerLogin(PlayerLoginEvent event)
{
final String username = event.getPlayer().getName();
final String ip = Ips.getIp(event);
// Regular ban
Ban ban = getByUsername(username);
if (ban == null)
{
ban = getByIp(ip);
}
if (ban != null && !ban.isExpired())
{
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, ban.bakeKickMessage());
}
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerJoin(PlayerJoinEvent event)
{
final Player player = event.getPlayer();
final PlayerData data = plugin.pl.getData(player);
if (!plugin.al.isAdmin(player))
{
return;
}
// Unban admins
for (String storedIp : data.getIps())
{
unbanIp(storedIp);
unbanIp(FUtil.getFuzzyIp(storedIp));
}
unbanUsername(player.getName());
player.setOp(true);
}
private void updateViews()
{
// Remove expired bans
for (Iterator<Ban> it = bans.iterator(); it.hasNext();)
{
if (it.next().isExpired())
{
it.remove();
}
}
nameBans.clear();
ipBans.clear();
for (Ban ban : bans)
{
if (ban.hasUsername())
{
nameBans.put(ban.getUsername().toLowerCase(), ban);
}
if (ban.hasIps())
{
for (String ip : ban.getIps())
{
ipBans.put(ip, ban);
}
}
}
}
}

View File

@ -0,0 +1,90 @@
package me.totalfreedom.totalfreedommod.banning;
import com.google.common.collect.Sets;
import java.util.Set;
import lombok.Getter;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.util.FLog;
import me.totalfreedom.totalfreedommod.util.FUtil;
import net.pravian.aero.config.YamlConfig;
import net.pravian.aero.util.Ips;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerLoginEvent;
public class PermbanList extends FreedomService
{
public static final String CONFIG_FILENAME = "permbans.yml";
@Getter
private final Set<String> permbannedNames = Sets.newHashSet();
@Getter
private final Set<String> permbannedIps = Sets.newHashSet();
public PermbanList(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
permbannedNames.clear();
permbannedIps.clear();
final YamlConfig config = new YamlConfig(plugin, CONFIG_FILENAME, true);
config.load();
for (String name : config.getKeys(false))
{
permbannedNames.add(name.toLowerCase().trim());
permbannedIps.addAll(config.getStringList(name));
}
FLog.info("Loaded " + permbannedIps.size() + " perm IP bans and " + permbannedNames.size() + " perm username bans.");
}
@Override
protected void onStop()
{
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerLogin(PlayerLoginEvent event)
{
final String username = event.getPlayer().getName();
final String ip = Ips.getIp(event);
// Permbanned IPs
for (String testIp : getPermbannedIps())
{
if (FUtil.fuzzyIpMatch(testIp, ip, 4))
{
event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
ChatColor.RED + "Your IP address is permanently banned from this server.\n"
+ "Release procedures are available at\n"
+ ChatColor.GOLD + ConfigEntry.SERVER_PERMBAN_URL.getString());
return;
}
}
// Permbanned usernames
for (String testPlayer : getPermbannedNames())
{
if (testPlayer.equalsIgnoreCase(username))
{
event.disallow(PlayerLoginEvent.Result.KICK_OTHER,
ChatColor.RED + "Your username is permanently banned from this server.\n"
+ "Release procedures are available at\n"
+ ChatColor.GOLD + ConfigEntry.SERVER_PERMBAN_URL.getString());
return;
}
}
}
}

View File

@ -0,0 +1,114 @@
package me.totalfreedom.totalfreedommod.blocking;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.util.FLog;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.inventory.ItemStack;
public class BlockBlocker extends FreedomService
{
public BlockBlocker(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
@EventHandler(priority = EventPriority.HIGH)
public void onBlockPlace(BlockPlaceEvent event)
{
final Player player = event.getPlayer();
switch (event.getBlockPlaced().getType())
{
case LAVA:
case STATIONARY_LAVA:
{
if (ConfigEntry.ALLOW_LAVA_PLACE.getBoolean())
{
FLog.info(String.format("%s placed lava @ %s", player.getName(), FUtil.formatLocation(event.getBlock().getLocation())));
player.getInventory().clear(player.getInventory().getHeldItemSlot());
}
else
{
player.getInventory().setItem(player.getInventory().getHeldItemSlot(), new ItemStack(Material.COOKIE, 1));
player.sendMessage(ChatColor.GRAY + "Lava placement is currently disabled.");
event.setCancelled(true);
}
break;
}
case WATER:
case STATIONARY_WATER:
{
if (ConfigEntry.ALLOW_WATER_PLACE.getBoolean())
{
FLog.info(String.format("%s placed water @ %s", player.getName(), FUtil.formatLocation(event.getBlock().getLocation())));
player.getInventory().clear(player.getInventory().getHeldItemSlot());
}
else
{
player.getInventory().setItem(player.getInventory().getHeldItemSlot(), new ItemStack(Material.COOKIE, 1));
player.sendMessage(ChatColor.GRAY + "Water placement is currently disabled.");
event.setCancelled(true);
}
break;
}
case FIRE:
{
if (ConfigEntry.ALLOW_FIRE_PLACE.getBoolean())
{
FLog.info(String.format("%s placed fire @ %s", player.getName(), FUtil.formatLocation(event.getBlock().getLocation())));
player.getInventory().clear(player.getInventory().getHeldItemSlot());
}
else
{
player.getInventory().setItem(player.getInventory().getHeldItemSlot(), new ItemStack(Material.COOKIE, 1));
player.sendMessage(ChatColor.GRAY + "Fire placement is currently disabled.");
event.setCancelled(true);
}
break;
}
case TNT:
{
if (ConfigEntry.ALLOW_EXPLOSIONS.getBoolean())
{
FLog.info(String.format("%s placed TNT @ %s", player.getName(), FUtil.formatLocation(event.getBlock().getLocation())));
player.getInventory().clear(player.getInventory().getHeldItemSlot());
}
else
{
player.getInventory().setItem(player.getInventory().getHeldItemSlot(), new ItemStack(Material.COOKIE, 1));
player.sendMessage(ChatColor.GRAY + "TNT is currently disabled.");
event.setCancelled(true);
}
break;
}
}
}
}

View File

@ -0,0 +1,172 @@
package me.totalfreedom.totalfreedommod.blocking;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Tameable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
public class EventBlocker extends FreedomService
{
public EventBlocker(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
@EventHandler(priority = EventPriority.HIGH)
public void onBlockBurn(BlockBurnEvent event)
{
if (!ConfigEntry.ALLOW_FIRE_SPREAD.getBoolean())
{
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onBlockIgnite(BlockIgniteEvent event)
{
if (!ConfigEntry.ALLOW_FIRE_PLACE.getBoolean())
{
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onBlockFromTo(BlockFromToEvent event)
{
if (!ConfigEntry.ALLOW_FLUID_SPREAD.getBoolean())
{
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onEntityExplode(EntityExplodeEvent event)
{
if (!ConfigEntry.ALLOW_EXPLOSIONS.getBoolean())
{
event.setCancelled(true);
return;
}
event.setYield(0.0F);
}
@EventHandler(priority = EventPriority.HIGH)
public void onExplosionPrime(ExplosionPrimeEvent event)
{
if (!ConfigEntry.ALLOW_EXPLOSIONS.getBoolean())
{
event.setCancelled(true);
return;
}
event.setRadius(ConfigEntry.EXPLOSIVE_RADIUS.getDouble().floatValue());
}
@EventHandler(priority = EventPriority.HIGH)
public void onEntityCombust(EntityCombustEvent event)
{
if (!ConfigEntry.ALLOW_EXPLOSIONS.getBoolean())
{
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onEntityDeath(EntityDeathEvent event)
{
if (ConfigEntry.AUTO_ENTITY_WIPE.getBoolean())
{
event.setDroppedExp(0);
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onProjectileHit(ProjectileHitEvent event)
{
if (ConfigEntry.ALLOW_EXPLOSIONS.getBoolean())
{
Projectile entity = event.getEntity();
if (event.getEntityType() == EntityType.ARROW)
{
entity.getWorld().createExplosion(entity.getLocation(), 2F);
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onEntityDamage(EntityDamageEvent event)
{
switch (event.getCause())
{
case LAVA:
{
if (!ConfigEntry.ALLOW_LAVA_DAMAGE.getBoolean())
{
event.setCancelled(true);
return;
}
}
}
if (ConfigEntry.ENABLE_PET_PROTECT.getBoolean())
{
Entity entity = event.getEntity();
if (entity instanceof Tameable)
{
if (((Tameable) entity).isTamed())
{
event.setCancelled(true);
}
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerDropItem(PlayerDropItemEvent event)
{
if (!ConfigEntry.AUTO_ENTITY_WIPE.getBoolean())
{
return;
}
if (event.getPlayer().getWorld().getEntities().size() > 750)
{
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onLeavesDecay(LeavesDecayEvent event)
{
event.setCancelled(true);
}
}

View File

@ -0,0 +1,103 @@
package me.totalfreedom.totalfreedommod.blocking;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.player.FPlayer;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
public class InteractBlocker extends FreedomService
{
public InteractBlocker(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerInteract(PlayerInteractEvent event)
{
final Player player = event.getPlayer();
final FPlayer playerdata = plugin.pl.getPlayer(player);
switch (event.getAction())
{
case RIGHT_CLICK_AIR:
case RIGHT_CLICK_BLOCK:
{
handleRightClick(event);
break;
}
case LEFT_CLICK_AIR:
case LEFT_CLICK_BLOCK:
{
//
break;
}
}
}
private void handleRightClick(PlayerInteractEvent event)
{
final Player player = event.getPlayer();
switch (event.getMaterial())
{
case WATER_BUCKET:
{
if (plugin.al.isAdmin(player) || ConfigEntry.ALLOW_WATER_PLACE.getBoolean())
{
break;
}
player.getInventory().setItem(player.getInventory().getHeldItemSlot(), new ItemStack(Material.COOKIE, 1));
player.sendMessage(ChatColor.GRAY + "Water buckets are currently disabled.");
event.setCancelled(true);
break;
}
case LAVA_BUCKET:
{
if (plugin.al.isAdmin(player) || ConfigEntry.ALLOW_LAVA_PLACE.getBoolean())
{
break;
}
player.getInventory().setItem(player.getInventory().getHeldItemSlot(), new ItemStack(Material.COOKIE, 1));
player.sendMessage(ChatColor.GRAY + "Lava buckets are currently disabled.");
event.setCancelled(true);
break;
}
case EXPLOSIVE_MINECART:
{
if (ConfigEntry.ALLOW_TNT_MINECARTS.getBoolean())
{
break;
}
player.getInventory().clear(player.getInventory().getHeldItemSlot());
player.sendMessage(ChatColor.GRAY + "TNT minecarts are currently disabled.");
event.setCancelled(true);
break;
}
}
}
}

View File

@ -0,0 +1,104 @@
package me.totalfreedom.totalfreedommod.blocking;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import org.bukkit.entity.Bat;
import org.bukkit.entity.EnderDragon;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Ghast;
import org.bukkit.entity.Giant;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Slime;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.CreatureSpawnEvent;
public class MobBlocker extends FreedomService
{
public MobBlocker(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
@EventHandler(priority = EventPriority.NORMAL)
public void onCreatureSpawn(CreatureSpawnEvent event)
{
if (!ConfigEntry.MOB_LIMITER_ENABLED.getBoolean())
{
return;
}
final Entity spawned = event.getEntity();
if (spawned instanceof EnderDragon)
{
if (ConfigEntry.MOB_LIMITER_DISABLE_DRAGON.getBoolean())
{
event.setCancelled(true);
return;
}
}
else if (spawned instanceof Ghast)
{
if (ConfigEntry.MOB_LIMITER_DISABLE_GHAST.getBoolean())
{
event.setCancelled(true);
return;
}
}
else if (spawned instanceof Slime)
{
if (ConfigEntry.MOB_LIMITER_DISABLE_SLIME.getBoolean())
{
event.setCancelled(true);
return;
}
}
else if (spawned instanceof Giant)
{
if (ConfigEntry.MOB_LIMITER_DISABLE_GIANT.getBoolean())
{
event.setCancelled(true);
return;
}
}
else if (spawned instanceof Bat)
{
event.setCancelled(true);
return;
}
int mobLimiterMax = ConfigEntry.MOB_LIMITER_MAX.getInteger();
if (mobLimiterMax <= 0)
{
return;
}
int mobcount = 0;
for (Entity entity : event.getLocation().getWorld().getLivingEntities())
{
if (!(entity instanceof HumanEntity))
{
mobcount++;
}
}
if (mobcount > mobLimiterMax)
{
event.setCancelled(true);
}
}
}

View File

@ -0,0 +1,62 @@
package me.totalfreedom.totalfreedommod.blocking;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.projectiles.ProjectileSource;
public class PotionBlocker extends FreedomService
{
public static final int POTION_BLOCK_RADIUS_SQUARED = 20 * 20;
public PotionBlocker(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onThrowPotion(PotionSplashEvent event)
{
ProjectileSource source = event.getEntity().getShooter();
if (!(source instanceof Player))
{
event.setCancelled(true);
return;
}
Player thrower = (Player) source;
if (plugin.al.isAdmin(thrower))
{
return;
}
for (Player player : thrower.getWorld().getPlayers())
{
if (thrower.getLocation().distanceSquared(player.getLocation()) < POTION_BLOCK_RADIUS_SQUARED)
{
thrower.sendMessage(ChatColor.RED + "You cannot use splash potions close to other players.");
event.setCancelled(true);
return;
}
}
}
}

View File

@ -0,0 +1,210 @@
package me.totalfreedom.totalfreedommod.blocking.command;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.util.FLog;
import me.totalfreedom.totalfreedommod.util.FUtil;
import net.pravian.aero.command.CommandReflection;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandMap;
import org.bukkit.command.CommandSender;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
public class CommandBlocker extends FreedomService
{
private final Pattern flagPattern = Pattern.compile("(:([0-9]){5,})");
//
private final Map<String, CommandBlockerEntry> entryList = Maps.newHashMap();
private final List<String> unknownCommands = Lists.newArrayList();
public CommandBlocker(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
load();
}
@Override
protected void onStop()
{
entryList.clear();
}
public void load()
{
entryList.clear();
unknownCommands.clear();
final CommandMap commandMap = CommandReflection.getCommandMap();
if (commandMap == null)
{
FLog.severe("Error loading commandMap.");
return;
}
@SuppressWarnings("unchecked")
List<String> blockedCommands = (List<String>) ConfigEntry.BLOCKED_COMMANDS.getList();
for (String rawEntry : blockedCommands)
{
final String[] parts = rawEntry.split(":");
if (parts.length < 3 || parts.length > 4)
{
FLog.warning("Invalid command blocker entry: " + rawEntry);
continue;
}
final CommandBlockerRank rank = CommandBlockerRank.fromToken(parts[0]);
final CommandBlockerAction action = CommandBlockerAction.fromToken(parts[1]);
String commandName = parts[2].toLowerCase().substring(1);
final String message = (parts.length > 3 ? parts[3] : null);
if (rank == null || action == null || commandName == null || commandName.isEmpty())
{
FLog.warning("Invalid command blocker entry: " + rawEntry);
continue;
}
final String[] commandParts = commandName.split(" ");
String subCommand = null;
if (commandParts.length > 1)
{
commandName = commandParts[0];
subCommand = StringUtils.join(commandParts, " ", 1, commandParts.length).trim().toLowerCase();
}
final Command command = commandMap.getCommand(commandName);
// Obtain command from alias
if (command == null)
{
unknownCommands.add(commandName);
}
else
{
commandName = command.getName().toLowerCase();
}
if (entryList.containsKey(commandName))
{
FLog.warning("Not blocking: /" + commandName + " - Duplicate entry exists!");
continue;
}
final CommandBlockerEntry blockedCommandEntry = new CommandBlockerEntry(rank, action, commandName, subCommand, message);
entryList.put(blockedCommandEntry.getCommand(), blockedCommandEntry);
if (command != null)
{
for (String alias : command.getAliases())
{
entryList.put(alias.toLowerCase(), blockedCommandEntry);
}
}
}
FLog.info("Loaded " + blockedCommands.size() + " blocked commands (" + (blockedCommands.size() - unknownCommands.size()) + " known).");
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event)
{
// Blocked commands
if (isCommandBlocked(event.getMessage(), event.getPlayer(), true))
{
// CommandBlocker handles messages and broadcasts
event.setCancelled(true);
}
}
public boolean isCommandBlocked(String command, CommandSender sender)
{
return isCommandBlocked(command, sender, false);
}
public boolean isCommandBlocked(String command, CommandSender sender, boolean doAction)
{
if (command == null || command.isEmpty())
{
return false;
}
// Format
command = command.toLowerCase().trim();
command = command.startsWith("/") ? command.substring(1) : command;
// Check for plugin specific commands
final String[] commandParts = command.split(" ");
if (commandParts[0].contains(":"))
{
if (doAction)
{
FUtil.playerMsg(sender, "Plugin specific commands are disabled.");
}
return true;
}
for (String part : commandParts)
{
Matcher matcher = flagPattern.matcher(part);
if (!matcher.matches())
{
continue;
}
if (doAction)
{
FUtil.playerMsg(sender, "That command contains an illegal number: " + matcher.group(1));
}
return true;
}
// Obtain sub command, if it exists
String subCommand = null;
if (commandParts.length > 1)
{
subCommand = StringUtils.join(commandParts, " ", 1, commandParts.length).toLowerCase();
}
// Obtain entry
final CommandBlockerEntry entry = entryList.get(commandParts[0]);
if (entry == null)
{
return false;
}
// Validate sub command
if (entry.getSubCommand() != null)
{
if (subCommand == null || !subCommand.startsWith(entry.getSubCommand()))
{
return false;
}
}
if (entry.getRank().hasPermission(sender))
{
return false;
}
if (doAction)
{
entry.doActions(sender);
}
return true;
}
}

View File

@ -0,0 +1,32 @@
package me.totalfreedom.totalfreedommod.blocking.command;
public enum CommandBlockerAction
{
BLOCK("b"),
BLOCK_AND_EJECT("a"),
BLOCK_UNKNOWN("u");
private final String token;
private CommandBlockerAction(String token)
{
this.token = token;
}
public String getToken()
{
return this.token;
}
public static CommandBlockerAction fromToken(String token)
{
for (CommandBlockerAction action : CommandBlockerAction.values())
{
if (action.getToken().equalsIgnoreCase(token))
{
return action;
}
}
return null;
}
}

View File

@ -0,0 +1,55 @@
package me.totalfreedom.totalfreedommod.blocking.command;
import lombok.Getter;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CommandBlockerEntry
{
@Getter
private final CommandBlockerRank rank;
@Getter
private final CommandBlockerAction action;
@Getter
private final String command;
@Getter
private final String subCommand;
@Getter
private final String message;
public CommandBlockerEntry(CommandBlockerRank rank, CommandBlockerAction action, String command, String message)
{
this(rank, action, command, null, message);
}
public CommandBlockerEntry(CommandBlockerRank rank, CommandBlockerAction action, String command, String subCommand, String message)
{
this.rank = rank;
this.action = action;
this.command = command;
this.subCommand = (subCommand == null ? null : subCommand.toLowerCase().trim());
this.message = (message == null || message.equals("_") ? "That command is blocked." : message);
}
public void doActions(CommandSender sender)
{
if (action == CommandBlockerAction.BLOCK_AND_EJECT && sender instanceof Player)
{
TotalFreedomMod.plugin().ae.autoEject((Player) sender, "You used a prohibited command: " + command);
FUtil.bcastMsg(sender.getName() + " was automatically kicked for using harmful commands.", ChatColor.RED);
return;
}
if (action == CommandBlockerAction.BLOCK_UNKNOWN)
{
FUtil.playerMsg(sender, "Unknown command. Type \"help\" for help.", ChatColor.RESET);
return;
}
FUtil.playerMsg(sender, FUtil.colorize(message));
}
}

View File

@ -0,0 +1,73 @@
package me.totalfreedom.totalfreedommod.blocking.command;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.admin.Admin;
import me.totalfreedom.totalfreedommod.rank.Rank;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public enum CommandBlockerRank
{
ANYONE("a"),
OP("o"),
SUPER("s"),
TELNET("t"),
SENIOR("c"),
NOBODY("n");
//
private final String token;
private CommandBlockerRank(String token)
{
this.token = token;
}
public String getToken()
{
return this.token;
}
public boolean hasPermission(CommandSender sender)
{
return fromSender(sender).ordinal() >= ordinal();
}
public static CommandBlockerRank fromSender(CommandSender sender)
{
if (!(sender instanceof Player))
{
return TELNET;
}
Admin admin = TotalFreedomMod.plugin().al.getAdmin(sender);
if (admin != null)
{
if (admin.getRank() == Rank.SENIOR_ADMIN)
{
return SENIOR;
}
return SUPER;
}
if (sender.isOp())
{
return OP;
}
return ANYONE;
}
public static CommandBlockerRank fromToken(String token)
{
for (CommandBlockerRank rank : CommandBlockerRank.values())
{
if (rank.getToken().equalsIgnoreCase(token))
{
return rank;
}
}
return ANYONE;
}
}

View File

@ -1,22 +1,36 @@
package me.StevenLawson.TotalFreedomMod.Listener; package me.totalfreedom.totalfreedommod.bridge;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import me.StevenLawson.BukkitTelnet.api.TelnetCommandEvent; import me.totalfreedom.bukkittelnet.api.TelnetCommandEvent;
import me.StevenLawson.BukkitTelnet.api.TelnetPreLoginEvent; import me.totalfreedom.bukkittelnet.api.TelnetPreLoginEvent;
import me.StevenLawson.BukkitTelnet.api.TelnetRequestDataTagsEvent; import me.totalfreedom.bukkittelnet.api.TelnetRequestDataTagsEvent;
import me.StevenLawson.TotalFreedomMod.Bridge.TFM_EssentialsBridge; import me.totalfreedom.totalfreedommod.FreedomService;
import me.StevenLawson.TotalFreedomMod.TFM_Admin; import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.StevenLawson.TotalFreedomMod.TFM_AdminList; import me.totalfreedom.totalfreedommod.admin.Admin;
import me.StevenLawson.TotalFreedomMod.TFM_CommandBlocker; import me.totalfreedom.totalfreedommod.rank.Rank;
import me.StevenLawson.TotalFreedomMod.TFM_PlayerData;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
public class TFM_TelnetListener implements Listener public class BukkitTelnetBridge extends FreedomService
{ {
public BukkitTelnetBridge(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void onTelnetPreLogin(TelnetPreLoginEvent event) public void onTelnetPreLogin(TelnetPreLoginEvent event)
{ {
@ -27,21 +41,21 @@ public class TFM_TelnetListener implements Listener
return; return;
} }
final TFM_Admin admin = TFM_AdminList.getEntryByIp(ip, true); final Admin admin = plugin.al.getEntryByIpFuzzy(ip);
if (admin == null || !admin.isActivated() || !admin.isTelnetAdmin()) if (admin == null || !admin.isActive() || !admin.getRank().hasConsoleVariant())
{ {
return; return;
} }
event.setBypassPassword(true); event.setBypassPassword(true);
event.setName(admin.getLastLoginName()); event.setName(admin.getName());
} }
@EventHandler(priority = EventPriority.NORMAL) @EventHandler(priority = EventPriority.NORMAL)
public void onTelnetCommand(TelnetCommandEvent event) public void onTelnetCommand(TelnetCommandEvent event)
{ {
if (TFM_CommandBlocker.isCommandBlocked(event.getCommand(), event.getSender())) if (plugin.cb.isCommandBlocked(event.getCommand(), event.getSender()))
{ {
event.setCancelled(true); event.setCancelled(true);
} }
@ -61,23 +75,23 @@ public class TFM_TelnetListener implements Listener
boolean isTelnetAdmin = false; boolean isTelnetAdmin = false;
boolean isSeniorAdmin = false; boolean isSeniorAdmin = false;
final TFM_Admin admin = TFM_AdminList.getEntry(player); final Admin admin = plugin.al.getAdmin(player);
if (admin != null) if (admin != null)
{ {
boolean isActivated = admin.isActivated(); boolean active = admin.isActive();
isAdmin = isActivated; isAdmin = active;
isTelnetAdmin = isActivated && admin.isTelnetAdmin(); isSeniorAdmin = active && admin.getRank() == Rank.SENIOR_ADMIN;
isSeniorAdmin = isActivated && admin.isSeniorAdmin(); isTelnetAdmin = active && (isSeniorAdmin || admin.getRank() == Rank.TELNET_ADMIN);
} }
playerTags.put("tfm.admin.isAdmin", isAdmin); playerTags.put("tfm.admin.isAdmin", isAdmin);
playerTags.put("tfm.admin.isTelnetAdmin", isTelnetAdmin); playerTags.put("tfm.admin.isTelnetAdmin", isTelnetAdmin);
playerTags.put("tfm.admin.isSeniorAdmin", isSeniorAdmin); playerTags.put("tfm.admin.isSeniorAdmin", isSeniorAdmin);
playerTags.put("tfm.playerdata.getTag", TFM_PlayerData.getPlayerData(player).getTag()); playerTags.put("tfm.playerdata.getTag", plugin.pl.getPlayer(player).getTag());
playerTags.put("tfm.essentialsBridge.getNickname", TFM_EssentialsBridge.getNickname(player.getName())); playerTags.put("tfm.essentialsBridge.getNickname", plugin.esb.getNickname(player.getName()));
} }
} }
} }

View File

@ -1,22 +1,35 @@
package me.StevenLawson.TotalFreedomMod.Bridge; package me.totalfreedom.totalfreedommod.bridge;
import com.earth2me.essentials.Essentials; import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User; import com.earth2me.essentials.User;
import me.StevenLawson.TotalFreedomMod.TFM_Log; import me.totalfreedom.totalfreedommod.FreedomService;
import me.StevenLawson.TotalFreedomMod.TFM_Util; import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.util.FLog;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
public class TFM_EssentialsBridge public class EssentialsBridge extends FreedomService
{ {
private static Essentials essentialsPlugin = null;
private TFM_EssentialsBridge() private Essentials essentialsPlugin = null;
public EssentialsBridge(TotalFreedomMod plugin)
{ {
throw new AssertionError(); super(plugin);
} }
public static Essentials getEssentialsPlugin() @Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
public Essentials getEssentialsPlugin()
{ {
if (essentialsPlugin == null) if (essentialsPlugin == null)
{ {
@ -33,13 +46,13 @@ public class TFM_EssentialsBridge
} }
catch (Exception ex) catch (Exception ex)
{ {
TFM_Log.severe(ex); FLog.severe(ex);
} }
} }
return essentialsPlugin; return essentialsPlugin;
} }
public static User getEssentialsUser(String username) public User getEssentialsUser(String username)
{ {
try try
{ {
@ -51,12 +64,12 @@ public class TFM_EssentialsBridge
} }
catch (Exception ex) catch (Exception ex)
{ {
TFM_Log.severe(ex); FLog.severe(ex);
} }
return null; return null;
} }
public static void setNickname(String username, String nickname) public void setNickname(String username, String nickname)
{ {
try try
{ {
@ -69,11 +82,11 @@ public class TFM_EssentialsBridge
} }
catch (Exception ex) catch (Exception ex)
{ {
TFM_Log.severe(ex); FLog.severe(ex);
} }
} }
public static String getNickname(String username) public String getNickname(String username)
{ {
try try
{ {
@ -85,29 +98,29 @@ public class TFM_EssentialsBridge
} }
catch (Exception ex) catch (Exception ex)
{ {
TFM_Log.severe(ex); FLog.severe(ex);
} }
return null; return null;
} }
public static long getLastActivity(String username) public long getLastActivity(String username)
{ {
try try
{ {
final User user = getEssentialsUser(username); final User user = getEssentialsUser(username);
if (user != null) if (user != null)
{ {
return TFM_Util.<Long>getField(user, "lastActivity"); // This is weird return FUtil.<Long>getField(user, "lastActivity"); // This is weird
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
TFM_Log.severe(ex); FLog.severe(ex);
} }
return 0L; return 0L;
} }
public static boolean isEssentialsEnabled() public boolean isEssentialsEnabled()
{ {
try try
{ {
@ -119,7 +132,7 @@ public class TFM_EssentialsBridge
} }
catch (Exception ex) catch (Exception ex)
{ {
TFM_Log.severe(ex); FLog.severe(ex);
} }
return false; return false;
} }

View File

@ -0,0 +1,138 @@
package me.totalfreedom.totalfreedommod.bridge;
import com.sk89q.worldedit.LocalSession;
import com.sk89q.worldedit.bukkit.BukkitPlayer;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.util.FLog;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class WorldEditBridge extends FreedomService
{
private final WorldEditListener listener;
//
private WorldEditPlugin worldedit = null;
public WorldEditBridge(TotalFreedomMod plugin)
{
super(plugin);
listener = new WorldEditListener(plugin);
}
@Override
protected void onStart()
{
listener.register();
}
@Override
protected void onStop()
{
listener.unregister();
}
public void undo(Player player, int count)
{
try
{
LocalSession session = getPlayerSession(player);
if (session != null)
{
final BukkitPlayer bukkitPlayer = getBukkitPlayer(player);
if (bukkitPlayer != null)
{
for (int i = 0; i < count; i++)
{
session.undo(session.getBlockBag(bukkitPlayer), bukkitPlayer);
}
}
}
}
catch (Exception ex)
{
FLog.severe(ex);
}
}
private WorldEditPlugin getWorldEditPlugin()
{
if (worldedit == null)
{
try
{
Plugin we = server.getPluginManager().getPlugin("WorldEdit");
if (we != null)
{
if (we instanceof WorldEditPlugin)
{
worldedit = (WorldEditPlugin) we;
}
}
}
catch (Exception ex)
{
FLog.severe(ex);
}
}
return worldedit;
}
public void setLimit(Player player, int limit)
{
try
{
final LocalSession session = getPlayerSession(player);
if (session != null)
{
session.setBlockChangeLimit(limit);
}
}
catch (Exception ex)
{
FLog.severe(ex);
}
}
private LocalSession getPlayerSession(Player player)
{
final WorldEditPlugin wep = getWorldEditPlugin();
if (wep == null)
{
return null;
}
try
{
return wep.getSession(player);
}
catch (Exception ex)
{
FLog.severe(ex);
return null;
}
}
private BukkitPlayer getBukkitPlayer(Player player)
{
final WorldEditPlugin wep = getWorldEditPlugin();
if (wep == null)
{
return null;
}
try
{
return wep.wrapPlayer(player);
}
catch (Exception ex)
{
FLog.severe(ex);
return null;
}
}
}

View File

@ -0,0 +1,66 @@
package me.totalfreedom.totalfreedommod.bridge;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.util.FUtil;
import me.totalfreedom.worldedit.LimitChangedEvent;
import me.totalfreedom.worldedit.SelectionChangedEvent;
import net.pravian.aero.component.PluginListener;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
public class WorldEditListener extends PluginListener<TotalFreedomMod>
{
public WorldEditListener(TotalFreedomMod plugin)
{
super(plugin);
}
@EventHandler
public void onSelectionChange(final SelectionChangedEvent event)
{
final Player player = event.getPlayer();
if (plugin.al.isAdmin(player))
{
return;
}
if (plugin.pa.isInProtectedArea(
event.getMinVector(),
event.getMaxVector(),
event.getWorld().getName()))
{
player.sendMessage(ChatColor.RED + "The region that you selected contained a protected area. Selection cleared.");
event.setCancelled(true);
}
}
@EventHandler
public void onLimitChanged(LimitChangedEvent event)
{
final Player player = event.getPlayer();
if (plugin.al.isAdmin(player))
{
return;
}
if (!event.getPlayer().equals(event.getTarget()))
{
player.sendMessage(ChatColor.RED + "Only admins can change the limit for other players!");
event.setCancelled(true);
}
if (event.getLimit() < 0 || event.getLimit() > 10000)
{
player.setOp(false);
FUtil.bcastMsg(event.getPlayer().getName() + " tried to set their WorldEdit limit to " + event.getLimit() + " and has been de-opped", ChatColor.RED);
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "You cannot set your limit higher than 10000 or to -1!");
}
}
}

View File

@ -0,0 +1,210 @@
package me.totalfreedom.totalfreedommod.caging;
import java.util.ArrayList;
import java.util.List;
import lombok.Getter;
import me.totalfreedom.totalfreedommod.player.FPlayer;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.SkullType;
import org.bukkit.block.Block;
import org.bukkit.block.Skull;
public class CageData
{
private final FPlayer fPlayer;
//
private final List<BlockData> cageHistory = new ArrayList<>();
//
@Getter
private boolean caged = false;
@Getter
private Location location;
@Getter
private Material outerMaterial = Material.GLASS;
@Getter
private Material innerMaterial = Material.AIR;
public CageData(FPlayer player)
{
this.fPlayer = player;
}
public void setCaged(boolean cage)
{
if (cage)
{
cage(fPlayer.getPlayer().getLocation(), Material.GLASS, Material.GLASS);
}
else
{
this.caged = false;
regenerateHistory();
clearHistory();
}
}
public void cage(Location location, Material outer, Material inner)
{
if (isCaged())
{
setCaged(false);
}
this.caged = true;
this.location = location;
this.outerMaterial = outer;
this.innerMaterial = inner;
buildHistory(location, 2, fPlayer);
regenerate();
}
public void regenerate()
{
if (!caged
|| location == null
|| outerMaterial == null
|| innerMaterial == null)
{
return;
}
generateHollowCube(location, 2, outerMaterial);
generateCube(location, 1, innerMaterial);
}
// TODO: EventHandlerize this?
public void playerJoin()
{
if (!isCaged())
{
return;
}
cage(fPlayer.getPlayer().getLocation(), outerMaterial, innerMaterial);
}
public void playerQuit()
{
regenerateHistory();
clearHistory();
}
public void clearHistory()
{
cageHistory.clear();
}
private void insertHistoryBlock(Location location, Material material)
{
cageHistory.add(new BlockData(location, material));
}
private void regenerateHistory()
{
for (BlockData blockdata : this.cageHistory)
{
blockdata.location.getBlock().setType(blockdata.material);
}
}
private void buildHistory(Location location, int length, FPlayer playerdata)
{
final Block center = location.getBlock();
for (int xOffset = -length; xOffset <= length; xOffset++)
{
for (int yOffset = -length; yOffset <= length; yOffset++)
{
for (int zOffset = -length; zOffset <= length; zOffset++)
{
final Block block = center.getRelative(xOffset, yOffset, zOffset);
insertHistoryBlock(block.getLocation(), block.getType());
}
}
}
}
// Util methods
public static void generateCube(Location location, int length, Material material)
{
final Block center = location.getBlock();
for (int xOffset = -length; xOffset <= length; xOffset++)
{
for (int yOffset = -length; yOffset <= length; yOffset++)
{
for (int zOffset = -length; zOffset <= length; zOffset++)
{
final Block block = center.getRelative(xOffset, yOffset, zOffset);
if (block.getType() != material)
{
block.setType(material);
}
}
}
}
}
public static void generateHollowCube(Location location, int length, Material material)
{
final Block center = location.getBlock();
for (int xOffset = -length; xOffset <= length; xOffset++)
{
for (int yOffset = -length; yOffset <= length; yOffset++)
{
for (int zOffset = -length; zOffset <= length; zOffset++)
{
// Hollow
if (Math.abs(xOffset) != length && Math.abs(yOffset) != length && Math.abs(zOffset) != length)
{
continue;
}
final Block block = center.getRelative(xOffset, yOffset, zOffset);
if (material != Material.SKULL)
{
// Glowstone light
if (material != Material.GLASS && xOffset == 0 && yOffset == 2 && zOffset == 0)
{
block.setType(Material.GLOWSTONE);
continue;
}
block.setType(material);
}
else // Darth mode
{
if (Math.abs(xOffset) == length && Math.abs(yOffset) == length && Math.abs(zOffset) == length)
{
block.setType(Material.GLOWSTONE);
continue;
}
block.setType(Material.SKULL);
final Skull skull = (Skull) block.getState();
skull.setSkullType(SkullType.PLAYER);
skull.setOwner("Prozza");
skull.update();
}
}
}
}
}
private static class BlockData
{
public Material material;
public Location location;
private BlockData(Location location, Material material)
{
this.location = location;
this.material = material;
}
}
}

View File

@ -0,0 +1,110 @@
package me.totalfreedom.totalfreedommod.caging;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.player.FPlayer;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
public class Cager extends FreedomService
{
public Cager(TotalFreedomMod plugin)
{
super(plugin);
}
@Override
protected void onStart()
{
}
@Override
protected void onStop()
{
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBreakBlock(BlockBreakEvent event)
{
Player player = event.getPlayer();
if (player == null
|| plugin.al.isAdmin(player))
{
return;
}
FPlayer fPlayer = plugin.pl.getPlayer(event.getPlayer());
CageData cage = fPlayer.getCageData();
if (cage.isCaged())
{
event.setCancelled(true);
}
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent event)
{
FPlayer player = plugin.pl.getPlayer(event.getPlayer());
CageData cage = player.getCageData();
if (!cage.isCaged())
{
return;
}
Location playerLoc = player.getPlayer().getLocation().add(0, 1, 0);
Location cageLoc = cage.getLocation();
final boolean outOfCage;
if (!playerLoc.getWorld().equals(cageLoc.getWorld()))
{
outOfCage = true;
}
else
{
outOfCage = playerLoc.distanceSquared(cageLoc) > (2.5D * 2.5D);
}
if (outOfCage)
{
player.getPlayer().teleport(cageLoc.subtract(0, 0.1, 0));
FUtil.playerMsg(player.getPlayer(), "You may not leave your cage.", ChatColor.RED);
cage.regenerate();
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerQuit(PlayerQuitEvent event)
{
FPlayer player = plugin.pl.getPlayer(event.getPlayer());
CageData cage = player.getCageData();
if (cage.isCaged())
{
cage.playerQuit();
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerJoin(PlayerJoinEvent event)
{
FPlayer player = plugin.pl.getPlayer(event.getPlayer());
CageData cage = player.getCageData();
if (cage.isCaged())
{
cage.playerJoin();
}
}
}

View File

@ -0,0 +1,13 @@
package me.totalfreedom.totalfreedommod.command;
public class CommandFailException extends RuntimeException
{
private static final long serialVersionUID = -92333791173123L;
public CommandFailException(String message)
{
super(message);
}
}

View File

@ -0,0 +1,45 @@
package me.totalfreedom.totalfreedommod.command;
import lombok.Getter;
import me.totalfreedom.totalfreedommod.FreedomService;
import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.totalfreedom.totalfreedommod.util.FLog;
import net.pravian.aero.command.handler.SimpleCommandHandler;
import org.bukkit.ChatColor;
public class CommandLoader extends FreedomService
{
@Getter
private final SimpleCommandHandler<TotalFreedomMod> handler;
public CommandLoader(TotalFreedomMod plugin)
{
super(plugin);
handler = new SimpleCommandHandler<>(plugin);
}
@Override
protected void onStart()
{
handler.clearCommands();
handler.setExecutorFactory(new FreedomCommandExecutor.FreedomExecutorFactory(plugin));
handler.setCommandClassPrefix("Command_");
handler.setPermissionMessage(ChatColor.RED + "You do not have permission to use this command.");
handler.setOnlyConsoleMessage(ChatColor.RED + "This command can only be used from the console.");
handler.setOnlyPlayerMessage(ChatColor.RED + "This command can only be used by players.");
handler.loadFrom(FreedomCommand.class.getPackage());
handler.registerAll("TotalFreedomMod", true);
FLog.info("Loaded " + handler.getExecutors().size() + " commands.");
}
@Override
protected void onStop()
{
handler.clearCommands();
}
}

View File

@ -1,4 +1,4 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;
@ -6,6 +6,7 @@ import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface CommandParameters public @interface CommandParameters
{ {
String description(); String description();
String usage(); String usage();

View File

@ -1,12 +1,14 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import java.lang.annotation.Retention; import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.RetentionPolicy;
import me.totalfreedom.totalfreedommod.rank.Rank;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface CommandPermissions public @interface CommandPermissions
{ {
AdminLevel level();
Rank level();
SourceType source(); SourceType source();

View File

@ -0,0 +1,41 @@
package me.totalfreedom.totalfreedommod.command;
import me.totalfreedom.totalfreedommod.player.FPlayer;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH)
@CommandParameters(
description = "AdminChat - Talk privately with other admins. Using <command> itself will toggle AdminChat on and off for all messages.",
usage = "/<command> [message...]",
aliases = "o,ac")
public class Command_adminchat extends FreedomCommand
{
@Override
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
if (args.length == 0)
{
if (senderIsConsole)
{
msg("Only in-game players can toggle AdminChat.");
return true;
}
FPlayer userinfo = plugin.pl.getPlayer(playerSender);
userinfo.setAdminChat(!userinfo.inAdminChat());
msg("Toggled Admin Chat " + (userinfo.inAdminChat() ? "on" : "off") + ".");
}
else
{
plugin.cm.adminChat(sender, StringUtils.join(args, " "));
}
return true;
}
}

View File

@ -0,0 +1,45 @@
package me.totalfreedom.totalfreedommod.command;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.ONLY_CONSOLE, blockHostConsole = true)
@CommandParameters(description = "Close server to non-superadmins.", usage = "/<command> [on | off]")
public class Command_adminmode extends FreedomCommand
{
@Override
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
if (args.length != 1)
{
return false;
}
if (args[0].equalsIgnoreCase("off"))
{
ConfigEntry.ADMIN_ONLY_MODE.setBoolean(false);
FUtil.adminAction(sender.getName(), "Opening the server to all players.", true);
return true;
}
else if (args[0].equalsIgnoreCase("on"))
{
ConfigEntry.ADMIN_ONLY_MODE.setBoolean(true);
FUtil.adminAction(sender.getName(), "Closing the server to non-superadmins.", true);
for (Player player : server.getOnlinePlayers())
{
if (!isAdmin(player))
{
player.kickPlayer("Server is now closed to non-superadmins.");
}
}
return true;
}
return false;
}
}

View File

@ -1,24 +1,28 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import me.StevenLawson.TotalFreedomMod.TFM_AdminList; import me.totalfreedom.totalfreedommod.rank.Rank;
import me.StevenLawson.TotalFreedomMod.TFM_Util; import me.totalfreedom.totalfreedommod.util.FUtil;
import me.StevenLawson.TotalFreedomMod.World.TFM_AdminWorld; import me.totalfreedom.totalfreedommod.world.WorldTime;
import me.totalfreedom.totalfreedommod.world.WorldWeather;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@CommandPermissions(level = AdminLevel.OP, source = SourceType.BOTH) @CommandPermissions(level = Rank.OP, source = SourceType.BOTH)
@CommandParameters(description = "Go to the AdminWorld.", usage = "/<command> [guest < list | purge | add <player> | remove <player> > | time <morning | noon | evening | night> | weather <off | on | storm>]") @CommandParameters(description = "Go to the AdminWorld.",
public class Command_adminworld extends TFM_Command usage = "/<command> [guest < list | purge | add <player> | remove <player> > | time <morning | noon | evening | night> | weather <off | on | storm>]")
public class Command_adminworld extends FreedomCommand
{ {
private enum CommandMode private enum CommandMode
{ {
TELEPORT, GUEST, TIME, WEATHER; TELEPORT, GUEST, TIME, WEATHER;
} }
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
CommandMode commandMode = null; CommandMode commandMode = null;
@ -53,7 +57,7 @@ public class Command_adminworld extends TFM_Command
{ {
case TELEPORT: case TELEPORT:
{ {
if (!(sender instanceof Player) || sender_p == null) if (!(sender instanceof Player) || playerSender == null)
{ {
return true; return true;
} }
@ -61,27 +65,27 @@ public class Command_adminworld extends TFM_Command
World adminWorld = null; World adminWorld = null;
try try
{ {
adminWorld = TFM_AdminWorld.getInstance().getWorld(); adminWorld = plugin.wm.adminworld.getWorld();
} }
catch (Exception ex) catch (Exception ex)
{ {
} }
if (adminWorld == null || sender_p.getWorld() == adminWorld) if (adminWorld == null || playerSender.getWorld() == adminWorld)
{ {
playerMsg("Going to the main world."); msg("Going to the main world.");
sender_p.teleport(server.getWorlds().get(0).getSpawnLocation()); playerSender.teleport(server.getWorlds().get(0).getSpawnLocation());
} }
else else
{ {
if (TFM_AdminWorld.getInstance().canAccessWorld(sender_p)) if (plugin.wm.adminworld.canAccessWorld(playerSender))
{ {
playerMsg("Going to the AdminWorld."); msg("Going to the AdminWorld.");
TFM_AdminWorld.getInstance().sendToWorld(sender_p); plugin.wm.adminworld.sendToWorld(playerSender);
} }
else else
{ {
playerMsg("You don't have permission to access the AdminWorld."); msg("You don't have permission to access the AdminWorld.");
} }
} }
@ -93,13 +97,13 @@ public class Command_adminworld extends TFM_Command
{ {
if ("list".equalsIgnoreCase(args[1])) if ("list".equalsIgnoreCase(args[1]))
{ {
playerMsg("AdminWorld guest list: " + TFM_AdminWorld.getInstance().guestListToString()); msg("AdminWorld guest list: " + plugin.wm.adminworld.guestListToString());
} }
else if ("purge".equalsIgnoreCase(args[1])) else if ("purge".equalsIgnoreCase(args[1]))
{ {
assertCommandPerms(sender, sender_p); assertCommandPerms(sender, playerSender);
TFM_AdminWorld.getInstance().purgeGuestList(); plugin.wm.adminworld.purgeGuestList();
TFM_Util.adminAction(sender.getName(), "AdminWorld guest list purged.", false); FUtil.adminAction(sender.getName(), "AdminWorld guest list purged.", false);
} }
else else
{ {
@ -108,7 +112,7 @@ public class Command_adminworld extends TFM_Command
} }
else if (args.length == 3) else if (args.length == 3)
{ {
assertCommandPerms(sender, sender_p); assertCommandPerms(sender, playerSender);
if ("add".equalsIgnoreCase(args[1])) if ("add".equalsIgnoreCase(args[1]))
{ {
@ -116,29 +120,29 @@ public class Command_adminworld extends TFM_Command
if (player == null) if (player == null)
{ {
sender.sendMessage(TFM_Command.PLAYER_NOT_FOUND); sender.sendMessage(FreedomCommand.PLAYER_NOT_FOUND);
return true; return true;
} }
if (TFM_AdminWorld.getInstance().addGuest(player, sender_p)) if (plugin.wm.adminworld.addGuest(player, playerSender))
{ {
TFM_Util.adminAction(sender.getName(), "AdminWorld guest added: " + player.getName(), false); FUtil.adminAction(sender.getName(), "AdminWorld guest added: " + player.getName(), false);
} }
else else
{ {
playerMsg("Could not add player to guest list."); msg("Could not add player to guest list.");
} }
} }
else if ("remove".equals(args[1])) else if ("remove".equals(args[1]))
{ {
final Player player = TFM_AdminWorld.getInstance().removeGuest(args[2]); final Player player = plugin.wm.adminworld.removeGuest(args[2]);
if (player != null) if (player != null)
{ {
TFM_Util.adminAction(sender.getName(), "AdminWorld guest removed: " + player.getName(), false); FUtil.adminAction(sender.getName(), "AdminWorld guest removed: " + player.getName(), false);
} }
else else
{ {
playerMsg("Can't find guest entry for: " + args[2]); msg("Can't find guest entry for: " + args[2]);
} }
} }
else else
@ -151,19 +155,19 @@ public class Command_adminworld extends TFM_Command
} }
case TIME: case TIME:
{ {
assertCommandPerms(sender, sender_p); assertCommandPerms(sender, playerSender);
if (args.length == 2) if (args.length == 2)
{ {
TFM_AdminWorld.TimeOfDay timeOfDay = TFM_AdminWorld.TimeOfDay.getByAlias(args[1]); WorldTime timeOfDay = WorldTime.getByAlias(args[1]);
if (timeOfDay != null) if (timeOfDay != null)
{ {
TFM_AdminWorld.getInstance().setTimeOfDay(timeOfDay); plugin.wm.adminworld.setTimeOfDay(timeOfDay);
playerMsg("AdminWorld time set to: " + timeOfDay.name()); msg("AdminWorld time set to: " + timeOfDay.name());
} }
else else
{ {
playerMsg("Invalid time of day. Can be: sunrise, noon, sunset, midnight"); msg("Invalid time of day. Can be: sunrise, noon, sunset, midnight");
} }
} }
else else
@ -175,19 +179,19 @@ public class Command_adminworld extends TFM_Command
} }
case WEATHER: case WEATHER:
{ {
assertCommandPerms(sender, sender_p); assertCommandPerms(sender, playerSender);
if (args.length == 2) if (args.length == 2)
{ {
TFM_AdminWorld.WeatherMode weatherMode = TFM_AdminWorld.WeatherMode.getByAlias(args[1]); WorldWeather weatherMode = WorldWeather.getByAlias(args[1]);
if (weatherMode != null) if (weatherMode != null)
{ {
TFM_AdminWorld.getInstance().setWeatherMode(weatherMode); plugin.wm.adminworld.setWeatherMode(weatherMode);
playerMsg("AdminWorld weather set to: " + weatherMode.name()); msg("AdminWorld weather set to: " + weatherMode.name());
} }
else else
{ {
playerMsg("Invalid weather mode. Can be: off, rain, storm"); msg("Invalid weather mode. Can be: off, rain, storm");
} }
} }
else else
@ -205,27 +209,40 @@ public class Command_adminworld extends TFM_Command
} }
catch (PermissionDeniedException ex) catch (PermissionDeniedException ex)
{ {
if (ex.getMessage().isEmpty())
{
return noPerms();
}
sender.sendMessage(ex.getMessage()); sender.sendMessage(ex.getMessage());
return true;
} }
return true; return true;
} }
private void assertCommandPerms(CommandSender sender, Player sender_p) throws PermissionDeniedException // TODO: Redo this properly
private void assertCommandPerms(CommandSender sender, Player playerSender) throws PermissionDeniedException
{ {
if (!(sender instanceof Player) || sender_p == null || !TFM_AdminList.isSuperAdmin(sender)) if (!(sender instanceof Player) || playerSender == null || !isAdmin(sender))
{ {
throw new PermissionDeniedException(TFM_Command.MSG_NO_PERMS); throw new PermissionDeniedException();
} }
} }
private class PermissionDeniedException extends Exception private class PermissionDeniedException extends Exception
{ {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private PermissionDeniedException()
{
super("");
}
private PermissionDeniedException(String string) private PermissionDeniedException(String string)
{ {
super(string); super(string);
} }
} }
} }

View File

@ -0,0 +1,26 @@
package me.totalfreedom.totalfreedommod.command;
import me.totalfreedom.totalfreedommod.rank.Rank;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH)
@CommandParameters(description = "Make an announcement", usage = "/<command> <message>")
public class Command_announce extends FreedomCommand
{
@Override
protected boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
if (args.length < 1)
{
return false;
}
plugin.an.announce(StringUtils.join(args, " "));
return true;
}
}

View File

@ -0,0 +1,37 @@
package me.totalfreedom.totalfreedommod.command;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.OP, source = SourceType.BOTH)
@CommandParameters(description = "Shows all banned player names. Superadmins may optionally use 'purge' to clear the list.", usage = "/<command> [purge]")
public class Command_banlist extends FreedomCommand {
@Override
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) {
if (args.length > 0) {
if (args[0].equalsIgnoreCase("purge")) {
checkRank(Rank.SENIOR_ADMIN);
FUtil.adminAction(sender.getName(), "Purging the ban list", true);
int amount = plugin.bm.purge();
sender.sendMessage(ChatColor.GRAY + "Purged " + amount + " player bans.");
return true;
}
return false;
}
msg(plugin.bm.getAllBans().size() + " player bans ("
+ plugin.bm.getUsernameBans().size() + " usernames, "
+ plugin.bm.getIpBans().size() + " IPs)");
return true;
}
}

View File

@ -0,0 +1,84 @@
package me.totalfreedom.totalfreedommod.command;
import me.totalfreedom.totalfreedommod.player.FPlayer;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH)
@CommandParameters(description = "Block all commands for a specific player.", usage = "/<command> <-a | purge | <player>>", aliases = "blockcommands,blockcommand,bc,bcmd")
public class Command_blockcmd extends FreedomCommand
{
@Override
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
if (args.length != 1)
{
return false;
}
if (args[0].equals("purge"))
{
FUtil.adminAction(sender.getName(), "Unblocking commands for all players", true);
int counter = 0;
for (Player player : server.getOnlinePlayers())
{
FPlayer playerdata = plugin.pl.getPlayer(player);
if (playerdata.allCommandsBlocked())
{
counter += 1;
playerdata.setCommandsBlocked(false);
}
}
msg("Unblocked commands for " + counter + " players.");
return true;
}
if (args[0].equals("-a"))
{
FUtil.adminAction(sender.getName(), "Blocking commands for all non-admins", true);
int counter = 0;
for (Player player : server.getOnlinePlayers())
{
if (isAdmin(player))
{
continue;
}
counter += 1;
plugin.pl.getPlayer(player).setCommandsBlocked(true);
msg(player, "Your commands have been blocked by an admin.", ChatColor.RED);
}
msg("Blocked commands for " + counter + " players.");
return true;
}
final Player player = getPlayer(args[0]);
if (player == null)
{
msg(FreedomCommand.PLAYER_NOT_FOUND);
return true;
}
if (isAdmin(player))
{
msg(player.getName() + " is a Superadmin, and cannot have their commands blocked.");
return true;
}
FPlayer playerdata = plugin.pl.getPlayer(player);
playerdata.setCommandsBlocked(!playerdata.allCommandsBlocked());
FUtil.adminAction(sender.getName(), (playerdata.allCommandsBlocked() ? "B" : "Unb") + "locking all commands for " + player.getName(), true);
msg((playerdata.allCommandsBlocked() ? "B" : "Unb") + "locked all commands.");
return true;
}
}

View File

@ -1,7 +1,8 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import me.StevenLawson.TotalFreedomMod.TFM_PlayerData; import me.totalfreedom.totalfreedommod.player.FPlayer;
import me.StevenLawson.TotalFreedomMod.TFM_Util; import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
@ -9,12 +10,13 @@ import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@CommandPermissions(level = AdminLevel.SUPER, source = SourceType.BOTH) @CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH)
@CommandParameters(description = "Place a cage around someone.", usage = "/<command> <purge | off | <partialname> [outermaterial] [innermaterial]>") @CommandParameters(description = "Place a cage around someone.", usage = "/<command> <purge | off | <partialname> [outermaterial] [innermaterial]>")
public class Command_cage extends TFM_Command public class Command_cage extends FreedomCommand
{ {
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
if (args.length == 0) if (args.length == 0)
{ {
@ -23,25 +25,20 @@ public class Command_cage extends TFM_Command
if ("off".equals(args[0]) && sender instanceof Player) if ("off".equals(args[0]) && sender instanceof Player)
{ {
TFM_Util.adminAction(sender.getName(), "Uncaging " + sender.getName(), true); FUtil.adminAction(sender.getName(), "Uncaging " + sender.getName(), true);
TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(sender_p); FPlayer playerdata = plugin.pl.getPlayer(playerSender);
playerdata.setCaged(false);
playerdata.regenerateHistory();
playerdata.clearHistory();
playerdata.getCageData().setCaged(false);
return true; return true;
} }
else if ("purge".equals(args[0])) else if ("purge".equals(args[0]))
{ {
TFM_Util.adminAction(sender.getName(), "Uncaging all players", true); FUtil.adminAction(sender.getName(), "Uncaging all players", true);
for (Player player : server.getOnlinePlayers()) for (Player player : server.getOnlinePlayers())
{ {
TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(player); FPlayer playerdata = plugin.pl.getPlayer(player);
playerdata.setCaged(false); playerdata.getCageData().setCaged(false);
playerdata.regenerateHistory();
playerdata.clearHistory();
} }
return true; return true;
@ -51,11 +48,11 @@ public class Command_cage extends TFM_Command
if (player == null) if (player == null)
{ {
sender.sendMessage(TFM_Command.PLAYER_NOT_FOUND); sender.sendMessage(FreedomCommand.PLAYER_NOT_FOUND);
return true; return true;
} }
TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(player); FPlayer playerdata = plugin.pl.getPlayer(player);
Material outerMaterial = Material.GLASS; Material outerMaterial = Material.GLASS;
Material innerMaterial = Material.AIR; Material innerMaterial = Material.AIR;
@ -64,11 +61,8 @@ public class Command_cage extends TFM_Command
{ {
if ("off".equals(args[1])) if ("off".equals(args[1]))
{ {
TFM_Util.adminAction(sender.getName(), "Uncaging " + player.getName(), true); FUtil.adminAction(sender.getName(), "Uncaging " + player.getName(), true);
playerdata.getCageData().setCaged(false);
playerdata.setCaged(false);
playerdata.regenerateHistory();
playerdata.clearHistory();
return true; return true;
} }
@ -98,22 +92,17 @@ public class Command_cage extends TFM_Command
} }
Location targetPos = player.getLocation().clone().add(0, 1, 0); Location targetPos = player.getLocation().clone().add(0, 1, 0);
playerdata.setCaged(true, targetPos, outerMaterial, innerMaterial); playerdata.getCageData().cage(targetPos, outerMaterial, innerMaterial);
playerdata.regenerateHistory();
playerdata.clearHistory();
TFM_Util.buildHistory(targetPos, 2, playerdata);
TFM_Util.generateHollowCube(targetPos, 2, outerMaterial);
TFM_Util.generateCube(targetPos, 1, innerMaterial);
player.setGameMode(GameMode.SURVIVAL); player.setGameMode(GameMode.SURVIVAL);
if (outerMaterial != Material.SKULL) if (outerMaterial != Material.SKULL)
{ {
TFM_Util.adminAction(sender.getName(), "Caging " + player.getName(), true); FUtil.adminAction(sender.getName(), "Caging " + player.getName(), true);
} }
else else
{ {
TFM_Util.adminAction(sender.getName(), "Caging " + player.getName() + " in PURE_DARTH", true); FUtil.adminAction(sender.getName(), "Caging " + player.getName() + " in PURE_DARTH", true);
} }
return true; return true;

View File

@ -1,7 +1,8 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import java.util.Random; import java.util.Random;
import me.StevenLawson.TotalFreedomMod.TFM_Util; import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.Achievement; import org.bukkit.Achievement;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Material; import org.bukkit.Material;
@ -11,15 +12,16 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
@CommandPermissions(level = AdminLevel.SUPER, source = SourceType.BOTH) @CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH)
@CommandParameters(description = "For the people that are still alive.", usage = "/<command>") @CommandParameters(description = "For the people that are still alive.", usage = "/<command>")
public class Command_cake extends TFM_Command public class Command_cake extends FreedomCommand
{ {
public static final String CAKE_LYRICS = "But there's no sense crying over every mistake. You just keep on trying till you run out of cake."; public static final String CAKE_LYRICS = "But there's no sense crying over every mistake. You just keep on trying till you run out of cake.";
private final Random random = new Random(); private final Random random = new Random();
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
final StringBuilder output = new StringBuilder(); final StringBuilder output = new StringBuilder();
@ -45,7 +47,7 @@ public class Command_cake extends TFM_Command
player.awardAchievement(Achievement.BAKE_CAKE); player.awardAchievement(Achievement.BAKE_CAKE);
} }
TFM_Util.bcastMsg(output.toString()); FUtil.bcastMsg(output.toString());
return true; return true;
} }

View File

@ -1,19 +1,20 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import me.StevenLawson.TotalFreedomMod.TFM_AdminList; import me.totalfreedom.totalfreedommod.rank.Rank;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Minecart; import org.bukkit.entity.Minecart;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@CommandPermissions(level = AdminLevel.ALL, source = SourceType.BOTH) @CommandPermissions(level = Rank.NON_OP, source = SourceType.BOTH)
@CommandParameters(description = "Sit in nearest minecart. If target is in a minecart already, they will disembark.", usage = "/<command> [partialname]") @CommandParameters(description = "Sit in nearest minecart. If target is in a minecart already, they will disembark.", usage = "/<command> [partialname]")
public class Command_cartsit extends TFM_Command public class Command_cartsit extends FreedomCommand
{ {
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
Player targetPlayer = sender_p; Player targetPlayer = playerSender;
if (args.length == 1) if (args.length == 1)
{ {
@ -22,7 +23,7 @@ public class Command_cartsit extends TFM_Command
if (targetPlayer == null) if (targetPlayer == null)
{ {
sender.sendMessage(TFM_Command.PLAYER_NOT_FOUND); sender.sendMessage(FreedomCommand.PLAYER_NOT_FOUND);
return true; return true;
} }
} }
@ -35,7 +36,7 @@ public class Command_cartsit extends TFM_Command
return true; return true;
} }
} }
else if (targetPlayer != sender_p && !TFM_AdminList.isSuperAdmin(sender)) else if (targetPlayer != playerSender && !isAdmin(sender))
{ {
sender.sendMessage("Only superadmins can select another player as a /cartsit target."); sender.sendMessage("Only superadmins can select another player as a /cartsit target.");
return true; return true;

View File

@ -1,11 +1,11 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import java.util.List; import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import me.StevenLawson.TotalFreedomMod.TFM_CommandBlocker; import me.totalfreedom.totalfreedommod.rank.Rank;
import me.StevenLawson.TotalFreedomMod.TFM_DepreciationAggregator; import me.totalfreedom.totalfreedommod.util.DepreciationAggregator;
import me.StevenLawson.TotalFreedomMod.TFM_Log; import me.totalfreedom.totalfreedommod.util.FLog;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -16,12 +16,13 @@ import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@CommandPermissions(level = AdminLevel.ALL, source = SourceType.BOTH) @CommandPermissions(level = Rank.NON_OP, source = SourceType.BOTH)
@CommandParameters(description = "No Description Yet", usage = "/<command>") @CommandParameters(description = "No Description Yet", usage = "/<command>")
public class Command_cbtool extends TFM_Command public class Command_cbtool extends FreedomCommand
{ {
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
if (args.length < 1) if (args.length < 1)
{ {
@ -30,8 +31,8 @@ public class Command_cbtool extends TFM_Command
if ("targetblock".equalsIgnoreCase(args[0]) && sender instanceof Player) if ("targetblock".equalsIgnoreCase(args[0]) && sender instanceof Player)
{ {
Block targetBlock = TFM_DepreciationAggregator.getTargetBlock(sender_p, null, 100); Block targetBlock = DepreciationAggregator.getTargetBlock(playerSender, null, 100);
playerMsg("Your target block: " + targetBlock.getLocation().toString()); msg("Your target block: " + targetBlock.getLocation().toString());
return true; return true;
} }
@ -46,7 +47,7 @@ public class Command_cbtool extends TFM_Command
} }
matcher.appendTail(generatedCommand); matcher.appendTail(generatedCommand);
if (TFM_CommandBlocker.isCommandBlocked(generatedCommand.toString(), sender, false)) if (plugin.cb.isCommandBlocked(generatedCommand.toString(), sender, false))
{ {
return true; return true;
} }
@ -58,7 +59,7 @@ public class Command_cbtool extends TFM_Command
} }
catch (Exception ex) catch (Exception ex)
{ {
TFM_Log.severe(ex); FLog.severe(ex);
} }
return true; return true;
@ -78,6 +79,7 @@ public class Command_cbtool extends TFM_Command
private static enum SubCommand private static enum SubCommand
{ {
PLAYER_DETECT("playerdetect", new SubCommandExecutable() PLAYER_DETECT("playerdetect", new SubCommandExecutable()
{ {
@Override @Override
@ -196,11 +198,13 @@ public class Command_cbtool extends TFM_Command
private interface SubCommandExecutable private interface SubCommandExecutable
{ {
public String execute(String[] args) throws SubCommandFailureException; public String execute(String[] args) throws SubCommandFailureException;
} }
private static class SubCommandFailureException extends Exception private static class SubCommandFailureException extends Exception
{ {
public SubCommandFailureException() public SubCommandFailureException()
{ {
} }
@ -210,4 +214,5 @@ public class Command_cbtool extends TFM_Command
super(message); super(message);
} }
} }
} }

View File

@ -0,0 +1,24 @@
package me.totalfreedom.totalfreedommod.command;
import me.totalfreedom.totalfreedommod.player.FPlayer;
import me.totalfreedom.totalfreedommod.rank.Rank;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.ONLY_IN_GAME)
@CommandParameters(description = "Spy on commands", usage = "/<command>", aliases = "commandspy")
public class Command_cmdspy extends FreedomCommand
{
@Override
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
FPlayer playerdata = plugin.pl.getPlayer(playerSender);
playerdata.setCommandSpy(!playerdata.cmdspyEnabled());
msg("CommandSpy " + (playerdata.cmdspyEnabled() ? "enabled." : "disabled."));
return true;
}
}

View File

@ -1,21 +1,22 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import me.StevenLawson.TotalFreedomMod.Bridge.TFM_EssentialsBridge; import me.totalfreedom.totalfreedommod.rank.Rank;
import me.StevenLawson.TotalFreedomMod.TFM_Util; import me.totalfreedom.totalfreedommod.util.FUtil;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@CommandPermissions(level = AdminLevel.OP, source = SourceType.ONLY_IN_GAME) @CommandPermissions(level = Rank.OP, source = SourceType.ONLY_IN_GAME)
@CommandParameters(description = "Essentials Interface Command - Color your current nickname.", usage = "/<command> <color>") @CommandParameters(description = "Essentials Interface Command - Color your current nickname.", usage = "/<command> <color>")
public class Command_colorme extends TFM_Command public class Command_colorme extends FreedomCommand
{ {
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
if (args.length != 1) if (args.length != 1)
{ {
@ -24,13 +25,13 @@ public class Command_colorme extends TFM_Command
if ("list".equalsIgnoreCase(args[0])) if ("list".equalsIgnoreCase(args[0]))
{ {
playerMsg("Colors: " + StringUtils.join(TFM_Util.CHAT_COLOR_NAMES.keySet(), ", ")); msg("Colors: " + StringUtils.join(FUtil.CHAT_COLOR_NAMES.keySet(), ", "));
return true; return true;
} }
final String needle = args[0].trim().toLowerCase(); final String needle = args[0].trim().toLowerCase();
ChatColor color = null; ChatColor color = null;
final Iterator<Map.Entry<String, ChatColor>> it = TFM_Util.CHAT_COLOR_NAMES.entrySet().iterator(); final Iterator<Map.Entry<String, ChatColor>> it = FUtil.CHAT_COLOR_NAMES.entrySet().iterator();
while (it.hasNext()) while (it.hasNext())
{ {
final Map.Entry<String, ChatColor> entry = it.next(); final Map.Entry<String, ChatColor> entry = it.next();
@ -43,15 +44,15 @@ public class Command_colorme extends TFM_Command
if (color == null) if (color == null)
{ {
playerMsg("Invalid color: " + needle + " - Use \"/colorme list\" to list colors."); msg("Invalid color: " + needle + " - Use \"/colorme list\" to list colors.");
return true; return true;
} }
final String newNick = color + ChatColor.stripColor(sender_p.getDisplayName()).trim() + ChatColor.WHITE; final String newNick = color + ChatColor.stripColor(playerSender.getDisplayName()).trim() + ChatColor.WHITE;
TFM_EssentialsBridge.setNickname(sender.getName(), newNick); plugin.esb.setNickname(sender.getName(), newNick);
playerMsg("Your nickname is now: " + newNick); msg("Your nickname is now: " + newNick);
return true; return true;
} }

View File

@ -1,10 +1,11 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import me.totalfreedom.totalfreedommod.rank.Rank;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
@ -12,14 +13,15 @@ import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginDescriptionFile;
@CommandPermissions(level = AdminLevel.ALL, source = SourceType.BOTH) @CommandPermissions(level = Rank.NON_OP, source = SourceType.BOTH)
@CommandParameters(description = "Show all commands for all server plugins.", usage = "/<command>") @CommandParameters(description = "Show all commands for all server plugins.", usage = "/<command>", aliases = "cmdlist")
public class Command_cmdlist extends TFM_Command public class Command_commandlist extends FreedomCommand
{ {
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
List<String> commands = new ArrayList<String>(); List<String> commands = new ArrayList<>();
for (Plugin targetPlugin : server.getPluginManager().getPlugins()) for (Plugin targetPlugin : server.getPluginManager().getPlugins())
{ {

View File

@ -0,0 +1,24 @@
package me.totalfreedom.totalfreedommod.command;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.ONLY_CONSOLE)
@CommandParameters(description = "Telnet command - Send a chat message with chat formatting over telnet.", usage = "/<command> <message...>", aliases = "csay")
public class Command_consolesay extends FreedomCommand
{
@Override
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
if (args.length > 0)
{
FUtil.bcastMsg(String.format("§7[CONSOLE]§f<§c%s§f> %s", sender.getName(), StringUtils.join(args, " ")));
}
return true;
}
}

View File

@ -0,0 +1,58 @@
package me.totalfreedom.totalfreedommod.command;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.GameMode;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.OP, source = SourceType.BOTH)
@CommandParameters(description = "Quickly change your own gamemode to creative, or define someone's username to change theirs.", usage = "/<command> <-a | [partialname]>", aliases = "gmc")
public class Command_creative extends FreedomCommand
{
@Override
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
if (args.length == 0)
{
if (isConsole())
{
sender.sendMessage("When used from the console, you must define a target player.");
return true;
}
playerSender.setGameMode(GameMode.CREATIVE);
msg("Gamemode set to creative.");
return true;
}
checkRank(Rank.SUPER_ADMIN);
if (args[0].equals("-a"))
{
for (Player targetPlayer : server.getOnlinePlayers())
{
targetPlayer.setGameMode(GameMode.CREATIVE);
}
FUtil.adminAction(sender.getName(), "Changing everyone's gamemode to creative", false);
return true;
}
Player player = getPlayer(args[0]);
if (player == null)
{
sender.sendMessage(FreedomCommand.PLAYER_NOT_FOUND);
return true;
}
msg("Setting " + player.getName() + " to game mode creative");
msg(player, sender.getName() + " set your game mode to creative");
player.setGameMode(GameMode.CREATIVE);
return true;
}
}

View File

@ -1,6 +1,7 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import java.util.Random; import java.util.Random;
import me.totalfreedom.totalfreedommod.rank.Rank;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Sound; import org.bukkit.Sound;
import org.bukkit.command.Command; import org.bukkit.command.Command;
@ -8,15 +9,16 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
@CommandPermissions(level = AdminLevel.SENIOR, source = SourceType.BOTH, blockHostConsole = true) @CommandPermissions(level = Rank.SENIOR_ADMIN, source = SourceType.BOTH, blockHostConsole = true)
@CommandParameters(description = "Make some noise.", usage = "/<command>") @CommandParameters(description = "Make some noise.", usage = "/<command>")
public class Command_deafen extends TFM_Command public class Command_deafen extends FreedomCommand
{ {
private static final Random random = new Random(); private static final Random random = new Random();
public static final double STEPS = 10.0; public static final double STEPS = 10.0;
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
for (final Player player : server.getOnlinePlayers()) for (final Player player : server.getOnlinePlayers())
{ {

View File

@ -1,18 +1,20 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import me.totalfreedom.totalfreedommod.rank.Rank;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@CommandPermissions(level = AdminLevel.SENIOR, source = SourceType.ONLY_CONSOLE) @CommandPermissions(level = Rank.SENIOR_ADMIN, source = SourceType.ONLY_CONSOLE)
@CommandParameters(description = "For developers only - debug things via reflection.", usage = "/<command>") @CommandParameters(description = "For developers only - debug things via reflection.", usage = "/<command>")
public class Command_debug extends TFM_Command public class Command_debug extends FreedomCommand
{ {
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
if (args.length < 3) if (args.length < 3)
{ {

View File

@ -0,0 +1,26 @@
package me.totalfreedom.totalfreedommod.command;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH)
@CommandParameters(description = "Essentials Interface Command - Remove the nickname of all players on the server.", usage = "/<command>")
public class Command_denick extends FreedomCommand
{
@Override
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
FUtil.adminAction(sender.getName(), "Removing all nicknames", false);
for (Player player : server.getOnlinePlayers())
{
plugin.esb.setNickname(player.getName(), null);
}
return true;
}
}

View File

@ -1,18 +1,20 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import me.StevenLawson.TotalFreedomMod.TFM_DepreciationAggregator; import me.totalfreedom.totalfreedommod.rank.Rank;
import me.StevenLawson.TotalFreedomMod.TFM_Util; import me.totalfreedom.totalfreedommod.util.DepreciationAggregator;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@CommandPermissions(level = AdminLevel.SUPER, source = SourceType.BOTH) @CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH)
@CommandParameters(description = "Deop a player.", usage = "/<command> <playername>") @CommandParameters(description = "Deop a player.", usage = "/<command> <playername>")
public class Command_deop extends TFM_Command public class Command_deop extends FreedomCommand
{ {
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
if (args.length != 1) if (args.length != 1)
{ {
@ -32,10 +34,10 @@ public class Command_deop extends TFM_Command
// if the player is not online // if the player is not online
if (player == null) if (player == null)
{ {
player = TFM_DepreciationAggregator.getOfflinePlayer(server, args[0]); player = DepreciationAggregator.getOfflinePlayer(server, args[0]);
} }
TFM_Util.adminAction(sender.getName(), "De-opping " + player.getName(), false); FUtil.adminAction(sender.getName(), "De-opping " + player.getName(), false);
player.setOp(false); player.setOp(false);

View File

@ -0,0 +1,27 @@
package me.totalfreedom.totalfreedommod.command;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH, blockHostConsole = true)
@CommandParameters(description = "Deop everyone on the server.", usage = "/<command>")
public class Command_deopall extends FreedomCommand
{
@Override
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
FUtil.adminAction(sender.getName(), "De-opping all players on the server", true);
for (Player player : server.getOnlinePlayers())
{
player.setOp(false);
player.sendMessage(FreedomCommand.YOU_ARE_NOT_OP);
}
return true;
}
}

View File

@ -1,9 +1,10 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import me.StevenLawson.TotalFreedomMod.TFM_DepreciationAggregator; import me.totalfreedom.totalfreedommod.rank.Rank;
import me.StevenLawson.TotalFreedomMod.TFM_Util; import me.totalfreedom.totalfreedommod.util.DepreciationAggregator;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
@ -15,12 +16,13 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@CommandPermissions(level = AdminLevel.OP, source = SourceType.ONLY_IN_GAME) @CommandPermissions(level = Rank.OP, source = SourceType.ONLY_IN_GAME)
@CommandParameters(description = "Fill nearby dispensers with a set of items of your choice.", usage = "/<command> <radius> <comma,separated,items>") @CommandParameters(description = "Fill nearby dispensers with a set of items of your choice.", usage = "/<command> <radius> <comma,separated,items>")
public class Command_dispfill extends TFM_Command public class Command_dispfill extends FreedomCommand
{ {
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
if (args.length == 2) if (args.length == 2)
{ {
@ -36,7 +38,7 @@ public class Command_dispfill extends TFM_Command
return true; return true;
} }
final List<ItemStack> items = new ArrayList<ItemStack>(); final List<ItemStack> items = new ArrayList<>();
final String[] itemsRaw = StringUtils.split(args[1], ","); final String[] itemsRaw = StringUtils.split(args[1], ",");
for (final String searchItem : itemsRaw) for (final String searchItem : itemsRaw)
@ -46,7 +48,7 @@ public class Command_dispfill extends TFM_Command
{ {
try try
{ {
material = TFM_DepreciationAggregator.getMaterial(Integer.parseInt(searchItem)); material = DepreciationAggregator.getMaterial(Integer.parseInt(searchItem));
} }
catch (NumberFormatException ex) catch (NumberFormatException ex)
{ {
@ -66,7 +68,7 @@ public class Command_dispfill extends TFM_Command
final ItemStack[] itemsArray = items.toArray(new ItemStack[items.size()]); final ItemStack[] itemsArray = items.toArray(new ItemStack[items.size()]);
int affected = 0; int affected = 0;
final Location centerLocation = sender_p.getLocation(); final Location centerLocation = playerSender.getLocation();
final Block centerBlock = centerLocation.getBlock(); final Block centerBlock = centerLocation.getBlock();
for (int xOffset = -radius; xOffset <= radius; xOffset++) for (int xOffset = -radius; xOffset <= radius; xOffset++)
{ {
@ -79,7 +81,7 @@ public class Command_dispfill extends TFM_Command
{ {
if (targetBlock.getType().equals(Material.DISPENSER)) if (targetBlock.getType().equals(Material.DISPENSER))
{ {
sender.sendMessage("Filling dispenser @ " + TFM_Util.formatLocation(targetBlock.getLocation())); sender.sendMessage("Filling dispenser @ " + FUtil.formatLocation(targetBlock.getLocation()));
setDispenserContents(targetBlock, itemsArray); setDispenserContents(targetBlock, itemsArray);
affected++; affected++;
} }

View File

@ -1,10 +1,9 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import me.StevenLawson.TotalFreedomMod.TFM_AdminList; import me.totalfreedom.totalfreedommod.admin.Admin;
import me.StevenLawson.TotalFreedomMod.TFM_Ban; import me.totalfreedom.totalfreedommod.banning.Ban;
import me.StevenLawson.TotalFreedomMod.TFM_BanManager; import me.totalfreedom.totalfreedommod.rank.Rank;
import me.StevenLawson.TotalFreedomMod.TFM_PlayerList; import me.totalfreedom.totalfreedommod.util.FUtil;
import me.StevenLawson.TotalFreedomMod.TFM_Util;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.command.Command; import org.bukkit.command.Command;
@ -13,12 +12,13 @@ import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
@CommandPermissions(level = AdminLevel.SENIOR, source = SourceType.ONLY_CONSOLE) @CommandPermissions(level = Rank.SENIOR_ADMIN, source = SourceType.ONLY_CONSOLE, blockHostConsole = true)
@CommandParameters(description = "For the bad Superadmins", usage = "/<command> <playername>") @CommandParameters(description = "For the bad admins", usage = "/<command> <playername>")
public class Command_doom extends TFM_Command public class Command_doom extends FreedomCommand
{ {
@Override @Override
public boolean run(final CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(final CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
if (args.length != 1) if (args.length != 1)
{ {
@ -29,48 +29,49 @@ public class Command_doom extends TFM_Command
if (player == null) if (player == null)
{ {
sender.sendMessage(TFM_Command.PLAYER_NOT_FOUND); sender.sendMessage(FreedomCommand.PLAYER_NOT_FOUND);
return true; return true;
} }
TFM_Util.adminAction(sender.getName(), "Casting oblivion over " + player.getName(), true); FUtil.adminAction(sender.getName(), "Casting oblivion over " + player.getName(), true);
TFM_Util.bcastMsg(player.getName() + " will be completely obliviated!", ChatColor.RED); FUtil.bcastMsg(player.getName() + " will be completely obliviated!", ChatColor.RED);
final String ip = player.getAddress().getAddress().getHostAddress().trim(); final String ip = player.getAddress().getAddress().getHostAddress().trim();
// remove from superadmin // Remove from superadmin
if (TFM_AdminList.isSuperAdmin(player)) Admin admin = getAdmin(player);
if (admin != null)
{ {
TFM_Util.adminAction(sender.getName(), "Removing " + player.getName() + " from the superadmin list.", true); FUtil.adminAction(sender.getName(), "Removing " + player.getName() + " from the superadmin list", true);
TFM_AdminList.removeSuperadmin(player); plugin.al.removeAdmin(admin);
} }
// remove from whitelist // Remove from whitelist
player.setWhitelisted(false); player.setWhitelisted(false);
// deop // Deop
player.setOp(false); player.setOp(false);
// ban IPs // Ban player
for (String playerIp : TFM_PlayerList.getEntry(player).getIps()) Ban ban = Ban.forPlayer(player, sender);
ban.setReason("&cFUCKOFF");
for (String playerIp : plugin.pl.getData(player).getIps())
{ {
TFM_BanManager.addIpBan(new TFM_Ban(playerIp, player.getName())); ban.addIp(playerIp);
} }
plugin.bm.addBan(ban);
// ban uuid // Set gamemode to survival
TFM_BanManager.addUuidBan(player);
// set gamemode to survival
player.setGameMode(GameMode.SURVIVAL); player.setGameMode(GameMode.SURVIVAL);
// clear inventory // Clear inventory
player.closeInventory(); player.closeInventory();
player.getInventory().clear(); player.getInventory().clear();
// ignite player // Ignite player
player.setFireTicks(10000); player.setFireTicks(10000);
// generate explosion // Generate explosion
player.getWorld().createExplosion(player.getLocation(), 4F); player.getWorld().createExplosion(player.getLocation(), 4F);
// Shoot the player in the sky // Shoot the player in the sky
@ -95,7 +96,7 @@ public class Command_doom extends TFM_Command
public void run() public void run()
{ {
// message // message
TFM_Util.adminAction(sender.getName(), "Banning " + player.getName() + ", IP: " + ip, true); FUtil.adminAction(sender.getName(), "Banning " + player.getName() + ", IP: " + ip, true);
// generate explosion // generate explosion
player.getWorld().createExplosion(player.getLocation(), 4F); player.getWorld().createExplosion(player.getLocation(), 4F);

View File

@ -1,29 +1,31 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import me.StevenLawson.TotalFreedomMod.TFM_Log; import me.totalfreedom.totalfreedommod.rank.Rank;
import org.bukkit.Material;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment; import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
@CommandPermissions(level = AdminLevel.OP, source = SourceType.ONLY_IN_GAME) @CommandPermissions(level = Rank.OP, source = SourceType.ONLY_IN_GAME)
@CommandParameters(description = "Enchant items.", usage = "/<command> <list | addall | reset | add <name> | remove <name>>") @CommandParameters(description = "Enchant items.", usage = "/<command> <list | addall | reset | add <name> | remove <name>>")
public class Command_enchant extends TFM_Command public class Command_enchant extends FreedomCommand
{ {
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
if (args.length < 1) if (args.length < 1)
{ {
return false; return false;
} }
ItemStack itemInHand = sender_p.getItemInHand(); ItemStack item = playerSender.getEquipment().getItemInMainHand();
if (itemInHand == null) if (item == null || item.getType() == Material.AIR)
{ {
playerMsg("You are holding an invalid item."); msg("You have to hold an item to enchant it");
return true; return true;
} }
@ -34,7 +36,7 @@ public class Command_enchant extends TFM_Command
StringBuilder possible_ench = new StringBuilder("Possible enchantments for held item: "); StringBuilder possible_ench = new StringBuilder("Possible enchantments for held item: ");
for (Enchantment ench : Enchantment.values()) for (Enchantment ench : Enchantment.values())
{ {
if (ench.canEnchantItem(itemInHand)) if (ench.canEnchantItem(item))
{ {
has_enchantments = true; has_enchantments = true;
possible_ench.append(ench.getName()).append(", "); possible_ench.append(ench.getName()).append(", ");
@ -43,11 +45,11 @@ public class Command_enchant extends TFM_Command
if (has_enchantments) if (has_enchantments)
{ {
playerMsg(possible_ench.toString()); msg(possible_ench.toString());
} }
else else
{ {
playerMsg("The held item has no enchantments."); msg("The held item has no enchantments.");
} }
} }
else if (args[0].equalsIgnoreCase("addall")) else if (args[0].equalsIgnoreCase("addall"))
@ -56,27 +58,27 @@ public class Command_enchant extends TFM_Command
{ {
try try
{ {
if (ench.canEnchantItem(itemInHand)) if (ench.canEnchantItem(item))
{ {
itemInHand.addEnchantment(ench, ench.getMaxLevel()); item.addEnchantment(ench, ench.getMaxLevel());
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
TFM_Log.info("Error using " + ench.getName() + " on " + itemInHand.getType().name() + " held by " + sender_p.getName() + "."); msg("Could not add enchantment: " + ench.getName());
} }
} }
playerMsg("Added all possible enchantments for this item."); msg("Added all possible enchantments for this item.");
} }
else if (args[0].equalsIgnoreCase("reset")) else if (args[0].equalsIgnoreCase("reset"))
{ {
for (Enchantment ench : itemInHand.getEnchantments().keySet()) for (Enchantment ench : item.getEnchantments().keySet())
{ {
itemInHand.removeEnchantment(ench); item.removeEnchantment(ench);
} }
playerMsg("Removed all enchantments."); msg("Removed all enchantments.");
} }
else else
{ {
@ -97,28 +99,28 @@ public class Command_enchant extends TFM_Command
if (ench == null) if (ench == null)
{ {
playerMsg(args[1] + " is an invalid enchantment for the held item. Type \"/enchant list\" for valid enchantments for this item."); msg(args[1] + " is an invalid enchantment for the held item. Type \"/enchant list\" for valid enchantments for this item.");
return true; return true;
} }
if (args[0].equalsIgnoreCase("add")) if (args[0].equalsIgnoreCase("add"))
{ {
if (ench.canEnchantItem(itemInHand)) if (ench.canEnchantItem(item))
{ {
itemInHand.addEnchantment(ench, ench.getMaxLevel()); item.addEnchantment(ench, ench.getMaxLevel());
playerMsg("Added enchantment: " + ench.getName()); msg("Added enchantment: " + ench.getName());
} }
else else
{ {
playerMsg("Can't use this enchantment on held item."); msg("Can't use this enchantment on held item.");
} }
} }
else if (args[0].equals("remove")) else if (args[0].equals("remove"))
{ {
itemInHand.removeEnchantment(ench); item.removeEnchantment(ench);
playerMsg("Removed enchantment: " + ench.getName()); msg("Removed enchantment: " + ench.getName());
} }
} }

View File

@ -0,0 +1,20 @@
package me.totalfreedom.totalfreedommod.command;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.NON_OP, source = SourceType.ONLY_IN_GAME)
@CommandParameters(description = "Goto the ender / \"The End\".", usage = "/<command>")
public class Command_ender extends FreedomCommand
{
@Override
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
plugin.wm.gotoWorld(playerSender, server.getWorlds().get(0).getName() + "_the_end");
return true;
}
}

View File

@ -0,0 +1,22 @@
package me.totalfreedom.totalfreedommod.command;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH)
@CommandParameters(description = "Remove various server entities that may cause lag, such as dropped items, minecarts, and boats.", usage = "/<command> <carts>", aliases = "ew,rd")
public class Command_entitywipe extends FreedomCommand
{
@Override
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
FUtil.adminAction(sender.getName(), "Removing all server entities.", true);
msg((plugin.ew.wipeEntities(true, true)) + " entities removed.");
return true;
}
}

View File

@ -1,7 +1,9 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.command.Command; import org.bukkit.command.Command;
@ -9,12 +11,13 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
@CommandPermissions(level = AdminLevel.SUPER, source = SourceType.ONLY_IN_GAME) @CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.ONLY_IN_GAME)
@CommandParameters(description = "Push people away from you.", usage = "/<command> [radius] [strength]") @CommandParameters(description = "Push people away from you.", usage = "/<command> [radius] [strength]")
public class Command_expel extends TFM_Command public class Command_expel extends FreedomCommand
{ {
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
double radius = 20.0; double radius = 20.0;
double strength = 5.0; double strength = 5.0;
@ -41,13 +44,13 @@ public class Command_expel extends TFM_Command
} }
} }
List<String> pushedPlayers = new ArrayList<String>(); List<String> pushedPlayers = new ArrayList<>();
final Vector senderPos = sender_p.getLocation().toVector(); final Vector senderPos = playerSender.getLocation().toVector();
final List<Player> players = sender_p.getWorld().getPlayers(); final List<Player> players = playerSender.getWorld().getPlayers();
for (final Player player : players) for (final Player player : players)
{ {
if (player.equals(sender_p)) if (player.equals(playerSender))
{ {
continue; continue;
} }
@ -67,7 +70,7 @@ public class Command_expel extends TFM_Command
if (inRange) if (inRange)
{ {
player.getWorld().createExplosion(targetPos, 0.0f, false); player.getWorld().createExplosion(targetPos, 0.0f, false);
player.setFlying(false); FUtil.setFlying(player, false);
player.setVelocity(targetPosVec.subtract(senderPos).normalize().multiply(strength)); player.setVelocity(targetPosVec.subtract(senderPos).normalize().multiply(strength));
pushedPlayers.add(player.getName()); pushedPlayers.add(player.getName());
} }
@ -75,11 +78,11 @@ public class Command_expel extends TFM_Command
if (pushedPlayers.isEmpty()) if (pushedPlayers.isEmpty())
{ {
playerMsg("No players pushed."); msg("No players pushed.");
} }
else else
{ {
playerMsg("Pushed " + pushedPlayers.size() + " players: " + StringUtils.join(pushedPlayers, ", ")); msg("Pushed " + pushedPlayers.size() + " players: " + StringUtils.join(pushedPlayers, ", "));
} }
return true; return true;

View File

@ -1,17 +1,18 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import me.StevenLawson.TotalFreedomMod.TFM_PlayerList; import me.totalfreedom.totalfreedommod.rank.Rank;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@CommandPermissions(level = AdminLevel.SUPER, source = SourceType.BOTH) @CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH)
@CommandParameters(description = "Shows all IPs registered to a player", usage = "/<command> <player>") @CommandParameters(description = "Shows all IPs registered to a player", usage = "/<command> <player>")
public class Command_findip extends TFM_Command public class Command_findip extends FreedomCommand
{ {
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
if (args.length != 1) if (args.length != 1)
{ {
@ -23,11 +24,11 @@ public class Command_findip extends TFM_Command
if (player == null) if (player == null)
{ {
playerMsg(TFM_Command.PLAYER_NOT_FOUND); msg(FreedomCommand.PLAYER_NOT_FOUND);
return true; return true;
} }
playerMsg("Player IPs: " + StringUtils.join(TFM_PlayerList.getEntry(player).getIps(), ", ")); msg("Player IPs: " + StringUtils.join(plugin.pl.getData(player).getIps(), ", "));
return true; return true;
} }

View File

@ -0,0 +1,27 @@
package me.totalfreedom.totalfreedommod.command;
import me.totalfreedom.totalfreedommod.config.ConfigEntry;
import me.totalfreedom.totalfreedommod.rank.Rank;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.NON_OP, source = SourceType.ONLY_IN_GAME)
@CommandParameters(description = "Goto the flatlands.", usage = "/<command>")
public class Command_flatlands extends FreedomCommand
{
@Override
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
if (ConfigEntry.FLATLANDS_GENERATE.getBoolean())
{
plugin.wm.flatlands.sendToWorld(playerSender);
}
else
{
msg("Flatlands is currently disabled.");
}
return true;
}
}

View File

@ -0,0 +1,67 @@
package me.totalfreedom.totalfreedommod.command;
import me.totalfreedom.totalfreedommod.freeze.FreezeData;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH)
@CommandParameters(description = "Freeze players (toggles on and off).", usage = "/<command> [target | purge]", aliases = "fr")
public class Command_freeze extends FreedomCommand
{
@Override
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
if (args.length == 0)
{
boolean gFreeze = !plugin.fm.isGlobalFreeze();
plugin.fm.setGlobalFreeze(gFreeze);
if (!gFreeze)
{
FUtil.adminAction(sender.getName(), "Disabling global player freeze", false);
msg("Players are now free to move.");
return true;
}
FUtil.adminAction(sender.getName(), "Enabling global player freeze", false);
for (Player player : server.getOnlinePlayers())
{
if (!isAdmin(player))
{
msg(player, "You have been frozen due to rulebreakers, you will be unfrozen soon.", ChatColor.RED);
}
}
msg("Players are now frozen.");
return true;
}
if (args[0].equals("purge"))
{
FUtil.adminAction(sender.getName(), "Unfreezing all players", false);
plugin.fm.purge();
return true;
}
final Player player = getPlayer(args[0]);
if (player == null)
{
msg(FreedomCommand.PLAYER_NOT_FOUND, ChatColor.RED);
return true;
}
final FreezeData fd = plugin.pl.getPlayer(player).getFreezeData();
fd.setFrozen(!fd.isFrozen());
msg(player.getName() + " has been " + (fd.isFrozen() ? "frozen" : "unfrozen") + ".");
msg(player, "You have been " + (fd.isFrozen() ? "frozen" : "unfrozen") + ".", ChatColor.AQUA);
return true;
}
}

View File

@ -0,0 +1,50 @@
package me.totalfreedom.totalfreedommod.command;
import me.totalfreedom.totalfreedommod.player.FPlayer;
import me.totalfreedom.totalfreedommod.rank.Rank;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.SENIOR_ADMIN, source = SourceType.ONLY_IN_GAME)
@CommandParameters(description = "You'll never even see it coming.", usage = "/<command> <on [radius (default=25)] | off>")
public class Command_fuckoff extends FreedomCommand
{
@Override
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
if (args.length < 1)
{
return false;
}
FPlayer player = plugin.pl.getPlayer(playerSender);
if (!args[0].equals("on"))
{
player.disableFuckoff();
}
else
{
double radius = 25.0;
if (args.length >= 2)
{
try
{
radius = Math.max(5.0, Math.min(50, Double.parseDouble(args[1])));
}
catch (NumberFormatException ex)
{
}
}
player.setFuckoff(radius);
}
msg("Fuckoff " + (player.isFuckOff() ? ("enabled. Radius: " + player.getFuckoffRadius() + ".") : "disabled."));
return true;
}
}

View File

@ -1,23 +1,27 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import java.nio.charset.StandardCharsets;
import java.util.Iterator; import java.util.Iterator;
import me.StevenLawson.TotalFreedomMod.TFM_BanManager; import java.util.UUID;
import me.StevenLawson.TotalFreedomMod.TFM_PlayerData; import me.totalfreedom.totalfreedommod.banning.Ban;
import me.StevenLawson.TotalFreedomMod.TFM_Util; import me.totalfreedom.totalfreedommod.freeze.FreezeData;
import me.StevenLawson.TotalFreedomMod.TFM_UuidManager; import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@CommandPermissions(level = AdminLevel.SUPER, source = SourceType.BOTH) @CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH, blockHostConsole = true)
@CommandParameters( @CommandParameters(
description = "Use admin commands on someone by hash. Use mode 'list' to get a player's hash. Other modes are kick, nameban, ipban, ban, op, deop, ci, fr, smite.", description = "Use admin commands on someone by hash. Use mode 'list' to get a player's hash. Other modes are kick, nameban, ipban, ban, op, deop, ci, fr, smite.",
usage = "/<command> [list | [<kick | nameban | ipban | ban | op | deop | ci | fr | smite> <targethash>] ]") usage = "/<command> [list | [<kick | nameban | ipban | ban | op | deop | ci | fr | smite> <targethash>] ]")
public class Command_gadmin extends TFM_Command public class Command_gadmin extends FreedomCommand
{ {
private enum GadminMode private enum GadminMode
{ {
LIST("list"), LIST("list"),
KICK("kick"), KICK("kick"),
NAMEBAN("nameban"), NAMEBAN("nameban"),
@ -53,8 +57,13 @@ public class Command_gadmin extends TFM_Command
} }
} }
public String getPlayerHash(Player player)
{
return UUID.nameUUIDFromBytes(player.getName().toLowerCase().getBytes(StandardCharsets.UTF_8)).toString().substring(0, 4);
}
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
if (args.length == 0) if (args.length == 0)
{ {
@ -64,7 +73,7 @@ public class Command_gadmin extends TFM_Command
final GadminMode mode = GadminMode.findMode(args[0].toLowerCase()); final GadminMode mode = GadminMode.findMode(args[0].toLowerCase());
if (mode == null) if (mode == null)
{ {
playerMsg("Invalid mode: " + args[0], ChatColor.RED); msg("Invalid mode: " + args[0], ChatColor.RED);
return true; return true;
} }
@ -72,15 +81,14 @@ public class Command_gadmin extends TFM_Command
if (mode == GadminMode.LIST) if (mode == GadminMode.LIST)
{ {
playerMsg("[ Real Name ] : [ Display Name ] - Hash:"); msg("[ Real Name ] : [ Display Name ] - Hash:");
while (it.hasNext()) while (it.hasNext())
{ {
final Player player = it.next(); final Player player = it.next();
final String hash = TFM_UuidManager.getUniqueId(player).toString().substring(0, 4);
sender.sendMessage(ChatColor.GRAY + String.format("[ %s ] : [ %s ] - %s", sender.sendMessage(ChatColor.GRAY + String.format("[ %s ] : [ %s ] - %s",
player.getName(), player.getName(),
ChatColor.stripColor(player.getDisplayName()), ChatColor.stripColor(player.getDisplayName()),
hash)); getPlayerHash(player)));
} }
return true; return true;
} }
@ -94,7 +102,7 @@ public class Command_gadmin extends TFM_Command
while (it.hasNext() && target == null) while (it.hasNext() && target == null)
{ {
final Player player = it.next(); final Player player = it.next();
final String hash = TFM_UuidManager.getUniqueId(player).toString().substring(0, 4); final String hash = getPlayerHash(player);
if (hash.equalsIgnoreCase(args[1])) if (hash.equalsIgnoreCase(args[1]))
{ {
@ -104,7 +112,7 @@ public class Command_gadmin extends TFM_Command
if (target == null) if (target == null)
{ {
playerMsg("Invalid player hash: " + args[1], ChatColor.RED); msg("Invalid player hash: " + args[1], ChatColor.RED);
return true; return true;
} }
@ -112,16 +120,15 @@ public class Command_gadmin extends TFM_Command
{ {
case KICK: case KICK:
{ {
TFM_Util.adminAction(sender.getName(), String.format("Kicking: %s.", target.getName()), false); FUtil.adminAction(sender.getName(), String.format("Kicking: %s.", target.getName()), false);
target.kickPlayer("Kicked by Administrator"); target.kickPlayer("Kicked by Administrator");
break; break;
} }
case NAMEBAN: case NAMEBAN:
{ {
TFM_BanManager.addUuidBan(target); FUtil.adminAction(sender.getName(), String.format("Banning Name: %s.", target.getName()), true);
plugin.bm.addBan(Ban.forPlayerName(target, sender, null, null));
TFM_Util.adminAction(sender.getName(), String.format("Banning Name: %s.", target.getName()), true);
target.kickPlayer("Username banned by Administrator."); target.kickPlayer("Username banned by Administrator.");
break; break;
@ -134,8 +141,8 @@ public class Command_gadmin extends TFM_Command
{ {
ip = String.format("%s.%s.*.*", ip_parts[0], ip_parts[1]); ip = String.format("%s.%s.*.*", ip_parts[0], ip_parts[1]);
} }
TFM_Util.adminAction(sender.getName(), String.format("Banning IP: %s.", ip), true); FUtil.adminAction(sender.getName(), String.format("Banning IP: %s.", ip), true);
TFM_BanManager.addIpBan(target); plugin.bm.addBan(Ban.forPlayerIp(ip, sender, null, null));
target.kickPlayer("IP address banned by Administrator."); target.kickPlayer("IP address banned by Administrator.");
@ -149,10 +156,9 @@ public class Command_gadmin extends TFM_Command
{ {
ip = String.format("%s.%s.*.*", ip_parts[0], ip_parts[1]); ip = String.format("%s.%s.*.*", ip_parts[0], ip_parts[1]);
} }
TFM_Util.adminAction(sender.getName(), String.format("Banning Name: %s, IP: %s.", target.getName(), ip), true); FUtil.adminAction(sender.getName(), String.format("Banning Name: %s, IP: %s.", target.getName(), ip), true);
TFM_BanManager.addUuidBan(target); plugin.bm.addBan(Ban.forPlayer(target, sender));
TFM_BanManager.addIpBan(target);
target.kickPlayer("IP and username banned by Administrator."); target.kickPlayer("IP and username banned by Administrator.");
@ -160,17 +166,17 @@ public class Command_gadmin extends TFM_Command
} }
case OP: case OP:
{ {
TFM_Util.adminAction(sender.getName(), String.format("Opping %s.", target.getName()), false); FUtil.adminAction(sender.getName(), String.format("Opping %s.", target.getName()), false);
target.setOp(false); target.setOp(true);
target.sendMessage(TFM_Command.YOU_ARE_OP); target.sendMessage(FreedomCommand.YOU_ARE_OP);
break; break;
} }
case DEOP: case DEOP:
{ {
TFM_Util.adminAction(sender.getName(), String.format("Deopping %s.", target.getName()), false); FUtil.adminAction(sender.getName(), String.format("Deopping %s.", target.getName()), false);
target.setOp(false); target.setOp(false);
target.sendMessage(TFM_Command.YOU_ARE_NOT_OP); target.sendMessage(FreedomCommand.YOU_ARE_NOT_OP);
break; break;
} }
@ -182,11 +188,11 @@ public class Command_gadmin extends TFM_Command
} }
case FR: case FR:
{ {
TFM_PlayerData playerdata = TFM_PlayerData.getPlayerData(target); FreezeData fd = plugin.pl.getPlayer(target).getFreezeData();
playerdata.setFrozen(!playerdata.isFrozen()); fd.setFrozen(!fd.isFrozen());
playerMsg(target.getName() + " has been " + (playerdata.isFrozen() ? "frozen" : "unfrozen") + "."); msg(target.getName() + " has been " + (fd.isFrozen() ? "frozen" : "unfrozen") + ".");
target.sendMessage(ChatColor.AQUA + "You have been " + (playerdata.isFrozen() ? "frozen" : "unfrozen") + "."); target.sendMessage(ChatColor.AQUA + "You have been " + (fd.isFrozen() ? "frozen" : "unfrozen") + ".");
break; break;
} }

View File

@ -1,17 +1,18 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import me.StevenLawson.TotalFreedomMod.TFM_CommandBlocker; import me.totalfreedom.totalfreedommod.rank.Rank;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@CommandPermissions(level = AdminLevel.SUPER, source = SourceType.BOTH) @CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH, blockHostConsole = true)
@CommandParameters(description = "Send a command as someone else.", usage = "/<command> <fromname> <outcommand>") @CommandParameters(description = "Send a command as someone else.", usage = "/<command> <fromname> <outcommand>")
public class Command_gcmd extends TFM_Command public class Command_gcmd extends FreedomCommand
{ {
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
if (args.length < 2) if (args.length < 2)
{ {
@ -22,32 +23,32 @@ public class Command_gcmd extends TFM_Command
if (player == null) if (player == null)
{ {
sender.sendMessage(TFM_Command.PLAYER_NOT_FOUND); sender.sendMessage(FreedomCommand.PLAYER_NOT_FOUND);
return true; return true;
} }
final String outCommand = StringUtils.join(args, " ", 1, args.length); final String outCommand = StringUtils.join(args, " ", 1, args.length);
if (TFM_CommandBlocker.isCommandBlocked(outCommand, sender)) if (plugin.cb.isCommandBlocked(outCommand, sender))
{ {
return true; return true;
} }
try try
{ {
playerMsg("Sending command as " + player.getName() + ": " + outCommand); msg("Sending command as " + player.getName() + ": " + outCommand);
if (server.dispatchCommand(player, outCommand)) if (server.dispatchCommand(player, outCommand))
{ {
playerMsg("Command sent."); msg("Command sent.");
} }
else else
{ {
playerMsg("Unknown error sending command."); msg("Unknown error sending command.");
} }
} }
catch (Throwable ex) catch (Throwable ex)
{ {
playerMsg("Error sending command: " + ex.getMessage()); msg("Error sending command: " + ex.getMessage());
} }
return true; return true;

View File

@ -0,0 +1,115 @@
package me.totalfreedom.totalfreedommod.command;
import java.util.ArrayList;
import java.util.List;
import me.totalfreedom.totalfreedommod.banning.Ban;
import me.totalfreedom.totalfreedommod.player.PlayerData;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH, blockHostConsole = true)
@CommandParameters(description = "Bans or unbans any player, even those who are not logged in anymore.", usage = "/<command> <purge | ban <username> [reason] | unban <username>>")
public class Command_glist extends FreedomCommand
{
@Override
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
if (args.length < 1)
{
return false;
}
if (args.length == 1)
{
if ("purge".equals(args[0]))
{
checkRank(Rank.SENIOR_ADMIN);
plugin.pl.purgeAllData();
msg("Purged playerbase.");
return true;
}
return false;
}
if (args.length < 2)
{
return false;
}
String username;
final List<String> ips = new ArrayList<>();
final Player player = getPlayer(args[1]);
if (player == null)
{
final PlayerData entry = plugin.pl.getData(args[1]);
if (entry == null)
{
msg("Can't find that user. If target is not logged in, make sure that you spelled the name exactly.");
return true;
}
username = entry.getUsername();
ips.addAll(entry.getIps());
}
else
{
final PlayerData entry = plugin.pl.getData(player);
username = player.getName();
ips.addAll(entry.getIps());
}
if ("ban".equals(args[0]))
{
FUtil.adminAction(sender.getName(), "Banning " + username + " and IPs: " + StringUtils.join(ips, ", "), true);
final String reason = args.length > 2 ? StringUtils.join(args, " ", 2, args.length) : null;
Ban ban = Ban.forPlayerName(username, sender, null, reason);
for (String ip : ips)
{
ban.addIp(ip);
ban.addIp(FUtil.getFuzzyIp(ip));
}
plugin.bm.addBan(ban);
if (player != null)
{
player.kickPlayer(ban.bakeKickMessage());
}
return true;
}
if ("unban".equals(args[0]))
{
FUtil.adminAction(sender.getName(), "Unbanning " + username + " and IPs: " + StringUtils.join(ips, ", "), true);
plugin.bm.removeBan(plugin.bm.getByUsername(username));
for (String ip : ips)
{
Ban ban = plugin.bm.getByIp(ip);
if (ban != null)
{
plugin.bm.removeBan(ban);
}
ban = plugin.bm.getByIp(FUtil.getFuzzyIp(ip));
if (ban != null)
{
plugin.bm.removeBan(ban);
}
}
return true;
}
return false;
}
}

View File

@ -1,11 +1,9 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import me.StevenLawson.TotalFreedomMod.Bridge.TFM_WorldEditBridge; import me.totalfreedom.totalfreedommod.banning.Ban;
import me.StevenLawson.TotalFreedomMod.TFM_Ban; import me.totalfreedom.totalfreedommod.rank.Rank;
import me.StevenLawson.TotalFreedomMod.TFM_BanManager; import me.totalfreedom.totalfreedommod.util.FUtil;
import me.StevenLawson.TotalFreedomMod.TFM_RollbackManager; import net.pravian.aero.util.Ips;
import me.StevenLawson.TotalFreedomMod.TFM_Util;
import me.StevenLawson.TotalFreedomMod.TFM_UuidManager;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
@ -15,12 +13,13 @@ import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@CommandPermissions(level = AdminLevel.SUPER, source = SourceType.BOTH) @CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH, blockHostConsole = true)
@CommandParameters(description = "Makes someone GTFO (deop and ip ban by username).", usage = "/<command> <partialname>") @CommandParameters(description = "Makes someone GTFO (deop and ip ban by username).", usage = "/<command> <partialname>")
public class Command_gtfo extends TFM_Command public class Command_gtfo extends FreedomCommand
{ {
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
if (args.length == 0) if (args.length == 0)
{ {
@ -31,7 +30,7 @@ public class Command_gtfo extends TFM_Command
if (player == null) if (player == null)
{ {
playerMsg(TFM_Command.PLAYER_NOT_FOUND, ChatColor.RED); msg(FreedomCommand.PLAYER_NOT_FOUND, ChatColor.RED);
return true; return true;
} }
@ -41,30 +40,30 @@ public class Command_gtfo extends TFM_Command
reason = StringUtils.join(ArrayUtils.subarray(args, 1, args.length), " "); reason = StringUtils.join(ArrayUtils.subarray(args, 1, args.length), " ");
} }
TFM_Util.bcastMsg(player.getName() + " has been a VERY naughty, naughty boy.", ChatColor.RED); FUtil.bcastMsg(player.getName() + " has been a VERY naughty, naughty boy.", ChatColor.RED);
// Undo WorldEdits: // Undo WorldEdits
try try
{ {
TFM_WorldEditBridge.undo(player, 15); plugin.web.undo(player, 15);
} }
catch (NoClassDefFoundError ex) catch (NoClassDefFoundError ex)
{ {
} }
// rollback // Rollback
TFM_RollbackManager.rollback(player.getName()); plugin.rb.rollback(player.getName());
// deop // Deop
player.setOp(false); player.setOp(false);
// set gamemode to survival: // Gamemode suvival
player.setGameMode(GameMode.SURVIVAL); player.setGameMode(GameMode.SURVIVAL);
// clear inventory: // Clear inventory
player.getInventory().clear(); player.getInventory().clear();
// strike with lightning effect: // Strike with lightning
final Location targetPos = player.getLocation(); final Location targetPos = player.getLocation();
for (int x = -1; x <= 1; x++) for (int x = -1; x <= 1; x++)
{ {
@ -75,30 +74,26 @@ public class Command_gtfo extends TFM_Command
} }
} }
// ban IP address: String ip = FUtil.getFuzzyIp(Ips.getIp(player));
String ip = TFM_Util.getFuzzyIp(player.getAddress().getAddress().getHostAddress());
// Broadcast
final StringBuilder bcast = new StringBuilder() final StringBuilder bcast = new StringBuilder()
.append(ChatColor.RED) .append(ChatColor.RED)
.append("Banning: ") .append("Banning: ")
.append(player.getName()) .append(player.getName())
.append(", IP: ") .append(", IP: ")
.append(ip); .append(ip);
if (reason != null) if (reason != null)
{ {
bcast.append(" - Reason: ").append(ChatColor.YELLOW).append(reason); bcast.append(" - Reason: ").append(ChatColor.YELLOW).append(reason);
} }
FUtil.bcastMsg(bcast.toString());
TFM_Util.bcastMsg(bcast.toString()); // Ban player
plugin.bm.addBan(Ban.forPlayerFuzzy(player, sender, null, reason));
TFM_BanManager.addIpBan(new TFM_Ban(ip, player.getName(), sender.getName(), null, reason)); // Kick player
player.kickPlayer(ChatColor.RED + "GTFO");
// ban username:
TFM_BanManager.addUuidBan(new TFM_Ban(TFM_UuidManager.getUniqueId(player), player.getName(), sender.getName(), null, reason));
// kick Player:
player.kickPlayer(ChatColor.RED + "GTFO" + (reason != null ? ("\nReason: " + ChatColor.YELLOW + reason) : ""));
return true; return true;
} }

View File

@ -1,9 +1,10 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import me.StevenLawson.TotalFreedomMod.TFM_Log; import me.totalfreedom.totalfreedommod.TotalFreedomMod;
import me.StevenLawson.TotalFreedomMod.TotalFreedomMod; import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FLog;
import org.apache.commons.lang.math.DoubleRange; import org.apache.commons.lang.math.DoubleRange;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.Command; import org.bukkit.command.Command;
@ -12,23 +13,25 @@ import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
@CommandPermissions(level = AdminLevel.SUPER, source = SourceType.BOTH) @CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH)
@CommandParameters(description = "View ticks-per-second", usage = "/<command>") @CommandParameters(description = "View ticks-per-second", usage = "/<command>")
public class Command_health extends TFM_Command public class Command_health extends FreedomCommand
{ {
private static final int BYTES_PER_MB = 1024 * 1024; private static final int BYTES_PER_MB = 1024 * 1024;
private static final DoubleRange TPS_RANGE = new DoubleRange(20.0 - 0.1, 20.0 + 0.1); private static final DoubleRange TPS_RANGE = new DoubleRange(20.0 - 0.1, 20.0 + 0.1);
@Override @Override
public boolean run(final CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(final CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
Runtime runtime = Runtime.getRuntime(); Runtime runtime = Runtime.getRuntime();
long usedMem = runtime.totalMemory() - runtime.freeMemory(); long usedMem = runtime.totalMemory() - runtime.freeMemory();
playerMsg("Reserved Memory: " + (double) runtime.totalMemory() / (double) BYTES_PER_MB + "mb"); msg("Reserved Memory: " + (double) runtime.totalMemory() / (double) BYTES_PER_MB + "mb");
playerMsg("Used Memory: " + new DecimalFormat("#").format((double) usedMem / (double) BYTES_PER_MB) + "mb (" + new DecimalFormat("#").format(((double) usedMem / (double) runtime.totalMemory()) * 100.0) + "%)"); msg("Used Memory: " + new DecimalFormat("#").format((double) usedMem / (double) BYTES_PER_MB)
playerMsg("Max Memory: " + (double) runtime.maxMemory() / (double) BYTES_PER_MB + "mb"); + "mb (" + new DecimalFormat("#").format(((double) usedMem / (double) runtime.totalMemory()) * 100.0) + "%)");
playerMsg("Calculating ticks per second, please wait..."); msg("Max Memory: " + (double) runtime.maxMemory() / (double) BYTES_PER_MB + "mb");
msg("Calculating ticks per second, please wait...");
new BukkitRunnable() new BukkitRunnable()
{ {
@ -42,18 +45,24 @@ public class Command_health extends TFM_Command
Thread.sleep(2500); Thread.sleep(2500);
final double ticksPerSecond = tickMeter.stopTicking(); final double ticksPerSecond = tickMeter.stopTicking();
// Plugin was disabled during async task
if (!plugin.isEnabled())
{
return;
}
new BukkitRunnable() new BukkitRunnable()
{ {
@Override @Override
public void run() public void run()
{ {
playerMsg("Ticks per second: " + (TPS_RANGE.containsDouble(ticksPerSecond) ? ChatColor.GREEN : ChatColor.RED) + ticksPerSecond); msg("Ticks per second: " + (TPS_RANGE.containsDouble(ticksPerSecond) ? ChatColor.GREEN : ChatColor.RED) + ticksPerSecond);
} }
}.runTask(plugin); }.runTask(plugin);
} }
catch (Exception ex) catch (Exception ex)
{ {
TFM_Log.severe(ex); FLog.severe(ex);
} }
} }
}.runTaskAsynchronously(plugin); }.runTaskAsynchronously(plugin);
@ -63,6 +72,7 @@ public class Command_health extends TFM_Command
private class TFM_TickMeter private class TFM_TickMeter
{ {
private final AtomicInteger ticks = new AtomicInteger(); private final AtomicInteger ticks = new AtomicInteger();
private final TotalFreedomMod plugin; private final TotalFreedomMod plugin;
private long startTime; private long startTime;
@ -97,4 +107,5 @@ public class Command_health extends TFM_Command
return (double) tickCount / ((double) elapsed / 1000.0); return (double) tickCount / ((double) elapsed / 1000.0);
} }
} }
} }

View File

@ -1,28 +1,29 @@
package me.StevenLawson.TotalFreedomMod.Commands; package me.totalfreedom.totalfreedommod.command;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import me.StevenLawson.TotalFreedomMod.TFM_AdminList; import me.totalfreedom.totalfreedommod.rank.Rank;
import me.StevenLawson.TotalFreedomMod.TFM_Util; import me.totalfreedom.totalfreedommod.util.FUtil;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType; import org.bukkit.potion.PotionEffectType;
@CommandPermissions(level = AdminLevel.SUPER, source = SourceType.BOTH) @CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH)
@CommandParameters(description = "Shows (optionally smites) invisisible players", usage = "/<command> (smite)") @CommandParameters(description = "Shows (optionally smites) invisisible players", usage = "/<command> (smite)")
public class Command_invis extends TFM_Command public class Command_invis extends FreedomCommand
{ {
@Override @Override
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{ {
boolean smite = false; boolean smite = false;
if (args.length >= 1) if (args.length >= 1)
{ {
if (args[0].equalsIgnoreCase("smite")) if (args[0].equalsIgnoreCase("smite"))
{ {
TFM_Util.adminAction(sender.getName(), "Smiting all invisible players", true); FUtil.adminAction(sender.getName(), "Smiting all invisible players", true);
smite = true; smite = true;
} }
else else
@ -31,7 +32,7 @@ public class Command_invis extends TFM_Command
} }
} }
List<String> players = new ArrayList<String>(); List<String> players = new ArrayList<>();
int smites = 0; int smites = 0;
for (Player player : server.getOnlinePlayers()) for (Player player : server.getOnlinePlayers())
@ -39,7 +40,7 @@ public class Command_invis extends TFM_Command
if (player.hasPotionEffect(PotionEffectType.INVISIBILITY)) if (player.hasPotionEffect(PotionEffectType.INVISIBILITY))
{ {
players.add(player.getName()); players.add(player.getName());
if (smite && !TFM_AdminList.isSuperAdmin(player)) if (smite && !plugin.al.isAdmin(player))
{ {
player.setHealth(0.0); player.setHealth(0.0);
smites++; smites++;
@ -49,17 +50,17 @@ public class Command_invis extends TFM_Command
if (players.isEmpty()) if (players.isEmpty())
{ {
playerMsg("There are no invisible players"); msg("There are no invisible players");
return true; return true;
} }
if (smite) if (smite)
{ {
playerMsg("Smitten " + smites + " players"); msg("Smitten " + smites + " players");
} }
else else
{ {
playerMsg("Invisble players (" + players.size() + "): " + StringUtils.join(players, ", ")); msg("Invisible players (" + players.size() + "): " + StringUtils.join(players, ", "));
} }
return true; return true;

View File

@ -0,0 +1,96 @@
package me.totalfreedom.totalfreedommod.command;
import me.totalfreedom.totalfreedommod.fun.Jumppads;
import me.totalfreedom.totalfreedommod.rank.Rank;
import me.totalfreedom.totalfreedommod.util.FUtil;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandPermissions(level = Rank.SUPER_ADMIN, source = SourceType.BOTH)
@CommandParameters(description = "Manage jumppads", usage = "/<command> <on | off | info | sideways <on | off> | strength <strength (1-10)>>", aliases = "launchpads,jp")
public class Command_jumppads extends FreedomCommand
{
@Override
public boolean run(CommandSender sender, Player playerSender, Command cmd, String commandLabel, String[] args, boolean senderIsConsole)
{
if (args.length == 0 || args.length > 2)
{
return false;
}
if (args.length == 1)
{
if (args[0].equalsIgnoreCase("info"))
{
msg("Jumppads: " + (plugin.jp.getMode().isOn() ? "Enabled" : "Disabled"), ChatColor.BLUE);
msg("Sideways: " + (plugin.jp.getMode() == Jumppads.JumpPadMode.NORMAL_AND_SIDEWAYS ? "Enabled" : "Disabled"), ChatColor.BLUE);
msg("Strength: " + (plugin.jp.getStrength() * 10 - 1), ChatColor.BLUE);
return true;
}
if ("off".equals(args[0]))
{
FUtil.adminAction(sender.getName(), "Disabling Jumppads", false);
plugin.jp.setMode(Jumppads.JumpPadMode.OFF);
}
else
{
FUtil.adminAction(sender.getName(), "Enabling Jumppads", false);
plugin.jp.setMode(Jumppads.JumpPadMode.MADGEEK);
}
}
else
{
if (plugin.jp.getMode() == Jumppads.JumpPadMode.OFF)
{
msg("Jumppads are currently disabled, please enable them before changing jumppads settings.");
return true;
}
if (args[0].equalsIgnoreCase("sideways"))
{
if ("off".equals(args[1]))
{
FUtil.adminAction(sender.getName(), "Setting Jumppads mode to: Madgeek", false);
plugin.jp.setMode(Jumppads.JumpPadMode.MADGEEK);
}
else
{
FUtil.adminAction(sender.getName(), "Setting Jumppads mode to: Normal and Sideways", false);
plugin.jp.setMode(Jumppads.JumpPadMode.NORMAL_AND_SIDEWAYS);
}
}
else if (args[0].equalsIgnoreCase("strength"))
{
final float strength;
try
{
strength = Float.parseFloat(args[1]);
}
catch (NumberFormatException ex)
{
msg("Invalid Strength");
return true;
}
if (strength > 10 || strength < 1)
{
msg("Invalid Strength: The strength may be 1 through 10.");
return true;
}
FUtil.adminAction(sender.getName(), "Setting Jumppads strength to: " + String.valueOf(strength), false);
plugin.jp.setStrength((strength / 10) + 0.1F);
}
else
{
return false;
}
}
return true;
}
}

Some files were not shown because too many files have changed in this diff Show More