diff --git a/LICENSE b/LICENSE
index 8dada3ed..9cecc1d4 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,201 +1,674 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
- 1. Definitions.
+ Preamble
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
- "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.
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
- "Work" 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
- (an example is provided in the Appendix below).
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
- "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.
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
- "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."
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
- "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.
+ The precise terms and conditions for copying, distribution and
+modification follow.
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
+ TERMS AND CONDITIONS
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
+ 0. Definitions.
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
+ "This License" refers to version 3 of the GNU General Public License.
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
- 5. 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.
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
+ 1. Source Code.
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
- END OF TERMS AND CONDITIONS
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
- APPENDIX: How to apply the Apache License to your work.
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "{}"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
- Copyright {yyyy} {name of copyright owner}
+ The Corresponding Source for a work in source code form is that
+same work.
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
+ 2. Basic Permissions.
- http://www.apache.org/licenses/LICENSE-2.0
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ {one line to give the program's name and a brief idea of what it does.}
+ Copyright (C) {year} {name of author}
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ {project} Copyright (C) {year} {fullname}
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+ .
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/advanced.yml b/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/advanced.yml
deleted file mode 100644
index 5493ecd6..00000000
--- a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/advanced.yml
+++ /dev/null
@@ -1,116 +0,0 @@
-# Advanced AuthMeReloaded configuration file
-
-sessionLogin:
- # Do you want to enable session? When enabled
- # the ip of a player will be bound to the nickname
- # of the player on login. As long as neither of those
- # two change players don't have to login on a reconnect
- enabled: false
- # After how many minutes a session should timeout?
- # 0 for unlimitted sessions, use 0 at your own risk!
- # consider that session will end only after timeout, and
- # if player's ip is changed but the timeout treshould isent
- # ended, player will kick out of sever for invalidSession!
- timeout: 10
- # Do we need to timeout the session if the player is offline
- # And try to login with an another IP Address?
- sessionExpireOnIpChange: true
-
-security:
- # Should players in the OP list have every permissions?
- opPermissions: true
-
- # Online players aren't kicked out for "Logged in from another location!", this option should always be set to true!
- forceSingleSession: true
- # Should we display all other accounts from a player when he joins?
- # permission: /authme.admin.accounts
- displayOtherAccounts: true
-
- # Should the purge command can be performed only from the console?
- purgeOnlyFromConsole: true
-
- # Minimum value for the purge ingame command (if enabled), prevent the destruction of the entire database.
- minIngamePurgeDays: 30
-
- captcha:
- # Do players need to write a captcha code if they use too many times a wrong password
- useCaptcha: false
- # Max allowed tries before request a captcha
- maxLoginTry: 5
- # Captcha length
- captchaLength: 5
-
- # Restricted users will be kicked if their IP aren't the same specified below.
- # Usage: - username;ip
- RestrictedUsers:
- - playername;127.0.0.1
-
- # User listed below will bypass every login/registration system. CASE SENSITIVE!!!
- # Use this at your own risk!!! USE ONLY WITH ONLINE MODE SERVERS!!!
- # This option can add compatibility with BuildCraft and some other mods.
- UnrestrictedName: []
-
- passwordEncryption:
- # possible values: MD5, SHA1, SHA256, WHIRLPOOL, XAUTH, MD5VB, PHPBB,
- # PLAINTEXT ( unhashed password),
- # MYBB, IPB3, PHPFUSION, SMF, XENFORO, SALTED2MD5, JOOMLA, BCRYPT, WBB3, SHA512,
- # DOUBLEMD5, PBKDF2, WORDPRESS, ROYALAUTH, CUSTOM(for developpers only)
- passwordHash: SHA256
- # salt length for the SALTED2MD5 MD5(MD5(password)+salt)
- doubleMD5SaltLength: 8
- # If password checking return false , do we need to check with all
- # other password algorithm to check an old password ?
- # AuthMe will update the password to the new passwordHash !
- supportOldPasswordHash: false
-
- SQLProblem:
- # Stop the server if we can't contact the sql database
- # Take care with this, if you set that to false,
- # AuthMe automatically disable and the server is not protected!
- stopServer: true
- ReloadCommand:
- # /reload support
- useReloadCommandSupport: true
- console:
- # Remove spam console
- noConsoleSpam: false
- # Replace passwords in the console when player type a command like /login
- removePassword: true
-
-externalBoard:
- # MySQL column for the salt , needed for some forum/cms support
- mySQLColumnSalt: ''
- # MySQL column for the group, needed for some forum/cms support
- mySQLColumnGroup: ''
- # -1 mean disabled. If u want that only
- # activated player can login in your server
- # u can put in this options the group number
- # of unactivated user, needed for some forum/cms support
- nonActivedUserGroup: -1
- # Other MySQL columns where we need to put the Username (case sensitive)
- mySQLOtherUsernameColumns: []
- # How much Log to Round needed in BCrypt(do not change it if you do not know what's your doing)
- bCryptLog2Round: 10
- # phpBB prefix defined during phpbb installation process
- phpbbTablePrefix: 'phpbb_'
- # phpBB activated group id , 2 is default registered group defined by phpbb
- phpbbActivatedGroupId: 2
- # WordPress prefix defined during WordPress installation process
- wordpressTablePrefix: 'wp_'
-
-hooks:
- # Do we need to hook with multiverse for spawn checking?
- multiverse: true
- # Do we need to hook with ChestShop for prevent buy or selling ?
- chestshop: true
- # Do we need to hook with BungeeCord for get the real Player ip ?
- bungeecord: false
- # Do we need to disable Essentials SocialSpy on join ?
- disableSocialSpy: true
- # Do we need to cache custom Attributes ?
- customAttributes: false
-
-# Spawn Priority, Values : authme, essentials, multiverse, default
-spawnPriority: authme,essentials,multiverse,default
-# AuthMe will NEVER teleport players !
-noTeleport: false
diff --git a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/database.yml b/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/database.yml
deleted file mode 100644
index 6a885599..00000000
--- a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/database.yml
+++ /dev/null
@@ -1,67 +0,0 @@
-# Database AuthMeReloaded configuration file
-
-# What type of database do you want to use? Avariable options: sqlite, mysql, redis
-# (The old flatfile backend is now deprecated, if you set this option to 'file' the 'file to SQLite' converter will be executed!)
-backend: sqlite
-# Do you like to cache all the queries? (Performance Boost)
-caching: true
-
-# Database Name
-databaseName: authme
-# Table of the database
-tableName: authme
-
-# MySql Database connection settings
-mysql:
- port: '3306'
- host: 127.0.0.1
- username: authme
- password: '12345'
-
-# Redis Database connection settings
-redis:
- # Get Redis from http://redis.io/
- host: 127.0.0.1
- port: 6379
- # If your Redis server uses AUTH, set here the password.
- password: ""
-
-# Database column names
-columnNames:
- idColumn: id
- nameColumn: username
- realNameColumn: realname
- passwordColumn: password
- ipColumn: ip
- emailColumn: email
- loginStatusColumn: loginstatus
- lastLoginColumn: lastlogin
- lastlLocationXColumn: x
- lastLocationYColumn: y
- lastLocationZColumn: z
- lastLocationWorldColumn: world
-
-backup:
- # Enable or disable Automatic Backup of the SQLite database, destination path: "/AuthMe/backups/%date%/%timestamp%.sql"
- ActivateBackup: false
- # Interval time (in minutes), set to 0 to disable periodic backup
- Interval: 300
- # Do you want to perform a Backup when the server starts?
- OnServerStart: false
- # Do you want to perform a Backup when the server stops?
- OnServerStop: true
-
-purge:
- # Does AuthMe need to purge automatically old unused accounts?
- useAutoPurge: false
- # Number of Days required to mark an account as Unused
- daysBeforeRemovePlayer: 60
- # What to remove
- remove:
- playerInventoryFile: true
- essentialsFiles: true
- permissions: true
- limitedCreativesInventories: true
- antiXRayFiles: true
- # World where players.dat are stored (necessary to remove inventory files)
- defaultWorld: 'world'
diff --git a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/emailSystem.yml b/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/emailSystem.yml
deleted file mode 100644
index 48c9b59a..00000000
--- a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/emailSystem.yml
+++ /dev/null
@@ -1,40 +0,0 @@
-emailSystem:
- # Do you want to replace the Password registration with an Email registration method?
- enableEmailRegistration: false
- # Do you want to enable the double check of the email address during a player registration?
- # When it's true, registration require that kind of command:
- # /register
- doubleEmailCheck: true
- # Like maxRegPerIp but with emails
- maxRegPerEmail: 1
- # Do you want to recall players to add an email to their accounts?
- recallPlayers: true
- # Delay in minute for the recall scheduler
- delayRecall: 5
-
- passwordRecovery:
- # Recovery password length
- RecoveryPasswordLength: 8
- # Recovery Email subject
- mailSubject: 'Your new AuthMe Password'
- # Recovery Email text
- mailText: 'Dear , This is your new AuthMe password for the server : Do not forget to change password after login! /changepassword newPassword'
-
- smtpOptions:
- # SMTP server host
- mailSMTP: smtp.gmail.com
- # SMTP server port
- mailPort: 465
- # Email account that sends the mails
- mailAccount: ''
- # Email account's password
- mailPassword: ''
- # Custom SenderName, that replace the mailAccount name in the emails
- mailSenderName: ''
-
- emailSecurity:
- # Blacklisted domains for emails
- emailBlacklist:
- - 10minutemail.com
- # Do you like a Whitelist instead of a Blacklist?
- blacklistAsWhitelist: false
diff --git a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/forcedActions.yml b/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/forcedActions.yml
deleted file mode 100644
index 86a03270..00000000
--- a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/forcedActions.yml
+++ /dev/null
@@ -1,33 +0,0 @@
-# ForcedActions AuthMeReloaded configuration file
-
-forcedActions:
-
-# example1:
-# at: firstlogin
-# executedBy: console
-# commands:
-# - 'msg %p Welcome!'
-# - pex user set group Player
-
-# example2:
-# at: connection
-# executedBy: console
-# commands:
-# - 'msg %p You need to register yourself to play this server!'
-
-#
-# Avariable events:
-# connection
-# firstconnection
-# login
-# firstlogin
-# wrongpassword
-# disconnection
-# logout
-# serverstop
-# serverstart
-# pluginreload
-# mysqlerror
-# antiboton
-# antibotoff
-#
\ No newline at end of file
diff --git a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/general.yml b/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/general.yml
deleted file mode 100644
index c1d290c2..00000000
--- a/PROTOTYPE AREA (future stuff and etc...)/NewConfiguration/general.yml
+++ /dev/null
@@ -1,102 +0,0 @@
-# █████╗ ██╗ ██╗████████╗██╗ ██╗ ███╗ ███╗███████╗ ██████╗ ███████╗██╗ ██████╗ ██████╗ ███████╗██████╗
-# ██╔══██╗██║ ██║╚══██╔══╝██║ ██║ ████╗ ████║██╔════╝ ██╔══██╗██╔════╝██║ ██╔═══██╗██╔══██╗██╔════╝██╔══██╗
-# ███████║██║ ██║ ██║ ███████║ ██╔████╔██║█████╗ ██████╔╝█████╗ ██║ ██║ ██║██║ ██║█████╗ ██║ ██║
-# ██╔══██║██║ ██║ ██║ ██╔══██║ ██║╚██╔╝██║██╔══╝ ██╔══██╗██╔══╝ ██║ ██║ ██║██║ ██║██╔══╝ ██║ ██║
-# ██║ ██║╚██████╔╝ ██║ ██║ ██║ ██║ ╚═╝ ██║███████╗ ██║ ██║███████╗███████╗╚██████╔╝██████╔╝███████╗██████╔╝
-# ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═════╝
-
-# Welcome to the AuthMeReloaded main configuration file!
-
-# Available languages: en, de, br, cz, pl, fr, ru, hu, sk, es, zhtw, fi, zhcn, lt, it, ko, pt
-language: en
-
-registration:
- # Do you want to enable the registration on the server?
- enabled: true
- # Do you want to force players to register before playing?
- force: true
- # Maximum Registration per IP
- maxRegPerIp: 1
- # Maximum allowed username length
- maxUsernameLength: 30
- # Minimum required username length
- minUsernameLength: 4
- # Regex syntax allowed in player's username
- allowedNicknameCharacters: '[a-zA-Z0-9_]*'
- # Do you want to kick players after a successful registration?
- # Do not use this option with the loginAfterRegister feature below!
- kickAfterRegistration: false
- # Do you want to force the player to login after a successful registration?
- loginAfterRegister: false
-
-login:
- # How many players per IP can join the server concurrently?
- maxInstanceForIP: 1
- # Should not registered players be kicked immediately?
- kickNonRegistered: false
- # Should the players be kicked immediately on wrong password?
- kickOnWrongPassword: false
- # Send every X seconds a message to a player to remind him that he has to login/register
- messageInterval: 5
- # How many second a player can login or register before being kicked? Set this to 0 to disable.
- timeout: 30
- # Teleport the player to the world's Spawn after login
- teleportToSpawnAfterLogin: true
- # Teleport provisionally not logged player to world's Spawn.
- # After the login, if teleportToSpawnAfterLogin is set to false the player will be teleported to his last location.
- teleportToSpawnBeforeLogin: true
-
- # ForceSurvivalMode to player when join?
- forceSurvivalMode: false
- # Do we need to force the survival mode ONLY after /login process?
- forceSurvivalOnlyAfterLogin: false
-
- # Reset every time the player's inventory?
- resetInventory: false
- # If player join with CreativeMode and ForceSurvivalMode: true inventory will be wiped.
- resetInventoryIfCreative: false
- # Should we protect the player inventory before logging in?
- protectInventoryBeforeLogIn: true
-
-password:
- # minimum Length of password
- minPasswordLength: 5
- # Regex sintax for allowed Chars in passwords.
- allowedPasswordCharacters: '[\x21-\x7E]*'
- # Enable double check of password when you register or change password.
- # When it's true, registration require that kind of command:
- # /register
- doublePasswordCheck: true
- # Should players can use their usernames as passwords?
- allowNameAsPassword: false
- # Deny unsafe passwords for being used, put them on lowercase!
- unsafePasswords:
- - '123456'
- - '12345'
- - 'qwerty'
- - 'password'
-
-protection:
- # Enable some server protection systems (country based login, antibot)
- enableProtection: false
- # Countries allowed to join the server and register, see http://dev.bukkit.org/bukkit-plugins/authme-reloaded/pages/countries-codes/ for countries' codes
- countries:
- - US
- - GB
- # Countries blacklisted automatically (It works also with enableProtection set to false)
- countriesBlacklist:
- - A1
-
- antiBot:
- # Do you like to enable the automatic antibot system?
- enableAntiBot: false
- # Do you want to show AntiBot messages to every player or only to person with the "authme.antibotmessages" permission node?
- broadcastMessages: true
- # Max number of player allowed to join in 5 secs before the AntiBot activates
- antiBotSensibility: 5
- # Duration in minutes of the antibot protection
- antiBotDuration: 10
-
-# These features are only available on the VeryGames Server Provider
-veryGames:
- enableIpCheck: false
diff --git a/PROTOTYPE AREA (future stuff and etc...)/converters.txt b/PROTOTYPE AREA (future stuff and etc...)/converters.txt
deleted file mode 100644
index 0290f672..00000000
--- a/PROTOTYPE AREA (future stuff and etc...)/converters.txt
+++ /dev/null
@@ -1,21 +0,0 @@
-_________________________________________________________________________________
-> <
-> WARNING: Conversions can't be undone! DO ALWAYS A BACKUP BEFORE!!! <
-> <
-_________________________________________________________________________________
-> AuthMe Reloaded converters description file <
-_________________________________________________________________________________
-
-Built-in converters (Into the Plugin's core module):
- Old File Backend ("file") >>> SQLite ("/authme converter flatfiletosqlite") THIS CONVERTER WILL BE REMOVED FROM THE CORE IN FUTURE VERSIONS!!!
-
-Converters in the Converters module (Into the Converters module avariable at: NEED LINK):
- SQlite >>> MySql ("/authme converter sqlitetomysql")
- MySql >>> Redis ("/authme converter mysqltoredis")
- Rakamak >>> SQlite ("/authme converter rakamaktosqlite [databasefile.rak] [(ip-mode) (ipdatabasefle.rak)]")
- CrazyLogin >>> SQlite ("/authme converter crazylogintosqlite [databasefile.db]")
- xAuth (Min version 2.6) >>> SQlite ("/authme converter xauthtosqlite") NOTE: xAUTH MUST BE INSTALLED AND CONFIGURED IN THE SERVER, it works with all the xAuth backends!
-
-Discontinued Converters (use an old AuthMe version like 3.4):
- RoyalAuth >>> SQlite
- vAuth >>> SQlite
diff --git a/README.md b/README.md
index 6468c75d..220a2ced 100644
--- a/README.md
+++ b/README.md
@@ -1,20 +1,27 @@
-
-
+
The most used authentication plugin for CraftBukkit/Spigot!
+
+####Development history:
+[](https://www.youtube.com/watch?v=hJRzNfYyd9k)
+
#####Development tools:
+- DEVELOPMENT TEAM REPO (please send PRs here! ): Github Development Page
+
- Developers ChatRoom: [](https://gitter.im/Xephi/AuthMeReloaded?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
-- Build status (Travis): [](https://travis-ci.org/Xephi/AuthMeReloaded)
+- Build status: [](https://travis-ci.org/Xephi/AuthMeReloaded) [](https://www.versioneye.com/user/projects/55bab9e8653762002000190a)
-- Build status (CircleCI): [CircleCI project Page](https://circleci.com/gh/xephi/AuthMeReloaded)
+- Build status (CircleCI): [](https://circleci.com/gh/Xephi/AuthMeReloaded)
-- Build Server (DEVELOPMENT BUILDS ): Xephi's Jenkins
+- Issue Tracking : [](https://waffle.io/Xephi/AuthMeReloaded) [](https://waffle.io/Xephi/AuthMeReloaded) [](https://waffle.io/Xephi/AuthMeReloaded)
+
+- Build Server (DEVELOPMENT BUILDS ): Xephi's Jenkins
- JavaDocs: AuthMe Javadoc
-- Maven Repo: AuthMe Repo
+- Maven Repo: AuthMe Repo
#####Statistics:
@@ -39,7 +46,9 @@ McStats: http://mcstats.org/plugin/AuthMe
#####Running Requirements:
>- Java 1.7 (should work also with Java 1.8)
->- Spigot or CraftBukkit
+>- Spigot or CraftBukkit (1.7.10 or 1.8.X)
+>- Vault
+>- Protocollib
###Plugin Description:
@@ -60,7 +69,7 @@ typing commands or use the inventory. It can also kick players with uncommon lon
Username spoofing protection.
Countries Whitelist/Blacklist! (countries codes)
Built-in AntiBot System!
- Passpartu Feature: Admin can login with all account more info here (Deprecated)
+ ForceLogin Feature: Admins can login with all account via console command!
Avoid the "Logged in from another location" message!
Session Login!
Editable translations and messages!
@@ -124,7 +133,11 @@ typing commands or use the inventory. It can also kick players with uncommon lon
EUR:
USD:
+#####Sponsor
+GameHosting.it is leader in Italy as Game Server Provider. With its own DataCenter offers Anti-DDoS solutions at affordable prices. Game Server of Minecraft based on Multicraft are equipped with the latest technology in hardware.
+[](http://www.gamehosting.it)
+
#####Credits
-Team members: Xephi(Main Developer, Author), Maxetto(Contributor) and sgdc3(Contributor)
+
Team members: look at the team.txt file
Credit for old version of the plugin to: d4rkwarriors, fabe1337 , Whoami2 and pomo4ka
Thanks also to: AS1LV3RN1NJA, Hoeze and eprimex
diff --git a/pom.xml b/pom.xml
index 9fcaa4c6..7547c90b 100644
--- a/pom.xml
+++ b/pom.xml
@@ -2,101 +2,122 @@
4.0.0
-
+
fr.xephi
authme
- 5.0-SNAPSHOT
-
+ 5.1-SNAPSHOT
+ jar
+
AuthMeReloaded
Authentication plugin for CraftBukkit/Spigot!
+ 2013
http://dev.bukkit.org/bukkit-plugins/authme-reloaded/
-
- jar
-
-
- UTF-8
-
-
- 1.7
- 1.7
-
-
- 1.8.7-R0.1-SNAPSHOT
-
-
-
+
+
+
+ AuthMe-Team
+ https://github.com/AuthMe-Team
+
+
+
+ scm:git:https://github.com/Xephi/AuthMeReloaded.git
+ scm:git:git@github.com:Xephi/AuthMeReloaded.git
+ http://github.com/Xephi/AuthMeReloaded
+
+
jenkins
http://ci.xephi.fr/job/AuthMeReloaded/
-
+
GitHub
https://github.com/Xephi/AuthMeReloaded/issues
+
+
+
+ The GNU General Public Licence version 3 (GPLv3)
+ http://www.gnu.org/licenses/gpl-3.0.html
+
+
+
+
+
+ UTF-8
+ fr.xephi.authme.AuthMe
+ CustomBuild
+ [Xephi, sgdc3, DNx5, timvisee, games647]
+
+
+ 1.7
+
+
+ 1.8.8-R0.1-SNAPSHOT
+
+ AuthMe-${project.version}
+
+
+ .
+ true
+ src/main/resources/
+
+ *.yml
+
+
+
+ ./messages/
+ false
+ src/main/resources/messages/
+
+ *.yml
+
+
+
org.apache.maven.plugins
maven-compiler-plugin
3.3
- ${maven.compiler.source}
- ${maven.compiler.target}
-
-
-
- com.google.code.maven-replacer-plugin
- replacer
- 1.5.3
-
-
- prepare-package
-
- replace
-
-
-
-
- target/classes/plugin.yml
-
-
- maven-version
- ${project.version}
-
-
-
-
-
- maven-jar-plugin
- 2.6
-
-
- ${manifest.file}
-
- AuthMe-${project.version}
+ 1.7
+ ${javaVersion}
org.apache.maven.plugins
maven-shade-plugin
- 2.3
+ 2.4.2
-
-
- com.maxmind.geoip:*
- javax.mail:*
- com.sun.mail:*
- com.comphenix.attribute:*
- org.mcstats.*:*
-
-
+ false
+ false
org.mcstats
fr.xephi.authme
+
+ com.google.gson
+ fr.xephi.authme.libs.gson
+
+
+ com.zaxxer.hikari
+ fr.xephi.authme.libs.hikari
+
+
+ org.slf4j
+ fr.xephi.authme.libs.slf4j
+
+
+ com.maxmind.geoip
+ fr.xephi.authme.libs.geoip
+
+
+ net.ricecode.similarity
+ fr.xephi.authme.libs.similarity
+
@@ -112,23 +133,16 @@
-
spigot-repo
- https://hub.spigotmc.org/nexus/content/groups/public
+ http://hub.spigotmc.org/nexus/content/groups/public
-
+
ess-repo
- http://repo.ess3.net/content/groups/public
-
-
-
-
- citizensapi-repo
- http://ci.citizensnpcs.co/plugin/repository/project/CitizensAPI/LastSuccessful/repository
+ http://ci.drtshock.net/plugin/repository/everything
@@ -137,10 +151,10 @@
http://repo.minelink.net/content/repositories/public
-
+
- comphenix-snapshots
- http://repo.comphenix.net/content/repositories/public
+ dmulloy2-repo
+ http://repo.dmulloy2.net/content/groups/public/
@@ -161,90 +175,144 @@
http://repo.luricos.de/content/repositories/releases
-
+
xephi-repo
http://ci.xephi.fr/plugin/repository/everything/
-
-
-
-
-
+
- mysql
- mysql-connector-java
- 5.1.36
+ com.zaxxer
+ HikariCP
+ 2.4.1
+ compile
+
+
+ slf4j-api
+ org.slf4j
+
+
+ true
+
+
+ org.slf4j
+ slf4j-jdk14
+ 1.7.12
+ compile
+ true
-
+
- org.xerial
- sqlite-jdbc
- 3.8.10.1
+ org.apache.logging.log4j
+ log4j-core
+
+ 2.0-beta9
+ provided
+ true
-
+
com.sun.mail
- javax.mail
+ mailapi
1.5.4
+ compile
+ true
+
+
+ com.sun.mail
+ smtp
+ 1.5.4
+ compile
+ true
+
+
+ org.apache.commons
+ commons-email
+ 1.4
+ compile
+ true
+
+
+
+
+ com.google.code.gson
+ gson
+ 2.4
+ compile
+ true
com.maxmind.geoip
geoip-api
- 1.2.14
+ 1.2.15
+ compile
+ true
+
org.mcstats.bukkit
metrics
- R7
+ R8-SNAPSHOT
compile
org.bukkit
bukkit
-
- org.bukkit
- craftbukkit
-
+ true
-
+
- org.spigotmc
- spigot-api
+ org.bukkit
+ bukkit
${bukkitVersion}
+ provided
+ true
- bungeecord-chat
- net.md-5
+ junit
+ junit
+
+
+ json-simple
+ com.googlecode.json-simple
+
+
+ gson
+ com.google.code.gson
+
+
+ persistence-api
+ javax.persistence
-
+
- com.comphenix.attribute
- AttributeStorage
- 0.0.2-SNAPSHOT
+ com.comphenix.protocol
+ ProtocolLib
+ 3.6.5-SNAPSHOT
+ provided
+ true
- org.bukkit
- bukkit
+ cglib-nodep
+ cglib
- org.bukkit
- craftbukkit
+ BukkitExecutors
+ com.comphenix.executors
@@ -265,23 +333,7 @@
craftbukkit
-
-
-
-
- net.citizensnpcs
- citizensapi
- 2.0.16-SNAPSHOT
-
-
- org.bukkit
- bukkit
-
-
- org.bukkit
- craftbukkit
-
-
+ true
@@ -290,7 +342,7 @@
Multiverse-Core
2.5
jar
- compile
+ provided
org.bukkit
@@ -312,31 +364,51 @@
CommandHandler
com.pneumaticraft.commandhandler
+
+ SerializationConfig
+ me.main__.util
+
+
+ Logging
+ com.dumptruckman.minecraft
+
+
+ metrics
+ org.mcstats.bukkit
+
+
+ buscript
+ com.dumptruckman.minecraft
+
+
+ junit
+ junit
+
+ true
-
+
net.ess3
- Essentials
- 2.14-SNAPSHOT
+ EssentialsX
+ 2.0.1-SNAPSHOT
+ provided
- org.bukkit
- bukkit
-
-
- org.bukkit
- craftbukkit
+ org.spigotmc
+ spigot-api
+ true
-
+
net.minelink
CombatTagPlus
1.2.1-SNAPSHOT
+ provided
org.bukkit
@@ -403,23 +475,7 @@
org.mcstats.bukkit
-
-
-
-
- com.trc202
- CombatTag
- 6.2.1-SNAPSHOT
-
-
- org.bukkit
- bukkit
-
-
- org.bukkit
- craftbukkit
-
-
+ true
@@ -427,6 +483,7 @@
de.luricos.bukkit
xAuth
2.6
+ provided
org.bukkit
@@ -456,103 +513,21 @@
AccountsClient
com.mojang
-
-
-
-
-
- com.acrobot.chestshop
- chestshop
- 3.8.12
-
- org.bukkit
- bukkit
-
-
- org.bukkit
- craftbukkit
-
-
- Vault
- net.milkbowl.vault
-
-
- odditem
- info.somethingodd
-
-
- scrollingmenusign
- me.desht
-
-
- truezip
- de.schlichtherle
-
-
- residence
- net.t00thpick1
-
-
- Heroes
- com.herocraftonline.heroes
-
-
- HeroChat
- com.dthielke.herochat
-
-
- worldguard
- com.sk89q
-
-
- worldedit
- com.sk89q
-
-
- lwc
- com.griefcraft.lwc
-
-
- js
- rhino
-
-
- jchronic
- com.sk89q
-
-
- deadbolt
- com.daemitus.deadbolt
-
-
- bukkit-classloader-check
- com.sk89q.spigot
-
-
- jsr305
- com.google.code.findbugs
-
-
- opencsv
- net.sf.opencsv
-
-
- simplechestlock
-
- com.webkonsept.bukkit.simplechestlock
-
-
-
- commandbook
- com.sk89q
-
-
- lockette
- org.yi.acru.bukkit.lockette
+ log4j-core
+ org.apache.logging.log4j
+ true
+
+
+ net.ricecode
+ string-similarity
+ 1.0.0
+ compile
+ true
+
diff --git a/src/main/java/fr/xephi/authme/AuthMe.java b/src/main/java/fr/xephi/authme/AuthMe.java
index ca7ae740..d8d80afc 100644
--- a/src/main/java/fr/xephi/authme/AuthMe.java
+++ b/src/main/java/fr/xephi/authme/AuthMe.java
@@ -1,809 +1,882 @@
-package fr.xephi.authme;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.lang.reflect.InvocationTargetException;
-import java.net.URL;
-import java.net.URLConnection;
-import java.util.Calendar;
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.logging.Logger;
-import java.util.zip.GZIPInputStream;
-
-import org.apache.logging.log4j.LogManager;
-import org.bukkit.Bukkit;
-import org.bukkit.Location;
-import org.bukkit.Server;
-import org.bukkit.World;
-import org.bukkit.command.CommandSender;
-import org.bukkit.entity.Player;
-import org.bukkit.plugin.PluginManager;
-import org.bukkit.plugin.RegisteredServiceProvider;
-import org.bukkit.plugin.java.JavaPlugin;
-import org.bukkit.scheduler.BukkitTask;
-import org.mcstats.Metrics;
-
-import com.earth2me.essentials.Essentials;
-import com.maxmind.geoip.LookupService;
-import com.onarandombox.MultiverseCore.MultiverseCore;
-
-import fr.xephi.authme.api.API;
-import fr.xephi.authme.api.NewAPI;
-import fr.xephi.authme.cache.auth.PlayerAuth;
-import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.cache.backup.FileCache;
-import fr.xephi.authme.cache.limbo.LimboCache;
-import fr.xephi.authme.cache.limbo.LimboPlayer;
-import fr.xephi.authme.commands.AdminCommand;
-import fr.xephi.authme.commands.CaptchaCommand;
-import fr.xephi.authme.commands.ChangePasswordCommand;
-import fr.xephi.authme.commands.ConverterCommand;
-import fr.xephi.authme.commands.EmailCommand;
-import fr.xephi.authme.commands.LoginCommand;
-import fr.xephi.authme.commands.LogoutCommand;
-import fr.xephi.authme.commands.PasspartuCommand;
-import fr.xephi.authme.commands.RegisterCommand;
-import fr.xephi.authme.commands.UnregisterCommand;
-import fr.xephi.authme.converter.Converter;
-import fr.xephi.authme.converter.ForceFlatToSqlite;
-import fr.xephi.authme.datasource.CacheDataSource;
-import fr.xephi.authme.datasource.DataSource;
-import fr.xephi.authme.datasource.DatabaseCalls;
-import fr.xephi.authme.datasource.FlatFile;
-import fr.xephi.authme.datasource.MySQL;
-import fr.xephi.authme.datasource.SQLite;
-import fr.xephi.authme.listener.AuthMeBlockListener;
-import fr.xephi.authme.listener.AuthMeChestShopListener;
-import fr.xephi.authme.listener.AuthMeEntityListener;
-import fr.xephi.authme.listener.AuthMePlayerListener;
-import fr.xephi.authme.listener.AuthMeServerListener;
-import fr.xephi.authme.plugin.manager.BungeeCordMessage;
-import fr.xephi.authme.plugin.manager.CitizensCommunicator;
-import fr.xephi.authme.plugin.manager.CombatTagComunicator;
-import fr.xephi.authme.plugin.manager.EssSpawn;
-import fr.xephi.authme.process.Management;
-import fr.xephi.authme.settings.Messages;
-import fr.xephi.authme.settings.OtherAccounts;
-import fr.xephi.authme.settings.Settings;
-import fr.xephi.authme.settings.Spawn;
-import net.milkbowl.vault.permission.Permission;
-
-public class AuthMe extends JavaPlugin {
-
- public DataSource database = null;
- private Settings settings;
- private Messages m;
- public OtherAccounts otherAccounts;
- public static Server server;
- public static Logger authmeLogger = Logger.getLogger("AuthMe");
- public static AuthMe authme;
- public Permission permission;
- private Utils utils = Utils.getInstance();
- private FileCache playerBackup = new FileCache(this);
- public CitizensCommunicator citizens;
- public boolean isCitizensActive = false;
- public SendMailSSL mail = null;
- public boolean CombatTag = false;
- public double ChestShop = 0;
- public boolean BungeeCord = false;
- public Essentials ess;
- public NewAPI api;
- public Management management;
- public ConcurrentHashMap captcha = new ConcurrentHashMap();
- public ConcurrentHashMap cap = new ConcurrentHashMap();
- public ConcurrentHashMap realIp = new ConcurrentHashMap();
- public MultiverseCore multiverse = null;
- public Location essentialsSpawn;
- public LookupService ls = null;
- public boolean antibotMod = false;
- public boolean delayedAntiBot = true;
- protected static String vgUrl = "http://monitor-1.verygames.net/api/?action=ipclean-real-ip&out=raw&ip=%IP%&port=%PORT%";
- public DataManager dataManager;
- public ConcurrentHashMap sessions = new ConcurrentHashMap();
-
- public Settings getSettings() {
- return settings;
- }
-
- public DataSource getAuthMeDatabase() {
- return database;
- }
-
- public void setAuthMeDatabase(DataSource database) {
- this.database = database;
- }
-
- @Override
- public void onEnable() {
- authme = this;
-
- authmeLogger.setParent(this.getLogger());
-
- try {
- settings = new Settings(this);
- settings.loadConfigOptions();
- } catch (Exception e) {
- ConsoleLogger.showError("Can't load the configuration file... Something went wrong, to avoid security issues the server will shutdown!");
- this.getServer().shutdown();
- return;
- }
-
- try {
- Metrics metrics = new Metrics(this);
- metrics.start();
- ConsoleLogger.info("Metrics started successfully!");
- } catch (IOException e) {
- // Failed to submit the metrics data
- ConsoleLogger.showError("Can't start Metrics! The plugin will work anyway...");
- }
-
- citizens = new CitizensCommunicator(this);
-
- if (Settings.enableAntiBot) {
- Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
-
- @Override
- public void run() {
- delayedAntiBot = false;
- }
- }, 2400);
- }
-
- m = Messages.getInstance();
-
- otherAccounts = OtherAccounts.getInstance();
-
- server = getServer();
-
- // Find Permissions
- checkVault();
-
- // Set Console Filter
- if (Settings.removePassword) {
- this.getLogger().setFilter(new ConsoleFilter());
- Bukkit.getLogger().setFilter(new ConsoleFilter());
- Logger.getLogger("Minecraft").setFilter(new ConsoleFilter());
- authmeLogger.setFilter(new ConsoleFilter());
- // Set Log4J Filter
- try {
- Class.forName("org.apache.logging.log4j.core.Filter");
- setLog4JFilter();
- } catch (ClassNotFoundException e) {
- ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled");
- } catch (NoClassDefFoundError e) {
- ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled");
- }
- }
-
- // Load MailApi
- if (!Settings.getmailAccount.isEmpty() && !Settings.getmailPassword.isEmpty())
- mail = new SendMailSSL(this);
-
- // Check Citizens Version
- citizensVersion();
-
- // Check Combat Tag Version
- combatTag();
-
- // Check Multiverse
- checkMultiverse();
-
- // Check ChestShop
- checkChestShop();
-
- // Check Essentials
- checkEssentials();
-
- /*
- * Back style on start if avalaible
- */
- if (Settings.isBackupActivated && Settings.isBackupOnStart) {
- Boolean Backup = new PerformBackup(this).DoBackup();
- if (Backup)
- ConsoleLogger.info("Backup performed correctly");
- else ConsoleLogger.showError("Error while performing the backup!");
- }
-
- setupDatabase();
-
- dataManager = new DataManager(this);
-
- // Setup API
- api = new NewAPI(this);
- new API(this);
-
- // Setup Management
- management = new Management(this);
-
- PluginManager pm = getServer().getPluginManager();
- if (Settings.bungee) {
- Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
- Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeCordMessage(this));
- }
-
- pm.registerEvents(new AuthMePlayerListener(this), this);
- pm.registerEvents(new AuthMeBlockListener(this), this);
- pm.registerEvents(new AuthMeEntityListener(this), this);
- pm.registerEvents(new AuthMeServerListener(this), this);
- if (ChestShop != 0) {
- pm.registerEvents(new AuthMeChestShopListener(this), this);
- ConsoleLogger.info("Hooked successfully with ChestShop!");
- }
-
- this.getCommand("authme").setExecutor(new AdminCommand(this));
- this.getCommand("register").setExecutor(new RegisterCommand(this));
- this.getCommand("login").setExecutor(new LoginCommand(this));
- this.getCommand("changepassword").setExecutor(new ChangePasswordCommand(this));
- this.getCommand("logout").setExecutor(new LogoutCommand(this));
- this.getCommand("unregister").setExecutor(new UnregisterCommand(this));
- this.getCommand("passpartu").setExecutor(new PasspartuCommand(this));
- this.getCommand("email").setExecutor(new EmailCommand(this));
- this.getCommand("captcha").setExecutor(new CaptchaCommand(this));
- this.getCommand("converter").setExecutor(new ConverterCommand(this));
-
- if (!Settings.isForceSingleSessionEnabled) {
- ConsoleLogger.showError("WARNING!!! By disabling ForceSingleSession, your server protection is inadequate!");
- }
-
- if (Settings.reloadSupport)
- try {
- int playersOnline = 0;
- try {
- if (Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).getReturnType() == Collection.class)
- playersOnline = ((Collection>) Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).invoke(null, new Object[0])).size();
- else playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).invoke(null, new Object[0])).length;
- } catch (Exception ex) {
- }
- if (playersOnline < 1) {
- try {
- database.purgeLogged();
- } catch (NullPointerException npe) {
- }
- } else {
- for (PlayerAuth auth : database.getLoggedPlayers()) {
- if (auth == null)
- continue;
- auth.setLastLogin(new Date().getTime());
- database.updateSession(auth);
- PlayerCache.getInstance().addPlayer(auth);
- }
- }
- } catch (Exception ex) {
- }
-
- if (Settings.usePurge)
- autoPurge();
-
- // Download GeoIp.dat file
- downloadGeoIp();
-
- // Start Email recall task if needed
- recallEmail();
-
- // Sponsor message
- ConsoleLogger.info("AuthMe hooks perfectly with the VERYGAMES server hosting!");
-
- ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " correctly enabled!");
- }
-
- private void setLog4JFilter() {
- Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
-
- @Override
- public void run() {
- org.apache.logging.log4j.core.Logger coreLogger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger();
- coreLogger.addFilter(new Log4JFilter());
- }
- });
- }
-
- public void checkVault() {
- if (this.getServer().getPluginManager().getPlugin("Vault") != null && this.getServer().getPluginManager().getPlugin("Vault").isEnabled()) {
- RegisteredServiceProvider permissionProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
- if (permissionProvider != null) {
- permission = permissionProvider.getProvider();
- ConsoleLogger.info("Vault detected, hooking with the " + permission.getName() + " permissions system...");
- } else {
- ConsoleLogger.showError("Vault detected, but I can't find any permissions plugin to hook with!");
- }
- } else {
- permission = null;
- }
- }
-
- public void checkChestShop() {
- if (!Settings.chestshop) {
- this.ChestShop = 0;
- return;
- }
- if (this.getServer().getPluginManager().getPlugin("ChestShop") != null && this.getServer().getPluginManager().getPlugin("ChestShop").isEnabled()) {
- try {
- String ver = com.Acrobot.ChestShop.ChestShop.getVersion();
- try {
- double version = Double.valueOf(ver.split(" ")[0]);
- if (version >= 3.50) {
- this.ChestShop = version;
- } else {
- ConsoleLogger.showError("Please Update your ChestShop version! Bugs may occur!");
- }
- } catch (NumberFormatException nfe) {
- try {
- double version = Double.valueOf(ver.split("t")[0]);
- if (version >= 3.50) {
- this.ChestShop = version;
- } else {
- ConsoleLogger.showError("Please Update your ChestShop version! Bugs may occur!");
- }
- } catch (NumberFormatException nfee) {
- }
- }
- } catch (Exception e) {
- }
- } else {
- this.ChestShop = 0;
- }
- }
-
- public void checkMultiverse() {
- if (!Settings.multiverse) {
- multiverse = null;
- return;
- }
- if (this.getServer().getPluginManager().getPlugin("Multiverse-Core") != null && this.getServer().getPluginManager().getPlugin("Multiverse-Core").isEnabled()) {
- try {
- multiverse = (MultiverseCore) this.getServer().getPluginManager().getPlugin("Multiverse-Core");
- ConsoleLogger.info("Hooked correctly with Multiverse-Core");
- } catch (NullPointerException npe) {
- multiverse = null;
- } catch (ClassCastException cce) {
- multiverse = null;
- } catch (NoClassDefFoundError ncdfe) {
- multiverse = null;
- }
- } else {
- multiverse = null;
- }
- }
-
- public void checkEssentials() {
- if (this.getServer().getPluginManager().getPlugin("Essentials") != null && this.getServer().getPluginManager().getPlugin("Essentials").isEnabled()) {
- try {
- ess = (Essentials) this.getServer().getPluginManager().getPlugin("Essentials");
- ConsoleLogger.info("Hooked correctly with Essentials");
- } catch (NullPointerException npe) {
- ess = null;
- } catch (ClassCastException cce) {
- ess = null;
- } catch (NoClassDefFoundError ncdfe) {
- ess = null;
- }
- } else {
- ess = null;
- }
- if (this.getServer().getPluginManager().getPlugin("EssentialsSpawn") != null && this.getServer().getPluginManager().getPlugin("EssentialsSpawn").isEnabled()) {
- try {
- essentialsSpawn = new EssSpawn().getLocation();
- ConsoleLogger.info("Hooked correctly with EssentialsSpawn");
- } catch (Exception e) {
- essentialsSpawn = null;
- ConsoleLogger.showError("Can't read the /plugins/Essentials/spawn.yml file!");
- }
- } else {
- essentialsSpawn = null;
- }
- }
-
- public void combatTag() {
- if (this.getServer().getPluginManager().getPlugin("CombatTag") != null && this.getServer().getPluginManager().getPlugin("CombatTag").isEnabled()) {
- this.CombatTag = true;
- } else {
- this.CombatTag = false;
- }
- }
-
- public void citizensVersion() {
- if (this.getServer().getPluginManager().getPlugin("Citizens") != null && this.getServer().getPluginManager().getPlugin("Citizens").isEnabled())
- this.isCitizensActive = true;
- else this.isCitizensActive = false;
- }
-
- @Override
- public void onDisable() {
- int playersOnline = 0;
- try {
- if (Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).getReturnType() == Collection.class)
- playersOnline = ((Collection>) Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).invoke(null, new Object[0])).size();
- else playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).invoke(null, new Object[0])).length;
- } catch (NoSuchMethodException ex) {
- } // can never happen
- catch (InvocationTargetException ex) {
- } // can also never happen
- catch (IllegalAccessException ex) {
- } // can still never happen
- if (playersOnline != 0)
- for (Player player : Bukkit.getOnlinePlayers()) {
- this.savePlayer(player);
- }
-
- if (database != null) {
- try {
- database.close();
- } catch (Exception e) {
- }
- }
-
- if (Settings.isBackupActivated && Settings.isBackupOnStop) {
- Boolean Backup = new PerformBackup(this).DoBackup();
- if (Backup)
- ConsoleLogger.info("Backup performed correctly.");
- else ConsoleLogger.showError("Error while performing the backup!");
- }
- ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " disabled!");
- }
-
- public static AuthMe getInstance() {
- return authme;
- }
-
- public void savePlayer(Player player) {
- try {
- if ((citizens.isNPC(player)) || (Utils.getInstance().isUnrestricted(player)) || (CombatTagComunicator.isNPC(player))) {
- return;
- }
- } catch (Exception e) {
- }
- try {
- String name = player.getName().toLowerCase();
- if (PlayerCache.getInstance().isAuthenticated(name) && !player.isDead() && Settings.isSaveQuitLocationEnabled) {
- final PlayerAuth auth = new PlayerAuth(player.getName().toLowerCase(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), player.getWorld().getName(), player.getName());
- database.updateQuitLoc(auth);
- }
- if (LimboCache.getInstance().hasLimboPlayer(name)) {
- LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
- if (Settings.protectInventoryBeforeLogInEnabled.booleanValue()) {
- player.getInventory().setArmorContents(limbo.getArmour());
- player.getInventory().setContents(limbo.getInventory());
- }
- if (!Settings.noTeleport)
- player.teleport(limbo.getLoc());
- this.utils.addNormal(player, limbo.getGroup());
- player.setOp(limbo.getOperator());
- limbo.getTimeoutTaskId().cancel();
- LimboCache.getInstance().deleteLimboPlayer(name);
- if (this.playerBackup.doesCacheExist(player)) {
- this.playerBackup.removeCache(player);
- }
- }
- PlayerCache.getInstance().removePlayer(name);
- database.setUnlogged(name);
- player.saveData();
- } catch (Exception ex) {
- }
- }
-
- public CitizensCommunicator getCitizensCommunicator() {
- return citizens;
- }
-
- public void setMessages(Messages m) {
- this.m = m;
- }
-
- public Messages getMessages() {
- return m;
- }
-
- public Player generateKickPlayer(Collection extends Player> collection) {
- Player player = null;
- for (Player p : collection) {
- if (!(authmePermissible(p, "authme.vip"))) {
- player = p;
- break;
- }
- }
- return player;
- }
-
- public boolean authmePermissible(Player player, String perm) {
- if (player.hasPermission(perm))
- return true;
- else if (permission != null) {
- return permission.playerHas(player, perm);
- }
- return false;
- }
-
- public boolean authmePermissible(CommandSender sender, String perm) {
- if (sender.hasPermission(perm))
- return true;
- else if (permission != null) {
- return permission.has(sender, perm);
- }
- return false;
- }
-
- private void autoPurge() {
- if (!Settings.usePurge) {
- return;
- }
- Calendar calendar = Calendar.getInstance();
- calendar.add(Calendar.DATE, -(Settings.purgeDelay));
- long until = calendar.getTimeInMillis();
- List cleared = database.autoPurgeDatabase(until);
- if (cleared == null)
- return;
- if (cleared.isEmpty())
- return;
- ConsoleLogger.info("AutoPurging the Database: " + cleared.size() + " accounts removed!");
- if (Settings.purgeEssentialsFile && this.ess != null)
- dataManager.purgeEssentials(cleared);
- if (Settings.purgePlayerDat)
- dataManager.purgeDat(cleared);
- if (Settings.purgeLimitedCreative)
- dataManager.purgeLimitedCreative(cleared);
- if (Settings.purgeAntiXray)
- dataManager.purgeAntiXray(cleared);
- if (Settings.purgePermissions)
- dataManager.purgePermissions(cleared, permission);
- }
-
- public Location getSpawnLocation(Player player) {
- World world = player.getWorld();
- String[] spawnPriority = Settings.spawnPriority.split(",");
- Location spawnLoc = world.getSpawnLocation();
- for (int i = spawnPriority.length - 1; i >= 0; i--) {
- String s = spawnPriority[i];
- if (s.equalsIgnoreCase("default") && getDefaultSpawn(world) != null)
- spawnLoc = getDefaultSpawn(world);
- if (s.equalsIgnoreCase("multiverse") && getMultiverseSpawn(world) != null)
- spawnLoc = getMultiverseSpawn(world);
- if (s.equalsIgnoreCase("essentials") && getEssentialsSpawn() != null)
- spawnLoc = getEssentialsSpawn();
- if (s.equalsIgnoreCase("authme") && getAuthMeSpawn(player) != null)
- spawnLoc = getAuthMeSpawn(player);
- }
- if (spawnLoc == null)
- spawnLoc = world.getSpawnLocation();
- return spawnLoc;
- }
-
- private Location getDefaultSpawn(World world) {
- return world.getSpawnLocation();
- }
-
- private Location getMultiverseSpawn(World world) {
- if (multiverse != null && Settings.multiverse) {
- try {
- return multiverse.getMVWorldManager().getMVWorld(world).getSpawnLocation();
- } catch (NullPointerException npe) {
- } catch (ClassCastException cce) {
- } catch (NoClassDefFoundError ncdfe) {
- }
- }
- return null;
- }
-
- private Location getEssentialsSpawn() {
- if (essentialsSpawn != null)
- return essentialsSpawn;
- return null;
- }
-
- private Location getAuthMeSpawn(Player player) {
- if ((!database.isAuthAvailable(player.getName().toLowerCase()) || !player.hasPlayedBefore()) && (Spawn.getInstance().getFirstSpawn() != null))
- return Spawn.getInstance().getFirstSpawn();
- if (Spawn.getInstance().getSpawn() != null)
- return Spawn.getInstance().getSpawn();
- return player.getWorld().getSpawnLocation();
- }
-
- public void downloadGeoIp() {
- ConsoleLogger.info("[LICENSE] This product uses data from the GeoLite API created by MaxMind, available at http://www.maxmind.com");
- File file = new File(getDataFolder(), "GeoIP.dat");
- if (!file.exists()) {
- try {
- String url = "http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz";
- URL downloadUrl = new URL(url);
- URLConnection conn = downloadUrl.openConnection();
- conn.setConnectTimeout(10000);
- conn.connect();
- InputStream input = conn.getInputStream();
- if (url.endsWith(".gz"))
- input = new GZIPInputStream(input);
- OutputStream output = new FileOutputStream(file);
- byte[] buffer = new byte[2048];
- int length = input.read(buffer);
- while (length >= 0) {
- output.write(buffer, 0, length);
- length = input.read(buffer);
- }
- output.close();
- input.close();
- } catch (Exception e) {
- }
- }
- }
-
- public String getCountryCode(String ip) {
- try {
- if (ls == null)
- ls = new LookupService(new File(getDataFolder(), "GeoIP.dat"));
- String code = ls.getCountry(ip).getCode();
- if (code != null && !code.isEmpty())
- return code;
- } catch (Exception e) {
- }
- return null;
- }
-
- public String getCountryName(String ip) {
- try {
- if (ls == null)
- ls = new LookupService(new File(getDataFolder(), "GeoIP.dat"));
- String code = ls.getCountry(ip).getName();
- if (code != null && !code.isEmpty())
- return code;
- } catch (Exception e) {
- }
- return null;
- }
-
- public void switchAntiBotMod(boolean mode) {
- this.antibotMod = mode;
- Settings.switchAntiBotMod(mode);
- }
-
- private void recallEmail() {
- if (!Settings.recallEmail)
- return;
- Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
-
- @Override
- public void run() {
- for (Player player : Bukkit.getOnlinePlayers()) {
- if (player.isOnline()) {
- String name = player.getName().toLowerCase();
- if (database.isAuthAvailable(name))
- if (PlayerCache.getInstance().isAuthenticated(name)) {
- String email = database.getAuth(name).getEmail();
- if (email == null || email.isEmpty() || email.equalsIgnoreCase("your@email.com"))
- m.send(player, "add_email");
- }
- }
- }
- }
- }, 1, 1200 * Settings.delayRecall);
- }
-
- public String replaceAllInfos(String message, Player player) {
- int playersOnline = 0;
- try {
- if (Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).getReturnType() == Collection.class)
- playersOnline = ((Collection>) Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).invoke(null, new Object[0])).size();
- else playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class>[0]).invoke(null, new Object[0])).length;
- } catch (NoSuchMethodException ex) {
- } // can never happen
- catch (InvocationTargetException ex) {
- } // can also never happen
- catch (IllegalAccessException ex) {
- } // can still never happen
- try {
- message = message.replace("&", "\u00a7");
- message = message.replace("{PLAYER}", player.getName());
- message = message.replace("{ONLINE}", "" + playersOnline);
- message = message.replace("{MAXPLAYERS}", "" + this.getServer().getMaxPlayers());
- message = message.replace("{IP}", getIP(player));
- message = message.replace("{LOGINS}", "" + PlayerCache.getInstance().getLogged());
- message = message.replace("{WORLD}", player.getWorld().getName());
- message = message.replace("{SERVER}", this.getServer().getServerName());
- message = message.replace("{VERSION}", this.getServer().getBukkitVersion());
- message = message.replace("{COUNTRY}", this.getCountryName(getIP(player)));
- } catch (Exception e) {
- }
- return message;
- }
-
- public String getIP(Player player) {
- String name = player.getName().toLowerCase();
- String ip = player.getAddress().getAddress().getHostAddress();
- if (Settings.bungee) {
- if (realIp.containsKey(name))
- ip = realIp.get(name);
- }
- if (Settings.checkVeryGames)
- if (getVeryGamesIP(player) != null)
- ip = getVeryGamesIP(player);
- return ip;
- }
-
- public boolean isLoggedIp(String name, String ip) {
- int count = 0;
- for (Player player : this.getServer().getOnlinePlayers()) {
- if (ip.equalsIgnoreCase(getIP(player)) && database.isLogged(player.getName().toLowerCase()) && !player.getName().equalsIgnoreCase(name))
- count++;
- }
- if (count >= Settings.getMaxLoginPerIp)
- return true;
- return false;
- }
-
- public boolean hasJoinedIp(String name, String ip) {
- int count = 0;
- for (Player player : this.getServer().getOnlinePlayers()) {
- if (ip.equalsIgnoreCase(getIP(player)) && !player.getName().equalsIgnoreCase(name))
- count++;
- }
- if (count >= Settings.getMaxJoinPerIp)
- return true;
- return false;
- }
-
- /**
- * Get Player real IP through VeryGames method
- *
- * @param Player
- * player
- */
- @Deprecated
- public String getVeryGamesIP(Player player) {
- String realIP = player.getAddress().getAddress().getHostAddress();
- String sUrl = vgUrl;
- sUrl = sUrl.replace("%IP%", player.getAddress().getAddress().getHostAddress()).replace("%PORT%", "" + player.getAddress().getPort());
- try {
- URL url = new URL(sUrl);
- URLConnection urlc = url.openConnection();
- BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
- String inputLine = in.readLine();
- if (inputLine != null && !inputLine.isEmpty() && !inputLine.equalsIgnoreCase("error") && !inputLine.contains("error")) {
- realIP = inputLine;
- }
- } catch (Exception e) {
- }
- return realIP;
- }
-
- public void setupDatabase() {
- /*
- * Backend MYSQL - FILE - SQLITE
- */
- switch (Settings.getDataSource) {
- case FILE:
- database = new FlatFile();
- break;
- case MYSQL:
- database = new MySQL();
- break;
- case SQLITE:
- database = new SQLite();
- final int b = database.getAccountsRegistered();
- if (b >= 4000)
- ConsoleLogger.showError("YOU'RE USING THE SQLITE DATABASE WITH " + b + "+ ACCOUNTS, FOR BETTER PERFORMANCES, PLEASE UPGRADE TO MYSQL!!");
- break;
- }
-
- if (Settings.isCachingEnabled) {
- database = new CacheDataSource(this, database);
- }
-
- database = new DatabaseCalls(database);
-
- if (Settings.getDataSource == DataSource.DataSourceType.FILE) {
- Converter converter = new ForceFlatToSqlite(database, this);
- try {
- Thread t = new Thread(converter);
- t.start();
- } catch (Exception e) {
- }
- ConsoleLogger.showError("FlatFile backend has been detected and is now deprecated, next time server starts up, it will be changed to SQLite... Conversion will be started Asynchronously, it will not drop down your performance !");
- ConsoleLogger.showError("If you want to keep FlatFile, set file again into config at backend, but this message and this change will appear again at the next restart");
- }
- }
-}
+package fr.xephi.authme;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.logging.Logger;
+
+import org.apache.logging.log4j.LogManager;
+import org.bukkit.Bukkit;
+import org.bukkit.Location;
+import org.bukkit.Server;
+import org.bukkit.World;
+import org.bukkit.command.Command;
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+import org.bukkit.plugin.PluginManager;
+import org.bukkit.plugin.RegisteredServiceProvider;
+import org.bukkit.plugin.java.JavaPlugin;
+import org.bukkit.scheduler.BukkitTask;
+import org.mcstats.Metrics;
+import org.mcstats.Metrics.Graph;
+
+import com.earth2me.essentials.Essentials;
+import com.onarandombox.MultiverseCore.MultiverseCore;
+
+import fr.xephi.authme.api.API;
+import fr.xephi.authme.api.NewAPI;
+import fr.xephi.authme.cache.auth.PlayerAuth;
+import fr.xephi.authme.cache.auth.PlayerCache;
+import fr.xephi.authme.cache.backup.JsonCache;
+import fr.xephi.authme.cache.limbo.LimboCache;
+import fr.xephi.authme.cache.limbo.LimboPlayer;
+import fr.xephi.authme.command.CommandHandler;
+import fr.xephi.authme.converter.Converter;
+import fr.xephi.authme.converter.ForceFlatToSqlite;
+import fr.xephi.authme.datasource.CacheDataSource;
+import fr.xephi.authme.datasource.DataSource;
+import fr.xephi.authme.datasource.DatabaseCalls;
+import fr.xephi.authme.datasource.FlatFile;
+import fr.xephi.authme.datasource.MySQL;
+import fr.xephi.authme.datasource.SQLite;
+import fr.xephi.authme.hooks.BungeeCordMessage;
+import fr.xephi.authme.hooks.EssSpawn;
+import fr.xephi.authme.listener.AuthMeBlockListener;
+import fr.xephi.authme.listener.AuthMeEntityListener;
+import fr.xephi.authme.listener.AuthMeInventoryPacketAdapter;
+import fr.xephi.authme.listener.AuthMePlayerListener;
+import fr.xephi.authme.listener.AuthMePlayerListener16;
+import fr.xephi.authme.listener.AuthMePlayerListener18;
+import fr.xephi.authme.listener.AuthMeServerListener;
+import fr.xephi.authme.modules.ModuleManager;
+import fr.xephi.authme.process.Management;
+import fr.xephi.authme.settings.Messages;
+import fr.xephi.authme.settings.OtherAccounts;
+import fr.xephi.authme.settings.Settings;
+import fr.xephi.authme.settings.Spawn;
+import fr.xephi.authme.util.Utils;
+import net.milkbowl.vault.permission.Permission;
+import net.minelink.ctplus.CombatTagPlus;
+
+public class AuthMe extends JavaPlugin {
+
+ /** Defines the name of the plugin. */
+ // TODO: Create a getter method for this constant, and make it private
+ public static final String PLUGIN_NAME = "AuthMeReloaded";
+ /** Defines the current AuthMeReloaded version name. */
+ private static final String PLUGIN_VERSION_NAME = "5.1-SNAPSHOT";
+ /** Defines the current AuthMeReloaded version code. */
+ private static final int PLUGIN_VERSION_CODE = 100; // Increase this number
+ // by one when an update
+ // is released
+
+ private static AuthMe plugin;
+ private static Server server;
+ private Logger authmeLogger;
+
+ // TODO: Move this to a better place! -- timvisee
+ private CommandHandler commandHandler = null;
+
+ public Management management;
+ public NewAPI api;
+ public SendMailSSL mail;
+ private Settings settings;
+ private Messages m;
+ public DataManager dataManager;
+ public DataSource database;
+ private JsonCache playerBackup;
+ public OtherAccounts otherAccounts;
+ public Location essentialsSpawn;
+ public boolean antibotMod = false;
+ public boolean delayedAntiBot = true;
+
+ // Hooks TODO: move into modules
+ public Permission permission;
+ public Essentials ess;
+ public MultiverseCore multiverse;
+ public CombatTagPlus combatTagPlus;
+ public AuthMeInventoryPacketAdapter inventoryProtector;
+
+ // Module manager
+ private ModuleManager moduleManager;
+
+ // TODO: Create Manager for fields below
+ public ConcurrentHashMap sessions = new ConcurrentHashMap<>();
+ public ConcurrentHashMap captcha = new ConcurrentHashMap<>();
+ public ConcurrentHashMap cap = new ConcurrentHashMap<>();
+ public ConcurrentHashMap realIp = new ConcurrentHashMap<>();
+
+ // In case we need to cache PlayerAuths, prevent connection before it's done
+ private boolean canConnect = true;
+
+ public boolean canConnect() {
+ return canConnect;
+ }
+
+ public void setCanConnect(boolean canConnect) {
+ this.canConnect = canConnect;
+ }
+
+ public static AuthMe getInstance() {
+ return plugin;
+ }
+
+ public Settings getSettings() {
+ return settings;
+ }
+
+ public void setMessages(Messages m) {
+ this.m = m;
+ }
+
+ public Messages getMessages() {
+ return m;
+ }
+
+ @Override
+ public void onEnable() {
+ // Set the Instance
+ server = getServer();
+ authmeLogger = Logger.getLogger("AuthMe");
+ plugin = this;
+
+ // Set up and initialize the command handler
+ this.commandHandler = new CommandHandler(false);
+ this.commandHandler.init();
+
+ // TODO: split the plugin in more modules
+ moduleManager = new ModuleManager(this);
+ @SuppressWarnings("unused")
+ int loaded = moduleManager.loadModules();
+
+ // TODO: remove vault as hard dependency
+ PluginManager pm = server.getPluginManager();
+
+ // Setup the Logger
+ if (authmeLogger == null)
+ authmeLogger = this.getLogger();
+ else authmeLogger.setParent(this.getLogger());
+
+ // Load settings and custom configurations
+ // TODO: new configuration style (more files)
+ try {
+ settings = new Settings(this);
+ Settings.reload();
+ } catch (Exception e) {
+ ConsoleLogger.writeStackTrace(e);
+ ConsoleLogger.showError("Can't load the configuration file... Something went wrong, to avoid security issues the server will shutdown!");
+ server.shutdown();
+ return;
+ }
+
+ // Setup otherAccounts file
+ otherAccounts = OtherAccounts.getInstance();
+
+ // Setup messages
+ m = Messages.getInstance();
+
+ // Start the metrics service
+ try {
+ Metrics metrics = new Metrics(this);
+ Graph messagesLanguage = metrics.createGraph("Messages language");
+ Graph databaseBackend = metrics.createGraph("Database backend");
+
+ // Custom graphs
+ if (Settings.messageFile.exists()) {
+ messagesLanguage.addPlotter(new Metrics.Plotter(Settings.messagesLanguage) {
+
+ @Override
+ public int getValue() {
+ return 1;
+ }
+ });
+ }
+ databaseBackend.addPlotter(new Metrics.Plotter(Settings.getDataSource.toString()) {
+
+ @Override
+ public int getValue() {
+ return 1;
+ }
+ });
+
+ metrics.start();
+ ConsoleLogger.info("Metrics started successfully!");
+ } catch (Exception e) {
+ // Failed to submit the metrics data
+ ConsoleLogger.writeStackTrace(e);
+ ConsoleLogger.showError("Can't start Metrics! The plugin will work anyway...");
+ }
+
+ // Set Console Filter
+ if (Settings.removePassword) {
+ ConsoleFilter filter = new ConsoleFilter();
+ this.getLogger().setFilter(filter);
+ Bukkit.getLogger().setFilter(filter);
+ Logger.getLogger("Minecraft").setFilter(filter);
+ authmeLogger.setFilter(filter);
+ // Set Log4J Filter
+ try {
+ Class.forName("org.apache.logging.log4j.core.Filter");
+ setLog4JFilter();
+ } catch (ClassNotFoundException | NoClassDefFoundError e) {
+ ConsoleLogger.info("You're using Minecraft 1.6.x or older, Log4J support will be disabled");
+ }
+ }
+
+ // AntiBot delay
+ if (Settings.enableAntiBot) {
+ Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
+
+ @Override
+ public void run() {
+ delayedAntiBot = false;
+ }
+ }, 2400);
+ }
+
+ // Download GeoIp.dat file
+ Utils.checkGeoIP();
+
+ // Load MailApi if needed
+ if (!Settings.getmailAccount.isEmpty() && !Settings.getmailPassword.isEmpty()) {
+ mail = new SendMailSSL(this);
+ }
+
+ // Find Permissions
+ checkVault();
+
+ // Check Combat Tag Plus Version
+ checkCombatTagPlus();
+
+ // Check Multiverse
+ checkMultiverse();
+
+ // Check Essentials
+ checkEssentials();
+
+ // Check if the protocollib is available. If so we could listen for
+ // inventory protection
+ checkProtocolLib();
+
+ // Do backup on start if enabled
+ if (Settings.isBackupActivated && Settings.isBackupOnStart) {
+ // Do backup and check return value!
+ if (new PerformBackup(this).doBackup()) {
+ ConsoleLogger.info("Backup performed correctly");
+ } else {
+ ConsoleLogger.showError("Error while performing the backup!");
+ }
+ }
+
+ // Connect to the database and setup tables
+ try {
+ setupDatabase();
+ } catch (Exception e) {
+ ConsoleLogger.writeStackTrace(e);
+ ConsoleLogger.showError(e.getMessage());
+ ConsoleLogger.showError("Fatal error occurred during database connection! Authme initialization ABORTED!");
+ stopOrUnload();
+ return;
+ }
+
+ // Setup the inventory backup
+ playerBackup = new JsonCache();
+
+ // Set the DataManager
+ dataManager = new DataManager(this);
+
+ // Setup the new API
+ api = new NewAPI(this);
+ // Setup the old deprecated API
+ new API(this);
+
+ // Setup Management
+ management = new Management(this);
+
+ // Bungeecord hook
+ if (Settings.bungee) {
+ Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
+ Bukkit.getMessenger().registerIncomingPluginChannel(this, "BungeeCord", new BungeeCordMessage(this));
+ }
+
+ // Reload support hook
+ if (database != null) {
+ int playersOnline = Utils.getOnlinePlayers().size();
+ if (playersOnline < 1) {
+ database.purgeLogged();
+ } else if (Settings.reloadSupport) {
+ for (PlayerAuth auth : database.getLoggedPlayers()) {
+ if (auth == null)
+ continue;
+ auth.setLastLogin(new Date().getTime());
+ database.updateSession(auth);
+ PlayerCache.getInstance().addPlayer(auth);
+ }
+ }
+ }
+
+ // Register events
+ pm.registerEvents(new AuthMePlayerListener(this), this);
+ // Try to register 1.6 player listeners
+ try {
+ Class.forName("org.bukkit.event.player.PlayerEditBookEvent");
+ pm.registerEvents(new AuthMePlayerListener16(this), this);
+ } catch (ClassNotFoundException ignore) {
+ }
+ // Try to register 1.8 player listeners
+ try {
+ Class.forName("org.bukkit.event.player.PlayerInteractAtEntityEvent");
+ pm.registerEvents(new AuthMePlayerListener18(this), this);
+ } catch (ClassNotFoundException ignore) {
+ }
+ pm.registerEvents(new AuthMeBlockListener(this), this);
+ pm.registerEvents(new AuthMeEntityListener(this), this);
+ pm.registerEvents(new AuthMeServerListener(this), this);
+
+ // TODO: This is moved to CommandManager.registerCommands() handled by
+ // AuthMe.onCommand() -- timvisee
+ // Register commands
+ // getCommand("authme").setExecutor(new AdminCommand(this));
+ // getCommand("register").setExecutor(new RegisterCommand(this));
+ // getCommand("login").setExecutor(new LoginCommand(this));
+ // getCommand("changepassword").setExecutor(new
+ // ChangePasswordCommand(this));
+ // getCommand("logout").setExecutor(new LogoutCommand(this));
+ // getCommand("unregister").setExecutor(new UnregisterCommand(this));
+ // getCommand("email").setExecutor(new EmailCommand(this));
+ // getCommand("captcha").setExecutor(new CaptchaCommand(this));
+ // getCommand("converter").setExecutor(new ConverterCommand(this));
+
+ // Purge on start if enabled
+ autoPurge();
+
+ // Start Email recall task if needed
+ recallEmail();
+
+ // Configuration Security Warnings
+ if (!Settings.isForceSingleSessionEnabled) {
+ ConsoleLogger.showError("WARNING!!! By disabling ForceSingleSession, your server protection is inadequate!");
+ }
+ if (Settings.getSessionTimeout == 0 && Settings.isSessionsEnabled) {
+ ConsoleLogger.showError("WARNING!!! You set session timeout to 0, this may cause security issues!");
+ }
+
+ // Sponsor messages
+ ConsoleLogger.info("AuthMe hooks perfectly with the VERYGAMES server hosting!");
+ ConsoleLogger.info("Development builds are available on our jenkins, thanks to f14stelt.");
+ ConsoleLogger.info("Do you want a good gameserver? Look at our sponsor GameHosting.it leader in Italy as Game Server Provider!");
+
+ // Successful message
+ ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " correctly enabled!");
+ }
+
+ @Override
+ public void onDisable() {
+ // Save player data
+ Collection extends Player> players = Utils.getOnlinePlayers();
+ if (players != null) {
+ for (Player player : players) {
+ this.savePlayer(player);
+ }
+ }
+
+ // Do backup on stop if enabled
+ if (Settings.isBackupActivated && Settings.isBackupOnStop) {
+ boolean Backup = new PerformBackup(this).doBackup();
+ if (Backup)
+ ConsoleLogger.info("Backup performed correctly.");
+ else ConsoleLogger.showError("Error while performing the backup!");
+ }
+
+ // Unload modules
+ moduleManager.unloadModules();
+
+ // Close the database
+ if (database != null) {
+ database.close();
+ }
+
+ // Disabled correctly
+ ConsoleLogger.info("AuthMe " + this.getDescription().getVersion() + " disabled!");
+ }
+
+ // Stop/unload the server/plugin as defined in the configuration
+ public void stopOrUnload() {
+ if (Settings.isStopEnabled) {
+ ConsoleLogger.showError("THE SERVER IS GOING TO SHUTDOWN AS DEFINED IN THE CONFIGURATION!");
+ server.shutdown();
+ } else {
+ server.getPluginManager().disablePlugin(AuthMe.getInstance());
+ }
+ }
+
+ // Show the exception message and stop/unload the server/plugin as defined
+ // in the configuration
+ public void stopOrUnload(Exception e) {
+ ConsoleLogger.showError(e.getMessage());
+ stopOrUnload();
+ }
+
+ // Initialize and setup the database
+ public void setupDatabase() throws Exception {
+ if (database != null)
+ database.close();
+ // Backend MYSQL - FILE - SQLITE - SQLITEHIKARI
+ boolean isSQLite = false;
+ switch (Settings.getDataSource) {
+ case FILE:
+ database = new FlatFile();
+ break;
+ case MYSQL:
+ database = new MySQL();
+ break;
+ case SQLITE:
+ database = new SQLite();
+ isSQLite = true;
+ break;
+ }
+
+ if (isSQLite) {
+ server.getScheduler().runTaskAsynchronously(this, new Runnable() {
+
+ @Override
+ public void run() {
+ int accounts = database.getAccountsRegistered();
+ if (accounts >= 4000)
+ ConsoleLogger.showError("YOU'RE USING THE SQLITE DATABASE WITH " + accounts + "+ ACCOUNTS, FOR BETTER PERFORMANCES, PLEASE UPGRADE TO MYSQL!!");
+ }
+ });
+ }
+
+ if (Settings.isCachingEnabled) {
+ database = new CacheDataSource(this, database);
+ } else {
+ database = new DatabaseCalls(database);
+ }
+
+ if (Settings.getDataSource == DataSource.DataSourceType.FILE) {
+ Converter converter = new ForceFlatToSqlite(database, this);
+ server.getScheduler().runTaskAsynchronously(this, converter);
+ ConsoleLogger.showError("FlatFile backend has been detected and is now deprecated, next time server starts up, it will be changed to SQLite... Conversion will be started Asynchronously, it will not drop down your performance !");
+ ConsoleLogger.showError("If you want to keep FlatFile, set file again into config at backend, but this message and this change will appear again at the next restart");
+ }
+ }
+
+ // Set the console filter to remove the passwords
+ private void setLog4JFilter() {
+ Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
+
+ @Override
+ public void run() {
+ org.apache.logging.log4j.core.Logger coreLogger = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger();
+ coreLogger.addFilter(new Log4JFilter());
+ }
+ });
+ }
+
+ // Check the presence of the Vault plugin and a permissions provider
+ public void checkVault() {
+ if (server.getPluginManager().isPluginEnabled("Vault")) {
+ RegisteredServiceProvider permissionProvider = server.getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
+ if (permissionProvider != null) {
+ permission = permissionProvider.getProvider();
+ ConsoleLogger.info("Vault detected, hooking with the " + permission.getName() + " permissions system...");
+ } else {
+ ConsoleLogger.showError("Vault detected, but I can't find any permissions plugin to hook with!");
+ }
+ } else {
+ permission = null;
+ }
+ }
+
+ // Get the Multiverse plugin
+ public void checkMultiverse() {
+ if (Settings.multiverse && server.getPluginManager().isPluginEnabled("Multiverse-Core")) {
+ try {
+ multiverse = (MultiverseCore) server.getPluginManager().getPlugin("Multiverse-Core");
+ ConsoleLogger.info("Hooked correctly with Multiverse-Core");
+ } catch (Exception | NoClassDefFoundError ignored) {
+ multiverse = null;
+ }
+ } else {
+ multiverse = null;
+ }
+ }
+
+ // Get the Essentials plugin
+ public void checkEssentials() {
+ if (server.getPluginManager().isPluginEnabled("Essentials")) {
+ try {
+ ess = (Essentials) server.getPluginManager().getPlugin("Essentials");
+ ConsoleLogger.info("Hooked correctly with Essentials");
+ } catch (Exception | NoClassDefFoundError ingnored) {
+ ess = null;
+ }
+ } else {
+ ess = null;
+ }
+ if (server.getPluginManager().isPluginEnabled("EssentialsSpawn")) {
+ try {
+ essentialsSpawn = new EssSpawn().getLocation();
+ ConsoleLogger.info("Hooked correctly with EssentialsSpawn");
+ } catch (Exception e) {
+ essentialsSpawn = null;
+ ConsoleLogger.showError("Can't read the /plugins/Essentials/spawn.yml file!");
+ }
+ } else {
+ essentialsSpawn = null;
+ }
+ }
+
+ // Check the presence of CombatTag
+ public void checkCombatTagPlus() {
+ if (server.getPluginManager().isPluginEnabled("CombatTagPlus")) {
+ try {
+ combatTagPlus = (CombatTagPlus) server.getPluginManager().getPlugin("CombatTagPlus");
+ ConsoleLogger.info("Hooked correctly with CombatTagPlus");
+ } catch (Exception | NoClassDefFoundError ingnored) {
+ combatTagPlus = null;
+ }
+ } else {
+ combatTagPlus = null;
+ }
+ }
+
+ // Check the presence of the ProtocolLib plugin
+ public void checkProtocolLib() {
+ if (Settings.protectInventoryBeforeLogInEnabled) {
+ if (server.getPluginManager().isPluginEnabled("ProtocolLib")) {
+ inventoryProtector = new AuthMeInventoryPacketAdapter(this);
+ inventoryProtector.register();
+ } else {
+ ConsoleLogger.showError("WARNING!!! The protectInventory feature requires ProtocolLib! Disabling it...");
+ Settings.protectInventoryBeforeLogInEnabled = false;
+ }
+ }
+ }
+
+ // Check if a player/command sender have a permission
+ public boolean authmePermissible(Player player, String perm) {
+ if (player.hasPermission(perm)) {
+ return true;
+ } else if (permission != null) {
+ return permission.playerHas(player, perm);
+ }
+ return false;
+ }
+
+ public boolean authmePermissible(CommandSender sender, String perm) {
+ if (sender.hasPermission(perm)) {
+ return true;
+ } else if (permission != null) {
+ return permission.has(sender, perm);
+ }
+ return false;
+ }
+
+ // Save Player Data
+ public void savePlayer(Player player) {
+ if ((Utils.isNPC(player)) || (Utils.isUnrestricted(player))) {
+ return;
+ }
+ String name = player.getName().toLowerCase();
+ if (PlayerCache.getInstance().isAuthenticated(name) && !player.isDead() && Settings.isSaveQuitLocationEnabled) {
+ final PlayerAuth auth = new PlayerAuth(player.getName().toLowerCase(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), player.getWorld().getName(), player.getName());
+ database.updateQuitLoc(auth);
+ }
+ if (LimboCache.getInstance().hasLimboPlayer(name)) {
+ LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name);
+ if (!Settings.noTeleport) {
+ player.teleport(limbo.getLoc());
+ }
+
+ Utils.addNormal(player, limbo.getGroup());
+ player.setOp(limbo.getOperator());
+ limbo.getTimeoutTaskId().cancel();
+ LimboCache.getInstance().deleteLimboPlayer(name);
+ if (this.playerBackup.doesCacheExist(player)) {
+ this.playerBackup.removeCache(player);
+ }
+ }
+ PlayerCache.getInstance().removePlayer(name);
+ player.saveData();
+ }
+
+ // Select the player to kick when a vip player join the server when full
+ public Player generateKickPlayer(Collection extends Player> collection) {
+ Player player = null;
+ for (Player p : collection) {
+ if (!(authmePermissible(p, "authme.vip"))) {
+ player = p;
+ break;
+ }
+ }
+ return player;
+ }
+
+ // Purge inactive players from the database, as defined in the configuration
+ private void autoPurge() {
+ if (!Settings.usePurge) {
+ return;
+ }
+ Calendar calendar = Calendar.getInstance();
+ calendar.add(Calendar.DATE, -(Settings.purgeDelay));
+ long until = calendar.getTimeInMillis();
+ List cleared = database.autoPurgeDatabase(until);
+ if (cleared == null) {
+ return;
+ }
+ if (cleared.isEmpty()) {
+ return;
+ }
+ ConsoleLogger.info("AutoPurging the Database: " + cleared.size() + " accounts removed!");
+ if (Settings.purgeEssentialsFile && this.ess != null)
+ dataManager.purgeEssentials(cleared); // name to UUID convertion
+ // needed with latest versions
+ if (Settings.purgePlayerDat)
+ dataManager.purgeDat(cleared); // name to UUID convertion needed
+ // with latest versions of MC
+ if (Settings.purgeLimitedCreative)
+ dataManager.purgeLimitedCreative(cleared);
+ if (Settings.purgeAntiXray)
+ dataManager.purgeAntiXray(cleared); // IDK if it uses UUID or
+ // names... (Actually it purges
+ // only names!)
+ if (Settings.purgePermissions)
+ dataManager.purgePermissions(cleared, permission);
+ }
+
+ // Return the spawn location of a player
+ public Location getSpawnLocation(Player player) {
+ World world = player.getWorld();
+ String[] spawnPriority = Settings.spawnPriority.split(",");
+ Location spawnLoc = world.getSpawnLocation();
+ for (int i = spawnPriority.length - 1; i >= 0; i--) {
+ String s = spawnPriority[i];
+ if (s.equalsIgnoreCase("default") && getDefaultSpawn(world) != null)
+ spawnLoc = getDefaultSpawn(world);
+ if (s.equalsIgnoreCase("multiverse") && getMultiverseSpawn(world) != null)
+ spawnLoc = getMultiverseSpawn(world);
+ if (s.equalsIgnoreCase("essentials") && getEssentialsSpawn() != null)
+ spawnLoc = getEssentialsSpawn();
+ if (s.equalsIgnoreCase("authme") && getAuthMeSpawn(player) != null)
+ spawnLoc = getAuthMeSpawn(player);
+ }
+ if (spawnLoc == null) {
+ spawnLoc = world.getSpawnLocation();
+ }
+ return spawnLoc;
+ }
+
+ // Return the default spawnpoint of a world
+ private Location getDefaultSpawn(World world) {
+ return world.getSpawnLocation();
+ }
+
+ // Return the multiverse spawnpoint of a world
+ private Location getMultiverseSpawn(World world) {
+ if (multiverse != null && Settings.multiverse) {
+ try {
+ return multiverse.getMVWorldManager().getMVWorld(world).getSpawnLocation();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ return null;
+ }
+
+ // Return the essentials spawnpoint
+ private Location getEssentialsSpawn() {
+ if (essentialsSpawn != null) {
+ return essentialsSpawn;
+ }
+ return null;
+ }
+
+ // Return the authme soawnpoint
+ private Location getAuthMeSpawn(Player player) {
+ if ((!database.isAuthAvailable(player.getName().toLowerCase()) || !player.hasPlayedBefore()) && (Spawn.getInstance().getFirstSpawn() != null)) {
+ return Spawn.getInstance().getFirstSpawn();
+ }
+ if (Spawn.getInstance().getSpawn() != null) {
+ return Spawn.getInstance().getSpawn();
+ }
+ return player.getWorld().getSpawnLocation();
+ }
+
+ public void switchAntiBotMod(boolean mode) {
+ this.antibotMod = mode;
+ Settings.switchAntiBotMod(mode);
+ }
+
+ public boolean getAntiBotModMode() {
+ return this.antibotMod;
+ }
+
+ private void recallEmail() {
+ if (!Settings.recallEmail)
+ return;
+ Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable() {
+
+ @Override
+ public void run() {
+ for (Player player : Utils.getOnlinePlayers()) {
+ if (player.isOnline()) {
+ String name = player.getName().toLowerCase();
+ if (database.isAuthAvailable(name))
+ if (PlayerCache.getInstance().isAuthenticated(name)) {
+ String email = database.getAuth(name).getEmail();
+ if (email == null || email.isEmpty() || email.equalsIgnoreCase("your@email.com"))
+ m.send(player, "add_email");
+ }
+ }
+ }
+ }
+ }, 1, 1200 * Settings.delayRecall);
+ }
+
+ public String replaceAllInfos(String message, Player player) {
+ int playersOnline = Utils.getOnlinePlayers().size();
+ message = message.replace("&", "\u00a7");
+ message = message.replace("{PLAYER}", player.getName());
+ message = message.replace("{ONLINE}", "" + playersOnline);
+ message = message.replace("{MAXPLAYERS}", "" + server.getMaxPlayers());
+ message = message.replace("{IP}", getIP(player));
+ message = message.replace("{LOGINS}", "" + PlayerCache.getInstance().getLogged());
+ message = message.replace("{WORLD}", player.getWorld().getName());
+ message = message.replace("{SERVER}", server.getServerName());
+ message = message.replace("{VERSION}", server.getBukkitVersion());
+ message = message.replace("{COUNTRY}", Utils.getCountryName(getIP(player)));
+ return message;
+ }
+
+ public String getIP(Player player) {
+ String name = player.getName().toLowerCase();
+ String ip = player.getAddress().getAddress().getHostAddress();
+ if (Settings.bungee) {
+ if (realIp.containsKey(name))
+ ip = realIp.get(name);
+ }
+ if (Settings.checkVeryGames)
+ if (getVeryGamesIP(player) != null)
+ ip = getVeryGamesIP(player);
+ return ip;
+ }
+
+ public boolean isLoggedIp(String name, String ip) {
+ int count = 0;
+ for (Player player : Utils.getOnlinePlayers()) {
+ if (ip.equalsIgnoreCase(getIP(player)) && database.isLogged(player.getName().toLowerCase()) && !player.getName().equalsIgnoreCase(name))
+ count++;
+ }
+ return count >= Settings.getMaxLoginPerIp;
+ }
+
+ public boolean hasJoinedIp(String name, String ip) {
+ int count = 0;
+ for (Player player : Utils.getOnlinePlayers()) {
+ if (ip.equalsIgnoreCase(getIP(player)) && !player.getName().equalsIgnoreCase(name))
+ count++;
+ }
+ return count >= Settings.getMaxJoinPerIp;
+ }
+
+ public ModuleManager getModuleManager() {
+ return moduleManager;
+ }
+
+ /**
+ * Get Player real IP through VeryGames method
+ *
+ * @param player
+ * player
+ */
+ @Deprecated
+ public String getVeryGamesIP(Player player) {
+ String realIP = player.getAddress().getAddress().getHostAddress();
+ String sUrl = "http://monitor-1.verygames.net/api/?action=ipclean-real-ip&out=raw&ip=%IP%&port=%PORT%";
+ sUrl = sUrl.replace("%IP%", player.getAddress().getAddress().getHostAddress()).replace("%PORT%", "" + player.getAddress().getPort());
+ try {
+ URL url = new URL(sUrl);
+ URLConnection urlc = url.openConnection();
+ BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
+ String inputLine = in.readLine();
+ if (inputLine != null && !inputLine.isEmpty() && !inputLine.equalsIgnoreCase("error") && !inputLine.contains("error")) {
+ realIP = inputLine;
+ }
+ } catch (Exception ignored) {
+ }
+ return realIP;
+ }
+
+ @Deprecated
+ public String getCountryCode(String ip) {
+ return Utils.getCountryCode(ip);
+ }
+
+ @Deprecated
+ public String getCountryName(String ip) {
+ return Utils.getCountryName(ip);
+ }
+
+ /**
+ * Get the command handler instance.
+ *
+ * @return Command handler.
+ */
+ public CommandHandler getCommandHandler() {
+ return this.commandHandler;
+ }
+
+ /**
+ * Handle Bukkit commands.
+ *
+ * @param sender
+ * The command sender (Bukkit).
+ * @param cmd
+ * The command (Bukkit).
+ * @param commandLabel
+ * The command label (Bukkit).
+ * @param args
+ * The command arguments (Bukkit).
+ *
+ * @return True if the command was executed, false otherwise.
+ */
+ @Override
+ public boolean onCommand(CommandSender sender, Command cmd,
+ String commandLabel, String[] args) {
+ // Get the command handler, and make sure it's valid
+ CommandHandler commandHandler = this.getCommandHandler();
+ if (commandHandler == null)
+ return false;
+
+ // Handle the command, return the result
+ return commandHandler.onCommand(sender, cmd, commandLabel, args);
+ }
+
+ /**
+ * Get the current installed AuthMeReloaded version name.
+ *
+ * @return The version name of the currently installed AuthMeReloaded
+ * instance.
+ */
+ public static String getVersionName() {
+ return PLUGIN_VERSION_NAME;
+ }
+
+ /**
+ * Get the current installed AuthMeReloaded version code.
+ *
+ * @return The version code of the currently installed AuthMeReloaded
+ * instance.
+ */
+ public static int getVersionCode() {
+ return PLUGIN_VERSION_CODE;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/ConsoleLogger.java b/src/main/java/fr/xephi/authme/ConsoleLogger.java
index 3a73ab5c..e2c4ba5f 100644
--- a/src/main/java/fr/xephi/authme/ConsoleLogger.java
+++ b/src/main/java/fr/xephi/authme/ConsoleLogger.java
@@ -1,63 +1,61 @@
package fr.xephi.authme;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileWriter;
import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.StandardOpenOption;
import java.text.DateFormat;
-import java.util.Calendar;
+import java.text.SimpleDateFormat;
+import java.util.Date;
import java.util.logging.Logger;
-import org.bukkit.Bukkit;
+import com.google.common.base.Throwables;
+import fr.xephi.authme.api.NewAPI;
import fr.xephi.authme.settings.Settings;
public class ConsoleLogger {
- private static final Logger log = Logger.getLogger("AuthMe");
+ private static final Logger log = AuthMe.getInstance().getLogger();
+ private static final DateFormat df = new SimpleDateFormat("[MM-dd HH:mm:ss]");
public static void info(String message) {
- if (AuthMe.getInstance().isEnabled()) {
- log.info("[AuthMe] " + message);
- if (Settings.useLogging) {
- Calendar date = Calendar.getInstance();
- final String actually = "[" + DateFormat.getDateInstance().format(date.getTime()) + ", " + date.get(Calendar.HOUR_OF_DAY) + ":" + date.get(Calendar.MINUTE) + ":" + date.get(Calendar.SECOND) + "] " + message;
- Bukkit.getScheduler().runTaskAsynchronously(AuthMe.getInstance(), new Runnable() {
- @Override
- public void run() {
- writeLog(actually);
- }
- });
+ log.info("[AuthMe] " + message);
+ if (Settings.useLogging) {
+ String dateTime;
+ synchronized (df) {
+ dateTime = df.format(new Date());
}
+ writeLog(dateTime + " " + message);
}
}
public static void showError(String message) {
- if (AuthMe.getInstance().isEnabled()) {
- log.warning("[AuthMe] ERROR: " + message);
- if (Settings.useLogging) {
- Calendar date = Calendar.getInstance();
- final String actually = "[" + DateFormat.getDateInstance().format(date.getTime()) + ", " + date.get(Calendar.HOUR_OF_DAY) + ":" + date.get(Calendar.MINUTE) + ":" + date.get(Calendar.SECOND) + "] ERROR : " + message;
- Bukkit.getScheduler().runTaskAsynchronously(AuthMe.getInstance(), new Runnable() {
- @Override
- public void run() {
- writeLog(actually);
- }
- });
+ log.warning("[AuthMe] " + message);
+ if (Settings.useLogging) {
+ String dateTime;
+ synchronized (df) {
+ dateTime = df.format(new Date());
}
+ writeLog(dateTime + " ERROR: " + message);
}
}
- public static void writeLog(String string) {
+ public static void writeLog(String message) {
try {
- FileWriter fw = new FileWriter(AuthMe.getInstance().getDataFolder() + File.separator + "authme.log", true);
- BufferedWriter w = new BufferedWriter(fw);
- w.write(string);
- w.newLine();
- w.close();
- } catch (IOException e) {
- e.printStackTrace();
+ Files.write(Settings.LOG_FILE.toPath(), (message + NewAPI.newline).getBytes(),
+ StandardOpenOption.APPEND,
+ StandardOpenOption.CREATE);
+ } catch (IOException ignored) {
}
}
+ public static void writeStackTrace(Exception ex) {
+ if (Settings.useLogging) {
+ String dateTime;
+ synchronized (df) {
+ dateTime = df.format(new Date());
+ }
+ writeLog(dateTime + " " + Throwables.getStackTraceAsString(ex));
+ }
+ }
}
diff --git a/src/main/java/fr/xephi/authme/DataManager.java b/src/main/java/fr/xephi/authme/DataManager.java
index 2bcfa17a..95a9ab53 100644
--- a/src/main/java/fr/xephi/authme/DataManager.java
+++ b/src/main/java/fr/xephi/authme/DataManager.java
@@ -12,6 +12,7 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import fr.xephi.authme.settings.Settings;
+import fr.xephi.authme.util.Utils;
import net.milkbowl.vault.permission.Permission;
public class DataManager {
@@ -46,6 +47,8 @@ public class DataManager {
return result.get();
} catch (Exception e) {
return (null);
+ } finally {
+ executor.shutdown();
}
}
@@ -102,30 +105,41 @@ public class DataManager {
for (String name : cleared) {
try {
org.bukkit.OfflinePlayer player = getOfflinePlayer(name);
- if (player == null)
+ if (player == null) {
continue;
- String playerName = player.getName();
- File playerFile = new File(plugin.getServer().getWorldContainer() + File.separator + Settings.defaultWorld + File.separator + "players" + File.separator + playerName + ".dat");
- if (playerFile.exists()) {
+ }
+
+ try {
+ File playerFile = new File(plugin.getServer().getWorldContainer() + File.separator + Settings.defaultWorld + File.separator + "players" + File.separator + player.getUniqueId() + ".dat");
playerFile.delete();
i++;
+ } catch(Exception ignore) {
+ File playerFile = new File(plugin.getServer().getWorldContainer() + File.separator + Settings.defaultWorld + File.separator + "players" + File.separator + player.getName() + ".dat");
+ if (playerFile.exists()) {
+ playerFile.delete();
+ i++;
+ }
}
- } catch (Exception e) {
+ } catch (Exception ignore) {
}
}
ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " .dat Files");
}
+ @SuppressWarnings("deprecation")
public void purgeEssentials(List cleared) {
int i = 0;
for (String name : cleared) {
try {
+ File playerFile = new File(plugin.ess.getDataFolder() + File.separator + "userdata" + File.separator + plugin.getServer().getOfflinePlayer(name).getUniqueId() + ".yml");
+ playerFile.delete();
+ i++;
+ } catch (Exception e) {
File playerFile = new File(plugin.ess.getDataFolder() + File.separator + "userdata" + File.separator + name + ".yml");
if (playerFile.exists()) {
playerFile.delete();
i++;
}
- } catch (Exception e) {
}
}
ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " EssentialsFiles");
@@ -146,4 +160,37 @@ public class DataManager {
}
ConsoleLogger.info("AutoPurgeDatabase : Remove " + i + " Permissions");
}
+
+ public boolean isOnline(Player player, final String name) {
+ if (player.isOnline())
+ return true;
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ Future result = executor.submit(new Callable() {
+
+ @Override
+ public synchronized Boolean call() throws Exception {
+ for (OfflinePlayer op : Utils.getOnlinePlayers())
+ if (op.getName().equalsIgnoreCase(name)) {
+ return true;
+ }
+ return false;
+ }
+ });
+ try {
+ return result.get();
+ } catch (Exception e) {
+ return false;
+ } finally {
+ executor.shutdown();
+ }
+ }
+
+ public Player getOnlinePlayerLower(String name) {
+ name = name.toLowerCase();
+ for (Player player : Utils.getOnlinePlayers()) {
+ if (player.getName().equalsIgnoreCase(name))
+ return player;
+ }
+ return null;
+ }
}
diff --git a/src/main/java/fr/xephi/authme/PerformBackup.java b/src/main/java/fr/xephi/authme/PerformBackup.java
index 71a69f04..0f7e1fcc 100644
--- a/src/main/java/fr/xephi/authme/PerformBackup.java
+++ b/src/main/java/fr/xephi/authme/PerformBackup.java
@@ -30,18 +30,15 @@ public class PerformBackup {
this.setInstance(instance);
}
- public boolean DoBackup() {
+ public boolean doBackup() {
switch (Settings.getDataSource) {
case FILE:
return FileBackup("auths.db");
-
case MYSQL:
return MySqlBackup();
-
case SQLITE:
return FileBackup(Settings.getMySQLDatabase + ".db");
-
}
return false;
diff --git a/src/main/java/fr/xephi/authme/SendMailSSL.java b/src/main/java/fr/xephi/authme/SendMailSSL.java
index 40056e33..eb4c2b8e 100644
--- a/src/main/java/fr/xephi/authme/SendMailSSL.java
+++ b/src/main/java/fr/xephi/authme/SendMailSSL.java
@@ -1,24 +1,12 @@
package fr.xephi.authme;
import java.io.File;
-import java.io.UnsupportedEncodingException;
-import java.util.Date;
-import java.util.Properties;
-import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.imageio.ImageIO;
-import javax.mail.BodyPart;
-import javax.mail.Message;
-import javax.mail.Multipart;
-import javax.mail.Session;
-import javax.mail.Transport;
-import javax.mail.internet.InternetAddress;
-import javax.mail.internet.MimeBodyPart;
-import javax.mail.internet.MimeMessage;
-import javax.mail.internet.MimeMultipart;
+import org.apache.commons.mail.HtmlEmail;
import org.bukkit.Bukkit;
import fr.xephi.authme.cache.auth.PlayerAuth;
@@ -46,7 +34,7 @@ public class SendMailSSL {
}
final String sender = sendername;
- final String port = String.valueOf(Settings.getMailPort);
+ final int port = Settings.getMailPort;
final String acc = Settings.getmailAccount;
final String subject = Settings.getMailSubject;
final String smtp = Settings.getmailSMTP;
@@ -58,49 +46,47 @@ public class SendMailSSL {
@Override
public void run() {
try {
- Properties props = new Properties();
- props.put("mail.smtp.host", smtp);
- props.put("mail.smtp.auth", "true");
- props.put("mail.smtp.port", port);
- props.put("mail.smtp.starttls.enable", true);
- Session session = Session.getInstance(props, null);
-
- Message message = new MimeMessage(session);
- try {
- message.setFrom(new InternetAddress(acc, sender));
- } catch (UnsupportedEncodingException uee) {
- message.setFrom(new InternetAddress(acc));
- }
- message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mail));
- message.setSubject(subject);
- message.setSentDate(new Date());
- BodyPart messageBodyPart = new MimeBodyPart();
- messageBodyPart.setContent(mailText, "text/html");
- Multipart multipart = new MimeMultipart();
- multipart.addBodyPart(messageBodyPart);
-
+ Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
+ HtmlEmail email = new HtmlEmail();
+ email.setSmtpPort(port);
+ email.setHostName(smtp);
+ email.addTo(mail);
+ email.setFrom(acc, sender);
+ email.setSubject(subject);
+ email.setAuthentication(acc, password);
+ email.setStartTLSEnabled(true);
+ email.setStartTLSRequired(true);
+ email.setSSLCheckServerIdentity(true);
+ String content = mailText;
// Generate an image ?
File file = null;
if (Settings.generateImage) {
- ImageGenerator gen = new ImageGenerator(newPass);
- file = new File(plugin.getDataFolder() + File.separator + auth.getNickname() + "_new_pass.jpg");
- ImageIO.write(gen.generateImage(), "jpg", file);
- messageBodyPart = new MimeBodyPart();
- DataSource source = new FileDataSource(file);
- messageBodyPart.setDataHandler(new DataHandler(source));
- messageBodyPart.setFileName(auth.getNickname() + "_new_pass.jpg");
- multipart.addBodyPart(messageBodyPart);
+ try {
+ ImageGenerator gen = new ImageGenerator(newPass);
+ file = new File(plugin.getDataFolder() + File.separator + auth.getNickname() + "_new_pass.jpg");
+ ImageIO.write(gen.generateImage(), "jpg", file);
+ DataSource source = new FileDataSource(file);
+ String tag = email.embed(source, auth.getNickname() + "_new_pass.jpg");
+ content = content.replace("", " ");
+ } catch (Exception e) {
+ ConsoleLogger.showError("Unable to send new password as image! Using normal text! Dest: " + mail);
+ }
+ }
+ email.setHtmlMsg(content);
+ email.setTextMsg(content);
+ try {
+ email.send();
+ } catch (Exception e) {
+ e.printStackTrace();
+ ConsoleLogger.showError("Fail to send a mail to " + mail);
}
-
- message.setContent(multipart);
- Transport transport = session.getTransport("smtp");
- transport.connect(smtp, acc, password);
- transport.sendMessage(message, message.getAllRecipients());
if (file != null)
file.delete();
} catch (Exception e) {
- ConsoleLogger.showError("Some error occured while trying to send a mail to " + mail);
+ // Print the stack trace
+ e.printStackTrace();
+ ConsoleLogger.showError("Some error occurred while trying to send a email to " + mail);
}
}
diff --git a/src/main/java/fr/xephi/authme/Utils.java b/src/main/java/fr/xephi/authme/Utils.java
deleted file mode 100644
index 15e01fe2..00000000
--- a/src/main/java/fr/xephi/authme/Utils.java
+++ /dev/null
@@ -1,212 +0,0 @@
-package fr.xephi.authme;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.bukkit.Bukkit;
-import org.bukkit.GameMode;
-import org.bukkit.Location;
-import org.bukkit.World;
-import org.bukkit.entity.Player;
-
-import fr.xephi.authme.cache.limbo.LimboCache;
-import fr.xephi.authme.cache.limbo.LimboPlayer;
-import fr.xephi.authme.events.AuthMeTeleportEvent;
-import fr.xephi.authme.security.RandomString;
-import fr.xephi.authme.settings.Settings;
-
-public class Utils {
-
- private String currentGroup;
- private static Utils singleton;
- int id;
- public AuthMe plugin;
- private static List tokens = new ArrayList();
-
- public Utils(AuthMe plugin) {
- this.plugin = plugin;
- }
-
- public void setGroup(Player player, groupType group) {
- setGroup(player.getName(), group);
- }
-
- @SuppressWarnings("deprecation")
- public void setGroup(String player, groupType group) {
- if (!Settings.isPermissionCheckEnabled)
- return;
- if (plugin.permission == null)
- return;
- String name = player;
- try {
- World world = null;
- currentGroup = plugin.permission.getPrimaryGroup(world, name);
- } catch (UnsupportedOperationException e) {
- ConsoleLogger.showError("Your permission plugin (" + plugin.permission.getName() + ") doesn't support the Group system... unhook!");
- plugin.permission = null;
- return;
- }
- World world = null;
- switch (group) {
- case UNREGISTERED: {
- plugin.permission.playerRemoveGroup(world, name, currentGroup);
- plugin.permission.playerAddGroup(world, name, Settings.unRegisteredGroup);
- break;
- }
- case REGISTERED: {
- plugin.permission.playerRemoveGroup(world, name, currentGroup);
- plugin.permission.playerAddGroup(world, name, Settings.getRegisteredGroup);
- break;
- }
- case NOTLOGGEDIN: {
- if (!useGroupSystem())
- break;
- plugin.permission.playerRemoveGroup(world, name, currentGroup);
- plugin.permission.playerAddGroup(world, name, Settings.getUnloggedinGroup);
- break;
- }
- case LOGGEDIN: {
- if (!useGroupSystem())
- break;
- LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(name.toLowerCase());
- if (limbo == null)
- break;
- String realGroup = limbo.getGroup();
- plugin.permission.playerRemoveGroup(world, name, currentGroup);
- plugin.permission.playerAddGroup(world, name, realGroup);
- break;
- }
- }
- return;
- }
-
- @SuppressWarnings("deprecation")
- public boolean addNormal(Player player, String group) {
- if (!useGroupSystem()) {
- return false;
- }
- if (plugin.permission == null)
- return false;
- World world = null;
- try {
- if (plugin.permission.playerRemoveGroup(world, player.getName().toString(), Settings.getUnloggedinGroup) && plugin.permission.playerAddGroup(world, player.getName().toString(), group)) {
- return true;
- }
- } catch (UnsupportedOperationException e) {
- ConsoleLogger.showError("Your permission system (" + plugin.permission.getName() + ") do not support Group system with that config... unhook!");
- plugin.permission = null;
- return false;
- }
- return false;
- }
-
- public void hasPermOnJoin(Player player) {
- if (plugin.permission == null)
- return;
- Iterator iter = Settings.getJoinPermissions.iterator();
- while (iter.hasNext()) {
- String permission = iter.next();
- if (plugin.permission.playerHas(player, permission)) {
- plugin.permission.playerAddTransient(player, permission);
- }
- }
- }
-
- public boolean isUnrestricted(Player player) {
- if (!Settings.isAllowRestrictedIp)
- return false;
- if (Settings.getUnrestrictedName == null || Settings.getUnrestrictedName.isEmpty())
- return false;
- return (Settings.getUnrestrictedName.contains(player.getName()));
- }
-
- public static Utils getInstance() {
- singleton = new Utils(AuthMe.getInstance());
- return singleton;
- }
-
- private boolean useGroupSystem() {
- if (Settings.isPermissionCheckEnabled && !Settings.getUnloggedinGroup.isEmpty())
- return true;
- return false;
- }
-
- public void packCoords(double x, double y, double z, String w,
- final Player pl) {
- World theWorld;
- if (w.equals("unavailableworld")) {
- theWorld = pl.getWorld();
- } else {
- theWorld = Bukkit.getWorld(w);
- }
- if (theWorld == null)
- theWorld = pl.getWorld();
- final World world = theWorld;
- final Location locat = new Location(world, x, y, z);
-
- Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
-
- @Override
- public void run() {
- AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(pl, locat);
- plugin.getServer().getPluginManager().callEvent(tpEvent);
- if (!tpEvent.isCancelled()) {
- if (!tpEvent.getTo().getChunk().isLoaded())
- tpEvent.getTo().getChunk().load();
- pl.teleport(tpEvent.getTo());
- }
- }
- });
- }
-
- /*
- * Random Token for passpartu
- */
- public boolean obtainToken() {
- try {
- final String token = new RandomString(10).nextString();
- tokens.add(token);
- ConsoleLogger.info("[AuthMe] Security passpartu token: " + token);
- Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, new Runnable() {
-
- @Override
- public void run() {
- tokens.remove(token);
- }
-
- }, 600);
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return false;
- }
-
- /*
- * Read Token
- */
- public boolean readToken(String inputToken) {
- boolean ret = false;
- if (tokens.contains(inputToken))
- ret = true;
- tokens.remove(inputToken);
- return (ret);
- }
-
- /*
- * Used for force player GameMode
- */
- public static void forceGM(Player player) {
- if (!AuthMe.getInstance().authmePermissible(player, "authme.bypassforcesurvival"))
- player.setGameMode(GameMode.SURVIVAL);
- }
-
- public enum groupType {
- UNREGISTERED,
- REGISTERED,
- NOTLOGGEDIN,
- LOGGEDIN
- }
-
-}
diff --git a/src/main/java/fr/xephi/authme/api/API.java b/src/main/java/fr/xephi/authme/api/API.java
index 7d284aad..96dcc2a6 100644
--- a/src/main/java/fr/xephi/authme/api/API.java
+++ b/src/main/java/fr/xephi/authme/api/API.java
@@ -1,176 +1,183 @@
-package fr.xephi.authme.api;
-
-import java.security.NoSuchAlgorithmException;
-
-import org.bukkit.Bukkit;
-import org.bukkit.Location;
-import org.bukkit.entity.Player;
-import org.bukkit.inventory.ItemStack;
-import org.bukkit.plugin.Plugin;
-
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.Utils;
-import fr.xephi.authme.cache.auth.PlayerAuth;
-import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.plugin.manager.CombatTagComunicator;
-import fr.xephi.authme.security.PasswordSecurity;
-import fr.xephi.authme.settings.Settings;
-
-public class API {
-
- public static final String newline = System.getProperty("line.separator");
- public static AuthMe instance;
-
- public API(AuthMe instance) {
- API.instance = instance;
- }
-
- /**
- * Hook into AuthMe
- *
- * @return AuthMe instance
- */
- public static AuthMe hookAuthMe() {
- if (instance != null)
- return instance;
- Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("AuthMe");
- if (plugin == null || !(plugin instanceof AuthMe)) {
- return null;
- }
- instance = (AuthMe) plugin;
- return instance;
- }
-
- public AuthMe getPlugin() {
- return instance;
- }
-
- /**
- *
- * @param player
- * @return true if player is authenticate
- */
- public static boolean isAuthenticated(Player player) {
- return PlayerCache.getInstance().isAuthenticated(player.getName());
- }
-
- /**
- *
- * @param player
- * @return true if player is a npc
- */
- @Deprecated
- public boolean isaNPC(Player player) {
- if (instance.getCitizensCommunicator().isNPC(player))
- return true;
- return CombatTagComunicator.isNPC(player);
- }
-
- /**
- *
- * @param player
- * @return true if player is a npc
- */
- public boolean isNPC(Player player) {
- if (instance.getCitizensCommunicator().isNPC(player))
- return true;
- return CombatTagComunicator.isNPC(player);
- }
-
- /**
- *
- * @param player
- * @return true if the player is unrestricted
- */
- public static boolean isUnrestricted(Player player) {
- return Utils.getInstance().isUnrestricted(player);
- }
-
- public static Location getLastLocation(Player player) {
- try {
- PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase());
-
- if (auth != null) {
- Location loc = new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ());
- return loc;
- } else {
- return null;
- }
-
- } catch (NullPointerException ex) {
- return null;
- }
- }
-
- public static void setPlayerInventory(Player player, ItemStack[] content,
- ItemStack[] armor) {
- try {
- player.getInventory().setContents(content);
- player.getInventory().setArmorContents(armor);
- } catch (NullPointerException npe) {
- }
- }
-
- /**
- *
- * @param playerName
- * @return true if player is registered
- */
- public static boolean isRegistered(String playerName) {
- String player = playerName.toLowerCase();
- return instance.database.isAuthAvailable(player);
- }
-
- /**
- * @param String
- * playerName, String passwordToCheck
- * @return true if the password is correct , false else
- */
- public static boolean checkPassword(String playerName,
- String passwordToCheck) {
- if (!isRegistered(playerName))
- return false;
- String player = playerName.toLowerCase();
- PlayerAuth auth = instance.database.getAuth(player);
- try {
- return PasswordSecurity.comparePasswordWithHash(passwordToCheck, auth.getHash(), playerName);
- } catch (NoSuchAlgorithmException e) {
- return false;
- }
- }
-
- /**
- * Register a player
- *
- * @param String
- * playerName, String password
- * @return true if the player is register correctly
- */
- public static boolean registerPlayer(String playerName, String password) {
- try {
- String name = playerName.toLowerCase();
- String hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
- if (isRegistered(name)) {
- return false;
- }
- PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0, "your@email.com");
- if (!instance.database.saveAuth(auth)) {
- return false;
- }
- return true;
- } catch (NoSuchAlgorithmException ex) {
- return false;
- }
- }
-
- /**
- * Force a player to login
- *
- * @param Player
- * player
- */
- public static void forceLogin(Player player) {
- instance.management.performLogin(player, "dontneed", true);
- }
-
-}
+package fr.xephi.authme.api;
+
+import java.security.NoSuchAlgorithmException;
+
+import org.bukkit.Bukkit;
+import org.bukkit.Location;
+import org.bukkit.entity.Player;
+import org.bukkit.inventory.ItemStack;
+import org.bukkit.plugin.Plugin;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.cache.auth.PlayerAuth;
+import fr.xephi.authme.cache.auth.PlayerCache;
+import fr.xephi.authme.security.PasswordSecurity;
+import fr.xephi.authme.settings.Settings;
+import fr.xephi.authme.util.Utils;
+
+public class API {
+
+ public static final String newline = System.getProperty("line.separator");
+ public static AuthMe instance;
+
+ @Deprecated
+ public API(AuthMe instance) {
+ API.instance = instance;
+ }
+
+ /**
+ * Hook into AuthMe
+ *
+ * @return AuthMe instance
+ */
+ @Deprecated
+ public static AuthMe hookAuthMe() {
+ if (instance != null)
+ return instance;
+ Plugin plugin = Bukkit.getServer().getPluginManager().getPlugin("AuthMe");
+ if (plugin == null || !(plugin instanceof AuthMe)) {
+ return null;
+ }
+ instance = (AuthMe) plugin;
+ return instance;
+ }
+
+ @Deprecated
+ public AuthMe getPlugin() {
+ return instance;
+ }
+
+ /**
+ *
+ * @param player
+ * @return true if player is authenticate
+ */
+ @Deprecated
+ public static boolean isAuthenticated(Player player) {
+ return PlayerCache.getInstance().isAuthenticated(player.getName());
+ }
+
+ /**
+ *
+ * @param player
+ * @return true if player is a npc
+ */
+ @Deprecated
+ public boolean isaNPC(Player player) {
+ return Utils.isNPC(player);
+ }
+
+ /**
+ *
+ * @param player
+ * @return true if player is a npc
+ */
+ @Deprecated
+ public boolean isNPC(Player player) {
+ return Utils.isNPC(player);
+ }
+
+ /**
+ *
+ * @param player
+ * @return true if the player is unrestricted
+ */
+ @Deprecated
+ public static boolean isUnrestricted(Player player) {
+ return Utils.isUnrestricted(player);
+ }
+
+ @Deprecated
+ public static Location getLastLocation(Player player) {
+ try {
+ PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase());
+
+ if (auth != null) {
+ Location loc = new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ());
+ return loc;
+ } else {
+ return null;
+ }
+
+ } catch (NullPointerException ex) {
+ return null;
+ }
+ }
+
+ @Deprecated
+ public static void setPlayerInventory(Player player, ItemStack[] content,
+ ItemStack[] armor) {
+ try {
+ player.getInventory().setContents(content);
+ player.getInventory().setArmorContents(armor);
+ } catch (NullPointerException npe) {
+ }
+ }
+
+ /**
+ *
+ * @param playerName
+ * @return true if player is registered
+ */
+ @Deprecated
+ public static boolean isRegistered(String playerName) {
+ String player = playerName.toLowerCase();
+ return instance.database.isAuthAvailable(player);
+ }
+
+ /**
+ * @param String
+ * playerName, String passwordToCheck
+ * @return true if the password is correct , false else
+ */
+ @Deprecated
+ public static boolean checkPassword(String playerName,
+ String passwordToCheck) {
+ if (!isRegistered(playerName))
+ return false;
+ String player = playerName.toLowerCase();
+ PlayerAuth auth = instance.database.getAuth(player);
+ try {
+ return PasswordSecurity.comparePasswordWithHash(passwordToCheck, auth.getHash(), playerName);
+ } catch (NoSuchAlgorithmException e) {
+ return false;
+ }
+ }
+
+ /**
+ * Register a player
+ *
+ * @param String
+ * playerName, String password
+ * @return true if the player is register correctly
+ */
+ @Deprecated
+ public static boolean registerPlayer(String playerName, String password) {
+ try {
+ String name = playerName.toLowerCase();
+ String hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
+ if (isRegistered(name)) {
+ return false;
+ }
+ PlayerAuth auth = new PlayerAuth(name, hash, "198.18.0.1", 0, "your@email.com", playerName);
+ if (!instance.database.saveAuth(auth)) {
+ return false;
+ }
+ return true;
+ } catch (NoSuchAlgorithmException ex) {
+ return false;
+ }
+ }
+
+ /**
+ * Force a player to login
+ *
+ * @param Player
+ * player
+ */
+ @Deprecated
+ public static void forceLogin(Player player) {
+ instance.management.performLogin(player, "dontneed", true);
+ }
+
+}
diff --git a/src/main/java/fr/xephi/authme/api/NewAPI.java b/src/main/java/fr/xephi/authme/api/NewAPI.java
index a632ea60..6c48286a 100644
--- a/src/main/java/fr/xephi/authme/api/NewAPI.java
+++ b/src/main/java/fr/xephi/authme/api/NewAPI.java
@@ -1,174 +1,187 @@
-package fr.xephi.authme.api;
-
-import java.security.NoSuchAlgorithmException;
-
-import org.bukkit.Bukkit;
-import org.bukkit.Location;
-import org.bukkit.Server;
-import org.bukkit.entity.Player;
-import org.bukkit.inventory.ItemStack;
-import org.bukkit.plugin.Plugin;
-
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.ConsoleLogger;
-import fr.xephi.authme.Utils;
-import fr.xephi.authme.cache.auth.PlayerAuth;
-import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.plugin.manager.CombatTagComunicator;
-import fr.xephi.authme.security.PasswordSecurity;
-import fr.xephi.authme.settings.Settings;
-
-public class NewAPI {
-
- public static final String newline = System.getProperty("line.separator");
- public static NewAPI singleton;
- public AuthMe plugin;
-
- public NewAPI(AuthMe plugin) {
- this.plugin = plugin;
- }
-
- public NewAPI(Server serv) {
- this.plugin = (AuthMe) serv.getPluginManager().getPlugin("AuthMe");
- }
-
- /**
- * Hook into AuthMe
- *
- * @return
- *
- * @return AuthMe plugin
- */
- public static NewAPI getInstance() {
- if (singleton != null)
- return singleton;
- Plugin p = Bukkit.getServer().getPluginManager().getPlugin("AuthMe");
- if (p == null || !(p instanceof AuthMe)) {
- return null;
- }
- AuthMe authme = (AuthMe) p;
- singleton = (new NewAPI(authme));
- return singleton;
- }
-
- public AuthMe getPlugin() {
- return plugin;
- }
-
- /**
- *
- * @param player
- * @return true if player is authenticate
- */
- public boolean isAuthenticated(Player player) {
- return PlayerCache.getInstance().isAuthenticated(player.getName());
- }
-
- /**
- *
- * @param player
- * @return true if player is a npc
- */
- public boolean isNPC(Player player) {
- if (plugin.getCitizensCommunicator().isNPC(player))
- return true;
- return CombatTagComunicator.isNPC(player);
- }
-
- /**
- *
- * @param player
- * @return true if the player is unrestricted
- */
- public boolean isUnrestricted(Player player) {
- return Utils.getInstance().isUnrestricted(player);
- }
-
- public Location getLastLocation(Player player) {
- try {
- PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase());
-
- if (auth != null) {
- Location loc = new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ());
- return loc;
- } else {
- return null;
- }
-
- } catch (NullPointerException ex) {
- return null;
- }
- }
-
- public void setPlayerInventory(Player player, ItemStack[] content,
- ItemStack[] armor) {
- try {
- player.getInventory().setContents(content);
- player.getInventory().setArmorContents(armor);
- } catch (Exception npe) {
- ConsoleLogger.showError("Some error appear while trying to set inventory for " + player.getName());
- }
- }
-
- /**
- *
- * @param playerName
- * @return true if player is registered
- */
- public boolean isRegistered(String playerName) {
- String player = playerName.toLowerCase();
- return plugin.database.isAuthAvailable(player);
- }
-
- /**
- * @param String
- * playerName, String passwordToCheck
- * @return true if the password is correct , false else
- */
- public boolean checkPassword(String playerName, String passwordToCheck) {
- if (!isRegistered(playerName))
- return false;
- String player = playerName.toLowerCase();
- PlayerAuth auth = plugin.database.getAuth(player);
- try {
- return PasswordSecurity.comparePasswordWithHash(passwordToCheck, auth.getHash(), playerName);
- } catch (NoSuchAlgorithmException e) {
- return false;
- }
- }
-
- /**
- * Register a player
- *
- * @param String
- * playerName, String password
- * @return true if the player is register correctly
- */
- public boolean registerPlayer(String playerName, String password) {
- try {
- String name = playerName.toLowerCase();
- String hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
- if (isRegistered(name)) {
- return false;
- }
- PlayerAuth auth = new PlayerAuth(name, hash, "192.168.0.1", 0, "your@email.com");
- if (!plugin.database.saveAuth(auth)) {
- return false;
- }
- return true;
- } catch (NoSuchAlgorithmException ex) {
- return false;
- }
- }
-
- /**
- * Force a player to login
- *
- * @param Player
- * player
- */
- public void forceLogin(Player player) {
- plugin.management.performLogin(player, "dontneed", true);
- }
-
-}
+package fr.xephi.authme.api;
+
+import java.security.NoSuchAlgorithmException;
+
+import org.bukkit.Bukkit;
+import org.bukkit.Location;
+import org.bukkit.Server;
+import org.bukkit.entity.Player;
+import org.bukkit.plugin.Plugin;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.cache.auth.PlayerAuth;
+import fr.xephi.authme.cache.auth.PlayerCache;
+import fr.xephi.authme.security.PasswordSecurity;
+import fr.xephi.authme.settings.Settings;
+import fr.xephi.authme.util.Utils;
+
+public class NewAPI {
+
+ public static final String newline = System.getProperty("line.separator");
+ public static NewAPI singleton;
+ public AuthMe plugin;
+
+ public NewAPI(AuthMe plugin) {
+ this.plugin = plugin;
+ }
+
+ public NewAPI(Server serv) {
+ this.plugin = (AuthMe) serv.getPluginManager().getPlugin("AuthMe");
+ }
+
+ /**
+ * Hook into AuthMe
+ *
+ * @return AuthMe plugin
+ */
+ public static NewAPI getInstance() {
+ if (singleton != null)
+ return singleton;
+ Plugin p = Bukkit.getServer().getPluginManager().getPlugin("AuthMe");
+ if (p == null || !(p instanceof AuthMe)) {
+ return null;
+ }
+ AuthMe authme = (AuthMe) p;
+ singleton = (new NewAPI(authme));
+ return singleton;
+ }
+
+ public AuthMe getPlugin() {
+ return plugin;
+ }
+
+ /**
+ *
+ * @param player
+ * @return true if player is authenticate
+ */
+ public boolean isAuthenticated(Player player) {
+ return PlayerCache.getInstance().isAuthenticated(player.getName());
+ }
+
+ /**
+ *
+ * @param player
+ * @return true if player is a npc
+ */
+ public boolean isNPC(Player player) {
+ return Utils.isNPC(player);
+ }
+
+ /**
+ *
+ * @param player
+ * @return true if the player is unrestricted
+ */
+ public boolean isUnrestricted(Player player) {
+ return Utils.isUnrestricted(player);
+ }
+
+ public Location getLastLocation(Player player) {
+ try {
+ PlayerAuth auth = PlayerCache.getInstance().getAuth(player.getName().toLowerCase());
+
+ if (auth != null) {
+ return new Location(Bukkit.getWorld(auth.getWorld()), auth.getQuitLocX(), auth.getQuitLocY(), auth.getQuitLocZ());
+ } else {
+ return null;
+ }
+
+ } catch (NullPointerException ex) {
+ return null;
+ }
+ }
+
+ /**
+ *
+ * @param playerName
+ * @return true if player is registered
+ */
+ public boolean isRegistered(String playerName) {
+ String player = playerName.toLowerCase();
+ return plugin.database.isAuthAvailable(player);
+ }
+
+ /**
+ * @param String
+ * playerName, String passwordToCheck
+ * @return true if the password is correct , false else
+ */
+ public boolean checkPassword(String playerName, String passwordToCheck) {
+ if (!isRegistered(playerName))
+ return false;
+ String player = playerName.toLowerCase();
+ PlayerAuth auth = plugin.database.getAuth(player);
+ try {
+ return PasswordSecurity.comparePasswordWithHash(passwordToCheck, auth.getHash(), playerName);
+ } catch (NoSuchAlgorithmException e) {
+ return false;
+ }
+ }
+
+ /**
+ * Register a player
+ *
+ * @param String
+ * playerName, String password
+ * @return true if the player is register correctly
+ */
+ public boolean registerPlayer(String playerName, String password) {
+ try {
+ String name = playerName.toLowerCase();
+ String hash = PasswordSecurity.getHash(Settings.getPasswordHash, password, name);
+ if (isRegistered(name)) {
+ return false;
+ }
+ PlayerAuth auth = new PlayerAuth(name, hash, "192.168.0.1", 0, "your@email.com", playerName);
+ return plugin.database.saveAuth(auth);
+ } catch (NoSuchAlgorithmException ex) {
+ return false;
+ }
+ }
+
+ /**
+ * Force a player to login
+ *
+ * @param Player
+ * player
+ */
+ public void forceLogin(Player player) {
+ plugin.management.performLogin(player, "dontneed", true);
+ }
+
+ /**
+ * Force a player to logout
+ *
+ * @param Player
+ * player
+ */
+ public void forceLogout(Player player)
+ {
+ plugin.management.performLogout(player);
+ }
+
+ /**
+ * Force a player to register
+ *
+ * @param Player
+ * player
+ * @param String
+ * password
+ */
+ public void forceRegister(Player player, String password)
+ {
+ plugin.management.performRegister(player, password, null);
+ }
+
+ /**
+ * Force a player to unregister
+ *
+ * @param Player
+ * player
+ */
+ public void forceUnregister(Player player)
+ {
+ plugin.management.performUnregister(player, "", true);
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/cache/auth/PlayerCache.java b/src/main/java/fr/xephi/authme/cache/auth/PlayerCache.java
index 8f39c0d3..491c33a4 100644
--- a/src/main/java/fr/xephi/authme/cache/auth/PlayerCache.java
+++ b/src/main/java/fr/xephi/authme/cache/auth/PlayerCache.java
@@ -8,7 +8,7 @@ public class PlayerCache {
private ConcurrentHashMap cache;
private PlayerCache() {
- cache = new ConcurrentHashMap();
+ cache = new ConcurrentHashMap<>();
}
public void addPlayer(PlayerAuth auth) {
diff --git a/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java b/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java
index ef5ab501..5aa40dde 100644
--- a/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java
+++ b/src/main/java/fr/xephi/authme/cache/backup/DataFileCache.java
@@ -1,37 +1,17 @@
package fr.xephi.authme.cache.backup;
-import org.bukkit.inventory.ItemStack;
-
public class DataFileCache {
- private ItemStack[] inventory;
- private ItemStack[] armor;
private String group;
private boolean operator;
private boolean flying;
- public DataFileCache(ItemStack[] inventory, ItemStack[] armor) {
- this.inventory = inventory;
- this.armor = armor;
- }
-
- public DataFileCache(ItemStack[] inventory, ItemStack[] armor,
- String group, boolean operator, boolean flying) {
- this.inventory = inventory;
- this.armor = armor;
+ public DataFileCache(String group, boolean operator, boolean flying) {
this.group = group;
this.operator = operator;
this.flying = flying;
}
- public ItemStack[] getInventory() {
- return inventory;
- }
-
- public ItemStack[] getArmour() {
- return armor;
- }
-
public String getGroup() {
return group;
}
diff --git a/src/main/java/fr/xephi/authme/cache/backup/FileCache.java b/src/main/java/fr/xephi/authme/cache/backup/FileCache.java
deleted file mode 100644
index 11fce587..00000000
--- a/src/main/java/fr/xephi/authme/cache/backup/FileCache.java
+++ /dev/null
@@ -1,583 +0,0 @@
-package fr.xephi.authme.cache.backup;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Scanner;
-import java.util.UUID;
-
-import org.bukkit.Material;
-import org.bukkit.enchantments.Enchantment;
-import org.bukkit.entity.Player;
-import org.bukkit.inventory.ItemStack;
-import org.bukkit.inventory.meta.ItemMeta;
-
-import com.comphenix.attribute.Attributes;
-import com.comphenix.attribute.Attributes.Attribute;
-import com.comphenix.attribute.Attributes.Attribute.Builder;
-import com.comphenix.attribute.Attributes.AttributeType;
-import com.comphenix.attribute.Attributes.Operation;
-
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.ConsoleLogger;
-import fr.xephi.authme.api.API;
-import fr.xephi.authme.settings.Settings;
-
-public class FileCache {
-
- private AuthMe plugin;
-
- public FileCache(AuthMe plugin) {
- this.plugin = plugin;
- final File file = new File(plugin.getDataFolder() + File.separator + "cache");
- if (!file.exists())
- file.mkdir();
- }
-
- public void createCache(Player player, DataFileCache playerData,
- String group, boolean operator, boolean flying) {
- String path = "";
- if (player == null)
- return;
- try {
- path = player.getUniqueId().toString();
- } catch (Exception e) {
- path = player.getName();
- } catch (Error e) {
- path = player.getName();
- }
- File file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "playerdatas.cache");
-
- if (!file.getParentFile().exists())
- file.getParentFile().mkdirs();
- if (file.exists()) {
- return;
- }
-
- FileWriter writer = null;
- try {
- file.createNewFile();
-
- writer = new FileWriter(file);
- writer.write(group + API.newline);
- writer.write(String.valueOf(operator) + API.newline);
- writer.write(String.valueOf(flying) + API.newline);
- writer.close();
-
- file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "inventory");
-
- file.mkdirs();
- ItemStack[] inv = playerData.getInventory();
- for (int i = 0; i < inv.length; i++) {
- ItemStack item = inv[i];
- file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "inventory" + File.separator + i + ".cache");
- file.createNewFile();
- writer = new FileWriter(file);
- if (item != null) {
- if (item.getType() == Material.AIR) {
- writer.write("AIR");
- writer.close();
- continue;
- }
- writer.write(item.getType().name() + API.newline);
- writer.write(item.getDurability() + API.newline);
- writer.write(item.getAmount() + API.newline);
- writer.flush();
- if (item.hasItemMeta()) {
- ItemMeta meta = item.getItemMeta();
- if (meta.hasDisplayName())
- writer.write("name=" + meta.getDisplayName() + API.newline);
- if (meta.hasLore()) {
- String lores = "";
- for (String lore : meta.getLore())
- lores = lore + "%newline%";
- writer.write("lore=" + lores + API.newline);
- }
- if (meta.hasEnchants()) {
- for (Enchantment ench : meta.getEnchants().keySet()) {
- writer.write("metaenchant=" + ench.getName() + ":" + meta.getEnchants().get(ench) + API.newline);
- }
- }
- writer.flush();
- }
- for (Enchantment ench : item.getEnchantments().keySet()) {
- writer.write("enchant=" + ench.getName() + ":" + item.getEnchantments().get(ench) + API.newline);
- }
- if (Settings.customAttributes) {
- try {
- Attributes attributes = new Attributes(item);
- if (attributes != null) {
- Iterator iter = attributes.values().iterator();
- Attribute a = null;
- while (iter.hasNext()) {
- Attribute b = iter.next();
- if (a != null && a == b)
- break;
- a = b;
- if (a != null) {
- if (a.getName() != null && a.getAttributeType() != null && a.getOperation() != null && a.getUUID() != null)
- writer.write("attribute=" + a.getName() + ";" + a.getAttributeType().getMinecraftId() + ";" + a.getAmount() + ";" + a.getOperation().getId() + ";" + a.getUUID().toString());
- }
- }
- }
- } catch (Exception e) {
- } catch (Error e) {
- }
- }
- } else {
- writer.write("AIR");
- }
- writer.close();
- }
-
- file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "armours");
- if (!file.getParentFile().exists())
- file.getParentFile().mkdirs();
- file.mkdirs();
-
- ItemStack[] armors = playerData.getArmour();
- for (int i = 0; i < armors.length; i++) {
- ItemStack item = armors[i];
- file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "armours" + File.separator + i + ".cache");
- file.createNewFile();
- writer = new FileWriter(file);
- if (item != null) {
- if (item.getType() == Material.AIR) {
- writer.write("AIR");
- writer.close();
- continue;
- }
- writer.write(item.getType().name() + API.newline);
- writer.write(item.getDurability() + API.newline);
- writer.write(item.getAmount() + API.newline);
- writer.flush();
- if (item.hasItemMeta()) {
- ItemMeta meta = item.getItemMeta();
- if (meta.hasDisplayName())
- writer.write("name=" + meta.getDisplayName() + API.newline);
- if (meta.hasLore()) {
- String lores = "";
- for (String lore : meta.getLore())
- lores = lore + "%newline%";
- writer.write("lore=" + lores + API.newline);
- }
- writer.flush();
- }
- for (Enchantment ench : item.getEnchantments().keySet()) {
- writer.write("enchant=" + ench.getName() + ":" + item.getEnchantments().get(ench) + API.newline);
- }
- if (Settings.customAttributes) {
- try {
- Attributes attributes = new Attributes(item);
- if (attributes != null)
- while (attributes.values().iterator().hasNext()) {
- Attribute a = attributes.values().iterator().next();
- if (a != null) {
- if (a.getName() != null && a.getAttributeType() != null && a.getOperation() != null && a.getUUID() != null && a.getAttributeType().getMinecraftId() != null)
- writer.write("attribute=" + a.getName() + ";" + a.getAttributeType().getMinecraftId() + ";" + a.getAmount() + ";" + a.getOperation().getId() + ";" + a.getUUID().toString());
- }
- }
- } catch (Exception e) {
- }
- }
- } else {
- writer.write("AIR" + API.newline);
- }
- writer.close();
- }
- } catch (final Exception e) {
- ConsoleLogger.showError("Some error on creating file cache...");
- }
- }
-
- public DataFileCache readCache(Player player) {
- String path = "";
- try {
- path = player.getUniqueId().toString();
- } catch (Exception e) {
- path = player.getName();
- } catch (Error e) {
- path = player.getName();
- }
- try {
- File file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "playerdatas.cache");
- String playername = player.getName().toLowerCase();
- if (!file.exists()) {
- // OLD METHOD
- file = new File("cache/" + playername + ".cache");
- ItemStack[] stacki = new ItemStack[36];
- ItemStack[] stacka = new ItemStack[4];
- if (!file.exists()) {
- return new DataFileCache(stacki, stacka);
- }
- String group = null;
- boolean op = false;
- boolean flying = false;
-
- Scanner reader = null;
- try {
- reader = new Scanner(file);
-
- int i = 0;
- int a = 0;
- while (reader.hasNextLine()) {
- String line = reader.nextLine();
-
- if (!line.contains(":")) {
- // the fist line represent the player group,
- // operator
- // status
- // and flying status
- final String[] playerInfo = line.split(";");
- group = playerInfo[0];
-
- if (Integer.parseInt(playerInfo[1]) == 1) {
- op = true;
- } else op = false;
- if (playerInfo.length > 2) {
- if (Integer.parseInt(playerInfo[2]) == 1)
- flying = true;
- else flying = false;
- }
-
- continue;
- }
-
- if (!line.startsWith("i") && !line.startsWith("w")) {
- continue;
- }
- String lores = "";
- String name = "";
- if (line.split("\\*").length > 1) {
- lores = line.split("\\*")[1];
- line = line.split("\\*")[0];
- }
- if (line.split(";").length > 1) {
- name = line.split(";")[1];
- line = line.split(";")[0];
- }
- final String[] in = line.split(":");
- // can enchant item? size ofstring in file - 4 all / 2 =
- // number
- // of enchant
- if (in[0].equals("i")) {
- stacki[i] = new ItemStack(Material.getMaterial(in[1]), Integer.parseInt(in[2]), Short.parseShort((in[3])));
- if (in.length > 4 && !in[4].isEmpty()) {
- for (int k = 4; k < in.length - 1; k++) {
- stacki[i].addUnsafeEnchantment(Enchantment.getByName(in[k]), Integer.parseInt(in[k + 1]));
- k++;
- }
- }
- try {
- ItemMeta meta = plugin.getServer().getItemFactory().getItemMeta(stacki[i].getType());
- if (!name.isEmpty()) {
- meta.setDisplayName(name);
- }
- if (!lores.isEmpty()) {
- List loreList = new ArrayList();
- for (String s : lores.split("%newline%")) {
- loreList.add(s);
- }
- meta.setLore(loreList);
- }
- if (meta != null)
- stacki[i].setItemMeta(meta);
- } catch (Exception e) {
- }
- i++;
- } else {
- stacka[a] = new ItemStack(Material.getMaterial(in[1]), Integer.parseInt(in[2]), Short.parseShort((in[3])));
- if (in.length > 4 && !in[4].isEmpty()) {
- for (int k = 4; k < in.length - 1; k++) {
- stacka[a].addUnsafeEnchantment(Enchantment.getByName(in[k]), Integer.parseInt(in[k + 1]));
- k++;
- }
- }
- try {
- ItemMeta meta = plugin.getServer().getItemFactory().getItemMeta(stacka[a].getType());
- if (!name.isEmpty())
- meta.setDisplayName(name);
- if (!lores.isEmpty()) {
- List loreList = new ArrayList();
- for (String s : lores.split("%newline%")) {
- loreList.add(s);
- }
- meta.setLore(loreList);
- }
- if (meta != null)
- stacki[i].setItemMeta(meta);
- } catch (Exception e) {
- }
- a++;
- }
- }
- } catch (final Exception e) {
- ConsoleLogger.showError("Error on creating a file cache for " + player.getName() + ", maybe wipe inventory...");
- } finally {
- if (reader != null) {
- reader.close();
- }
- }
- return new DataFileCache(stacki, stacka, group, op, flying);
- } else {
- // NEW METHOD
- ItemStack[] inv = new ItemStack[36];
- ItemStack[] armours = new ItemStack[4];
- String group = null;
- boolean op = false;
- boolean flying = false;
-
- Scanner reader = null;
- try {
- reader = new Scanner(file);
-
- int count = 1;
- while (reader.hasNextLine()) {
- String line = reader.nextLine();
- switch (count) {
- case 1:
- group = line;
- break;
- case 2:
- op = Boolean.parseBoolean(line);
- break;
- case 3:
- flying = Boolean.parseBoolean(line);
- break;
- default:
- break;
- }
- count++;
- }
- if (reader != null)
- reader.close();
- for (int i = 0; i < inv.length; i++) {
- reader = new Scanner(new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "inventory" + File.separator + i + ".cache"));
- ItemStack item = new ItemStack(Material.AIR);
- ItemMeta meta = item.getItemMeta();
- Attributes attributes = null;
- count = 1;
- boolean v = true;
- while (reader.hasNextLine() && v == true) {
- String line = reader.nextLine();
- switch (count) {
- case 1:
- item = new ItemStack(Material.getMaterial(line));
- if (item.getType() == Material.AIR)
- v = false;
- meta = item.getItemMeta();
- count++;
- continue;
- case 2:
- item.setDurability((short) Integer.parseInt(line));
- count++;
- continue;
- case 3:
- item.setAmount(Integer.parseInt(line));
- count++;
- continue;
- default:
- break;
- }
- meta = item.getItemMeta();
- if (line.startsWith("name=")) {
- line = line.substring(5);
- meta.setDisplayName(line);
- item.setItemMeta(meta);
- continue;
- }
- if (line.startsWith("lore=")) {
- line = line.substring(5);
- List lore = new ArrayList();
- for (String s : line.split("%newline%"))
- lore.add(s);
- meta.setLore(lore);
- item.setItemMeta(meta);
- continue;
- }
- if (line.startsWith("enchant=")) {
- line = line.substring(8);
- item.addEnchantment(Enchantment.getByName(line.split(":")[0]), Integer.parseInt(line.split(":")[1]));
- continue;
- }
- if (Settings.customAttributes) {
- if (line.startsWith("attribute=")) {
- if (attributes == null)
- attributes = new Attributes(item);
- try {
- line = line.substring(10);
- String[] args = line.split(";");
- if (args.length != 5)
- continue;
- String name = args[0];
- AttributeType type = AttributeType.fromId(args[1]);
- double amount = Double.parseDouble(args[2]);
- Operation operation = Operation.fromId(Integer.parseInt(args[3]));
- UUID uuid = UUID.fromString(args[4]);
- Builder build = Attribute.newBuilder();
- build.amount(amount);
- build.operation(operation);
- build.type(type);
- build.name(name);
- build.uuid(uuid);
- attributes.add(build.build());
- } catch (Exception e) {
- }
- }
- }
- count++;
- }
- if (reader != null)
- reader.close();
- if (Settings.customAttributes && attributes != null)
- inv[i] = attributes.getStack();
- else inv[i] = item;
- }
- for (int i = 0; i < armours.length; i++) {
- reader = new Scanner(new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "armours" + File.separator + i + ".cache"));
- ItemStack item = new ItemStack(Material.AIR);
- ItemMeta meta = null;
- Attributes attributes = null;
- count = 1;
- boolean v = true;
- while (reader.hasNextLine() && v == true) {
- String line = reader.nextLine();
- switch (count) {
- case 1:
- item = new ItemStack(Material.getMaterial(line));
- if (item.getType() == Material.AIR)
- v = false;
- meta = item.getItemMeta();
- count++;
- continue;
- case 2:
- item.setDurability((short) Integer.parseInt(line));
- count++;
- continue;
- case 3:
- item.setAmount(Integer.parseInt(line));
- count++;
- continue;
- default:
- break;
- }
- meta = item.getItemMeta();
- if (line.startsWith("name=")) {
- line = line.substring(5);
- meta.setDisplayName(line);
- item.setItemMeta(meta);
- continue;
- }
- if (line.startsWith("lore=")) {
- line = line.substring(5);
- List lore = new ArrayList();
- for (String s : line.split("%newline%"))
- lore.add(s);
- meta.setLore(lore);
- item.setItemMeta(meta);
- continue;
- }
- if (line.startsWith("enchant=")) {
- line = line.substring(8);
- item.addEnchantment(Enchantment.getByName(line.split(":")[0]), Integer.parseInt(line.split(":")[1]));
- }
- if (Settings.customAttributes) {
- if (line.startsWith("attribute=")) {
- if (attributes == null)
- attributes = new Attributes(item);
- try {
- line = line.substring(10);
- String[] args = line.split(";");
- if (args.length != 5)
- continue;
- String name = args[0];
- AttributeType type = AttributeType.fromId(args[1]);
- double amount = Double.parseDouble(args[2]);
- Operation operation = Operation.fromId(Integer.parseInt(args[3]));
- UUID uuid = UUID.fromString(args[4]);
- Builder build = Attribute.newBuilder();
- build.amount(amount);
- build.operation(operation);
- build.type(type);
- build.name(name);
- build.uuid(uuid);
- attributes.add(build.build());
- } catch (Exception e) {
- }
- }
- }
- count++;
- }
- if (reader != null)
- reader.close();
- if (attributes != null)
- armours[i] = attributes.getStack();
- else armours[i] = item;
- }
-
- } catch (final Exception e) {
- ConsoleLogger.showError("Error while reading file for " + player.getName() + ", some wipe inventory incoming...");
- } finally {
- if (reader != null)
- reader.close();
- }
- return new DataFileCache(inv, armours, group, op, flying);
- }
- } catch (Exception e) {
- ConsoleLogger.showError("Error while reading file for " + player.getName() + ", some wipe inventory incoming...");
- return null;
- }
- }
-
- public void removeCache(Player player) {
- String path = "";
- try {
- path = player.getUniqueId().toString();
- } catch (Exception e) {
- path = player.getName();
- } catch (Error e) {
- path = player.getName();
- }
- try {
- File file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path);
- if (!file.exists()) {
- file = new File("cache/" + player.getName().toLowerCase() + ".cache");
- }
- if (file.exists()) {
- if (file.isDirectory() && file.listFiles() != null) {
- for (File f : file.listFiles()) {
- if (f.isDirectory() && f.listFiles() != null) {
- for (File a : f.listFiles()) {
- a.delete();
- }
- f.delete();
- } else f.delete();
- }
- file.delete();
- } else file.delete();
- }
- } catch (Exception e) {
- ConsoleLogger.showError("File cannot be removed correctly :/");
- }
- }
-
- public boolean doesCacheExist(Player player) {
- String path = "";
- try {
- path = player.getUniqueId().toString();
- } catch (Exception e) {
- path = player.getName();
- } catch (Error e) {
- path = player.getName();
- }
- File file = new File(plugin.getDataFolder() + File.separator + "cache" + File.separator + path + File.separator + "playerdatas.cache");
- if (!file.exists()) {
- file = new File("cache/" + player.getName().toLowerCase() + ".cache");
- }
-
- return file.exists();
- }
-
-}
diff --git a/src/main/java/fr/xephi/authme/cache/backup/JsonCache.java b/src/main/java/fr/xephi/authme/cache/backup/JsonCache.java
new file mode 100644
index 00000000..31c647cb
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/cache/backup/JsonCache.java
@@ -0,0 +1,158 @@
+package fr.xephi.authme.cache.backup;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.Type;
+
+import org.bukkit.entity.Player;
+
+import com.google.common.base.Charsets;
+import com.google.common.io.Files;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonDeserializationContext;
+import com.google.gson.JsonDeserializer;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonSerializationContext;
+import com.google.gson.JsonSerializer;
+
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.settings.Settings;
+import fr.xephi.authme.util.Utils;
+
+public class JsonCache {
+
+ private final Gson gson;
+ private final File cacheDir;
+
+ public JsonCache() {
+ cacheDir = Settings.CACHE_FOLDER;
+ if (!cacheDir.exists() && !cacheDir.isDirectory() && !cacheDir.mkdir()) {
+ ConsoleLogger.showError("Failed to create cache directory.");
+ }
+ gson = new GsonBuilder()
+ .registerTypeAdapter(DataFileCache.class, new PlayerDataSerializer())
+ .registerTypeAdapter(DataFileCache.class, new PlayerDataDeserializer())
+ .setPrettyPrinting()
+ .create();
+ }
+
+ public void createCache(Player player, DataFileCache playerData) {
+ if (player == null) {
+ return;
+ }
+
+ String path;
+ try {
+ path = player.getUniqueId().toString();
+ } catch (Exception | Error e) {
+ path = player.getName().toLowerCase();
+ }
+
+ File file = new File(cacheDir, path + File.separator + "cache.json");
+ if (file.exists()) {
+ return;
+ }
+ if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
+ return;
+ }
+
+ try {
+ String data = gson.toJson(playerData);
+ Files.touch(file);
+ Files.write(data, file, Charsets.UTF_8);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public DataFileCache readCache(Player player) {
+ String path;
+ try {
+ path = player.getUniqueId().toString();
+ } catch (Exception | Error e) {
+ path = player.getName().toLowerCase();
+ }
+
+ File file = new File(cacheDir, path + File.separator + "cache.json");
+ if (!file.exists()) {
+ return null;
+ }
+
+ try {
+ String str = Files.toString(file, Charsets.UTF_8);
+ return gson.fromJson(str, DataFileCache.class);
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ private class PlayerDataSerializer implements JsonSerializer {
+ @Override
+ public JsonElement serialize(DataFileCache dataFileCache, Type type, JsonSerializationContext jsonSerializationContext) {
+ JsonObject jsonObject = new JsonObject();
+ jsonObject.addProperty("group", dataFileCache.getGroup());
+ jsonObject.addProperty("operator", dataFileCache.getOperator());
+ jsonObject.addProperty("flying", dataFileCache.isFlying());
+
+ return jsonObject;
+ }
+ }
+
+ private static class PlayerDataDeserializer implements JsonDeserializer {
+ @Override
+ public DataFileCache deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
+ JsonObject jsonObject = jsonElement.getAsJsonObject();
+ if (jsonObject == null) {
+ return null;
+ }
+ JsonElement e;
+ String group = null;
+ boolean operator = false;
+ boolean flying = false;
+
+ if ((e = jsonObject.get("group")) != null) {
+ group = e.getAsString();
+ }
+ if ((e = jsonObject.get("operator")) != null) {
+ operator = e.getAsBoolean();
+ }
+ if ((e = jsonObject.get("flying")) != null) {
+ flying = e.getAsBoolean();
+ }
+
+ return new DataFileCache(group, operator, flying);
+ }
+ }
+
+ public void removeCache(Player player) {
+ String path;
+ try {
+ path = player.getUniqueId().toString();
+ } catch (Exception | Error e) {
+ path = player.getName().toLowerCase();
+ }
+ File file = new File(cacheDir, path);
+ if (file.exists()) {
+ Utils.purgeDirectory(file);
+ if (!file.delete()) {
+ ConsoleLogger.showError("Failed to remove" + player.getName() + "cache.");
+ }
+ }
+ }
+
+ public boolean doesCacheExist(Player player) {
+ String path;
+ try {
+ path = player.getUniqueId().toString();
+ } catch (Exception | Error e) {
+ path = player.getName().toLowerCase();
+ }
+ File file = new File(cacheDir, path + File.separator + "cache.json");
+ return file.exists();
+ }
+
+}
diff --git a/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java b/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java
index 2c3d89be..70614107 100644
--- a/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java
+++ b/src/main/java/fr/xephi/authme/cache/limbo/LimboCache.java
@@ -6,34 +6,32 @@ import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;
-import org.bukkit.inventory.ItemStack;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
-import fr.xephi.authme.cache.backup.FileCache;
+import fr.xephi.authme.cache.backup.DataFileCache;
+import fr.xephi.authme.cache.backup.JsonCache;
import fr.xephi.authme.events.ResetInventoryEvent;
import fr.xephi.authme.events.StoreInventoryEvent;
import fr.xephi.authme.settings.Settings;
public class LimboCache {
- private volatile static LimboCache singleton = null;
+ private volatile static LimboCache singleton;
public ConcurrentHashMap cache;
- private FileCache playerData;
+ private JsonCache playerData;
public AuthMe plugin;
private LimboCache(AuthMe plugin) {
this.plugin = plugin;
- this.cache = new ConcurrentHashMap();
- this.playerData = new FileCache(plugin);
+ this.cache = new ConcurrentHashMap<>();
+ this.playerData = new JsonCache();
}
public void addLimboPlayer(Player player) {
String name = player.getName().toLowerCase();
Location loc = player.getLocation();
GameMode gameMode = player.getGameMode();
- ItemStack[] arm;
- ItemStack[] inv;
boolean operator = false;
String playerGroup = "";
boolean flying = false;
@@ -42,35 +40,26 @@ public class LimboCache {
final StoreInventoryEvent event = new StoreInventoryEvent(player, playerData);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled() && event.getInventory() != null && event.getArmor() != null) {
- inv = event.getInventory();
- arm = event.getArmor();
- } else {
- inv = null;
- arm = null;
+ player.getInventory().setContents(event.getInventory());
+ player.getInventory().setArmorContents(event.getArmor());
}
- try {
- playerGroup = playerData.readCache(player).getGroup();
- operator = playerData.readCache(player).getOperator();
- flying = playerData.readCache(player).isFlying();
- } catch (Exception e) {
- ConsoleLogger.showError("Some error on reading cache of " + name);
+
+ DataFileCache cache = playerData.readCache(player);
+ if (cache != null) {
+ playerGroup = cache.getGroup();
+ operator = cache.getOperator();
+ flying = cache.isFlying();
}
} else {
StoreInventoryEvent event = new StoreInventoryEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled() && event.getInventory() != null && event.getArmor() != null) {
- inv = event.getInventory();
- arm = event.getArmor();
- } else {
- inv = null;
- arm = null;
+ player.getInventory().setContents(event.getInventory());
+ player.getInventory().setArmorContents(event.getArmor());
}
- if (player.isOp())
- operator = true;
- else operator = false;
- if (player.isFlying())
- flying = true;
- else flying = false;
+
+ operator = player.isOp();
+ flying = player.isFlying();
if (plugin.permission != null) {
try {
playerGroup = plugin.permission.getPrimaryGroup(player);
@@ -82,7 +71,7 @@ public class LimboCache {
}
if (Settings.isForceSurvivalModeEnabled) {
- if (Settings.isResetInventoryIfCreative && player.getGameMode() == GameMode.CREATIVE) {
+ if (Settings.isResetInventoryIfCreative && gameMode == GameMode.CREATIVE) {
ResetInventoryEvent event = new ResetInventoryEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
@@ -98,7 +87,7 @@ public class LimboCache {
if (player.isDead()) {
loc = plugin.getSpawnLocation(player);
}
- cache.put(name, new LimboPlayer(name, loc, inv, arm, gameMode, operator, playerGroup, flying));
+ cache.put(name, new LimboPlayer(name, loc, gameMode, operator, playerGroup, flying));
}
public void addLimboPlayer(Player player, String group) {
@@ -128,7 +117,7 @@ public class LimboCache {
if (this.hasLimboPlayer(player.getName().toLowerCase())) {
this.deleteLimboPlayer(player.getName().toLowerCase());
}
- this.addLimboPlayer(player);
+ addLimboPlayer(player);
}
}
diff --git a/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java b/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java
index 702ddb38..f4ae0466 100644
--- a/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java
+++ b/src/main/java/fr/xephi/authme/cache/limbo/LimboPlayer.java
@@ -2,14 +2,11 @@ package fr.xephi.authme.cache.limbo;
import org.bukkit.GameMode;
import org.bukkit.Location;
-import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitTask;
public class LimboPlayer {
private String name;
- private ItemStack[] inventory;
- private ItemStack[] armour;
private Location loc = null;
private BukkitTask timeoutTaskId = null;
private BukkitTask messageTaskId = null;
@@ -18,19 +15,6 @@ public class LimboPlayer {
private String group = "";
private boolean flying = false;
- public LimboPlayer(String name, Location loc, ItemStack[] inventory,
- ItemStack[] armour, GameMode gameMode, boolean operator,
- String group, boolean flying) {
- this.name = name;
- this.loc = loc;
- this.inventory = inventory;
- this.armour = armour;
- this.gameMode = gameMode;
- this.operator = operator;
- this.group = group;
- this.flying = flying;
- }
-
public LimboPlayer(String name, Location loc, GameMode gameMode,
boolean operator, String group, boolean flying) {
this.name = name;
@@ -54,22 +38,6 @@ public class LimboPlayer {
return loc;
}
- public ItemStack[] getArmour() {
- return armour;
- }
-
- public ItemStack[] getInventory() {
- return inventory;
- }
-
- public void setArmour(ItemStack[] armour) {
- this.armour = armour;
- }
-
- public void setInventory(ItemStack[] inventory) {
- this.inventory = inventory;
- }
-
public GameMode getGameMode() {
return gameMode;
}
@@ -105,5 +73,4 @@ public class LimboPlayer {
public boolean isFlying() {
return flying;
}
-
}
diff --git a/src/main/java/fr/xephi/authme/command/CommandArgumentDescription.java b/src/main/java/fr/xephi/authme/command/CommandArgumentDescription.java
new file mode 100644
index 00000000..a5ea63d0
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/CommandArgumentDescription.java
@@ -0,0 +1,90 @@
+package fr.xephi.authme.command;
+
+public class CommandArgumentDescription {
+
+ // TODO: Allow argument to consist of infinite parts.
+
+ /** Argument label. */
+ private String label;
+ /** Argument description. */
+ private String description;
+ /** Defines whether the argument is optional. */
+ private boolean optional = false;
+
+ /**
+ * Constructor.
+ *
+ * @param label The argument label.
+ * @param description The argument description.
+ */
+ public CommandArgumentDescription(String label, String description) {
+ this(label, description, false);
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param label The argument label.
+ * @param description The argument description.
+ * @param optional True if the argument is optional, false otherwise.
+ */
+ public CommandArgumentDescription(String label, String description, boolean optional) {
+ setLabel(label);
+ setDescription(description);
+ setOptional(optional);
+ }
+
+ /**
+ * Get the argument label.
+ *
+ * @return Argument label.
+ */
+ public String getLabel() {
+ return this.label;
+ }
+
+ /**
+ * Set the argument label.
+ *
+ * @param label Argument label.
+ */
+ public void setLabel(String label) {
+ this.label = label;
+ }
+
+ /**
+ * Get the argument description.
+ *
+ * @return Argument description.
+ */
+ public String getDescription() {
+ return description;
+ }
+
+ /**
+ * Set the argument description.
+ *
+ * @param description Argument description.
+ */
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ /**
+ * Check whether the argument is optional.
+ *
+ * @return True if the argument is optional, false otherwise.
+ */
+ public boolean isOptional() {
+ return optional;
+ }
+
+ /**
+ * Set whether the argument is optional.
+ *
+ * @param optional True if the argument is optional, false otherwise.
+ */
+ public void setOptional(boolean optional) {
+ this.optional = optional;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/CommandDescription.java b/src/main/java/fr/xephi/authme/command/CommandDescription.java
new file mode 100644
index 00000000..302a6e6c
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/CommandDescription.java
@@ -0,0 +1,918 @@
+package fr.xephi.authme.command;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import org.bukkit.command.CommandSender;
+
+import fr.xephi.authme.util.StringUtils;
+
+public class CommandDescription {
+
+ /** Defines the acceptable labels. */
+ private List labels = new ArrayList<>();
+ /** Command description. */
+ private String description = "";
+ /** Detailed description. */
+ private String detailedDescription = "";
+ /** The executable command instance. */
+ private ExecutableCommand executableCommand;
+ /** The parent command. */
+ private CommandDescription parent = null;
+ /** The child labels. */
+ private List children = new ArrayList<>();
+ /** The command arguments. */
+ private List arguments = new ArrayList<>();
+ /** Defines whether there is an argument maximum or not. */
+ private boolean noArgumentMaximum = false;
+ /** Defines the command permissions. */
+ private CommandPermissions permissions = new CommandPermissions();
+
+ /**
+ * Constructor.
+ *
+ * @param executableCommand The executable command, or null.
+ * @param label Command label.
+ * @param description Command description.
+ * @param detailedDescription Detailed comment description.
+ * @param parent Parent command.
+ */
+ public CommandDescription(ExecutableCommand executableCommand, String label, String description, String detailedDescription, CommandDescription parent) {
+ this(executableCommand, label, description, parent, detailedDescription, null);
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param executableCommand The executable command, or null.
+ * @param labels List of command labels.
+ * @param description Command description.
+ * @param detailedDescription Detailed comment description.
+ * @param parent Parent command.
+ */
+ public CommandDescription(ExecutableCommand executableCommand, List labels, String description, String detailedDescription, CommandDescription parent) {
+ this(executableCommand, labels, description, detailedDescription, parent, null);
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param executableCommand The executable command, or null.
+ * @param label Command label.
+ * @param description Command description.
+ * @param parent Parent command.
+ * @param detailedDescription Detailed comment description.
+ * @param arguments Command arguments.
+ */
+ public CommandDescription(ExecutableCommand executableCommand, String label, String description, CommandDescription parent, String detailedDescription, List arguments) {
+ setExecutableCommand(executableCommand);
+ setLabel(label);
+ setDescription(description);
+ setDetailedDescription(detailedDescription);
+ setParent(parent);
+ setArguments(arguments);
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param executableCommand The executable command, or null.
+ * @param labels List of command labels.
+ * @param description Command description.
+ * @param detailedDescription Detailed comment description.
+ * @param parent Parent command.
+ * @param arguments Command arguments.
+ */
+ public CommandDescription(ExecutableCommand executableCommand, List labels, String description, String detailedDescription, CommandDescription parent, List arguments) {
+ setExecutableCommand(executableCommand);
+ setLabels(labels);
+ setDescription(description);
+ setDetailedDescription(detailedDescription);
+ setParent(parent);
+ setArguments(arguments);
+ }
+
+ /**
+ * Get the first relative command label.
+ *
+ * @return First relative command label.
+ */
+ public String getLabel() {
+ // Ensure there's any item in the command list
+ if(this.labels.size() == 0)
+ return "";
+
+ // Return the first command on the list
+ return this.labels.get(0);
+ }
+
+ /**
+ * Get the label most similar to the reference. The first label will be returned if no reference was supplied.
+ *
+ * @param reference The command reference.
+ *
+ * @return The most similar label, or the first label. An empty label will be returned if no label was set.
+ */
+ public String getLabel(CommandParts reference) {
+ // Ensure there's any item in the command list
+ if(this.labels.size() == 0)
+ return "";
+
+ // Return the first label if we can't use the reference
+ if(reference == null)
+ return this.labels.get(0);
+
+ // Get the correct label from the reference
+ String preferred = reference.get(getParentCount());
+
+ // Check whether the preferred label is in the label list
+ double currentDifference = -1;
+ String currentLabel = this.labels.get(0);
+ for(String entry : this.labels) {
+ double entryDifference = StringUtils.getDifference(entry, preferred);
+ if(entryDifference < currentDifference || currentDifference < 0) {
+ currentDifference = entryDifference;
+ currentLabel = entry;
+ }
+ }
+
+ // Return the most similar label
+ return currentLabel;
+ }
+
+ /**
+ * Get all relative command labels.
+ *
+ * @return All relative labels labels.
+ */
+ public List getLabels() {
+ return this.labels;
+ }
+
+ /**
+ * Set the list of command labels.
+ *
+ * @param labels New list of command labels. Null to clear the list of labels.
+ */
+ public void setLabels(List labels) {
+ // Check whether the command label list should be cleared
+ if(labels == null)
+ this.labels.clear();
+
+ else
+ this.labels = labels;
+ }
+
+ /**
+ * Set the command label, this will append the command label to already existing ones.
+ *
+ * @param commandLabel Command label to set or add.
+ */
+ public void setLabel(String commandLabel) {
+ setLabel(commandLabel, false);
+ }
+
+ /**
+ * Set the command label.
+ *
+ * @param commandLabel Command label to set.
+ * @param overwrite True to replace all old command labels, false to append this command label to the currently
+ * existing labels.
+ *
+ * @return Trie if the command label is added, or if it was added already. False on failure.
+ */
+ public boolean setLabel(String commandLabel, boolean overwrite) {
+ // Check whether this new command should overwrite the previous ones
+ if(!overwrite)
+ return addLabel(commandLabel);
+
+ // Replace all labels with this new one
+ this.labels.clear();
+ return this.labels.add(commandLabel);
+ }
+
+ /**
+ * Add a command label to the list.
+ *
+ * @param commandLabel Command label to add.
+ *
+ * @return True if the label was added, or if it was added already. False on error.
+ */
+ public boolean addLabel(String commandLabel) {
+ // Verify the label
+ if(!isValidLabel(commandLabel))
+ return false;
+
+ // Ensure this command isn't a duplicate
+ if(hasLabel(commandLabel))
+ return true;
+
+ // Add the command to the list
+ return this.labels.add(commandLabel);
+ }
+
+ /**
+ * Add a list of command labels.
+ *
+ * @param commandLabels List of command labels to add.
+ *
+ * @return True if succeed, false on failure.
+ */
+ public boolean addLabels(List commandLabels) {
+ // Add each command label separately
+ for(String cmd : commandLabels)
+ if(!addLabel(cmd))
+ return false;
+ return true;
+ }
+
+ /**
+ * Check whether this command description has a specific command.
+ *
+ * @param commandLabel Command to check for.
+ *
+ * @return True if this command label equals to the param command.
+ */
+ public boolean hasLabel(String commandLabel) {
+ // Check whether any command matches with the argument
+ for(String entry : this.labels)
+ if(commandLabelEquals(entry, commandLabel))
+ return true;
+
+ // No match found, return false
+ return false;
+ }
+
+ /**
+ * Check whether this command description has a list of labels
+ * @param commandLabels List of labels
+ * @return True if all labels match, false otherwise
+ */
+ public boolean hasLabels(List commandLabels) {
+ // Check if there's a match for every command
+ for(String cmd : commandLabels)
+ if(!hasLabel(cmd))
+ return false;
+
+ // There seems to be a match for every command, return true
+ return true;
+ }
+
+ /**
+ * Check whether this command label is applicable with a command reference. This doesn't check if the parent
+ * are suitable too.
+ *
+ * @param commandReference The command reference.
+ *
+ * @return True if the command reference is suitable to this command label, false otherwise.
+ */
+ public boolean isSuitableLabel(CommandParts commandReference) {
+ // Make sure the command reference is valid
+ if(commandReference.getCount() <= 0)
+ return false;
+
+ // Get the parent count
+ String element = commandReference.get(getParentCount());
+
+ // Check whether this command description has this command label
+ return hasLabel(element);
+ }
+
+ /**
+ * Check whether a label is valid to use.
+ *
+ * @param label The label to test.
+ *
+ * @return True if the label is valid to use, false otherwise.
+ */
+ public static boolean isValidLabel(String label) {
+ // Make sure the label isn't null
+ if(label == null)
+ return false;
+
+ // Trim the label
+ label = label.trim();
+
+ // Make sure the label is at least one character long
+ if(label.length() <= 0)
+ return false;
+
+ // Make sure the label doesn't contain any spaces, return the result
+ return !label.contains(" ");
+ }
+
+ /**
+ * Get the absolute command label, without a slash.
+ */
+ public String getAbsoluteLabel() {
+ return getAbsoluteLabel(false);
+ }
+
+ /**
+ * Get the absolute command label.
+ *
+ * @return Absolute command label.
+ */
+ public String getAbsoluteLabel(boolean includeSlash) {
+ return getAbsoluteLabel(includeSlash, null);
+ }
+
+ /**
+ * Get the absolute command label.
+ *
+ * @return Absolute command label.
+ */
+ public String getAbsoluteLabel(boolean includeSlash, CommandParts reference) {
+ // Get the command reference, and make sure it is valid
+ CommandParts out = getCommandReference(reference);
+ if(out == null)
+ return "";
+
+ // Return the result
+ return (includeSlash ? "/" : "") + out.toString();
+ }
+
+ /**
+ * Get the command reference.
+ *
+ * @param reference The reference to use as template, which is used to choose the most similar reference.
+ *
+ * @return Command reference.
+ */
+ public CommandParts getCommandReference(CommandParts reference) {
+ // Build the reference
+ List referenceList = new ArrayList<>();
+
+ // Check whether this command has a parent, if so, add the absolute parent command
+ if(getParent() != null)
+ referenceList.addAll(getParent().getCommandReference(reference).getList());
+
+ // Get the current label
+ referenceList.add(getLabel(reference));
+
+ // Return the reference
+ return new CommandParts(referenceList);
+ }
+
+ /**
+ * Get the difference between this command and another command reference.
+ *
+ * @param other The other command reference.
+ *
+ * @return The command difference. Zero if there's no difference. A negative number on error.
+ */
+ public double getCommandDifference(CommandParts other) {
+ return getCommandDifference(other, false);
+ }
+
+ /**
+ * Get the difference between this command and another command reference.
+ *
+ * @param other The other command reference.
+ * @param fullCompare True to fully compare both command references.
+ *
+ * @return The command difference. Zero if there's no difference. A negative number on error.
+ */
+ public double getCommandDifference(CommandParts other, boolean fullCompare) {
+ // Make sure the reference is valid
+ if(other == null)
+ return -1;
+
+ // Get the command reference
+ CommandParts reference = getCommandReference(other);
+
+ // Compare the two references, return the result
+ return reference.getDifference(new CommandParts(other.getRange(0, reference.getCount())), fullCompare);
+ }
+
+ /**
+ * Get the executable command.
+ *
+ * @return The executable command.
+ */
+ public ExecutableCommand getExecutableCommand() {
+ return this.executableCommand;
+ }
+
+ /**
+ * Set the executable command.
+ *
+ * @param executableCommand The executable command.
+ */
+ public void setExecutableCommand(ExecutableCommand executableCommand) {
+ this.executableCommand = executableCommand;
+ }
+
+ /**
+ * Check whether this command is executable, based on the assigned executable command.
+ *
+ * @return True if this command is executable.
+ */
+ public boolean isExecutable() {
+ return this.executableCommand != null;
+ }
+
+ /**
+ * Execute the command, if possible.
+ *
+ * @param sender The command sender that triggered the execution of this command.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True on success, false on failure.
+ */
+ public boolean execute(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // Make sure the command is executable
+ if(!isExecutable())
+ return false;
+
+ // Execute the command, return the result
+ return getExecutableCommand().executeCommand(sender, commandReference, commandArguments);
+ }
+
+ /**
+ * Get the parent command if this command description has a parent.
+ *
+ * @return Parent command, or null
+ */
+ public CommandDescription getParent() {
+ return this.parent;
+ }
+
+ /**
+ * Get the number of parent this description has.
+ *
+ * @return The number of parents.
+ */
+ public int getParentCount() {
+ // Check whether the this description has a parent
+ if(!hasParent())
+ return 0;
+
+ // Get the parent count of the parent, return the result
+ return getParent().getParentCount() + 1;
+ }
+
+ /**
+ * Set the parent command.
+ *
+ * @param parent Parent command.
+ *
+ * @return True on success, false on failure.
+ */
+ public boolean setParent(CommandDescription parent) {
+ // Make sure the parent is different
+ if(this.parent == parent)
+ return true;
+
+ // Set the parent
+ this.parent = parent;
+
+ // Make sure the parent isn't null
+ if(parent == null)
+ return true;
+
+ // Add this description as a child to the parent
+ return parent.addChild(this);
+ }
+
+ /**
+ * Check whether the plugin description has a parent command.
+ *
+ * @return True if the description has a parent command, false otherwise.
+ */
+ public boolean hasParent() {
+ return this.parent != null;
+ }
+
+ /**
+ * Get all command children.
+ *
+ * @return Command children.
+ */
+ public List getChildren() {
+ return this.children;
+ }
+
+ /**
+ * Add a child to the command description.
+ *
+ * @param commandDescription The child to add.
+ *
+ * @return True on success, false on failure.
+ */
+ public boolean addChild(CommandDescription commandDescription) {
+ // Make sure the description is valid
+ if(commandDescription == null)
+ return false;
+ if(!commandDescription.isValid())
+ return false;
+
+ // Make sure the child doesn't exist already
+ if(isChild(commandDescription))
+ return true;
+
+ // The command description to add as a child
+ if(!this.children.add(commandDescription))
+ return false;
+
+ // Set this description as parent on the child
+ return commandDescription.setParent(this);
+ }
+
+ /**
+ * Set the children of this command.
+ *
+ * @param children New command children. Null to remove all children.
+ */
+ public void setChildren(List children) {
+ // Check whether the children list should be cleared
+ if(children == null)
+ this.children.clear();
+
+ else
+ this.children = children;
+ }
+
+ /**
+ * Check whether this command has any child labels.
+ *
+ * @return True if this command has any child labels.
+ */
+ public boolean hasChilds() {
+ return (this.children.size() != 0);
+ }
+
+ /**
+ * Check if this command description has a specific child.
+ *
+ * @param commandDescription The command description to check for.
+ *
+ * @return True if this command description has the specific child, false otherwise.
+ */
+ public boolean isChild(CommandDescription commandDescription) {
+ // Make sure the description is valid
+ if(commandDescription == null)
+ return false;
+ if(!commandDescription.isValid())
+ return false;
+
+ // Check whether this child exists, return the result
+ return this.children.contains(commandDescription);
+ }
+
+ /**
+ * Add an argument.
+ *
+ * @param argument The argument to add.
+ *
+ * @return True if succeed, false if failed.
+ */
+ public boolean addArgument(CommandArgumentDescription argument) {
+ // Make sure the argument is valid
+ if(argument == null)
+ return false;
+
+ // Make sure the argument isn't added already
+ if(hasArgument(argument))
+ return true;
+
+ // Add the argument, return the result
+ return this.arguments.add(argument);
+ }
+
+ /**
+ * Get all command arguments.
+ *
+ * @return Command arguments.
+ */
+ public List getArguments() {
+ return this.arguments;
+ }
+
+ /**
+ * Set the arguments of this command.
+ *
+ * @param arguments New command arguments. Null to clear the list of arguments.
+ */
+ public void setArguments(List arguments) {
+ // Convert null into an empty argument list
+ if(arguments == null)
+ this.arguments.clear();
+
+ else
+ this.arguments = arguments;
+ }
+
+ /**
+ * Check whether an argument exists.
+ *
+ * @param argument The argument to check for.
+ *
+ * @return True if this argument already exists, false otherwise.
+ */
+ public boolean hasArgument(CommandArgumentDescription argument) {
+ // Make sure the argument is valid
+ if(argument == null)
+ return false;
+
+ // Check whether the argument exists, return the result
+ return this.arguments.contains(argument);
+ }
+
+ /**
+ * Check whether this command has any arguments.
+ *
+ * @return True if this command has any arguments.
+ */
+ public boolean hasArguments() {
+ return (this.arguments.size() != 0);
+ }
+
+ /**
+ * The minimum number of arguments required for this command.
+ *
+ * @return The minimum number of required arguments.
+ */
+ public int getMinimumArguments() {
+ // Get the number of required and optional arguments
+ int requiredArguments = 0;
+ int optionalArgument = 0;
+
+ // Loop through each argument
+ for(CommandArgumentDescription argument : this.arguments) {
+ // Check whether the command is optional
+ if(!argument.isOptional()) {
+ requiredArguments += optionalArgument + 1;
+ optionalArgument = 0;
+
+ } else
+ optionalArgument++;
+ }
+
+ // Return the number of required arguments
+ return requiredArguments;
+ }
+
+ /**
+ * Get the maximum number of arguments.
+ *
+ * @return The maximum number of arguments. A negative number will be returned if there's no maximum.
+ */
+ public int getMaximumArguments() {
+ // Check whether there is a maximum set
+ if(this.noArgumentMaximum)
+ return -1;
+
+ // Return the maximum based on the registered arguments
+ return this.arguments.size();
+ }
+
+ /**
+ * Set whether there is an argument maximum.
+ *
+ * @param maximumArguments True if there is an argument maximum, based on the number of registered arguments.
+ */
+ public void setMaximumArguments(boolean maximumArguments) {
+ this.noArgumentMaximum = !maximumArguments;
+ }
+
+ /**
+ * Get the command description.
+ *
+ * @return Command description.
+ */
+ public String getDescription() {
+ return hasDescription() ? this.description : this.detailedDescription;
+ }
+
+ /**
+ * Set the command description.
+ *
+ * @param description New command description. Null to reset the description.
+ */
+ public void setDescription(String description) {
+ if(description == null)
+ this.description = "";
+
+ else
+ this.description = description;
+ }
+
+ /**
+ * Check whether this command has any description.
+ *
+ * @return True if this command has any description.
+ */
+ public boolean hasDescription() {
+ return (this.description.trim().length() != 0);
+ }
+
+ /**
+ * Get the command detailed description.
+ *
+ * @return Command detailed description.
+ */
+ public String getDetailedDescription() {
+ return hasDetailedDescription() ? this.detailedDescription : this.description;
+ }
+
+ /**
+ * Set the command detailed description.
+ *
+ * @param detailedDescription New command description. Null to reset the description.
+ */
+ public void setDetailedDescription(String detailedDescription) {
+ if(detailedDescription == null)
+ this.detailedDescription = "";
+
+ else
+ this.detailedDescription = detailedDescription;
+ }
+
+ /**
+ * Check whether this command has any detailed description.
+ *
+ * @return True if this command has any detailed description.
+ */
+ public boolean hasDetailedDescription() {
+ return (this.detailedDescription.trim().length() != 0);
+ }
+
+ /**
+ * Find the best suitable command for a query reference.
+ *
+ * @param queryReference The query reference to find a command for.
+ *
+ * @return The command found, or null.
+ */
+ public FoundCommandResult findCommand(final CommandParts queryReference) {
+ // Make sure the command reference is valid
+ if(queryReference.getCount() <= 0)
+ return null;
+
+ // Check whether this description is for the last element in the command reference, if so return the current command
+ if(queryReference.getCount() <= getParentCount() + 1)
+ return new FoundCommandResult(
+ this,
+ getCommandReference(queryReference),
+ new CommandParts(),
+ queryReference);
+
+ // Get the new command reference and arguments
+ CommandParts newReference = new CommandParts(queryReference.getRange(0, getParentCount() + 1));
+ CommandParts newArguments = new CommandParts(queryReference.getRange(getParentCount() + 1));
+
+ // Handle the child's, if this command has any
+ if(getChildren().size() > 0) {
+ // Get a new instance of the child's list, and sort them by their difference in comparison to the query reference
+ List commandChildren = new ArrayList<>(getChildren());
+ Collections.sort(commandChildren, new Comparator() {
+ @Override
+ public int compare(CommandDescription o1, CommandDescription o2) {
+ return Double.compare(
+ o1.getCommandDifference(queryReference),
+ o2.getCommandDifference(queryReference));
+ }
+ });
+
+ // Get the difference of the first child in the list
+ double firstChildDifference = commandChildren.get(0).getCommandDifference(queryReference, true);
+
+ // Check if the reference perfectly suits the arguments of the current command if it doesn't perfectly suits a child command
+ if(firstChildDifference > 0.0)
+ if(getSuitableArgumentsDifference(queryReference) == 0)
+ return new FoundCommandResult(this, newReference, newArguments, queryReference);
+
+ // Loop through each child
+ for(CommandDescription child : commandChildren) {
+ // Get the best suitable command
+ FoundCommandResult result = child.findCommand(queryReference);
+ if(result != null)
+ return result;
+ }
+ }
+
+ // Check if the remaining command reference elements fit the arguments for this command
+ if(getSuitableArgumentsDifference(queryReference) >= 0)
+ return new FoundCommandResult(this, newReference, newArguments, queryReference);
+
+ // No command found, return null
+ return null;
+ }
+
+ /**
+ * Check whether there's any command description that matches the specified command reference.
+ *
+ * @param commandReference The command reference.
+ *
+ * @return True if so, false otherwise.
+ */
+ public boolean hasSuitableCommand(CommandParts commandReference) {
+ return findCommand(commandReference) != null;
+ }
+
+ /**
+ * Check if the remaining command reference elements are suitable with arguments of the current command description.
+ *
+ * @param commandReference The command reference.
+ *
+ * @return True if the arguments are suitable, false otherwise.
+ */
+ public boolean hasSuitableArguments(CommandParts commandReference) {
+ return getSuitableArgumentsDifference(commandReference) == 0;
+ }
+
+ /**
+ * Check if the remaining command reference elements are suitable with arguments of the current command description,
+ * and get the difference in argument count.
+ *
+ * @param commandReference The command reference.
+ *
+ * @return The difference in argument count between the reference and the actual command.
+ */
+ public int getSuitableArgumentsDifference(CommandParts commandReference) {
+ // Make sure the command reference is valid
+ if(commandReference.getCount() <= 0)
+ return -1;
+
+ // Get the remaining command reference element count
+ int remainingElementCount = commandReference.getCount() - getParentCount() - 1;
+
+ // Check if there are too less arguments
+ if(getMinimumArguments() > remainingElementCount)
+ return Math.abs(getMinimumArguments() - remainingElementCount);
+
+ // Check if there are too many arguments
+ if(getMaximumArguments() < remainingElementCount && getMaximumArguments() >= 0)
+ return Math.abs(remainingElementCount - getMaximumArguments());
+
+ // The arguments seem to be EQUALS, return the result
+ return 0;
+ }
+
+ /**
+ * Get the command permissions.
+ *
+ * @return The command permissions.
+ */
+ public CommandPermissions getCommandPermissions() {
+ return this.permissions;
+ }
+
+ /**
+ * Set the command permissions.
+ *
+ * @param commandPermissions The command permissions.
+ */
+ public void setCommandPermissions(CommandPermissions commandPermissions) {
+ this.permissions = commandPermissions;
+ }
+
+ /**
+ * Set the command permissions.
+ *
+ * @param permissionNode The permission node required.
+ * @param defaultPermission The default permission.
+ */
+ public void setCommandPermissions(String permissionNode, CommandPermissions.DefaultPermission defaultPermission) {
+ this.permissions = new CommandPermissions(permissionNode, defaultPermission);
+ }
+
+ /**
+ * Check whether two labels equal to each other.
+ *
+ * @param commandLabel The first command label.
+ * @param otherCommandLabel The other command label.
+ *
+ * @return True if the labels are equal to each other.
+ */
+ private static boolean commandLabelEquals(String commandLabel, String otherCommandLabel) {
+ // Trim the command labels from unwanted whitespaces
+ commandLabel = commandLabel.trim();
+ otherCommandLabel = otherCommandLabel.trim();
+
+ // Check whether the the two command labels are equal (case insensitive)
+ return (commandLabel.equalsIgnoreCase(otherCommandLabel));
+ }
+
+ /**
+ * Check whether the command description has been set up properly.
+ *
+ * @return True if the command description is valid, false otherwise.
+ */
+ public boolean isValid() {
+ // Make sure any command label is set
+ if(getLabels().size() == 0)
+ return false;
+
+ // Make sure the permissions are set up properly
+ if(this.permissions == null)
+ return false;
+
+ // Everything seems to be correct, return the result
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/CommandHandler.java b/src/main/java/fr/xephi/authme/command/CommandHandler.java
new file mode 100644
index 00000000..063f8935
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/CommandHandler.java
@@ -0,0 +1,207 @@
+package fr.xephi.authme.command;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.bukkit.ChatColor;
+import org.bukkit.command.CommandSender;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.command.help.HelpProvider;
+
+public class CommandHandler {
+
+ /** The command manager instance. */
+ private CommandManager commandManager;
+
+ /**
+ * Constructor.
+ *
+ * @param init True to immediately initialize.
+ */
+ public CommandHandler(boolean init) {
+ // Initialize
+ if(init)
+ init();
+ }
+
+ /**
+ * Initialize the command handler.
+ *
+ * @return True if succeed, false on failure. True will also be returned if the command handler was already
+ * initialized.
+ */
+ public boolean init() {
+ // Make sure the handler isn't initialized already
+ if(isInit())
+ return true;
+
+ // Initialize the command manager
+ this.commandManager = new CommandManager(false);
+ this.commandManager.registerCommands();
+
+ // Return the result
+ return true;
+ }
+
+ /**
+ * Check whether the command handler is initialized.
+ *
+ * @return True if the command handler is initialized.
+ */
+ public boolean isInit() {
+ return this.commandManager != null;
+ }
+
+ /**
+ * Destroy the command handler.
+ *
+ * @return True if the command handler was destroyed successfully, false otherwise. True will also be returned if
+ * the command handler wasn't initialized.
+ */
+ public boolean destroy() {
+ // Make sure the command handler is initialized
+ if(!isInit())
+ return true;
+
+ // Unset the command manager
+ this.commandManager = null;
+ return true;
+ }
+
+ /**
+ * Get the command manager.
+ *
+ * @return Command manager instance.
+ */
+ public CommandManager getCommandManager() {
+ return this.commandManager;
+ }
+
+ /**
+ * Process a command.
+ *
+ * @param sender The command sender (Bukkit).
+ * @param bukkitCommand The command (Bukkit).
+ * @param bukkitCommandLabel The command label (Bukkit).
+ * @param bukkitArgs The command arguments (Bukkit).
+ *
+ * @return True if the command was executed, false otherwise.
+ */
+ public boolean onCommand(CommandSender sender, org.bukkit.command.Command bukkitCommand, String bukkitCommandLabel, String[] bukkitArgs) {
+ // Process the arguments
+ List args = processArguments(bukkitArgs);
+
+ // Create a command reference, and make sure at least one command part is available
+ CommandParts commandReference = new CommandParts(bukkitCommandLabel, args);
+ if(commandReference.getCount() == 0)
+ return false;
+
+ // Get a suitable command for this reference, and make sure it isn't null
+ FoundCommandResult result = this.commandManager.findCommand(commandReference);
+ if(result == null) {
+ sender.sendMessage(ChatColor.DARK_RED + "Failed to parse " + AuthMe.PLUGIN_NAME + " command!");
+ return false;
+ }
+
+ // Get the base command
+ String baseCommand = commandReference.get(0);
+
+ // Make sure the difference between the command reference and the actual command isn't too big
+ final double commandDifference = result.getDifference();
+ if(commandDifference > 0.12) {
+ // Show the unknown command warning
+ sender.sendMessage(ChatColor.DARK_RED + "Unknown command!");
+
+ // Show a command suggestion if available and the difference isn't too big
+ if(commandDifference < 0.75)
+ if(result.getCommandDescription() != null)
+ sender.sendMessage(ChatColor.YELLOW + "Did you mean " + ChatColor.GOLD + "/" + result.getCommandDescription().getCommandReference(commandReference) + ChatColor.YELLOW + "?");
+
+ // Show the help command
+ sender.sendMessage(ChatColor.YELLOW + "Use the command " + ChatColor.GOLD + "/" + baseCommand + " help" + ChatColor.YELLOW + " to view help.");
+ return true;
+ }
+
+ // Show a message when the command handler is assuming a command
+ if(commandDifference > 0) {
+ // Get the suggested command
+ CommandParts suggestedCommandParts = new CommandParts(result.getCommandDescription().getCommandReference(commandReference));
+
+ // Show the suggested command
+ sender.sendMessage(ChatColor.DARK_RED + "Unknown command, assuming " + ChatColor.GOLD + "/" + suggestedCommandParts +
+ ChatColor.DARK_RED + "!");
+ }
+
+ // Make sure the command is executable
+ if(!result.isExecutable()) {
+ // Get the command reference
+ CommandParts helpCommandReference = new CommandParts(result.getCommandReference().getRange(1));
+
+ // Show the unknown command warning
+ sender.sendMessage(ChatColor.DARK_RED + "Invalid command!");
+
+ // Show the help command
+ sender.sendMessage(ChatColor.YELLOW + "Use the command " + ChatColor.GOLD + "/" + baseCommand + " help " + helpCommandReference + ChatColor.YELLOW + " to view help.");
+ return true;
+ }
+
+ // Make sure the command sender has permission
+ if(!result.hasPermission(sender)) {
+ // Show the no permissions warning
+ sender.sendMessage(ChatColor.DARK_RED + "You don't have permission to use this command!");
+ return true;
+ }
+
+ // Make sure the command sender has permission
+ if(!result.hasProperArguments()) {
+ // Get the command and the suggested command reference
+ CommandParts suggestedCommandReference = new CommandParts(result.getCommandDescription().getCommandReference(commandReference));
+ CommandParts helpCommandReference = new CommandParts(suggestedCommandReference.getRange(1));
+
+ // Show the invalid arguments warning
+ sender.sendMessage(ChatColor.DARK_RED + "Incorrect command arguments!");
+
+ // Show the command argument help
+ HelpProvider.showHelp(sender, commandReference, suggestedCommandReference, true, false, true, false, false, false);
+
+ // Show the command to use for detailed help
+ sender.sendMessage(ChatColor.GOLD + "Detailed help: " + ChatColor.WHITE + "/" + baseCommand + " help " + helpCommandReference);
+ return true;
+ }
+
+ // Execute the command if it's suitable
+ return result.executeCommand(sender);
+ }
+
+ /**
+ * Process the command arguments, and return them as an array list.
+ *
+ * @param args The command arguments to process.
+ *
+ * @return The processed command arguments.
+ */
+ private List processArguments(String[] args) {
+ // Convert the array into a list of arguments
+ List arguments = new ArrayList<>(Arrays.asList(args));
+
+ /// Remove all empty arguments
+ for(int i = 0; i < arguments.size(); i++) {
+ // Get the argument value
+ final String arg = arguments.get(i);
+
+ // Check whether the argument value is empty
+ if(arg.trim().length() == 0) {
+ // Remove the current argument
+ arguments.remove(i);
+
+ // Decrease the index by one, continue to the next argument
+ i--;
+ }
+ }
+
+ // Return the argument
+ return arguments;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/CommandManager.java b/src/main/java/fr/xephi/authme/command/CommandManager.java
new file mode 100644
index 00000000..37efc8e3
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/CommandManager.java
@@ -0,0 +1,616 @@
+package fr.xephi.authme.command;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import fr.xephi.authme.command.executable.HelpCommand;
+import fr.xephi.authme.command.executable.authme.AccountsCommand;
+import fr.xephi.authme.command.executable.authme.AuthMeCommand;
+import fr.xephi.authme.command.executable.authme.ChangePasswordCommand;
+import fr.xephi.authme.command.executable.authme.FirstSpawnCommand;
+import fr.xephi.authme.command.executable.authme.ForceLoginCommand;
+import fr.xephi.authme.command.executable.authme.GetEmailCommand;
+import fr.xephi.authme.command.executable.authme.GetIpCommand;
+import fr.xephi.authme.command.executable.authme.LastLoginCommand;
+import fr.xephi.authme.command.executable.authme.PurgeBannedPlayersCommand;
+import fr.xephi.authme.command.executable.authme.PurgeCommand;
+import fr.xephi.authme.command.executable.authme.PurgeLastPositionCommand;
+import fr.xephi.authme.command.executable.authme.RegisterCommand;
+import fr.xephi.authme.command.executable.authme.ReloadCommand;
+import fr.xephi.authme.command.executable.authme.SetEmailCommand;
+import fr.xephi.authme.command.executable.authme.SetFirstSpawnCommand;
+import fr.xephi.authme.command.executable.authme.SetSpawnCommand;
+import fr.xephi.authme.command.executable.authme.SpawnCommand;
+import fr.xephi.authme.command.executable.authme.SwitchAntiBotCommand;
+import fr.xephi.authme.command.executable.authme.UnregisterCommand;
+import fr.xephi.authme.command.executable.authme.VersionCommand;
+import fr.xephi.authme.command.executable.captcha.CaptchaCommand;
+import fr.xephi.authme.command.executable.converter.ConverterCommand;
+import fr.xephi.authme.command.executable.email.AddEmailCommand;
+import fr.xephi.authme.command.executable.email.ChangeEmailCommand;
+import fr.xephi.authme.command.executable.email.RecoverEmailCommand;
+import fr.xephi.authme.command.executable.login.LoginCommand;
+import fr.xephi.authme.command.executable.logout.LogoutCommand;
+
+public class CommandManager {
+
+ /** The list of commandDescriptions. */
+ private List commandDescriptions = new ArrayList<>();
+
+ /**
+ * Constructor.
+ *
+ * @param registerCommands
+ * True to register the commands, false otherwise.
+ */
+ public CommandManager(boolean registerCommands) {
+ // Register the commands
+ if (registerCommands)
+ registerCommands();
+ }
+
+ /**
+ * Register all commands.
+ */
+ @SuppressWarnings({ "serial" })
+ public void registerCommands() {
+ // Register the base AuthMe Reloaded command
+ CommandDescription authMeBaseCommand = new CommandDescription(new AuthMeCommand(), new ArrayList() {
+
+ {
+ add("authme");
+ }
+ }, "Main command", "The main AuthMeReloaded command. The root for all admin commands.", null);
+
+ // Register the help command
+ CommandDescription authMeHelpCommand = new CommandDescription(new HelpCommand(), new ArrayList() {
+
+ {
+ add("help");
+ add("hlp");
+ add("h");
+ add("sos");
+ add("?");
+ }
+ }, "View help", "View detailed help pages about AuthMeReloaded commands.", authMeBaseCommand);
+ authMeHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
+ authMeHelpCommand.setMaximumArguments(false);
+
+ // Register the register command
+ CommandDescription registerCommand = new CommandDescription(new RegisterCommand(), new ArrayList() {
+
+ {
+ add("register");
+ add("reg");
+ add("r");
+ }
+ }, "Register a player", "Register the specified player with the specified password.", authMeBaseCommand);
+ registerCommand.setCommandPermissions("authme.admin.register", CommandPermissions.DefaultPermission.OP_ONLY);
+ registerCommand.addArgument(new CommandArgumentDescription("player", "Player name", false));
+ registerCommand.addArgument(new CommandArgumentDescription("password", "Password", false));
+
+ // Register the unregister command
+ CommandDescription unregisterCommand = new CommandDescription(new UnregisterCommand(), new ArrayList() {
+
+ {
+ add("unregister");
+ add("unreg");
+ add("unr");
+ add("delete");
+ add("del");
+ }
+ }, "Unregister a player", "Unregister the specified player.", authMeBaseCommand);
+ unregisterCommand.setCommandPermissions("authme.admin.unregister", CommandPermissions.DefaultPermission.OP_ONLY);
+ unregisterCommand.addArgument(new CommandArgumentDescription("player", "Player name", false));
+
+ // Register the forcelogin command
+ CommandDescription forceLoginCommand = new CommandDescription(new ForceLoginCommand(), new ArrayList() {
+
+ {
+ add("forcelogin");
+ add("login");
+ }
+ }, "Enforce login player", "Enforce the specified player to login.", authMeBaseCommand);
+ forceLoginCommand.setCommandPermissions("authme.admin.forcelogin", CommandPermissions.DefaultPermission.OP_ONLY);
+ forceLoginCommand.addArgument(new CommandArgumentDescription("player", "Online player name", true));
+
+ // Register the changepassword command
+ CommandDescription changePasswordCommand = new CommandDescription(new ChangePasswordCommand(), new ArrayList() {
+
+ {
+ add("password");
+ add("changepassword");
+ add("changepass");
+ add("cp");
+ }
+ }, "Change player's password", "Change the password of a player.", authMeBaseCommand);
+ changePasswordCommand.setCommandPermissions("authme.admin.changepassword", CommandPermissions.DefaultPermission.OP_ONLY);
+ changePasswordCommand.addArgument(new CommandArgumentDescription("player", "Player name", false));
+ changePasswordCommand.addArgument(new CommandArgumentDescription("pwd", "New password", false));
+
+ // Register the purge command
+ CommandDescription lastLoginCommand = new CommandDescription(new LastLoginCommand(), new ArrayList() {
+
+ {
+ add("lastlogin");
+ add("ll");
+ }
+ }, "Player's last login", "View the date of the specified players last login", authMeBaseCommand);
+ lastLoginCommand.setCommandPermissions("authme.admin.lastlogin", CommandPermissions.DefaultPermission.OP_ONLY);
+ lastLoginCommand.addArgument(new CommandArgumentDescription("player", "Player name", true));
+
+ // Register the accounts command
+ CommandDescription accountsCommand = new CommandDescription(new AccountsCommand(), new ArrayList() {
+
+ {
+ add("accounts");
+ add("account");
+ }
+ }, "Display player accounts", "Display all accounts of a player by it's player name or IP.", authMeBaseCommand);
+ accountsCommand.setCommandPermissions("authme.admin.accounts", CommandPermissions.DefaultPermission.OP_ONLY);
+ accountsCommand.addArgument(new CommandArgumentDescription("player", "Player name or IP", true));
+
+ // Register the getemail command
+ CommandDescription getEmailCommand = new CommandDescription(new GetEmailCommand(), new ArrayList() {
+
+ {
+ add("getemail");
+ add("getmail");
+ add("email");
+ add("mail");
+ }
+ }, "Display player's email", "Display the email address of the specified player if set.", authMeBaseCommand);
+ getEmailCommand.setCommandPermissions("authme.admin.getemail", CommandPermissions.DefaultPermission.OP_ONLY);
+ getEmailCommand.addArgument(new CommandArgumentDescription("player", "Player name", true));
+
+ // Register the setemail command
+ CommandDescription setEmailCommand = new CommandDescription(new SetEmailCommand(), new ArrayList() {
+
+ {
+ add("chgemail");
+ add("chgmail");
+ add("setemail");
+ add("setmail");
+ }
+ }, "Change player's email", "Change the email address of the specified player.", authMeBaseCommand);
+ setEmailCommand.setCommandPermissions("authme.admin.chgemail", CommandPermissions.DefaultPermission.OP_ONLY);
+ setEmailCommand.addArgument(new CommandArgumentDescription("player", "Player name", false));
+ setEmailCommand.addArgument(new CommandArgumentDescription("email", "Player email", false));
+
+ // Register the getip command
+ CommandDescription getIpCommand = new CommandDescription(new GetIpCommand(), new ArrayList() {
+
+ {
+ add("getip");
+ add("ip");
+ }
+ }, "Get player's IP", "Get the IP address of the specified online player.", authMeBaseCommand);
+ getIpCommand.setCommandPermissions("authme.admin.getip", CommandPermissions.DefaultPermission.OP_ONLY);
+ getIpCommand.addArgument(new CommandArgumentDescription("player", "Online player name", true));
+
+ // Register the spawn command
+ CommandDescription spawnCommand = new CommandDescription(new SpawnCommand(), new ArrayList() {
+
+ {
+ add("spawn");
+ add("home");
+ }
+ }, "Teleport to spawn", "Teleport to the spawn.", authMeBaseCommand);
+ spawnCommand.setCommandPermissions("authme.admin.spawn", CommandPermissions.DefaultPermission.OP_ONLY);
+
+ // Register the setspawn command
+ CommandDescription setSpawnCommand = new CommandDescription(new SetSpawnCommand(), new ArrayList() {
+
+ {
+ add("setspawn");
+ add("chgspawn");
+ }
+ }, "Change the spawn", "Change the player's spawn to your current position.", authMeBaseCommand);
+ setSpawnCommand.setCommandPermissions("authme.admin.setspawn", CommandPermissions.DefaultPermission.OP_ONLY);
+
+ // Register the firstspawn command
+ CommandDescription firstSpawnCommand = new CommandDescription(new FirstSpawnCommand(), new ArrayList() {
+
+ {
+ add("firstspawn");
+ add("firsthome");
+ }
+ }, "Teleport to first spawn", "Teleport to the first spawn.", authMeBaseCommand);
+ firstSpawnCommand.setCommandPermissions("authme.admin.firstspawn", CommandPermissions.DefaultPermission.OP_ONLY);
+
+ // Register the setfirstspawn command
+ CommandDescription setFirstSpawnCommand = new CommandDescription(new SetFirstSpawnCommand(), new ArrayList() {
+
+ {
+ add("setfirstspawn");
+ add("chgfirstspawn");
+ }
+ }, "Change the first spawn", "Change the first player's spawn to your current position.", authMeBaseCommand);
+ setFirstSpawnCommand.setCommandPermissions("authme.admin.setfirstspawn", CommandPermissions.DefaultPermission.OP_ONLY);
+
+ // Register the purge command
+ CommandDescription purgeCommand = new CommandDescription(new PurgeCommand(), new ArrayList() {
+
+ {
+ add("purge");
+ add("delete");
+ }
+ }, "Purge old data", "Purge old AuthMeReloaded data longer than the specified amount of days ago.", authMeBaseCommand);
+ purgeCommand.setCommandPermissions("authme.admin.purge", CommandPermissions.DefaultPermission.OP_ONLY);
+ purgeCommand.addArgument(new CommandArgumentDescription("days", "Number of days", false));
+
+ // Register the purgelastposition command
+ CommandDescription purgeLastPositionCommand = new CommandDescription(new PurgeLastPositionCommand(), new ArrayList() {
+
+ {
+ add("resetpos");
+ add("purgelastposition");
+ add("purgelastpos");
+ add("resetposition");
+ add("resetlastposition");
+ add("resetlastpos");
+ }
+ }, "Purge player's last position", "Purge the last know position of the specified player.", authMeBaseCommand);
+ purgeLastPositionCommand.setCommandPermissions("authme.admin.purgelastpos", CommandPermissions.DefaultPermission.OP_ONLY);
+ purgeLastPositionCommand.addArgument(new CommandArgumentDescription("player", "Player name", true));
+
+ // Register the purgebannedplayers command
+ CommandDescription purgeBannedPlayersCommand = new CommandDescription(new PurgeBannedPlayersCommand(), new ArrayList() {
+
+ {
+ add("purgebannedplayers");
+ add("purgebannedplayer");
+ add("deletebannedplayers");
+ add("deletebannedplayer");
+ }
+ }, "Purge banned palyers data", "Purge all AuthMeReloaded data for banned players.", authMeBaseCommand);
+ purgeBannedPlayersCommand.setCommandPermissions("authme.admin.purgebannedplayers", CommandPermissions.DefaultPermission.OP_ONLY);
+
+ // Register the switchantibot command
+ CommandDescription switchAntiBotCommand = new CommandDescription(new SwitchAntiBotCommand(), new ArrayList() {
+
+ {
+ add("switchantibot");
+ add("toggleantibot");
+ add("antibot");
+ }
+ }, "Switch AntiBot mode", "Switch or toggle the AntiBot mode to the specified state.", authMeBaseCommand);
+ switchAntiBotCommand.setCommandPermissions("authme.admin.switchantibot", CommandPermissions.DefaultPermission.OP_ONLY);
+ switchAntiBotCommand.addArgument(new CommandArgumentDescription("mode", "ON / OFF", true));
+
+ // // Register the resetname command
+ // CommandDescription resetNameCommand = new CommandDescription(
+ // new ResetNameCommand(),
+ // new ArrayList() {{
+ // add("resetname");
+ // add("resetnames");
+ // }},
+ // "Reset name",
+ // "Reset name",
+ // authMeCommand);
+ // resetNameCommand.setCommandPermissions("authme.admin.resetname",
+ // CommandPermissions.DefaultPermission.OP_ONLY);
+
+ // Register the reload command
+ CommandDescription reloadCommand = new CommandDescription(new ReloadCommand(), new ArrayList() {
+
+ {
+ add("reload");
+ add("rld");
+ }
+ }, "Reload plugin", "Reload the AuthMeReloaded plugin.", authMeBaseCommand);
+ reloadCommand.setCommandPermissions("authme.admin.reload", CommandPermissions.DefaultPermission.OP_ONLY);
+
+ // Register the version command
+ CommandDescription versionCommand = new CommandDescription(new VersionCommand(), new ArrayList() {
+
+ {
+ add("version");
+ add("ver");
+ add("v");
+ add("about");
+ add("info");
+ }
+ }, "Version info", "Show detailed information about the installed AuthMeReloaded version, and shows the developers, contributors, license and other information.", authMeBaseCommand);
+ versionCommand.setMaximumArguments(false);
+
+ // Register the base Dungeon Maze command
+ CommandDescription loginBaseCommand = new CommandDescription(new LoginCommand(), new ArrayList() {
+
+ {
+ add("login");
+ add("l");
+ }
+ }, "Login command", "Command to login using AuthMeReloaded.", null);
+ loginBaseCommand.setCommandPermissions("authme.login", CommandPermissions.DefaultPermission.ALLOWED);
+ loginBaseCommand.addArgument(new CommandArgumentDescription("password", "Login password", false));
+
+ // Register the help command
+ CommandDescription loginHelpCommand = new CommandDescription(new HelpCommand(), new ArrayList() {
+
+ {
+ add("help");
+ add("hlp");
+ add("h");
+ add("sos");
+ add("?");
+ }
+ }, "View help", "View detailed help pages about AuthMeReloaded login commands.", loginBaseCommand);
+ loginHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
+ loginHelpCommand.setMaximumArguments(false);
+
+ // Register the base logout command
+ CommandDescription logoutBaseCommand = new CommandDescription(new LogoutCommand(), new ArrayList() {
+
+ {
+ add("logout");
+ }
+ }, "Logout command", "Command to logout using AuthMeReloaded.", null);
+ logoutBaseCommand.setCommandPermissions("authme.logout", CommandPermissions.DefaultPermission.ALLOWED);
+
+ // Register the help command
+ CommandDescription logoutHelpCommand = new CommandDescription(new HelpCommand(), new ArrayList() {
+
+ {
+ add("help");
+ add("hlp");
+ add("h");
+ add("sos");
+ add("?");
+ }
+ }, "View help", "View detailed help pages about AuthMeReloaded logout commands.", logoutBaseCommand);
+ logoutHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
+ logoutHelpCommand.setMaximumArguments(false);
+
+ // Register the base register command
+ CommandDescription registerBaseCommand = new CommandDescription(new fr.xephi.authme.command.executable.register.RegisterCommand(), new ArrayList() {
+
+ {
+ add("register");
+ add("reg");
+ }
+ }, "Registration command", "Command to register using AuthMeReloaded.", null);
+ registerBaseCommand.setCommandPermissions("authme.register", CommandPermissions.DefaultPermission.ALLOWED);
+ registerBaseCommand.addArgument(new CommandArgumentDescription("password", "Password", false));
+ registerBaseCommand.addArgument(new CommandArgumentDescription("verifyPassword", "Verify password", false));
+ registerBaseCommand.setMaximumArguments(false);
+
+ // Register the help command
+ CommandDescription registerHelpCommand = new CommandDescription(new HelpCommand(), new ArrayList() {
+
+ {
+ add("help");
+ add("hlp");
+ add("h");
+ add("sos");
+ add("?");
+ }
+ }, "View help", "View detailed help pages about AuthMeReloaded register commands.", registerBaseCommand);
+ registerHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
+ registerHelpCommand.setMaximumArguments(false);
+
+ // Register the base unregister command
+ CommandDescription unregisterBaseCommand = new CommandDescription(new fr.xephi.authme.command.executable.unregister.UnregisterCommand(), new ArrayList() {
+
+ {
+ add("unregister");
+ add("unreg");
+ }
+ }, "Unregistration command", "Command to unregister using AuthMeReloaded.", null);
+ unregisterBaseCommand.setCommandPermissions("authme.unregister", CommandPermissions.DefaultPermission.ALLOWED);
+ unregisterBaseCommand.addArgument(new CommandArgumentDescription("password", "Password", false));
+
+ // Register the help command
+ CommandDescription unregisterHelpCommand = new CommandDescription(new HelpCommand(), new ArrayList() {
+
+ {
+ add("help");
+ add("hlp");
+ add("h");
+ add("sos");
+ add("?");
+ }
+ }, "View help", "View detailed help pages about AuthMeReloaded unregister commands.", unregisterBaseCommand);
+ unregisterHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
+ unregisterHelpCommand.setMaximumArguments(false);
+
+ // Register the base changepassword command
+ CommandDescription changePasswordBaseCommand = new CommandDescription(new fr.xephi.authme.command.executable.changepassword.ChangePasswordCommand(), new ArrayList() {
+
+ {
+ add("changepassword");
+ add("changepass");
+ }
+ }, "Change password command", "Command to change your password using AuthMeReloaded.", null);
+ changePasswordBaseCommand.setCommandPermissions("authme.changepassword", CommandPermissions.DefaultPermission.ALLOWED);
+ changePasswordBaseCommand.addArgument(new CommandArgumentDescription("password", "Password", false));
+ changePasswordBaseCommand.addArgument(new CommandArgumentDescription("verifyPassword", "Verify password", false));
+ changePasswordBaseCommand.setMaximumArguments(false);
+
+ // Register the help command
+ CommandDescription changePasswordHelpCommand = new CommandDescription(new HelpCommand(), new ArrayList() {
+
+ {
+ add("help");
+ add("hlp");
+ add("h");
+ add("sos");
+ add("?");
+ }
+ }, "View help", "View detailed help pages about AuthMeReloaded change password commands.", changePasswordBaseCommand);
+ changePasswordHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
+ changePasswordHelpCommand.setMaximumArguments(false);
+
+ // Register the base Dungeon Maze command
+ CommandDescription emailBaseCommand = new CommandDescription(new HelpCommand(), new ArrayList() {
+
+ {
+ add("email");
+ add("mail");
+ }
+ }, "E-mail command", "The AuthMe Reloaded E-mail command. The root for all E-mail commands.", null);
+
+ // Register the help command
+ CommandDescription emailHelpCommand = new CommandDescription(new HelpCommand(), new ArrayList() {
+
+ {
+ add("help");
+ add("hlp");
+ add("h");
+ add("sos");
+ add("?");
+ }
+ }, "View help", "View detailed help pages about AuthMeReloaded help commands.", emailBaseCommand);
+ emailHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
+ emailHelpCommand.setMaximumArguments(false);
+
+ // Register the add command
+ CommandDescription addEmailCommand = new CommandDescription(new AddEmailCommand(), new ArrayList() {
+
+ {
+ add("add");
+ add("addemail");
+ add("addmail");
+ }
+ }, "Add E-mail", "Add an new E-Mail address to your account.", emailBaseCommand);
+ addEmailCommand.setCommandPermissions("authme.email.add", CommandPermissions.DefaultPermission.ALLOWED);
+ addEmailCommand.addArgument(new CommandArgumentDescription("email", "Email address", false));
+ addEmailCommand.addArgument(new CommandArgumentDescription("verifyEmail", "Email address verification", false));
+
+ // Register the change command
+ CommandDescription changeEmailCommand = new CommandDescription(new ChangeEmailCommand(), new ArrayList() {
+
+ {
+ add("change");
+ add("changeemail");
+ add("changemail");
+ }
+ }, "Change E-mail", "Change an E-Mail address of your account.", emailBaseCommand);
+ changeEmailCommand.setCommandPermissions("authme.email.change", CommandPermissions.DefaultPermission.ALLOWED);
+ changeEmailCommand.addArgument(new CommandArgumentDescription("oldEmail", "Old email address", false));
+ changeEmailCommand.addArgument(new CommandArgumentDescription("newEmail", "New email address", false));
+
+ // Register the recover command
+ CommandDescription recoverEmailCommand = new CommandDescription(new RecoverEmailCommand(), new ArrayList() {
+
+ {
+ add("recover");
+ add("recovery");
+ add("recoveremail");
+ add("recovermail");
+ }
+ }, "Recover using E-mail", "Recover your account using an E-mail address.", emailBaseCommand);
+ recoverEmailCommand.setCommandPermissions("authme.email.recover", CommandPermissions.DefaultPermission.ALLOWED);
+ recoverEmailCommand.addArgument(new CommandArgumentDescription("email", "Email address", false));
+
+ // Register the base captcha command
+ CommandDescription captchaBaseCommand = new CommandDescription(new CaptchaCommand(), new ArrayList() {
+
+ {
+ add("captcha");
+ add("capt");
+ }
+ }, "Captcha command", "Captcha command for AuthMeReloaded.", null);
+ captchaBaseCommand.setCommandPermissions("authme.captcha", CommandPermissions.DefaultPermission.ALLOWED);
+ captchaBaseCommand.addArgument(new CommandArgumentDescription("captcha", "The captcha", false));
+ captchaBaseCommand.setMaximumArguments(false);
+
+ // Register the help command
+ CommandDescription captchaHelpCommand = new CommandDescription(new HelpCommand(), new ArrayList() {
+
+ {
+ add("help");
+ add("hlp");
+ add("h");
+ add("sos");
+ add("?");
+ }
+ }, "View help", "View detailed help pages about AuthMeReloaded change captcha commands.", captchaBaseCommand);
+ captchaHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
+ captchaHelpCommand.setMaximumArguments(false);
+
+ // Register the base converter command
+ CommandDescription converterBaseCommand = new CommandDescription(new ConverterCommand(), new ArrayList() {
+
+ {
+ add("converter");
+ add("convert");
+ add("conv");
+ }
+ }, "Convert command", "Convert command for AuthMeReloaded.", null);
+ converterBaseCommand.setCommandPermissions("authme.converter", CommandPermissions.DefaultPermission.OP_ONLY);
+ converterBaseCommand.addArgument(new CommandArgumentDescription("job", "Conversion job: flattosql / flattosqlite /| xauth / crazylogin / rakamak / royalauth / vauth / sqltoflat", false));
+ converterBaseCommand.setMaximumArguments(false);
+
+ // Register the help command
+ CommandDescription converterHelpCommand = new CommandDescription(new HelpCommand(), new ArrayList() {
+
+ {
+ add("help");
+ add("hlp");
+ add("h");
+ add("sos");
+ add("?");
+ }
+ }, "View help", "View detailed help pages about AuthMeReloaded change captcha commands.", converterBaseCommand);
+ converterHelpCommand.addArgument(new CommandArgumentDescription("query", "The command or query to view help for.", true));
+ converterHelpCommand.setMaximumArguments(false);
+
+ // Add the base commands to the commands array
+ this.commandDescriptions.add(authMeBaseCommand);
+ this.commandDescriptions.add(loginBaseCommand);
+ this.commandDescriptions.add(logoutBaseCommand);
+ this.commandDescriptions.add(registerBaseCommand);
+ this.commandDescriptions.add(unregisterBaseCommand);
+ this.commandDescriptions.add(changePasswordBaseCommand);
+ this.commandDescriptions.add(emailBaseCommand);
+ this.commandDescriptions.add(captchaBaseCommand);
+ this.commandDescriptions.add(converterBaseCommand);
+ }
+
+ /**
+ * Get the list of command descriptions
+ *
+ * @return List of command descriptions.
+ */
+ public List getCommandDescriptions() {
+ return this.commandDescriptions;
+ }
+
+ /**
+ * Get the number of command description count.
+ *
+ * @return Command description count.
+ */
+ public int getCommandDescriptionCount() {
+ return this.getCommandDescriptions().size();
+ }
+
+ /**
+ * Find the best suitable command for the specified reference.
+ *
+ * @param queryReference
+ * The query reference to find a command for.
+ *
+ * @return The command found, or null.
+ */
+ public FoundCommandResult findCommand(CommandParts queryReference) {
+ // Make sure the command reference is valid
+ if (queryReference.getCount() <= 0)
+ return null;
+
+ // Get the base command description
+ for (CommandDescription commandDescription : this.commandDescriptions) {
+ // Check whether there's a command description available for the
+ // current command
+ if (!commandDescription.isSuitableLabel(queryReference))
+ continue;
+
+ // Find the command reference, return the result
+ return commandDescription.findCommand(queryReference);
+ }
+
+ // No applicable command description found, return false
+ return null;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/CommandParts.java b/src/main/java/fr/xephi/authme/command/CommandParts.java
new file mode 100644
index 00000000..6e833482
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/CommandParts.java
@@ -0,0 +1,203 @@
+package fr.xephi.authme.command;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import fr.xephi.authme.util.ListUtils;
+import fr.xephi.authme.util.StringUtils;
+
+public class CommandParts {
+
+ /** The list of parts for this command. */
+ private List parts = new ArrayList<>();
+
+ /**
+ * Constructor.
+ */
+ public CommandParts() { }
+
+ /**
+ * Constructor.
+ *
+ * @param part The part to add.
+ */
+ public CommandParts(String part) {
+ this.parts.add(part);
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param commandParts The command parts instance.
+ */
+ public CommandParts(CommandParts commandParts) {
+ this.parts.addAll(commandParts.getList());
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param parts The list of parts.
+ */
+ public CommandParts(List parts) {
+ this.parts.addAll(parts);
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param base The base part.
+ * @param parts The list of additional parts.
+ */
+ public CommandParts(String base, List parts) {
+ this.parts.add(base);
+ this.parts.addAll(parts);
+ }
+
+ /**
+ * Get the command parts.
+ *
+ * @return Command parts.
+ */
+ public List getList() {
+ return this.parts;
+ }
+
+ /**
+ * Add a part.
+ *
+ * @param part The part to add.
+ *
+ * @return The result.
+ */
+ public boolean add(String part) {
+ return this.parts.add(part);
+ }
+
+ /**
+ * Add some parts.
+ *
+ * @param parts The parts to add.
+ *
+ * @return The result.
+ */
+ public boolean add(List parts) {
+ return this.parts.addAll(parts);
+ }
+
+ /**
+ * Add some parts.
+ *
+ * @param parts The parts to add.
+ *
+ * @return The result.
+ */
+ public boolean add(String[] parts) {
+ for(String entry : parts)
+ add(entry);
+ return true;
+ }
+
+ /**
+ * Get the number of parts.
+ *
+ * @return Part count.
+ */
+ public int getCount() {
+ return this.parts.size();
+ }
+
+ /**
+ * Get a part by it's index.
+ *
+ * @param i Part index.
+ *
+ * @return The part.
+ */
+ public String get(int i) {
+ // Make sure the index is in-bound
+ if(i < 0 || i >= getCount())
+ return null;
+
+ // Get and return the argument
+ return this.parts.get(i);
+ }
+
+ /**
+ * Get a range of the parts starting at the specified index up to the end of the range.
+ *
+ * @param start The starting index.
+ *
+ * @return The parts range. Arguments that were out of bound are not included.
+ */
+ public List getRange(int start) {
+ return getRange(start, getCount() - start);
+ }
+
+ /**
+ * Get a range of the parts.
+ *
+ * @param start The starting index.
+ * @param count The number of parts to get.
+ *
+ * @return The parts range. Parts that were out of bound are not included.
+ */
+ public List getRange(int start, int count) {
+ // Create a new list to put the range into
+ List elements = new ArrayList<>();
+
+ // Get the range
+ for(int i = start; i < start + count; i++) {
+ // Get the part and add it if it's valid
+ String element = get(i);
+ if(element != null)
+ elements.add(element);
+ }
+
+ // Return the list of parts
+ return elements;
+ }
+
+ /**
+ * Get the difference value between two references. This won't do a full compare, just the last reference parts instead.
+ *
+ * @param other The other reference.
+ *
+ * @return The result from zero to above. A negative number will be returned on error.
+ */
+ public double getDifference(CommandParts other) {
+ return getDifference(other, false);
+ }
+
+ /**
+ * Get the difference value between two references.
+ *
+ * @param other The other reference.
+ * @param fullCompare True to compare the full references as far as the range reaches.
+ *
+ * @return The result from zero to above. A negative number will be returned on error.
+ */
+ public double getDifference(CommandParts other, boolean fullCompare) {
+ // Make sure the other reference is correct
+ if(other == null)
+ return -1;
+
+ // Get the range to use
+ int range = Math.min(this.getCount(), other.getCount());
+
+ // Get and the difference
+ if(fullCompare)
+ return StringUtils.getDifference(this.toString(), other.toString());
+ return StringUtils.getDifference(this.getRange(range - 1, 1).toString(), other.getRange(range - 1, 1).toString());
+ }
+
+ /**
+ * Convert the parts to a string.
+ *
+ * @return The part as a string.
+ */
+ @Override
+ public String toString() {
+ return ListUtils.implode(this.parts, " ");
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/CommandPermissions.java b/src/main/java/fr/xephi/authme/command/CommandPermissions.java
new file mode 100644
index 00000000..89007835
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/CommandPermissions.java
@@ -0,0 +1,183 @@
+package fr.xephi.authme.command;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+//import com.timvisee.dungeonmaze.Core;
+//import com.timvisee.dungeonmaze.permission.PermissionsManager;
+import fr.xephi.authme.AuthMe;
+
+public class CommandPermissions {
+
+ /** Defines the permission nodes required to have permission to execute this command. */
+ private List permissionNodes = new ArrayList<>();
+ /** Defines the default permission if the permission nodes couldn't be used. */
+ private DefaultPermission defaultPermission = DefaultPermission.NOT_ALLOWED;
+
+ /**
+ * Constructor.
+ */
+ public CommandPermissions() { }
+
+ /**
+ * Constructor.
+ *
+ * @param permissionNode The permission node required to execute a command.
+ * @param defaultPermission The default permission if the permission nodes couldn't be used.
+ */
+ public CommandPermissions(String permissionNode, DefaultPermission defaultPermission) {
+ this.permissionNodes.add(permissionNode);
+ this.defaultPermission = defaultPermission;
+ }
+
+ /**
+ * Constructor.
+ *
+ * @param permissionNodes The permission nodes required to execute a command.
+ * @param defaultPermission The default permission if the permission nodes couldn't be used.
+ */
+ public CommandPermissions(List permissionNodes, DefaultPermission defaultPermission) {
+ this.permissionNodes.addAll(permissionNodes);
+ }
+
+ /**
+ * Add a permission node required to execute this command.
+ *
+ * @param permissionNode The permission node to add.
+ *
+ * @return True on success, false on failure.
+ */
+ public boolean addPermissionNode(String permissionNode) {
+ // Trim the permission node
+ permissionNode = permissionNode.trim();
+
+ // Make sure the permission node is valid
+ if(permissionNode.length() == 0)
+ return false;
+
+ // Make sure this permission node hasn't been added already
+ if(hasPermissionNode(permissionNode))
+ return true;
+
+ // Add the permission node, return the result
+ return this.permissionNodes.add(permissionNode);
+ }
+
+ /**
+ * Check whether this command requires a specified permission node to execute.
+ *
+ * @param permissionNode The permission node to check for.
+ *
+ * @return True if this permission node is required, false if not.
+ */
+ public boolean hasPermissionNode(String permissionNode) {
+ return this.permissionNodes.contains(permissionNode);
+ }
+
+ /**
+ * Get the permission nodes required to execute this command.
+ *
+ * @return The permission nodes required to execute this command.
+ */
+ public List getPermissionNodes() {
+ return this.permissionNodes;
+ }
+
+ /**
+ * Get the number of permission nodes set.
+ *
+ * @return Permission node count.
+ */
+ public int getPermissionNodeCount() {
+ return this.permissionNodes.size();
+ }
+
+ /**
+ * Set the permission nodes required to execute this command.
+ *
+ * @param permissionNodes The permission nodes required to execute this command.
+ */
+ public void setPermissionNodes(List permissionNodes) {
+ this.permissionNodes = permissionNodes;
+ }
+
+ /**
+ * Check whether this command requires any permission to be executed. This is based on the getPermission() method.
+ *
+ * @return True if this command requires any permission to be executed by a player.
+ */
+ public boolean hasPermission(CommandSender sender) {
+ // Make sure any permission node is set
+ if(getPermissionNodeCount() == 0)
+ return true;
+
+ // Get the default permission
+ final boolean defaultPermission = getDefaultPermissionCommandSender(sender);
+
+ // Make sure the command sender is a player, if not use the default
+ if(!(sender instanceof Player))
+ return defaultPermission;
+
+ // Get the player instance
+ Player player = (Player) sender;
+
+// // Get the permissions manager, and make sure it's instance is valid
+// PermissionsManager permissionsManager = Core.getPermissionsManager();
+// if(permissionsManager == null)
+// return false;
+
+ // Check whether the player has permission, return the result
+ for(String node : this.permissionNodes)
+ if(!AuthMe.getInstance().authmePermissible(player, node))
+ return false;
+ return true;
+ }
+
+ /**
+ * Get the default permission if the permission nodes couldn't be used.
+ *
+ * @return The default permission.
+ */
+ public DefaultPermission getDefaultPermission() {
+ return this.defaultPermission;
+ }
+
+ /**
+ * Set the default permission used if the permission nodes couldn't be used.
+ *
+ * @param defaultPermission The default permission.
+ */
+ public void setDefaultPermission(DefaultPermission defaultPermission) {
+ this.defaultPermission = defaultPermission;
+ }
+
+ /**
+ * Get the default permission for a specified command sender.
+ *
+ * @param sender The command sender to get the default permission for.
+ *
+ * @return True if the command sender has permission by default, false otherwise.
+ */
+ public boolean getDefaultPermissionCommandSender(CommandSender sender) {
+ switch(getDefaultPermission()) {
+ case ALLOWED:
+ return true;
+
+ case OP_ONLY:
+ return sender.isOp();
+
+ case NOT_ALLOWED:
+ default:
+ return false;
+ }
+ }
+
+ public enum DefaultPermission {
+ NOT_ALLOWED,
+ OP_ONLY,
+ ALLOWED
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/ExecutableCommand.java b/src/main/java/fr/xephi/authme/command/ExecutableCommand.java
new file mode 100644
index 00000000..9550824b
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/ExecutableCommand.java
@@ -0,0 +1,17 @@
+package fr.xephi.authme.command;
+
+import org.bukkit.command.CommandSender;
+
+public abstract class ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ public abstract boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments);
+}
diff --git a/src/main/java/fr/xephi/authme/command/FoundCommandResult.java b/src/main/java/fr/xephi/authme/command/FoundCommandResult.java
new file mode 100644
index 00000000..207cf8dc
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/FoundCommandResult.java
@@ -0,0 +1,150 @@
+package fr.xephi.authme.command;
+
+import org.bukkit.command.CommandSender;
+
+public class FoundCommandResult {
+
+ /** The command description instance. */
+ private CommandDescription commandDescription;
+ /** The command reference. */
+ private CommandParts commandReference;
+ /** The command arguments. */
+ private CommandParts commandArguments;
+ /** The original search query reference. */
+ private CommandParts queryReference;
+
+ /**
+ * Constructor.
+ *
+ * @param commandDescription The command description.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ * @param queryReference The original query reference.
+ */
+ public FoundCommandResult(CommandDescription commandDescription, CommandParts commandReference, CommandParts commandArguments, CommandParts queryReference) {
+ this.commandDescription = commandDescription;
+ this.commandReference = commandReference;
+ this.commandArguments = commandArguments;
+ this.queryReference = queryReference;
+ }
+
+ /**
+ * Check whether the command was suitable.
+ *
+ * @return True if the command was suitable, false otherwise.
+ */
+ public boolean hasProperArguments() {
+ // Make sure the command description is set
+ if(this.commandDescription == null)
+ return false;
+
+ // Get and return the result
+ return getCommandDescription().getSuitableArgumentsDifference(this.queryReference) == 0;
+ }
+
+ /**
+ * Get the command description.
+ *
+ * @return Command description.
+ */
+ public CommandDescription getCommandDescription() {
+ return this.commandDescription;
+ }
+
+ /**
+ * Set the command description.
+ *
+ * @param commandDescription The command description.
+ *
+ */
+ public void setCommandDescription(CommandDescription commandDescription) {
+ this.commandDescription = commandDescription;
+ }
+
+ /**
+ * Check whether the command is executable.
+ *
+ * @return True if the command is executable, false otherwise.
+ */
+ public boolean isExecutable() {
+ // Make sure the command description is valid
+ if(this.commandDescription == null)
+ return false;
+
+ // Check whether the command is executable, return the result
+ return this.commandDescription.isExecutable();
+ }
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender that executed the command.
+ *
+ * @return True on success, false on failure.
+ */
+ public boolean executeCommand(CommandSender sender) {
+ // Make sure the command description is valid
+ if(this.commandDescription == null)
+ return false;
+
+ // Execute the command
+ return this.commandDescription.execute(sender, this.commandReference, this.commandArguments);
+ }
+
+ /**
+ * Check whether a command sender has permission to execute the command.
+ *
+ * @param sender The command sender.
+ *
+ * @return True if the command sender has permission, false otherwise.
+ */
+ public boolean hasPermission(CommandSender sender) {
+ // Make sure the command description is valid
+ if(this.commandDescription == null)
+ return false;
+
+ // Get and return the permission
+ return this.commandDescription.getCommandPermissions().hasPermission(sender);
+ }
+
+ /**
+ * Get the command reference.
+ *
+ * @return The command reference.
+ */
+ public CommandParts getCommandReference() {
+ return this.commandReference;
+ }
+
+ /**
+ * Get the command arguments.
+ *
+ * @return The command arguments.
+ */
+ public CommandParts getCommandArguments() {
+ return this.commandArguments;
+ }
+
+ /**
+ * Get the original query reference.
+ *
+ * @return Original query reference.
+ */
+ public CommandParts getQueryReference() {
+ return this.queryReference;
+ }
+
+ /**
+ * Get the difference value between the original query and the result reference.
+ *
+ * @return The difference value.
+ */
+ public double getDifference() {
+ // Get the difference through the command found
+ if(this.commandDescription != null)
+ return this.commandDescription.getCommandDifference(this.queryReference);
+
+ // Get the difference from the query reference
+ return this.queryReference.getDifference(commandReference, true);
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/HelpCommand.java b/src/main/java/fr/xephi/authme/command/executable/HelpCommand.java
new file mode 100644
index 00000000..831db024
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/HelpCommand.java
@@ -0,0 +1,38 @@
+package fr.xephi.authme.command.executable;
+
+import org.bukkit.command.CommandSender;
+
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.command.help.HelpProvider;
+
+public class HelpCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // Check whether quick help should be shown
+ boolean quickHelp = commandArguments.getCount() == 0;
+
+ // Set the proper command arguments for the quick help
+ if(quickHelp)
+ commandArguments = new CommandParts(commandReference.get(0));
+
+ // Show the new help
+ if(quickHelp)
+ HelpProvider.showHelp(sender, commandReference, commandArguments, false, false, false, false, false, true);
+ else
+ HelpProvider.showHelp(sender, commandReference, commandArguments);
+
+ // Return the result
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/AccountsCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/AccountsCommand.java
new file mode 100644
index 00000000..ad29b365
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/AccountsCommand.java
@@ -0,0 +1,122 @@
+package fr.xephi.authme.command.executable.authme;
+
+import java.util.List;
+
+import org.bukkit.Bukkit;
+import org.bukkit.command.CommandSender;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.cache.auth.PlayerAuth;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.settings.Messages;
+
+public class AccountsCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(final CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Messages instance
+ final Messages m = Messages.getInstance();
+
+ // Get the player query
+ String playerQuery = sender.getName();
+ if(commandArguments.getCount() >= 1)
+ playerQuery = commandArguments.get(0);
+ final String playerQueryFinal = playerQuery;
+
+ // Command logic
+ if (!playerQuery.contains(".")) {
+ Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
+
+ @Override
+ public void run() {
+ PlayerAuth auth;
+ StringBuilder message = new StringBuilder("[AuthMe] ");
+ try {
+ auth = plugin.database.getAuth(playerQueryFinal.toLowerCase());
+ } catch (NullPointerException npe) {
+ m.send(sender, "unknown_user");
+ return;
+ }
+ if (auth == null) {
+ m.send(sender, "unknown_user");
+ return;
+ }
+ List accountList = plugin.database.getAllAuthsByName(auth);
+ if (accountList == null || accountList.isEmpty()) {
+ m.send(sender, "user_unknown");
+ return;
+ }
+ if (accountList.size() == 1) {
+ sender.sendMessage("[AuthMe] " + playerQueryFinal + " is a single account player");
+ return;
+ }
+ int i = 0;
+ for (String account : accountList) {
+ i++;
+ message.append(account);
+ if (i != accountList.size()) {
+ message.append(", ");
+ } else {
+ message.append(".");
+ }
+ }
+ sender.sendMessage("[AuthMe] " + playerQueryFinal + " has " + String.valueOf(accountList.size()) + " accounts");
+ sender.sendMessage(message.toString());
+ }
+ });
+ return true;
+ } else {
+ Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
+ @Override
+ public void run() {
+ List accountList;
+ try {
+ accountList = plugin.database.getAllAuthsByIp(playerQueryFinal);
+ } catch (Exception e) {
+ ConsoleLogger.showError(e.getMessage());
+ ConsoleLogger.writeStackTrace(e);
+ m.send(sender, "error");
+ return;
+ }
+
+ StringBuilder message = new StringBuilder("[AuthMe] ");
+ if (accountList == null || accountList.isEmpty()) {
+ sender.sendMessage("[AuthMe] This IP does not exist in the database");
+ return;
+ }
+ if (accountList.size() == 1) {
+ sender.sendMessage("[AuthMe] " + playerQueryFinal + " is a single account player");
+ return;
+ }
+ int i = 0;
+ for (String account : accountList) {
+ i++;
+ message.append(account);
+ if (i != accountList.size()) {
+ message.append(", ");
+ } else {
+ message.append(".");
+ }
+ }
+ sender.sendMessage("[AuthMe] " + playerQueryFinal + " has " + String.valueOf(accountList.size()) + " accounts");
+ sender.sendMessage(message.toString());
+ }
+ });
+ return true;
+ }
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/AuthMeCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/AuthMeCommand.java
new file mode 100644
index 00000000..8edb818e
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/AuthMeCommand.java
@@ -0,0 +1,29 @@
+package fr.xephi.authme.command.executable.authme;
+
+import org.bukkit.ChatColor;
+import org.bukkit.command.CommandSender;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+
+public class AuthMeCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // Show some version info
+ sender.sendMessage(ChatColor.GREEN + "This server is running " + AuthMe.PLUGIN_NAME + " v" + AuthMe.getVersionName() + "! " + ChatColor.RED + "<3");
+ sender.sendMessage(ChatColor.YELLOW + "Use the command " + ChatColor.GOLD + "/" + commandReference.get(0) + " help" + ChatColor.YELLOW + " to view help.");
+ sender.sendMessage(ChatColor.YELLOW + "Use the command " + ChatColor.GOLD + "/" + commandReference.get(0) + " about" + ChatColor.YELLOW + " to view about.");
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/ChangePasswordCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/ChangePasswordCommand.java
new file mode 100644
index 00000000..d226a436
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/ChangePasswordCommand.java
@@ -0,0 +1,101 @@
+package fr.xephi.authme.command.executable.authme;
+
+import java.security.NoSuchAlgorithmException;
+
+import org.bukkit.Bukkit;
+import org.bukkit.command.CommandSender;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.cache.auth.PlayerAuth;
+import fr.xephi.authme.cache.auth.PlayerCache;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.security.PasswordSecurity;
+import fr.xephi.authme.settings.Messages;
+import fr.xephi.authme.settings.Settings;
+
+public class ChangePasswordCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(final CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Messages instance
+ final Messages m = Messages.getInstance();
+
+ // Get the player and password
+ String playerName = commandArguments.get(0);
+ final String playerPass = commandArguments.get(1);
+
+ // Validate the password
+ String playerPassLowerCase = playerPass.toLowerCase();
+ if (playerPassLowerCase.contains("delete") || playerPassLowerCase.contains("where") || playerPassLowerCase.contains("insert") || playerPassLowerCase.contains("modify") || playerPassLowerCase.contains("from") || playerPassLowerCase.contains("select") || playerPassLowerCase.contains(";") || playerPassLowerCase.contains("null") || !playerPassLowerCase.matches(Settings.getPassRegex)) {
+ m.send(sender, "password_error");
+ return true;
+ }
+ if (playerPassLowerCase.equalsIgnoreCase(playerName)) {
+ m.send(sender, "password_error_nick");
+ return true;
+ }
+ if (playerPassLowerCase.length() < Settings.getPasswordMinLen || playerPassLowerCase.length() > Settings.passwordMaxLength) {
+ m.send(sender, "pass_len");
+ return true;
+ }
+ if (!Settings.unsafePasswords.isEmpty()) {
+ if (Settings.unsafePasswords.contains(playerPassLowerCase)) {
+ m.send(sender, "password_error_unsafe");
+ return true;
+ }
+ }
+
+ // Set the password
+ final String playerNameLowerCase = playerName.toLowerCase();
+ Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
+
+ @Override
+ public void run() {
+ String hash;
+ try {
+ hash = PasswordSecurity.getHash(Settings.getPasswordHash, playerPass, playerNameLowerCase);
+ } catch (NoSuchAlgorithmException e) {
+ m.send(sender, "error");
+ return;
+ }
+ PlayerAuth auth = null;
+ if (PlayerCache.getInstance().isAuthenticated(playerNameLowerCase)) {
+ auth = PlayerCache.getInstance().getAuth(playerNameLowerCase);
+ } else if (plugin.database.isAuthAvailable(playerNameLowerCase)) {
+ auth = plugin.database.getAuth(playerNameLowerCase);
+ }
+ if (auth == null) {
+ m.send(sender, "unknown_user");
+ return;
+ }
+ auth.setHash(hash);
+ if (PasswordSecurity.userSalt.containsKey(playerNameLowerCase)) {
+ auth.setSalt(PasswordSecurity.userSalt.get(playerNameLowerCase));
+ plugin.database.updateSalt(auth);
+ }
+ if (!plugin.database.updatePassword(auth)) {
+ m.send(sender, "error");
+ return;
+ }
+ sender.sendMessage("pwd_changed");
+ ConsoleLogger.info(playerNameLowerCase + "'s password changed");
+ }
+
+ });
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommand.java
new file mode 100644
index 00000000..99907080
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/FirstSpawnCommand.java
@@ -0,0 +1,38 @@
+package fr.xephi.authme.command.executable.authme;
+
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.settings.Spawn;
+
+public class FirstSpawnCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // Make sure the command executor is a player
+ try {
+ if (sender instanceof Player) {
+ if (Spawn.getInstance().getFirstSpawn() != null)
+ ((Player) sender).teleport(Spawn.getInstance().getFirstSpawn());
+ else sender.sendMessage("[AuthMe] First spawn has failed, please try to define the first spawn");
+ } else {
+ sender.sendMessage("[AuthMe] Please use that command in game");
+ }
+ } catch (NullPointerException ex) {
+ ConsoleLogger.showError(ex.getMessage());
+ }
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/ForceLoginCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/ForceLoginCommand.java
new file mode 100644
index 00000000..17c5d8a4
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/ForceLoginCommand.java
@@ -0,0 +1,52 @@
+package fr.xephi.authme.command.executable.authme;
+
+import org.bukkit.Bukkit;
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+
+public class ForceLoginCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Get the player query
+ String playerName = sender.getName();
+ if(commandArguments.getCount() >= 1)
+ playerName = commandArguments.get(0);
+
+ // Command logic
+ try {
+ @SuppressWarnings("deprecation")
+ Player player = Bukkit.getPlayer(playerName);
+ if (player == null || !player.isOnline()) {
+ sender.sendMessage("Player needs to be online!");
+ return true;
+ }
+ if (!plugin.authmePermissible(player, "authme.canbeforced")) {
+ sender.sendMessage("You cannot force login for the player " + playerName + "!");
+ return true;
+ }
+ plugin.management.performLogin(player, "dontneed", true);
+ sender.sendMessage("Force Login for " + playerName + " performed!");
+ } catch (Exception e) {
+ sender.sendMessage("An error occurred while trying to get that player!");
+ }
+
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/GetEmailCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/GetEmailCommand.java
new file mode 100644
index 00000000..1ed99ff9
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/GetEmailCommand.java
@@ -0,0 +1,46 @@
+package fr.xephi.authme.command.executable.authme;
+
+import org.bukkit.command.CommandSender;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.cache.auth.PlayerAuth;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.settings.Messages;
+
+public class GetEmailCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ AuthMe plugin = AuthMe.getInstance();
+
+ // Messages instance
+ Messages m = Messages.getInstance();
+
+ // Get the player name
+ String playerName = sender.getName();
+ if(commandArguments.getCount() >= 1)
+ playerName = commandArguments.get(0);
+
+ // Get the authenticated user
+ PlayerAuth auth = plugin.database.getAuth(playerName.toLowerCase());
+ if (auth == null) {
+ m.send(sender, "unknown_user");
+ return true;
+ }
+
+ // Show the email address
+ sender.sendMessage("[AuthMe] " + playerName + "'s email: " + auth.getEmail());
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/GetIpCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/GetIpCommand.java
new file mode 100644
index 00000000..61a4c2b6
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/GetIpCommand.java
@@ -0,0 +1,42 @@
+package fr.xephi.authme.command.executable.authme;
+
+import org.bukkit.Bukkit;
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+
+public class GetIpCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Get the player query
+ String playerName = sender.getName();
+ if(commandArguments.getCount() >= 1)
+ playerName = commandArguments.get(0);
+
+ @SuppressWarnings("deprecation")
+ Player player = Bukkit.getPlayer(playerName);
+ if (player == null) {
+ sender.sendMessage("This player is not actually online");
+ return true;
+ }
+ sender.sendMessage(player.getName() + "'s actual IP is : " + player.getAddress().getAddress().getHostAddress() + ":" + player.getAddress().getPort());
+ sender.sendMessage(player.getName() + "'s real IP is : " + plugin.getIP(player));
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/LastLoginCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/LastLoginCommand.java
new file mode 100644
index 00000000..1cef6e56
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/LastLoginCommand.java
@@ -0,0 +1,69 @@
+package fr.xephi.authme.command.executable.authme;
+
+import java.util.Date;
+
+import org.bukkit.command.CommandSender;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.cache.auth.PlayerAuth;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.settings.Messages;
+
+public class LastLoginCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ AuthMe plugin = AuthMe.getInstance();
+
+ // Messages instance
+ Messages m = Messages.getInstance();
+
+ // Get the player
+ String playerName = sender.getName();
+ if(commandArguments.getCount() >= 1)
+ playerName = commandArguments.get(0);
+
+ // Validate the player
+ PlayerAuth auth;
+ try {
+ auth = plugin.database.getAuth(playerName.toLowerCase());
+ } catch (NullPointerException e) {
+ m.send(sender, "unknown_user");
+ return true;
+ }
+ if (auth == null) {
+ m.send(sender, "user_unknown");
+ return true;
+ }
+
+ // Get the last login date
+ long lastLogin = auth.getLastLogin();
+ Date date = new Date(lastLogin);
+
+ // Get the difference
+ final long diff = System.currentTimeMillis() - lastLogin;
+
+ // Build the message
+ final String msg = (int) (diff / 86400000) + " days " + (int) (diff / 3600000 % 24) + " hours " + (int) (diff / 60000 % 60) + " mins " + (int) (diff / 1000 % 60) + " secs.";
+
+ // Get the player's last IP
+ String lastIP = auth.getIp();
+
+ // Show the player status
+ sender.sendMessage("[AuthMe] " + playerName + " last login : " + date.toString());
+ sender.sendMessage("[AuthMe] The player " + auth.getNickname() + " is unlogged since " + msg);
+ sender.sendMessage("[AuthMe] Last Player's IP: " + lastIP);
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommand.java
new file mode 100644
index 00000000..ad966b44
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/PurgeBannedPlayersCommand.java
@@ -0,0 +1,51 @@
+package fr.xephi.authme.command.executable.authme;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.bukkit.OfflinePlayer;
+import org.bukkit.command.CommandSender;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.settings.Settings;
+
+public class PurgeBannedPlayersCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Get the list of banned players
+ List bannedPlayers = new ArrayList<>();
+ for (OfflinePlayer offlinePlayer : plugin.getServer().getBannedPlayers()) {
+ bannedPlayers.add(offlinePlayer.getName().toLowerCase());
+ }
+
+ // Purge the banned players
+ plugin.database.purgeBanned(bannedPlayers);
+ if (Settings.purgeEssentialsFile && plugin.ess != null)
+ plugin.dataManager.purgeEssentials(bannedPlayers);
+ if (Settings.purgePlayerDat)
+ plugin.dataManager.purgeDat(bannedPlayers);
+ if (Settings.purgeLimitedCreative)
+ plugin.dataManager.purgeLimitedCreative(bannedPlayers);
+ if (Settings.purgeAntiXray)
+ plugin.dataManager.purgeAntiXray(bannedPlayers);
+
+ // Show a status message
+ sender.sendMessage("[AuthMe] Database has been purged correctly");
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/PurgeCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/PurgeCommand.java
new file mode 100644
index 00000000..e2f855e6
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/PurgeCommand.java
@@ -0,0 +1,73 @@
+package fr.xephi.authme.command.executable.authme;
+
+import java.util.Calendar;
+import java.util.List;
+
+import org.bukkit.ChatColor;
+import org.bukkit.command.CommandSender;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.settings.Settings;
+
+public class PurgeCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ AuthMe plugin = AuthMe.getInstance();
+
+ // Get the days parameter
+ String daysStr = commandArguments.get(0);
+
+ // Convert the days string to an integer value, and make sure it's valid
+ int days;
+ try {
+ days = Integer.valueOf(daysStr);
+ } catch(Exception ex) {
+ sender.sendMessage(ChatColor.RED + "The value you've entered is invalid!");
+ return true;
+ }
+
+ // Validate the value
+ if(days < 30) {
+ sender.sendMessage(ChatColor.RED + "You can only purge data older than 30 days");
+ return true;
+ }
+
+ // Create a calender instance to determine the date
+ Calendar calendar = Calendar.getInstance();
+ calendar.add(Calendar.DATE, -days);
+ long until = calendar.getTimeInMillis();
+
+ // Purge the data, get the purged values
+ List purged = plugin.database.autoPurgeDatabase(until);
+
+ // Show a status message
+ sender.sendMessage(ChatColor.GOLD + "Deleted " + purged.size() + " user accounts");
+
+ // Purge other data
+ if(Settings.purgeEssentialsFile && plugin.ess != null)
+ plugin.dataManager.purgeEssentials(purged);
+ if(Settings.purgePlayerDat)
+ plugin.dataManager.purgeDat(purged);
+ if(Settings.purgeLimitedCreative)
+ plugin.dataManager.purgeLimitedCreative(purged);
+ if(Settings.purgeAntiXray)
+ plugin.dataManager.purgeAntiXray(purged);
+
+ // Show a status message
+ sender.sendMessage(ChatColor.GREEN + "[AuthMe] Database has been purged correctly");
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/PurgeLastPositionCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/PurgeLastPositionCommand.java
new file mode 100644
index 00000000..c7ea009b
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/PurgeLastPositionCommand.java
@@ -0,0 +1,65 @@
+package fr.xephi.authme.command.executable.authme;
+
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.cache.auth.PlayerAuth;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.settings.Messages;
+
+public class PurgeLastPositionCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(final CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Messages instance
+ final Messages m = Messages.getInstance();
+
+ // Get the player
+ String playerName = sender.getName();
+ if(commandArguments.getCount() >= 1)
+ playerName = commandArguments.get(0);
+ String playerNameLowerCase = playerName.toLowerCase();
+
+ // Purge the last position of the player
+ try {
+ // Get the user auth and make sure the user exists
+ PlayerAuth auth = plugin.database.getAuth(playerNameLowerCase);
+ if (auth == null) {
+ m.send(sender, "unknown_user");
+ return true;
+ }
+
+ // Set the last position
+ auth.setQuitLocX(0D);
+ auth.setQuitLocY(0D);
+ auth.setQuitLocZ(0D);
+ auth.setWorld("world");
+ plugin.database.updateQuitLoc(auth);
+
+ // Show a status message
+ sender.sendMessage(playerNameLowerCase + "'s last position location is now reset");
+
+ } catch (Exception e) {
+ ConsoleLogger.showError("An error occurred while trying to reset location or player do not exist, please see below: ");
+ ConsoleLogger.showError(e.getMessage());
+ if (sender instanceof Player)
+ sender.sendMessage("An error occurred while trying to reset location or player do not exist, please see logs");
+ }
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/RegisterCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/RegisterCommand.java
new file mode 100644
index 00000000..7a51fd3c
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/RegisterCommand.java
@@ -0,0 +1,93 @@
+package fr.xephi.authme.command.executable.authme;
+
+import java.security.NoSuchAlgorithmException;
+
+import org.bukkit.Bukkit;
+import org.bukkit.command.CommandSender;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.cache.auth.PlayerAuth;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.security.PasswordSecurity;
+import fr.xephi.authme.settings.Messages;
+import fr.xephi.authme.settings.Settings;
+
+public class RegisterCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(final CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Messages instance
+ final Messages m = Messages.getInstance();
+
+ // Get the player name and password
+ final String playerName = commandArguments.get(0);
+ final String playerPass = commandArguments.get(1);
+ final String playerNameLowerCase = playerName.toLowerCase();
+ final String playerPassLowerCase = playerPass.toLowerCase();
+
+ // Command logic
+ if (playerPassLowerCase.contains("delete") || playerPassLowerCase.contains("where") || playerPassLowerCase.contains("insert") || playerPassLowerCase.contains("modify") || playerPassLowerCase.contains("from") || playerPassLowerCase.contains("select") || playerPassLowerCase.contains(";") || playerPassLowerCase.contains("null") || !playerPassLowerCase.matches(Settings.getPassRegex)) {
+ m.send(sender, "password_error");
+ return true;
+ }
+ if (playerPassLowerCase.equalsIgnoreCase(playerName)) {
+ m.send(sender, "password_error_nick");
+ return true;
+ }
+ if (playerPassLowerCase.length() < Settings.getPasswordMinLen || playerPassLowerCase.length() > Settings.passwordMaxLength) {
+ m.send(sender, "pass_len");
+ return true;
+ }
+ if (!Settings.unsafePasswords.isEmpty()) {
+ if (Settings.unsafePasswords.contains(playerPassLowerCase)) {
+ m.send(sender, "password_error_unsafe");
+ return true;
+ }
+ }
+ plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
+ @SuppressWarnings("deprecation")
+ @Override
+ public void run() {
+ try {
+ if (plugin.database.isAuthAvailable(playerNameLowerCase)) {
+ m.send(sender, "user_regged");
+ return;
+ }
+ String hash = PasswordSecurity.getHash(Settings.getPasswordHash, playerPassLowerCase, playerNameLowerCase);
+ PlayerAuth auth = new PlayerAuth(playerNameLowerCase, hash, "192.168.0.1", 0L, "your@email.com", playerName);
+ if (PasswordSecurity.userSalt.containsKey(playerNameLowerCase) && PasswordSecurity.userSalt.get(playerNameLowerCase) != null)
+ auth.setSalt(PasswordSecurity.userSalt.get(playerNameLowerCase));
+ else auth.setSalt("");
+ if (!plugin.database.saveAuth(auth)) {
+ m.send(sender, "error");
+ return;
+ }
+ plugin.database.setUnlogged(playerNameLowerCase);
+ if (Bukkit.getPlayerExact(playerName) != null)
+ Bukkit.getPlayerExact(playerName).kickPlayer("An admin just registered you, please log again");
+ m.send(sender, "registered");
+ ConsoleLogger.info(playerNameLowerCase + " registered");
+ } catch (NoSuchAlgorithmException ex) {
+ ConsoleLogger.showError(ex.getMessage());
+ m.send(sender, "error");
+ }
+
+ }
+ });
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/ReloadCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/ReloadCommand.java
new file mode 100644
index 00000000..4cb450d0
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/ReloadCommand.java
@@ -0,0 +1,59 @@
+package fr.xephi.authme.command.executable.authme;
+
+//import org.bukkit.ChatColor;
+import org.bukkit.command.CommandSender;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.settings.Messages;
+import fr.xephi.authme.settings.Settings;
+import fr.xephi.authme.util.Profiler;
+
+public class ReloadCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // Profile the reload process
+ Profiler p = new Profiler(true);
+
+ // AuthMe plugin instance
+ AuthMe plugin = AuthMe.getInstance();
+
+ // Messages instance
+ Messages m = Messages.getInstance();
+
+ // Show a status message
+ // sender.sendMessage(ChatColor.YELLOW + "Reloading AuthMeReloaded...");
+
+ try {
+ Settings.reload();
+ plugin.getModuleManager().reloadModules();
+ Messages.getInstance().reloadMessages();
+ plugin.setupDatabase();
+ } catch (Exception e) {
+ ConsoleLogger.showError("Fatal error occurred! AuthMe instance ABORTED!");
+ ConsoleLogger.writeStackTrace(e);
+ plugin.stopOrUnload();
+ return false;
+ }
+
+ // Show a status message
+ // TODO: add the profiler result
+ m.send(sender, "reload");
+
+ // AuthMeReloaded reloaded, show a status message
+ // sender.sendMessage(ChatColor.GREEN + "AuthMeReloaded has been reloaded successfully, took " + p.getTimeFormatted() + "!");
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/ResetNameCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/ResetNameCommand.java
new file mode 100644
index 00000000..4715c00d
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/ResetNameCommand.java
@@ -0,0 +1,43 @@
+package fr.xephi.authme.command.executable.authme;
+
+import java.util.List;
+
+import org.bukkit.Bukkit;
+import org.bukkit.command.CommandSender;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.cache.auth.PlayerAuth;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+
+public class ResetNameCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Command logic
+ Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
+ @Override
+ public void run() {
+ List authentications = plugin.database.getAllAuths();
+ for(PlayerAuth auth : authentications) {
+ auth.setRealName("Player");
+ plugin.database.updateSession(auth);
+ }
+ }
+ });
+
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/SetEmailCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/SetEmailCommand.java
new file mode 100644
index 00000000..8011de24
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/SetEmailCommand.java
@@ -0,0 +1,64 @@
+package fr.xephi.authme.command.executable.authme;
+
+import org.bukkit.command.CommandSender;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.cache.auth.PlayerAuth;
+import fr.xephi.authme.cache.auth.PlayerCache;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.settings.Messages;
+import fr.xephi.authme.settings.Settings;
+
+public class SetEmailCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ AuthMe plugin = AuthMe.getInstance();
+
+ // Messages instance
+ Messages m = Messages.getInstance();
+
+ // Get the player name and email address
+ String playerName = commandArguments.get(0);
+ String playerEmail = commandArguments.get(1);
+
+ // Validate the email address
+ if (!Settings.isEmailCorrect(playerEmail)) {
+ m.send(sender, "email_invalid");
+ return true;
+ }
+
+ // Validate the user
+ PlayerAuth auth = plugin.database.getAuth(playerName.toLowerCase());
+ if (auth == null) {
+ m.send(sender, "unknown_user");
+ return true;
+ }
+
+ // Set the email address
+ auth.setEmail(playerEmail);
+ if (!plugin.database.updateEmail(auth)) {
+ m.send(sender, "error");
+ return true;
+ }
+
+ // Update the player cache
+ if (PlayerCache.getInstance().getAuth(playerName.toLowerCase()) != null)
+ PlayerCache.getInstance().updatePlayer(auth);
+
+ // Show a status message
+ m.send(sender, "email_changed");
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/SetFirstSpawnCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/SetFirstSpawnCommand.java
new file mode 100644
index 00000000..f8c469d7
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/SetFirstSpawnCommand.java
@@ -0,0 +1,37 @@
+package fr.xephi.authme.command.executable.authme;
+
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.settings.Spawn;
+
+public class SetFirstSpawnCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ try {
+ if (sender instanceof Player) {
+ if (Spawn.getInstance().setFirstSpawn(((Player) sender).getLocation()))
+ sender.sendMessage("[AuthMe] Correctly defined new first spawn point");
+ else sender.sendMessage("[AuthMe] SetFirstSpawn has failed, please retry");
+ } else {
+ sender.sendMessage("[AuthMe] Please use that command in game");
+ }
+ } catch (NullPointerException ex) {
+ ConsoleLogger.showError(ex.getMessage());
+ }
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/SetSpawnCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/SetSpawnCommand.java
new file mode 100644
index 00000000..7d65d666
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/SetSpawnCommand.java
@@ -0,0 +1,40 @@
+package fr.xephi.authme.command.executable.authme;
+
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.settings.Spawn;
+
+public class SetSpawnCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // Make sure the command executor is a player
+ try {
+ if (sender instanceof Player) {
+ if (Spawn.getInstance().setSpawn(((Player) sender).getLocation())) {
+ sender.sendMessage("[AuthMe] Correctly defined new spawn point");
+ } else {
+ sender.sendMessage("[AuthMe] SetSpawn has failed, please retry");
+ }
+ } else {
+ sender.sendMessage("[AuthMe] Please use that command in game");
+ }
+ } catch (NullPointerException ex) {
+ ConsoleLogger.showError(ex.getMessage());
+ }
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/SpawnCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/SpawnCommand.java
new file mode 100644
index 00000000..250e9d2f
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/SpawnCommand.java
@@ -0,0 +1,38 @@
+package fr.xephi.authme.command.executable.authme;
+
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.settings.Spawn;
+
+public class SpawnCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // Make sure the command executor is a player
+ try {
+ if (sender instanceof Player) {
+ if (Spawn.getInstance().getSpawn() != null)
+ ((Player) sender).teleport(Spawn.getInstance().getSpawn());
+ else sender.sendMessage("[AuthMe] Spawn has failed, please try to define the spawn");
+ } else {
+ sender.sendMessage("[AuthMe] Please use that command in game");
+ }
+ } catch (NullPointerException ex) {
+ ConsoleLogger.showError(ex.getMessage());
+ }
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/SwitchAntiBotCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/SwitchAntiBotCommand.java
new file mode 100644
index 00000000..a9e34662
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/SwitchAntiBotCommand.java
@@ -0,0 +1,57 @@
+package fr.xephi.authme.command.executable.authme;
+
+import org.bukkit.ChatColor;
+import org.bukkit.command.CommandSender;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.command.help.HelpProvider;
+
+public class SwitchAntiBotCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(final CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Get the new state
+ String newState = plugin.getAntiBotModMode() ? "OFF" : "ON";
+ if(commandArguments.getCount() >= 1)
+ newState = commandArguments.get(0);
+
+ // Enable the mod
+ if(newState.equalsIgnoreCase("ON")) {
+ plugin.switchAntiBotMod(true);
+ sender.sendMessage("[AuthMe] AntiBotMod enabled");
+ return true;
+ }
+
+ // Disable the mod
+ if(newState.equalsIgnoreCase("OFF")) {
+ plugin.switchAntiBotMod(false);
+ sender.sendMessage("[AuthMe] AntiBotMod disabled");
+ return true;
+ }
+
+ // Show the invalid arguments warning
+ sender.sendMessage(ChatColor.DARK_RED + "Invalid AntiBot mode!");
+
+ // Show the command argument help
+ HelpProvider.showHelp(sender, commandReference, commandReference, true, false, true, false, false, false);
+
+ // Show the command to use for detailed help
+ CommandParts helpCommandReference = new CommandParts(commandReference.getRange(1));
+ sender.sendMessage(ChatColor.GOLD + "Detailed help: " + ChatColor.WHITE + "/" + commandReference.get(0) + " help " + helpCommandReference);
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterCommand.java
new file mode 100644
index 00000000..3ff3ed3f
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/UnregisterCommand.java
@@ -0,0 +1,88 @@
+package fr.xephi.authme.command.executable.authme;
+
+import org.bukkit.Bukkit;
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+import org.bukkit.potion.PotionEffect;
+import org.bukkit.potion.PotionEffectType;
+import org.bukkit.scheduler.BukkitScheduler;
+import org.bukkit.scheduler.BukkitTask;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.cache.auth.PlayerCache;
+import fr.xephi.authme.cache.limbo.LimboCache;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.settings.Messages;
+import fr.xephi.authme.settings.Settings;
+import fr.xephi.authme.task.MessageTask;
+import fr.xephi.authme.task.TimeoutTask;
+import fr.xephi.authme.util.Utils;
+
+public class UnregisterCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(final CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Messages instance
+ final Messages m = Messages.getInstance();
+
+ // Get the player name
+ String playerName = commandArguments.get(0);
+ String playerNameLowerCase = playerName.toLowerCase();
+
+ // Make sure the user is valid
+ if (!plugin.database.isAuthAvailable(playerNameLowerCase)) {
+ m.send(sender, "user_unknown");
+ return true;
+ }
+
+ // Remove the player
+ if (!plugin.database.removeAuth(playerNameLowerCase)) {
+ m.send(sender, "error");
+ return true;
+ }
+
+ // Unregister the player
+ @SuppressWarnings("deprecation")
+ Player target = Bukkit.getPlayer(playerNameLowerCase);
+ PlayerCache.getInstance().removePlayer(playerNameLowerCase);
+ Utils.setGroup(target, Utils.GroupType.UNREGISTERED);
+ if (target != null && target.isOnline()) {
+ Utils.teleportToSpawn(target);
+ LimboCache.getInstance().addLimboPlayer(target);
+ int delay = Settings.getRegistrationTimeout * 20;
+ int interval = Settings.getWarnMessageInterval;
+ BukkitScheduler scheduler = sender.getServer().getScheduler();
+ if (delay != 0) {
+ BukkitTask id = scheduler.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, playerNameLowerCase, target), delay);
+ LimboCache.getInstance().getLimboPlayer(playerNameLowerCase).setTimeoutTaskId(id);
+ }
+ LimboCache.getInstance().getLimboPlayer(playerNameLowerCase).setMessageTaskId(scheduler.runTaskAsynchronously(plugin, new MessageTask(plugin, playerNameLowerCase, m.send("reg_msg"), interval)));
+ if (Settings.applyBlindEffect)
+ target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
+ if (!Settings.isMovementAllowed && Settings.isRemoveSpeedEnabled) {
+ target.setWalkSpeed(0.0f);
+ target.setFlySpeed(0.0f);
+ }
+ m.send(target, "unregistered");
+
+ }
+
+ // Show a status message
+ m.send(sender, "unregistered");
+ ConsoleLogger.info(playerName + " unregistered");
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/authme/VersionCommand.java b/src/main/java/fr/xephi/authme/command/executable/authme/VersionCommand.java
new file mode 100644
index 00000000..45e1e3df
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/authme/VersionCommand.java
@@ -0,0 +1,82 @@
+package fr.xephi.authme.command.executable.authme;
+
+import org.bukkit.Bukkit;
+import org.bukkit.ChatColor;
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+
+public class VersionCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // Show some version info
+ sender.sendMessage(ChatColor.GOLD + "==========[ " + AuthMe.PLUGIN_NAME.toUpperCase() + " ABOUT ]==========");
+ sender.sendMessage(ChatColor.GOLD + "Version: " + ChatColor.WHITE + AuthMe.PLUGIN_NAME + " v" + AuthMe.getVersionName() + ChatColor.GRAY + " (code: " + AuthMe.getVersionCode() + ")");
+ sender.sendMessage(ChatColor.GOLD + "Developers:");
+ printDeveloper(sender, "Xephi", "xephi59", "Lead Developer");
+ printDeveloper(sender, "DNx5", "DNx5", "Developer");
+ printDeveloper(sender, "games647", "games647", "Developer");
+ printDeveloper(sender, "Tim Visee", "timvisee", "Developer");
+ printDeveloper(sender, "Sgdc3", "sgdc3", "Project manager, Contributor");
+ sender.sendMessage(ChatColor.GOLD + "Website: " + ChatColor.WHITE + "http://dev.bukkit.org/bukkit-plugins/authme-reloaded/");
+ sender.sendMessage(ChatColor.GOLD + "License: " + ChatColor.WHITE + "GNU GPL v3.0" + ChatColor.GRAY + ChatColor.ITALIC + " (See LICENSE file)");
+ sender.sendMessage(ChatColor.GOLD + "Copyright: " + ChatColor.WHITE + "Copyright (c) Xephi 2015. All rights reserved.");
+ return true;
+ }
+
+ /**
+ * Print a developer with proper styling.
+ *
+ * @param sender The command sender.
+ * @param name The display name of the developer.
+ * @param minecraftName The Minecraft username of the developer, if available.
+ * @param function The function of the developer.
+ */
+ @SuppressWarnings("StringConcatenationInsideStringBufferAppend")
+ private void printDeveloper(CommandSender sender, String name, String minecraftName, String function) {
+ // Print the name
+ StringBuilder msg = new StringBuilder();
+ msg.append(" " + ChatColor.WHITE);
+ msg.append(name);
+
+ // Append the Minecraft name, if available
+ if(minecraftName.length() != 0)
+ msg.append(ChatColor.GRAY + " // " + ChatColor.WHITE + minecraftName);
+ msg.append(ChatColor.GRAY + "" + ChatColor.ITALIC + " (" + function + ")");
+
+ // Show the online status
+ if(minecraftName.length() != 0)
+ if(isPlayerOnline(minecraftName))
+ msg.append(ChatColor.GREEN + "" + ChatColor.ITALIC + " (In-Game)");
+
+ // Print the message
+ sender.sendMessage(msg.toString());
+ }
+
+ /**
+ * Check whether a player is online.
+ *
+ * @param minecraftName The Minecraft player name.
+ *
+ * @return True if the player is online, false otherwise.
+ */
+ private boolean isPlayerOnline(String minecraftName) {
+ for(Player player : Bukkit.getOnlinePlayers())
+ if(player.getName().equalsIgnoreCase(minecraftName))
+ return true;
+ return false;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/captcha/CaptchaCommand.java b/src/main/java/fr/xephi/authme/command/executable/captcha/CaptchaCommand.java
new file mode 100644
index 00000000..81f4c50f
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/captcha/CaptchaCommand.java
@@ -0,0 +1,83 @@
+package fr.xephi.authme.command.executable.captcha;
+
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.cache.auth.PlayerCache;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.security.RandomString;
+import fr.xephi.authme.settings.Messages;
+import fr.xephi.authme.settings.Settings;
+
+public class CaptchaCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Messages instance
+ final Messages m = Messages.getInstance();
+
+ // Random string instance, for captcha generation (I think) -- timvisee
+ RandomString randStr = new RandomString(Settings.captchaLength);
+
+ // Get the parameter values
+ String captcha = commandArguments.get(0);
+
+ // Make sure the current command executor is a player
+ if(!(sender instanceof Player)) {
+ return true;
+ }
+
+ // Get the player instance and name
+ final Player player = (Player) sender;
+ final String playerNameLowerCase = player.getName().toLowerCase();
+
+ // Command logic
+ if (PlayerCache.getInstance().isAuthenticated(playerNameLowerCase)) {
+ m.send(player, "logged_in");
+ return true;
+ }
+
+ if (!Settings.useCaptcha) {
+ m.send(player, "usage_log");
+ return true;
+ }
+
+ if (!plugin.cap.containsKey(playerNameLowerCase)) {
+ m.send(player, "usage_log");
+ return true;
+ }
+
+ if (Settings.useCaptcha && !captcha.equals(plugin.cap.get(playerNameLowerCase))) {
+ plugin.cap.remove(playerNameLowerCase);
+ plugin.cap.put(playerNameLowerCase, randStr.nextString());
+ for (String s : m.send("wrong_captcha")) {
+ player.sendMessage(s.replace("THE_CAPTCHA", plugin.cap.get(playerNameLowerCase)));
+ }
+ return true;
+ }
+
+ try {
+ plugin.captcha.remove(playerNameLowerCase);
+ plugin.cap.remove(playerNameLowerCase);
+ } catch (NullPointerException ignored) { }
+
+ // Show a status message
+ m.send(player, "valid_captcha");
+ m.send(player, "login_msg");
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommand.java b/src/main/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommand.java
new file mode 100644
index 00000000..20649792
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/changepassword/ChangePasswordCommand.java
@@ -0,0 +1,75 @@
+package fr.xephi.authme.command.executable.changepassword;
+
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.cache.auth.PlayerCache;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.settings.Messages;
+import fr.xephi.authme.settings.Settings;
+import fr.xephi.authme.task.ChangePasswordTask;
+
+public class ChangePasswordCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Messages instance
+ final Messages m = Messages.getInstance();
+
+ // Get the passwords
+ String playerPass = commandArguments.get(0);
+ String playerPassVerify = commandArguments.get(1);
+
+ // Make sure the current command executor is a player
+ if(!(sender instanceof Player)) {
+ return true;
+ }
+
+ // Get the player instance and make sure it's authenticated
+ Player player = (Player) sender;
+ String name = player.getName().toLowerCase();
+ if (!PlayerCache.getInstance().isAuthenticated(name)) {
+ m.send(player, "not_logged_in");
+ return true;
+ }
+
+ // Make sure the password is allowed
+ String playerPassLowerCase = playerPass.toLowerCase();
+ if (playerPassLowerCase.contains("delete") || playerPassLowerCase.contains("where") || playerPassLowerCase.contains("insert") || playerPassLowerCase.contains("modify") || playerPassLowerCase.contains("from") || playerPassLowerCase.contains("select") || playerPassLowerCase.contains(";") || playerPassLowerCase.contains("null") || !playerPassLowerCase.matches(Settings.getPassRegex)) {
+ m.send(player, "password_error");
+ return true;
+ }
+ if (playerPassLowerCase.equalsIgnoreCase(name)) {
+ m.send(player, "password_error_nick");
+ return true;
+ }
+ if (playerPassLowerCase.length() < Settings.getPasswordMinLen || playerPassLowerCase.length() > Settings.passwordMaxLength) {
+ m.send(player, "pass_len");
+ return true;
+ }
+ if (!Settings.unsafePasswords.isEmpty()) {
+ if (Settings.unsafePasswords.contains(playerPassLowerCase)) {
+ m.send(player, "password_error_unsafe");
+ return true;
+ }
+ }
+
+ // Set the password
+ plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new ChangePasswordTask(plugin, player, playerPass, playerPassVerify));
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/converter/ConverterCommand.java b/src/main/java/fr/xephi/authme/command/executable/converter/ConverterCommand.java
new file mode 100644
index 00000000..a593dc3a
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/converter/ConverterCommand.java
@@ -0,0 +1,116 @@
+package fr.xephi.authme.command.executable.converter;
+
+import org.bukkit.Bukkit;
+import org.bukkit.command.CommandSender;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.converter.Converter;
+import fr.xephi.authme.converter.CrazyLoginConverter;
+import fr.xephi.authme.converter.FlatToSql;
+import fr.xephi.authme.converter.FlatToSqlite;
+import fr.xephi.authme.converter.RakamakConverter;
+import fr.xephi.authme.converter.RoyalAuthConverter;
+import fr.xephi.authme.converter.SqlToFlat;
+import fr.xephi.authme.converter.vAuthConverter;
+import fr.xephi.authme.converter.xAuthConverter;
+import fr.xephi.authme.settings.Messages;
+
+public class ConverterCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Messages instance
+ final Messages m = Messages.getInstance();
+
+ // Get the conversion job
+ String job = commandArguments.get(0);
+
+ // Determine the job type
+ ConvertType jobType = ConvertType.fromName(job);
+ if (jobType == null) {
+ m.send(sender, "error");
+ return true;
+ }
+
+ // Get the proper converter instance
+ Converter converter = null;
+ switch (jobType) {
+ case ftsql:
+ converter = new FlatToSql();
+ break;
+ case ftsqlite:
+ converter = new FlatToSqlite(sender);
+ break;
+ case xauth:
+ converter = new xAuthConverter(plugin, sender);
+ break;
+ case crazylogin:
+ converter = new CrazyLoginConverter(plugin, sender);
+ break;
+ case rakamak:
+ converter = new RakamakConverter(plugin, sender);
+ break;
+ case royalauth:
+ converter = new RoyalAuthConverter(plugin);
+ break;
+ case vauth:
+ converter = new vAuthConverter(plugin, sender);
+ break;
+ case sqltoflat:
+ converter = new SqlToFlat(plugin, sender);
+ break;
+ default:
+ break;
+ }
+
+ // Run the convert job
+ Bukkit.getScheduler().runTaskAsynchronously(plugin, converter);
+
+ // Show a status message
+ sender.sendMessage("[AuthMe] Successfully converted from " + jobType.getName());
+ return true;
+ }
+
+ public enum ConvertType {
+ ftsql("flattosql"),
+ ftsqlite("flattosqlite"),
+ xauth("xauth"),
+ crazylogin("crazylogin"),
+ rakamak("rakamak"),
+ royalauth("royalauth"),
+ vauth("vauth"),
+ sqltoflat("sqltoflat");
+
+ String name;
+
+ ConvertType(String name) {
+ this.name = name;
+ }
+
+ String getName() {
+ return this.name;
+ }
+
+ public static ConvertType fromName(String name) {
+ for (ConvertType type : ConvertType.values()) {
+ if (type.getName().equalsIgnoreCase(name))
+ return type;
+ }
+ return null;
+ }
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/email/AddEmailCommand.java b/src/main/java/fr/xephi/authme/command/executable/email/AddEmailCommand.java
new file mode 100644
index 00000000..c9d38cdc
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/email/AddEmailCommand.java
@@ -0,0 +1,46 @@
+package fr.xephi.authme.command.executable.email;
+
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.settings.Messages;
+
+public class AddEmailCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Messages instance
+ final Messages m = Messages.getInstance();
+
+ // Get the parameter values
+ String playerMail = commandArguments.get(0);
+ String playerMailVerify = commandArguments.get(1);
+
+ // Make sure the current command executor is a player
+ if (!(sender instanceof Player)) {
+ return true;
+ }
+
+ // Get the player instance and name
+ final Player player = (Player) sender;
+ final String playerName = player.getName().toLowerCase();
+
+ // Command logic
+ plugin.management.performAddEmail(player, playerMail, playerMailVerify);
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/email/ChangeEmailCommand.java b/src/main/java/fr/xephi/authme/command/executable/email/ChangeEmailCommand.java
new file mode 100644
index 00000000..d02fdb9a
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/email/ChangeEmailCommand.java
@@ -0,0 +1,46 @@
+package fr.xephi.authme.command.executable.email;
+
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.settings.Messages;
+
+public class ChangeEmailCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Messages instance
+ final Messages m = Messages.getInstance();
+
+ // Get the parameter values
+ String playerMailOld = commandArguments.get(0);
+ String playerMailNew = commandArguments.get(1);
+
+ // Make sure the current command executor is a player
+ if (!(sender instanceof Player)) {
+ return true;
+ }
+
+ // Get the player instance and name
+ final Player player = (Player) sender;
+ final String playerName = player.getName();
+
+ // Command logic
+ plugin.management.performChangeEmail(player, playerMailOld, playerMailNew);
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/email/RecoverEmailCommand.java b/src/main/java/fr/xephi/authme/command/executable/email/RecoverEmailCommand.java
new file mode 100644
index 00000000..26e74165
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/email/RecoverEmailCommand.java
@@ -0,0 +1,97 @@
+package fr.xephi.authme.command.executable.email;
+
+import java.security.NoSuchAlgorithmException;
+
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.ConsoleLogger;
+import fr.xephi.authme.cache.auth.PlayerAuth;
+import fr.xephi.authme.cache.auth.PlayerCache;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.security.PasswordSecurity;
+import fr.xephi.authme.security.RandomString;
+import fr.xephi.authme.settings.Messages;
+import fr.xephi.authme.settings.Settings;
+
+public class RecoverEmailCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Messages instance
+ final Messages m = Messages.getInstance();
+
+ // Get the parameter values
+ String playerMail = commandArguments.get(0);
+
+ // Make sure the current command executor is a player
+ if(!(sender instanceof Player)) {
+ return true;
+ }
+
+ // Get the player instance and name
+ final Player player = (Player) sender;
+ final String playerName = player.getName();
+
+ // Command logic
+ if (plugin.mail == null) {
+ m.send(player, "error");
+ return true;
+ }
+ if (plugin.database.isAuthAvailable(playerName)) {
+ if (PlayerCache.getInstance().isAuthenticated(playerName)) {
+ m.send(player, "logged_in");
+ return true;
+ }
+ try {
+ RandomString rand = new RandomString(Settings.getRecoveryPassLength);
+ String thePass = rand.nextString();
+ String hashNew = PasswordSecurity.getHash(Settings.getPasswordHash, thePass, playerName);
+ PlayerAuth auth;
+ if (PlayerCache.getInstance().isAuthenticated(playerName)) {
+ auth = PlayerCache.getInstance().getAuth(playerName);
+ } else if (plugin.database.isAuthAvailable(playerName)) {
+ auth = plugin.database.getAuth(playerName);
+ } else {
+ m.send(player, "unknown_user");
+ return true;
+ }
+ if (Settings.getmailAccount.equals("") || Settings.getmailAccount.isEmpty()) {
+ m.send(player, "error");
+ return true;
+ }
+
+ if (!playerMail.equalsIgnoreCase(auth.getEmail()) || playerMail.equalsIgnoreCase("your@email.com") || auth.getEmail().equalsIgnoreCase("your@email.com")) {
+ m.send(player, "email_invalid");
+ return true;
+ }
+ auth.setHash(hashNew);
+ plugin.database.updatePassword(auth);
+ plugin.mail.main(auth, thePass);
+ m.send(player, "email_send");
+ } catch (NoSuchAlgorithmException | NoClassDefFoundError ex) {
+ ex.printStackTrace();
+ ConsoleLogger.showError(ex.getMessage());
+ m.send(sender, "error");
+ }
+ } else {
+ m.send(player, "reg_email_msg");
+ }
+
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/login/LoginCommand.java b/src/main/java/fr/xephi/authme/command/executable/login/LoginCommand.java
new file mode 100644
index 00000000..edb34910
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/login/LoginCommand.java
@@ -0,0 +1,41 @@
+package fr.xephi.authme.command.executable.login;
+
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+
+public class LoginCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Make sure the current command executor is a player
+ if(!(sender instanceof Player)) {
+ return true;
+ }
+
+ // Get the player instance
+ final Player player = (Player) sender;
+
+ // Get the password
+ String playerPass = commandArguments.get(0);
+
+ // Login the player
+ plugin.management.performLogin(player, playerPass, false);
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/logout/LogoutCommand.java b/src/main/java/fr/xephi/authme/command/executable/logout/LogoutCommand.java
new file mode 100644
index 00000000..0dfcbaf4
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/logout/LogoutCommand.java
@@ -0,0 +1,38 @@
+package fr.xephi.authme.command.executable.logout;
+
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+
+public class LogoutCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Make sure the current command executor is a player
+ if(!(sender instanceof Player)) {
+ return true;
+ }
+
+ // Get the player instance
+ final Player player = (Player) sender;
+
+ // Logout the player
+ plugin.management.performLogout(player);
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/register/RegisterCommand.java b/src/main/java/fr/xephi/authme/command/executable/register/RegisterCommand.java
new file mode 100644
index 00000000..45e3c470
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/register/RegisterCommand.java
@@ -0,0 +1,70 @@
+package fr.xephi.authme.command.executable.register;
+
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.security.RandomString;
+import fr.xephi.authme.settings.Messages;
+import fr.xephi.authme.settings.Settings;
+
+public class RegisterCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Messages instance
+ final Messages m = Messages.getInstance();
+
+ // Make sure the sender is a player
+ if (!(sender instanceof Player)) {
+ sender.sendMessage("Player Only! Use 'authme register ' instead");
+ return true;
+ }
+
+ // Make sure the command arguments are valid
+ final Player player = (Player) sender;
+ if (commandArguments.getCount() == 0 || (Settings.getEnablePasswordVerifier && commandArguments.getCount() < 2)) {
+ m.send(player, "usage_reg");
+ return true;
+ }
+
+ if (Settings.emailRegistration && !Settings.getmailAccount.isEmpty()) {
+ if (Settings.doubleEmailCheck) {
+ if (commandArguments.getCount() < 2 || !commandArguments.get(0).equals(commandArguments.get(1))) {
+ m.send(player, "usage_reg");
+ return true;
+ }
+ }
+ final String email = commandArguments.get(0);
+ if (!Settings.isEmailCorrect(email)) {
+ m.send(player, "email_invalid");
+ return true;
+ }
+ RandomString rand = new RandomString(Settings.getRecoveryPassLength);
+ final String thePass = rand.nextString();
+ plugin.management.performRegister(player, thePass, email);
+ return true;
+ }
+ if (commandArguments.getCount() > 1 && Settings.getEnablePasswordVerifier)
+ if (!commandArguments.get(0).equals(commandArguments.get(1))) {
+ m.send(player, "password_error");
+ return true;
+ }
+ plugin.management.performRegister(player, commandArguments.get(0), "");
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/executable/unregister/UnregisterCommand.java b/src/main/java/fr/xephi/authme/command/executable/unregister/UnregisterCommand.java
new file mode 100644
index 00000000..66af5abc
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/executable/unregister/UnregisterCommand.java
@@ -0,0 +1,53 @@
+package fr.xephi.authme.command.executable.unregister;
+
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.cache.auth.PlayerCache;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.ExecutableCommand;
+import fr.xephi.authme.settings.Messages;
+
+public class UnregisterCommand extends ExecutableCommand {
+
+ /**
+ * Execute the command.
+ *
+ * @param sender The command sender.
+ * @param commandReference The command reference.
+ * @param commandArguments The command arguments.
+ *
+ * @return True if the command was executed successfully, false otherwise.
+ */
+ @Override
+ public boolean executeCommand(CommandSender sender, CommandParts commandReference, CommandParts commandArguments) {
+ // AuthMe plugin instance
+ final AuthMe plugin = AuthMe.getInstance();
+
+ // Messages instance
+ final Messages m = Messages.getInstance();
+
+ // Make sure the current command executor is a player
+ if(!(sender instanceof Player)) {
+ return true;
+ }
+
+ // Get the password
+ String playerPass = commandArguments.get(0);
+
+ // Get the player instance and name
+ final Player player = (Player) sender;
+ final String playerNameLowerCase = player.getName().toLowerCase();
+
+ // Make sure the player is authenticated
+ if (!PlayerCache.getInstance().isAuthenticated(playerNameLowerCase)) {
+ m.send(player, "not_logged_in");
+ return true;
+ }
+
+ // Unregister the player
+ plugin.management.performUnregister(player, playerPass, false);
+ return true;
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/help/HelpPrinter.java b/src/main/java/fr/xephi/authme/command/help/HelpPrinter.java
new file mode 100644
index 00000000..4f28eb29
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/help/HelpPrinter.java
@@ -0,0 +1,196 @@
+package fr.xephi.authme.command.help;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+import org.bukkit.ChatColor;
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.command.CommandArgumentDescription;
+import fr.xephi.authme.command.CommandDescription;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.CommandPermissions;
+import fr.xephi.authme.util.StringUtils;
+
+public class HelpPrinter {
+
+ /**
+ * Print the command help information.
+ *
+ * @param sender The command sender to print the help to.
+ * @param command The command to print.
+ * @param commandReference The command reference used.
+ */
+ public static void printCommand(CommandSender sender, CommandDescription command, CommandParts commandReference) {
+ // Print the proper command syntax
+ sender.sendMessage(ChatColor.GOLD + "Command: " + HelpSyntaxHelper.getCommandSyntax(command, commandReference, null, true));
+ }
+
+ /**
+ * Print the command help description information. This will print both the short, as the detailed description if available.
+ *
+ * @param sender The command sender to print the help to.
+ * @param command The command to print the description help for.
+ */
+ public static void printCommandDescription(CommandSender sender, CommandDescription command) {
+ // Print the regular description, if available
+ if(command.hasDescription())
+ sender.sendMessage(ChatColor.GOLD + "Short Description: " + ChatColor.WHITE + command.getDescription());
+
+ // Print the detailed description, if available
+ if(command.hasDetailedDescription()) {
+ sender.sendMessage(ChatColor.GOLD + "Detailed Description:");
+ sender.sendMessage(ChatColor.WHITE + " " + command.getDetailedDescription());
+ }
+ }
+
+ /**
+ * Print the command help arguments information if available.
+ *
+ * @param sender The command sender to print the help to.
+ * @param command The command to print the argument help for.
+ */
+ @SuppressWarnings("StringConcatenationInsideStringBufferAppend")
+ public static void printArguments(CommandSender sender, CommandDescription command) {
+ // Make sure there are any commands to print
+ if(!command.hasArguments() && command.getMaximumArguments() >= 0)
+ return;
+
+ // Print the header
+ sender.sendMessage(ChatColor.GOLD + "Arguments:");
+
+ // Print each argument
+ for(CommandArgumentDescription arg : command.getArguments()) {
+ // Create a string builder to build the syntax in
+ StringBuilder argString = new StringBuilder();
+ argString.append(" " + ChatColor.YELLOW + ChatColor.ITALIC + arg.getLabel() + " : " + ChatColor.WHITE + arg.getDescription());
+
+ // Suffix a note if the command is optional
+ if(arg.isOptional())
+ argString.append(ChatColor.GRAY + "" + ChatColor.ITALIC + " (Optional)");
+
+ // Print the syntax
+ sender.sendMessage(argString.toString());
+ }
+
+ // Show the unlimited arguments argument
+ if(command.getMaximumArguments() < 0)
+ sender.sendMessage(" " + ChatColor.YELLOW + ChatColor.ITALIC + "... : " + ChatColor.WHITE + "Any additional arguments." + ChatColor.GRAY + ChatColor.ITALIC + " (Optional)");
+ }
+
+ /**
+ * Print the command help permissions information if available.
+ *
+ * @param sender The command sender to print the help to.
+ * @param command The command to print the permissions help for.
+ */
+ public static void printPermissions(CommandSender sender, CommandDescription command) {
+ // Get the permissions and make sure it isn't null
+ CommandPermissions permissions = command.getCommandPermissions();
+ if(permissions == null)
+ return;
+
+ // Make sure any permission node is set
+ if(permissions.getPermissionNodeCount() <= 0)
+ return;
+
+ // Print the header
+ sender.sendMessage(ChatColor.GOLD + "Permissions:");
+
+ // Print each node
+ for(String node : permissions.getPermissionNodes()) {
+ boolean nodePermission = true;
+ if(sender instanceof Player)
+ nodePermission = AuthMe.getInstance().authmePermissible((Player) sender, node);
+ final String nodePermsString = ChatColor.GRAY + (nodePermission ? ChatColor.ITALIC + " (Permission!)" : ChatColor.ITALIC + " (No Permission!)");
+ sender.sendMessage(" " + ChatColor.YELLOW + ChatColor.ITALIC + node + nodePermsString);
+ }
+
+ // Print the default permission
+ switch(permissions.getDefaultPermission()) {
+ case ALLOWED:
+ sender.sendMessage(ChatColor.GOLD + " Default: " + ChatColor.GRAY + ChatColor.ITALIC + "Permission!");
+ break;
+
+ case OP_ONLY:
+ final String defaultPermsString = ChatColor.GRAY + (permissions.getDefaultPermissionCommandSender(sender) ? ChatColor.ITALIC + " (Permission!)" : ChatColor.ITALIC + " (No Permission!)");
+ sender.sendMessage(ChatColor.GOLD + " Default: " + ChatColor.YELLOW + ChatColor.ITALIC + "OP's Only!" + defaultPermsString);
+ break;
+
+ case NOT_ALLOWED:
+ default:
+ sender.sendMessage(ChatColor.GOLD + " Default: " + ChatColor.GRAY + ChatColor.ITALIC + "No Permission!");
+ break;
+ }
+
+ // Print the permission result
+ if(permissions.hasPermission(sender))
+ sender.sendMessage(ChatColor.GOLD + " Result: " + ChatColor.GREEN + ChatColor.ITALIC + "Permission!");
+ else
+ sender.sendMessage(ChatColor.GOLD + " Result: " + ChatColor.DARK_RED + ChatColor.ITALIC + "No Permission!");
+ }
+
+ /**
+ * Print the command help alternatives information if available.
+ *
+ * @param sender The command sender to print the help to.
+ * @param command The command used.
+ * @param commandReference The original command reference used for this command.
+ */
+ public static void printAlternatives(CommandSender sender, CommandDescription command, CommandParts commandReference) {
+ // Make sure there are any alternatives
+ if(command.getLabels().size() <= 1)
+ return;
+
+ // Print the header
+ sender.sendMessage(ChatColor.GOLD + "Alternatives:");
+
+ // Get the label used
+ final String usedLabel = commandReference.get(command.getParentCount());
+
+ // Create a list of alternatives
+ List alternatives = new ArrayList<>();
+ for(String entry : command.getLabels()) {
+ // Exclude the proper argument
+ if(entry.equalsIgnoreCase(usedLabel))
+ continue;
+ alternatives.add(entry);
+ }
+
+ // Sort the alternatives
+ Collections.sort(alternatives, new Comparator() {
+ @Override
+ public int compare(String o1, String o2) {
+ return Double.compare(StringUtils.getDifference(usedLabel, o1), StringUtils.getDifference(usedLabel, o2));
+ }
+ });
+
+ // Print each alternative with proper syntax
+ for(String alternative : alternatives)
+ sender.sendMessage(" " + HelpSyntaxHelper.getCommandSyntax(command, commandReference, alternative, true));
+ }
+
+ /**
+ * Print the command help child's information if available.
+ *
+ * @param sender The command sender to print the help to.
+ * @param command The command to print the help for.
+ * @param commandReference The original command reference used for this command.
+ */
+ public static void printChildren(CommandSender sender, CommandDescription command, CommandParts commandReference) {
+ // Make sure there are child's
+ if(command.getChildren().size() <= 0)
+ return;
+
+ // Print the header
+ sender.sendMessage(ChatColor.GOLD + "Commands:");
+
+ // Loop through each child
+ for(CommandDescription child : command.getChildren())
+ sender.sendMessage(" " + HelpSyntaxHelper.getCommandSyntax(child, commandReference, null, false) + ChatColor.GRAY + ChatColor.ITALIC + " : " + child.getDescription());
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/help/HelpProvider.java b/src/main/java/fr/xephi/authme/command/help/HelpProvider.java
new file mode 100644
index 00000000..4cf27c6d
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/help/HelpProvider.java
@@ -0,0 +1,117 @@
+package fr.xephi.authme.command.help;
+
+import org.bukkit.ChatColor;
+import org.bukkit.command.CommandSender;
+
+import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.command.CommandDescription;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.command.FoundCommandResult;
+
+public class HelpProvider {
+
+ /**
+ * Show help for a specific command.
+ *
+ * @param sender The command sender the help needs to be shown to.
+ * @param reference The command reference to the help command.
+ * @param helpQuery The query to show help for.
+ */
+ public static void showHelp(CommandSender sender, CommandParts reference, CommandParts helpQuery) {
+ showHelp(sender, reference, helpQuery, true, true, true, true, true, true);
+ }
+
+ /**
+ * Show help for a specific command.
+ *
+ * @param sender The command sender the help needs to be shown to.
+ * @param reference The command reference to the help command.
+ * @param helpQuery The query to show help for.
+ * @param showCommand True to show the command.
+ * @param showDescription True to show the command description, both the short and detailed description.
+ * @param showArguments True to show the command argument help.
+ * @param showPermissions True to show the command permission help.
+ * @param showAlternatives True to show the command alternatives.
+ * @param showCommands True to show the child commands.
+ */
+ public static void showHelp(CommandSender sender, CommandParts reference, CommandParts helpQuery, boolean showCommand, boolean showDescription, boolean showArguments, boolean showPermissions, boolean showAlternatives, boolean showCommands) {
+ // Find the command for this help query, one with and one without a prefixed base command
+ FoundCommandResult result = AuthMe.getInstance().getCommandHandler().getCommandManager().findCommand(new CommandParts(helpQuery.getList()));
+ CommandParts commandReferenceOther = new CommandParts(reference.get(0), helpQuery.getList());
+ FoundCommandResult resultOther = AuthMe.getInstance().getCommandHandler().getCommandManager().findCommand(commandReferenceOther);
+ if(resultOther != null) {
+ if(result == null)
+ result = resultOther;
+
+ else if(result.getDifference() > resultOther.getDifference())
+ result = resultOther;
+ }
+
+ // Make sure a result was found
+ if(result == null) {
+ // Show a warning message
+ sender.sendMessage(ChatColor.DARK_RED + "" + ChatColor.ITALIC + helpQuery);
+ sender.sendMessage(ChatColor.DARK_RED + "Couldn't show any help information for this help query.");
+ return;
+ }
+
+ // Get the command description, and make sure it's valid
+ CommandDescription command = result.getCommandDescription();
+ if(command == null) {
+ // Show a warning message
+ sender.sendMessage(ChatColor.DARK_RED + "Failed to retrieve any help information!");
+ return;
+ }
+
+ // Get the proper command reference to use for the help page
+ CommandParts commandReference = command.getCommandReference(result.getQueryReference());
+
+ // Get the base command
+ String baseCommand = commandReference.get(0);
+
+ // Make sure the difference between the command reference and the actual command isn't too big
+ final double commandDifference = result.getDifference();
+ if(commandDifference > 0.20) {
+ // Show the unknown command warning
+ sender.sendMessage(ChatColor.DARK_RED + "No help found for '" + helpQuery + "'!");
+
+ // Get the suggested command
+ CommandParts suggestedCommandParts = new CommandParts(result.getCommandDescription().getCommandReference(commandReference).getRange(1));
+
+ // Show a command suggestion if available and the difference isn't too big
+ if(commandDifference < 0.75)
+ if(result.getCommandDescription() != null)
+ sender.sendMessage(ChatColor.YELLOW + "Did you mean " + ChatColor.GOLD + "/" + baseCommand + " help " + suggestedCommandParts + ChatColor.YELLOW + "?");
+
+ // Show the help command
+ sender.sendMessage(ChatColor.YELLOW + "Use the command " + ChatColor.GOLD + "/" + baseCommand + " help" + ChatColor.YELLOW + " to view help.");
+ return;
+ }
+
+ // Show a message when the command handler is assuming a command
+ if(commandDifference > 0) {
+ // Get the suggested command
+ CommandParts suggestedCommandParts = new CommandParts(result.getCommandDescription().getCommandReference(commandReference).getRange(1));
+
+ // Show the suggested command
+ sender.sendMessage(ChatColor.DARK_RED + "No help found, assuming '" + ChatColor.GOLD + suggestedCommandParts + ChatColor.DARK_RED + "'!");
+ }
+
+ // Print the help header
+ sender.sendMessage(ChatColor.GOLD + "==========[ " + AuthMe.PLUGIN_NAME.toUpperCase() + " HELP ]==========");
+
+ // Print the command help information
+ if(showCommand)
+ HelpPrinter.printCommand(sender, command, commandReference);
+ if(showDescription)
+ HelpPrinter.printCommandDescription(sender, command);
+ if(showArguments)
+ HelpPrinter.printArguments(sender, command);
+ if(showPermissions)
+ HelpPrinter.printPermissions(sender, command);
+ if(showAlternatives)
+ HelpPrinter.printAlternatives(sender, command, commandReference);
+ if(showCommands)
+ HelpPrinter.printChildren(sender, command, commandReference);
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/command/help/HelpSyntaxHelper.java b/src/main/java/fr/xephi/authme/command/help/HelpSyntaxHelper.java
new file mode 100644
index 00000000..b2c40875
--- /dev/null
+++ b/src/main/java/fr/xephi/authme/command/help/HelpSyntaxHelper.java
@@ -0,0 +1,61 @@
+package fr.xephi.authme.command.help;
+
+import org.bukkit.ChatColor;
+
+import fr.xephi.authme.command.CommandArgumentDescription;
+import fr.xephi.authme.command.CommandDescription;
+import fr.xephi.authme.command.CommandParts;
+import fr.xephi.authme.util.ListUtils;
+
+public class HelpSyntaxHelper {
+
+ /**
+ * Get the proper syntax for a command.
+ *
+ * @param commandDescription The command to get the syntax for.
+ * @param commandReference The reference of the command.
+ * @param alternativeLabel The alternative label to use for this command syntax.
+ * @param highlight True to highlight the important parts of this command.
+ *
+ * @return The command with proper syntax.
+ */
+ @SuppressWarnings("StringConcatenationInsideStringBufferAppend")
+ public static String getCommandSyntax(CommandDescription commandDescription, CommandParts commandReference, String alternativeLabel, boolean highlight) {
+ // Create a string builder to build the command
+ StringBuilder sb = new StringBuilder();
+
+ // Set the color and prefix a slash
+ sb.append(ChatColor.WHITE + "/");
+
+ // Get the help command reference, and the command label
+ CommandParts helpCommandReference = commandDescription.getCommandReference(commandReference);
+ final String parentCommand = (new CommandParts(helpCommandReference.getRange(0, helpCommandReference.getCount() - 1))).toString();
+ String commandLabel = helpCommandReference.get(helpCommandReference.getCount() - 1);
+
+ // Check whether the alternative label should be used
+ if(alternativeLabel != null)
+ if(alternativeLabel.trim().length() > 0)
+ commandLabel = alternativeLabel;
+
+ // Show the important bit of the command, highlight this part if required
+ sb.append(ListUtils.implode(parentCommand, (highlight ? ChatColor.YELLOW + "" + ChatColor.BOLD : "") + commandLabel, " "));
+ if(highlight)
+ sb.append(ChatColor.YELLOW);
+
+ // Add each command arguments
+ for(CommandArgumentDescription arg : commandDescription.getArguments()) {
+ // Add the argument as optional or non-optional argument
+ if(!arg.isOptional())
+ sb.append(ChatColor.ITALIC + " <" + arg.getLabel() + ">");
+ else
+ sb.append(ChatColor.ITALIC + " [" + arg.getLabel() + "]");
+ }
+
+ // Add some dots if the command allows unlimited arguments
+ if(commandDescription.getMaximumArguments() < 0)
+ sb.append(ChatColor.ITALIC + " ...");
+
+ // Return the build command syntax
+ return sb.toString();
+ }
+}
diff --git a/src/main/java/fr/xephi/authme/commands/AdminCommand.java b/src/main/java/fr/xephi/authme/commands/AdminCommand.java
deleted file mode 100644
index 1f6a15ef..00000000
--- a/src/main/java/fr/xephi/authme/commands/AdminCommand.java
+++ /dev/null
@@ -1,611 +0,0 @@
-package fr.xephi.authme.commands;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.InputStream;
-import java.security.NoSuchAlgorithmException;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.List;
-
-import org.bukkit.Bukkit;
-import org.bukkit.Location;
-import org.bukkit.OfflinePlayer;
-import org.bukkit.command.Command;
-import org.bukkit.command.CommandExecutor;
-import org.bukkit.command.CommandSender;
-import org.bukkit.command.ConsoleCommandSender;
-import org.bukkit.configuration.file.YamlConfiguration;
-import org.bukkit.entity.Player;
-import org.bukkit.potion.PotionEffect;
-import org.bukkit.potion.PotionEffectType;
-import org.bukkit.scheduler.BukkitScheduler;
-import org.bukkit.scheduler.BukkitTask;
-
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.ConsoleLogger;
-import fr.xephi.authme.Utils;
-import fr.xephi.authme.Utils.groupType;
-import fr.xephi.authme.cache.auth.PlayerAuth;
-import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.cache.limbo.LimboCache;
-import fr.xephi.authme.events.SpawnTeleportEvent;
-import fr.xephi.authme.security.PasswordSecurity;
-import fr.xephi.authme.settings.Messages;
-import fr.xephi.authme.settings.Settings;
-import fr.xephi.authme.settings.Spawn;
-import fr.xephi.authme.task.MessageTask;
-import fr.xephi.authme.task.TimeoutTask;
-
-public class AdminCommand implements CommandExecutor {
-
- public AuthMe plugin;
- private Messages m = Messages.getInstance();
-
- public AdminCommand(AuthMe plugin) {
- this.plugin = plugin;
- }
-
- @Override
- public boolean onCommand(CommandSender sender, Command cmnd, String label,
- String[] args) {
- if (args.length == 0) {
- sender.sendMessage("Usage:");
- sender.sendMessage("/authme reload - Reload the config");
- sender.sendMessage("/authme version - Get AuthMe version info");
- sender.sendMessage("/authme register - Register a player");
- sender.sendMessage("/authme unregister - Unregister a player");
- sender.sendMessage("/authme changepassword - Change a player's password");
- sender.sendMessage("/authme chgemail - Change a player's email");
- sender.sendMessage("/authme getemail - Get a player's email");
- sender.sendMessage("/authme getip - Display a player's IP if he's online");
- sender.sendMessage("/authme lastlogin - Display the date of a player's last login");
- sender.sendMessage("/authme accounts - Display all player's accounts");
- sender.sendMessage("/authme purge - Purge database");
- sender.sendMessage("/authme purgebannedplayers - Purge database from banned players");
- sender.sendMessage("/authme purgelastpos - Purge last position infos for a player");
- sender.sendMessage("/authme setspawn - Set player's spawn to your current position");
- sender.sendMessage("/authme setfirstspawn - Set player's first spawn to your current position");
- sender.sendMessage("/authme spawn - Teleport yourself to the spawn point");
- sender.sendMessage("/authme firstspawn - Teleport yourself to the first spawn point");
- sender.sendMessage("/authme switchantibot on/off - Enable/Disable AntiBot feature");
- sender.sendMessage("/authme forcelogin - Enforce the login of a connected player");
- sender.sendMessage("/authme passpartutoken - Generate a timed token to login with every player's account (CONSOLE ONLY)");
- return true;
- }
-
- if (!plugin.authmePermissible(sender, "authme.admin." + args[0].toLowerCase())) {
- m.send(sender, "no_perm");
- return true;
- }
-
- if ((sender instanceof ConsoleCommandSender) && args[0].equalsIgnoreCase("passpartutoken")) {
- if (args.length > 1) {
- ConsoleLogger.info("[AuthMe] command usage: /authme passpartutoken");
- return true;
- }
- if (Utils.getInstance().obtainToken()) {
- ConsoleLogger.info("[AuthMe] You have 30s to insert this token ingame with /passpartu ");
- } else {
- ConsoleLogger.info("[AuthMe] Security error on passpartu token, please redo the command.");
- }
- return true;
- }
-
- if (args[0].equalsIgnoreCase("version")) {
- sender.sendMessage("AuthMe Version: " + AuthMe.getInstance().getDescription().getVersion());
- return true;
- }
-
- if (args[0].equalsIgnoreCase("purge")) {
- if (args.length != 2) {
- sender.sendMessage("Usage: /authme purge ");
- return true;
- }
- if (Integer.parseInt(args[1]) < 30) {
- sender.sendMessage("You can only purge data older than 30 days");
- return true;
- }
- try {
- Calendar calendar = Calendar.getInstance();
- calendar.add(Calendar.DATE, -(Integer.parseInt(args[1])));
- long until = calendar.getTimeInMillis();
- List purged = plugin.database.autoPurgeDatabase(until);
- sender.sendMessage("Deleted " + purged.size() + " user accounts");
- if (Settings.purgeEssentialsFile && plugin.ess != null)
- plugin.dataManager.purgeEssentials(purged);
- if (Settings.purgePlayerDat)
- plugin.dataManager.purgeDat(purged);
- if (Settings.purgeLimitedCreative)
- plugin.dataManager.purgeLimitedCreative(purged);
- if (Settings.purgeAntiXray)
- plugin.dataManager.purgeAntiXray(purged);
- sender.sendMessage("[AuthMe] Database has been purged correctly");
- return true;
- } catch (NumberFormatException e) {
- sender.sendMessage("Usage: /authme purge ");
- return true;
- }
- } else if (args[0].equalsIgnoreCase("reload")) {
- File newConfigFile = new File("plugins" + File.separator + "AuthMe", "config.yml");
- if (!newConfigFile.exists()) {
- InputStream fis = getClass().getResourceAsStream("" + File.separator + "config.yml");
- FileOutputStream fos = null;
- try {
- fos = new FileOutputStream(newConfigFile);
- byte[] buf = new byte[1024];
- int i = 0;
-
- while ((i = fis.read(buf)) != -1) {
- fos.write(buf, 0, i);
- }
- } catch (Exception e) {
- ConsoleLogger.showError("Failed to load config from JAR");
- } finally {
- try {
- if (fis != null) {
- fis.close();
- }
- if (fos != null) {
- fos.close();
- }
- } catch (Exception e) {
- }
- }
- }
- YamlConfiguration newConfig = YamlConfiguration.loadConfiguration(newConfigFile);
- Settings.reloadConfigOptions(newConfig);
- m.reLoad();
- plugin.database.close();
- plugin.setupDatabase();
- m.send(sender, "reload");
- } else if (args[0].equalsIgnoreCase("lastlogin")) {
- if (args.length != 2) {
- sender.sendMessage("Usage: /authme lastlogin ");
- return true;
- }
- PlayerAuth auth = null;
- try {
- auth = plugin.database.getAuth(args[1].toLowerCase());
- } catch (NullPointerException e) {
- m.send(sender, "unknown_user");
- return true;
- }
- if (auth == null) {
- m.send(sender, "user_unknown");
- return true;
- }
- long lastLogin = auth.getLastLogin();
- Date d = new Date(lastLogin);
- final long diff = System.currentTimeMillis() - lastLogin;
- final String msg = (int) (diff / 86400000) + " days " + (int) (diff / 3600000 % 24) + " hours " + (int) (diff / 60000 % 60) + " mins " + (int) (diff / 1000 % 60) + " secs.";
- String lastIP = auth.getIp();
- sender.sendMessage("[AuthMe] " + args[1] + " lastlogin : " + d.toString());
- sender.sendMessage("[AuthMe] The player " + auth.getNickname() + " is unlogged since " + msg);
- sender.sendMessage("[AuthMe] Last Player's IP: " + lastIP);
- } else if (args[0].equalsIgnoreCase("accounts")) {
- if (args.length != 2) {
- sender.sendMessage("Usage: /authme accounts ");
- sender.sendMessage("Or: /authme accounts ");
- return true;
- }
- if (!args[1].contains(".")) {
- final CommandSender fSender = sender;
- final String[] arguments = args;
- Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
-
- @Override
- public void run() {
- PlayerAuth auth = null;
- String message = "[AuthMe] ";
- try {
- auth = plugin.database.getAuth(arguments[1].toLowerCase());
- } catch (NullPointerException npe) {
- m.send(fSender, "unknown_user");
- return;
- }
- if (auth == null) {
- m.send(fSender, "unknown_user");
- return;
- }
- List accountList = plugin.database.getAllAuthsByName(auth);
- if (accountList == null || accountList.isEmpty()) {
- m.send(fSender, "user_unknown");
- return;
- }
- if (accountList.size() == 1) {
- fSender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player");
- return;
- }
- int i = 0;
- for (String account : accountList) {
- i++;
- message = message + account;
- if (i != accountList.size()) {
- message = message + ", ";
- } else {
- message = message + ".";
- }
- }
- fSender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts");
- fSender.sendMessage(message);
- }
- });
- return true;
- } else {
- final CommandSender fSender = sender;
- final String[] arguments = args;
- Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
-
- @Override
- public void run() {
- String message = "[AuthMe] ";
- if (arguments[1] == null) {
- fSender.sendMessage("[AuthMe] Please put a valid IP");
- return;
- }
- List accountList = plugin.database.getAllAuthsByIp(arguments[1]);
- if (accountList == null || accountList.isEmpty()) {
- fSender.sendMessage("[AuthMe] This IP does not exist in the database");
- return;
- }
- if (accountList.size() == 1) {
- fSender.sendMessage("[AuthMe] " + arguments[1] + " is a single account player");
- return;
- }
- int i = 0;
- for (String account : accountList) {
- i++;
- message = message + account;
- if (i != accountList.size()) {
- message = message + ", ";
- } else {
- message = message + ".";
- }
- }
- fSender.sendMessage("[AuthMe] " + arguments[1] + " has " + String.valueOf(accountList.size()) + " accounts");
- fSender.sendMessage(message);
- }
- });
- return true;
- }
- } else
- if (args[0].equalsIgnoreCase("register") || args[0].equalsIgnoreCase("reg")) {
- if (args.length != 3) {
- sender.sendMessage("Usage: /authme register ");
- return true;
- }
- String lowpass = args[2].toLowerCase();
- if (lowpass.contains("delete") || lowpass.contains("where") || lowpass.contains("insert") || lowpass.contains("modify") || lowpass.contains("from") || lowpass.contains("select") || lowpass.contains(";") || lowpass.contains("null") || !lowpass.matches(Settings.getPassRegex)) {
- m.send(sender, "password_error");
- return true;
- }
- if (lowpass.equalsIgnoreCase(args[1])) {
- m.send(sender, "password_error_nick");
- return true;
- }
- if (lowpass.length() < Settings.getPasswordMinLen || lowpass.length() > Settings.passwordMaxLength) {
- m.send(sender, "pass_len");
- return true;
- }
- if (!Settings.unsafePasswords.isEmpty()) {
- if (Settings.unsafePasswords.contains(lowpass)) {
- m.send(sender, "password_error_unsafe");
- return true;
- }
- }
- try {
- String name = args[1].toLowerCase();
- if (plugin.database.isAuthAvailable(name)) {
- m.send(sender, "user_regged");
- return true;
- }
- String hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[2], name);
- PlayerAuth auth = new PlayerAuth(name, hash, "192.168.0.1", 0L, "your@email.com");
- if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null)
- auth.setSalt(PasswordSecurity.userSalt.get(name));
- else auth.setSalt("");
- if (!plugin.database.saveAuth(auth)) {
- m.send(sender, "error");
- return true;
- }
- m.send(sender, "registered");
- ConsoleLogger.info(args[1] + " registered");
- } catch (NoSuchAlgorithmException ex) {
- ConsoleLogger.showError(ex.getMessage());
- m.send(sender, "error");
- }
- return true;
- } else if (args[0].equalsIgnoreCase("getemail")) {
- if (args.length != 2) {
- sender.sendMessage("Usage: /authme getemail ");
- return true;
- }
- String playername = args[1].toLowerCase();
- PlayerAuth auth = plugin.database.getAuth(playername);
- if (auth == null) {
- m.send(sender, "unknown_user");
- return true;
- }
- sender.sendMessage("[AuthMe] " + args[1] + "'s email: " + auth.getEmail());
- return true;
- } else if (args[0].equalsIgnoreCase("chgemail")) {
- if (args.length != 3) {
- sender.sendMessage("Usage: /authme chgemail ");
- return true;
- }
- if (!Settings.isEmailCorrect(args[2])) {
- m.send(sender, "email_invalid");
- return true;
- }
- String playername = args[1].toLowerCase();
- PlayerAuth auth = plugin.database.getAuth(playername);
- if (auth == null) {
- m.send(sender, "unknown_user");
- return true;
- }
- auth.setEmail(args[2]);
- if (!plugin.database.updateEmail(auth)) {
- m.send(sender, "error");
- return true;
- }
- if (PlayerCache.getInstance().getAuth(playername) != null)
- PlayerCache.getInstance().updatePlayer(auth);
- m.send(sender, "email_changed");
- return true;
- } else if (args[0].equalsIgnoreCase("setspawn")) {
- try {
- if (sender instanceof Player) {
- if (Spawn.getInstance().setSpawn(((Player) sender).getLocation())) {
- sender.sendMessage("[AuthMe] Correctly defined new spawn point");
- } else {
- sender.sendMessage("[AuthMe] SetSpawn has failed, please retry");
- }
- } else {
- sender.sendMessage("[AuthMe] Please use that command in game");
- }
- } catch (NullPointerException ex) {
- ConsoleLogger.showError(ex.getMessage());
- }
- return true;
- } else if (args[0].equalsIgnoreCase("setfirstspawn")) {
- try {
- if (sender instanceof Player) {
- if (Spawn.getInstance().setFirstSpawn(((Player) sender).getLocation()))
- sender.sendMessage("[AuthMe] Correctly defined new first spawn point");
- else sender.sendMessage("[AuthMe] SetFirstSpawn has failed, please retry");
- } else {
- sender.sendMessage("[AuthMe] Please use that command in game");
- }
- } catch (NullPointerException ex) {
- ConsoleLogger.showError(ex.getMessage());
- }
- return true;
- } else if (args[0].equalsIgnoreCase("purgebannedplayers")) {
- List bannedPlayers = new ArrayList();
- for (OfflinePlayer off : plugin.getServer().getBannedPlayers()) {
- bannedPlayers.add(off.getName().toLowerCase());
- }
- plugin.database.purgeBanned(bannedPlayers);
- if (Settings.purgeEssentialsFile && plugin.ess != null)
- plugin.dataManager.purgeEssentials(bannedPlayers);
- if (Settings.purgePlayerDat)
- plugin.dataManager.purgeDat(bannedPlayers);
- if (Settings.purgeLimitedCreative)
- plugin.dataManager.purgeLimitedCreative(bannedPlayers);
- if (Settings.purgeAntiXray)
- plugin.dataManager.purgeAntiXray(bannedPlayers);
- sender.sendMessage("[AuthMe] Database has been purged correctly");
- return true;
- } else if (args[0].equalsIgnoreCase("spawn")) {
- try {
- if (sender instanceof Player) {
- if (Spawn.getInstance().getSpawn() != null)
- ((Player) sender).teleport(Spawn.getInstance().getSpawn());
- else sender.sendMessage("[AuthMe] Spawn has failed, please try to define the spawn");
- } else {
- sender.sendMessage("[AuthMe] Please use that command in game");
- }
- } catch (NullPointerException ex) {
- ConsoleLogger.showError(ex.getMessage());
- }
- return true;
- } else if (args[0].equalsIgnoreCase("firstspawn")) {
- try {
- if (sender instanceof Player) {
- if (Spawn.getInstance().getFirstSpawn() != null)
- ((Player) sender).teleport(Spawn.getInstance().getFirstSpawn());
- else sender.sendMessage("[AuthMe] First spawn has failed, please try to define the first spawn");
- } else {
- sender.sendMessage("[AuthMe] Please use that command in game");
- }
- } catch (NullPointerException ex) {
- ConsoleLogger.showError(ex.getMessage());
- }
- return true;
- } else
- if (args[0].equalsIgnoreCase("changepassword") || args[0].equalsIgnoreCase("cp")) {
- if (args.length != 3) {
- sender.sendMessage("Usage: /authme changepassword ");
- return true;
- }
- String lowpass = args[2].toLowerCase();
- if (lowpass.contains("delete") || lowpass.contains("where") || lowpass.contains("insert") || lowpass.contains("modify") || lowpass.contains("from") || lowpass.contains("select") || lowpass.contains(";") || lowpass.contains("null") || !lowpass.matches(Settings.getPassRegex)) {
- m.send(sender, "password_error");
- return true;
- }
- if (lowpass.equalsIgnoreCase(args[1])) {
- m.send(sender, "password_error_nick");
- return true;
- }
- if (lowpass.length() < Settings.getPasswordMinLen || lowpass.length() > Settings.passwordMaxLength) {
- m.send(sender, "pass_len");
- return true;
- }
- if (!Settings.unsafePasswords.isEmpty()) {
- if (Settings.unsafePasswords.contains(lowpass)) {
- m.send(sender, "password_error_unsafe");
- return true;
- }
- }
- try {
- String name = args[1].toLowerCase();
- String hash = PasswordSecurity.getHash(Settings.getPasswordHash, args[2], name);
- PlayerAuth auth = null;
- if (PlayerCache.getInstance().isAuthenticated(name)) {
- auth = PlayerCache.getInstance().getAuth(name);
- } else if (plugin.database.isAuthAvailable(name)) {
- auth = plugin.database.getAuth(name);
- }
- if (auth == null) {
- m.send(sender, "unknown_user");
- return true;
- }
- auth.setHash(hash);
- if (PasswordSecurity.userSalt.containsKey(name)) {
- auth.setSalt(PasswordSecurity.userSalt.get(name));
- plugin.database.updateSalt(auth);
- }
- if (!plugin.database.updatePassword(auth)) {
- m.send(sender, "error");
- return true;
- }
- sender.sendMessage("pwd_changed");
- ConsoleLogger.info(args[1] + "'s password changed");
- } catch (NoSuchAlgorithmException ex) {
- ConsoleLogger.showError(ex.getMessage());
- m.send(sender, "error");
- }
- return true;
- } else if (args[0].equalsIgnoreCase("unregister") || args[0].equalsIgnoreCase("unreg") || args[0].equalsIgnoreCase("del")) {
- if (args.length != 2) {
- sender.sendMessage("Usage: /authme unregister ");
- return true;
- }
- String name = args[1].toLowerCase();
- if (!plugin.database.isAuthAvailable(name)) {
- m.send(sender, "user_unknown");
- return true;
- }
- if (!plugin.database.removeAuth(name)) {
- m.send(sender, "error");
- return true;
- }
- Player target = Bukkit.getPlayer(name);
- PlayerCache.getInstance().removePlayer(name);
- Utils.getInstance().setGroup(name, groupType.UNREGISTERED);
- if (target != null) {
- if (target.isOnline()) {
- if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
- Location spawn = plugin.getSpawnLocation(target);
- SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(target, target.getLocation(), spawn, false);
- plugin.getServer().getPluginManager().callEvent(tpEvent);
- if (!tpEvent.isCancelled()) {
- target.teleport(tpEvent.getTo());
- }
- }
- LimboCache.getInstance().addLimboPlayer(target);
- int delay = Settings.getRegistrationTimeout * 20;
- int interval = Settings.getWarnMessageInterval;
- BukkitScheduler sched = sender.getServer().getScheduler();
- if (delay != 0) {
- BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, target), delay);
- LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
- }
- LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("reg_msg"), interval)));
- if (Settings.applyBlindEffect)
- target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
- m.send(target, "unregistered");
- } else {
- // Player isn't online, do nothing else
- }
- } else {
- // Player does not exist, do nothing else
- }
- m.send(sender, "unregistered");
- ConsoleLogger.info(args[1] + " unregistered");
- return true;
- } else
- if (args[0].equalsIgnoreCase("purgelastpos") || args[0].equalsIgnoreCase("resetposition")) {
- if (args.length != 2) {
- sender.sendMessage("Usage: /authme purgelastpos ");
- return true;
- }
- try {
- String name = args[1].toLowerCase();
- PlayerAuth auth = plugin.database.getAuth(name);
- if (auth == null) {
- m.send(sender, "unknown_user");
- return true;
- }
- auth.setQuitLocX(0D);
- auth.setQuitLocY(0D);
- auth.setQuitLocZ(0D);
- auth.setWorld("world");
- plugin.database.updateQuitLoc(auth);
- sender.sendMessage(name + "'s last position location is now reset");
- } catch (Exception e) {
- ConsoleLogger.showError("An error occured while trying to reset location or player do not exist, please see below: ");
- ConsoleLogger.showError(e.getMessage());
- if (sender instanceof Player)
- sender.sendMessage("An error occured while trying to reset location or player do not exist, please see logs");
- }
- return true;
- } else if (args[0].equalsIgnoreCase("switchantibot")) {
- if (args.length != 2) {
- sender.sendMessage("Usage: /authme switchantibot on/off");
- return true;
- }
- if (args[1].equalsIgnoreCase("on")) {
- plugin.switchAntiBotMod(true);
- sender.sendMessage("[AuthMe] AntiBotMod enabled");
- return true;
- }
- if (args[1].equalsIgnoreCase("off")) {
- plugin.switchAntiBotMod(false);
- sender.sendMessage("[AuthMe] AntiBotMod disabled");
- return true;
- }
- sender.sendMessage("Usage: /authme switchantibot on/off");
- return true;
- } else if (args[0].equalsIgnoreCase("getip")) {
- if (args.length < 2) {
- sender.sendMessage("Usage: /authme getip ");
- return true;
- }
- Player player = Bukkit.getPlayer(args[1]);
- if (player == null) {
- sender.sendMessage("This player is not actually online");
- sender.sendMessage("Usage: /authme getip ");
- return true;
- }
- sender.sendMessage(player.getName() + "'s actual IP is : " + player.getAddress().getAddress().getHostAddress() + ":" + player.getAddress().getPort());
- sender.sendMessage(player.getName() + "'s real IP is : " + plugin.getIP(player));
- return true;
- } else if (args[0].equalsIgnoreCase("forcelogin")) {
- if (args.length < 2) {
- sender.sendMessage("Usage: /authme forcelogin ");
- return true;
- }
- try {
- Player player = Bukkit.getPlayer(args[1]);
- if (player == null || !player.isOnline()) {
- sender.sendMessage("Player needs to be online!");
- return true;
- }
- if (!plugin.authmePermissible(player, "authme.canbeforced")) {
- sender.sendMessage("You cannot force login for this player!");
- return true;
- }
- plugin.management.performLogin(player, "dontneed", true);
- sender.sendMessage("Force Login performed!");
- } catch (Exception e) {
- sender.sendMessage("An error occured while trying to get that player!");
- }
- } else {
- sender.sendMessage("Usage: /authme reload|register playername password|changepassword playername password|unregister playername");
- }
- return true;
- }
-}
diff --git a/src/main/java/fr/xephi/authme/commands/CaptchaCommand.java b/src/main/java/fr/xephi/authme/commands/CaptchaCommand.java
deleted file mode 100644
index 0c0e242a..00000000
--- a/src/main/java/fr/xephi/authme/commands/CaptchaCommand.java
+++ /dev/null
@@ -1,78 +0,0 @@
-package fr.xephi.authme.commands;
-
-import org.bukkit.command.Command;
-import org.bukkit.command.CommandExecutor;
-import org.bukkit.command.CommandSender;
-import org.bukkit.entity.Player;
-
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.security.RandomString;
-import fr.xephi.authme.settings.Messages;
-import fr.xephi.authme.settings.Settings;
-
-public class CaptchaCommand implements CommandExecutor {
-
- public AuthMe plugin;
- private Messages m = Messages.getInstance();
- public static RandomString rdm = new RandomString(Settings.captchaLength);
-
- public CaptchaCommand(AuthMe plugin) {
- this.plugin = plugin;
- }
-
- @Override
- public boolean onCommand(CommandSender sender, Command cmnd, String label,
- String[] args) {
-
- if (!(sender instanceof Player)) {
- return true;
- }
-
- Player player = (Player) sender;
- String name = player.getName().toLowerCase();
-
- if (args.length == 0) {
- m.send(player, "usage_captcha");
- return true;
- }
-
- if (PlayerCache.getInstance().isAuthenticated(name)) {
- m.send(player, "logged_in");
- return true;
- }
-
- if (!plugin.authmePermissible(player, "authme." + label.toLowerCase())) {
- m.send(player, "no_perm");
- return true;
- }
-
- if (!Settings.useCaptcha) {
- m.send(player, "usage_log");
- return true;
- }
-
- if (!plugin.cap.containsKey(name)) {
- m.send(player, "usage_log");
- return true;
- }
-
- if (Settings.useCaptcha && !args[0].equals(plugin.cap.get(name))) {
- plugin.cap.remove(name);
- plugin.cap.put(name, rdm.nextString());
- for (String s : m.send("wrong_captcha")) {
- player.sendMessage(s.replace("THE_CAPTCHA", plugin.cap.get(name)));
- }
- return true;
- }
- try {
- plugin.captcha.remove(name);
- plugin.cap.remove(name);
- } catch (NullPointerException npe) {
- }
- m.send(player, "valid_captcha");
- m.send(player, "login_msg");
- return true;
- }
-
-}
diff --git a/src/main/java/fr/xephi/authme/commands/ChangePasswordCommand.java b/src/main/java/fr/xephi/authme/commands/ChangePasswordCommand.java
deleted file mode 100644
index 7577a202..00000000
--- a/src/main/java/fr/xephi/authme/commands/ChangePasswordCommand.java
+++ /dev/null
@@ -1,96 +0,0 @@
-package fr.xephi.authme.commands;
-
-import java.security.NoSuchAlgorithmException;
-
-import org.bukkit.command.Command;
-import org.bukkit.command.CommandExecutor;
-import org.bukkit.command.CommandSender;
-import org.bukkit.entity.Player;
-
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.ConsoleLogger;
-import fr.xephi.authme.cache.auth.PlayerAuth;
-import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.security.PasswordSecurity;
-import fr.xephi.authme.settings.Messages;
-import fr.xephi.authme.settings.Settings;
-
-public class ChangePasswordCommand implements CommandExecutor {
-
- private Messages m = Messages.getInstance();
- public AuthMe plugin;
-
- public ChangePasswordCommand(AuthMe plugin) {
- this.plugin = plugin;
- }
-
- @Override
- public boolean onCommand(CommandSender sender, Command cmnd, String label,
- String[] args) {
- if (!(sender instanceof Player)) {
- return true;
- }
-
- if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
- m.send(sender, "no_perm");
- return true;
- }
-
- Player player = (Player) sender;
- String name = player.getName().toLowerCase();
- if (!PlayerCache.getInstance().isAuthenticated(name)) {
- m.send(player, "not_logged_in");
- return true;
- }
-
- if (args.length != 2) {
- m.send(player, "usage_changepassword");
- return true;
- }
-
- String lowpass = args[1].toLowerCase();
- if (lowpass.contains("delete") || lowpass.contains("where") || lowpass.contains("insert") || lowpass.contains("modify") || lowpass.contains("from") || lowpass.contains("select") || lowpass.contains(";") || lowpass.contains("null") || !lowpass.matches(Settings.getPassRegex)) {
- m.send(player, "password_error");
- return true;
- }
- if (lowpass.equalsIgnoreCase(name)) {
- m.send(player, "password_error_nick");
- return true;
- }
- if (lowpass.length() < Settings.getPasswordMinLen || lowpass.length() > Settings.passwordMaxLength) {
- m.send(player, "pass_len");
- return true;
- }
- if (!Settings.unsafePasswords.isEmpty()) {
- if (Settings.unsafePasswords.contains(lowpass)) {
- m.send(player, "password_error_unsafe");
- return true;
- }
- }
- try {
- String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, args[1], name);
-
- if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) {
- PlayerAuth auth = PlayerCache.getInstance().getAuth(name);
- auth.setHash(hashnew);
- if (PasswordSecurity.userSalt.containsKey(name) && PasswordSecurity.userSalt.get(name) != null)
- auth.setSalt(PasswordSecurity.userSalt.get(name));
- else auth.setSalt("");
- if (!plugin.database.updatePassword(auth)) {
- m.send(player, "error");
- return true;
- }
- plugin.database.updateSalt(auth);
- PlayerCache.getInstance().updatePlayer(auth);
- m.send(player, "pwd_changed");
- ConsoleLogger.info(player.getName() + " changed his password");
- } else {
- m.send(player, "wrong_pwd");
- }
- } catch (NoSuchAlgorithmException ex) {
- ConsoleLogger.showError(ex.getMessage());
- m.send(sender, "error");
- }
- return true;
- }
-}
diff --git a/src/main/java/fr/xephi/authme/commands/ConverterCommand.java b/src/main/java/fr/xephi/authme/commands/ConverterCommand.java
deleted file mode 100644
index 56deecdf..00000000
--- a/src/main/java/fr/xephi/authme/commands/ConverterCommand.java
+++ /dev/null
@@ -1,114 +0,0 @@
-package fr.xephi.authme.commands;
-
-import org.bukkit.Bukkit;
-import org.bukkit.command.Command;
-import org.bukkit.command.CommandExecutor;
-import org.bukkit.command.CommandSender;
-
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.converter.Converter;
-import fr.xephi.authme.converter.CrazyLoginConverter;
-import fr.xephi.authme.converter.FlatToSql;
-import fr.xephi.authme.converter.FlatToSqlite;
-import fr.xephi.authme.converter.RakamakConverter;
-import fr.xephi.authme.converter.RoyalAuthConverter;
-import fr.xephi.authme.converter.SqlToFlat;
-import fr.xephi.authme.converter.vAuthConverter;
-import fr.xephi.authme.converter.xAuthConverter;
-import fr.xephi.authme.settings.Messages;
-
-public class ConverterCommand implements CommandExecutor {
-
- private AuthMe plugin;
- private Messages m = Messages.getInstance();
-
- public ConverterCommand(AuthMe plugin) {
- this.plugin = plugin;
- }
-
- @Override
- public boolean onCommand(CommandSender sender, Command cmnd, String label,
- final String[] args) {
- if (!plugin.authmePermissible(sender, "authme.admin.converter")) {
- m.send(sender, "no_perm");
- return true;
- }
-
- if (args.length == 0) {
- sender.sendMessage("Usage : /converter flattosql | flattosqlite | xauth | crazylogin | rakamak | royalauth | vauth | sqltoflat");
- return true;
- }
-
- ConvertType type = ConvertType.fromName(args[0]);
- if (type == null) {
- m.send(sender, "error");
- return true;
- }
- Converter converter = null;
- switch (type) {
- case ftsql:
- converter = new FlatToSql();
- break;
- case ftsqlite:
- converter = new FlatToSqlite(sender);
- break;
- case xauth:
- converter = new xAuthConverter(plugin, sender);
- break;
- case crazylogin:
- converter = new CrazyLoginConverter(plugin, sender);
- break;
- case rakamak:
- converter = new RakamakConverter(plugin, sender);
- break;
- case royalauth:
- converter = new RoyalAuthConverter(plugin);
- break;
- case vauth:
- converter = new vAuthConverter(plugin, sender);
- break;
- case sqltoflat:
- converter = new SqlToFlat(plugin, sender);
- break;
- default:
- break;
- }
- if (converter == null) {
- m.send(sender, "error");
- return true;
- }
- Bukkit.getScheduler().runTaskAsynchronously(plugin, converter);
- sender.sendMessage("[AuthMe] Successfully converted from " + args[0]);
- return true;
- }
-
- public enum ConvertType {
-
- ftsql("flattosql"),
- ftsqlite("flattosqlite"),
- xauth("xauth"),
- crazylogin("crazylogin"),
- rakamak("rakamak"),
- royalauth("royalauth"),
- vauth("vauth"),
- sqltoflat("sqltoflat");
-
- String name;
-
- ConvertType(String name) {
- this.name = name;
- }
-
- String getName() {
- return this.name;
- }
-
- public static ConvertType fromName(String name) {
- for (ConvertType type : ConvertType.values()) {
- if (type.getName().equalsIgnoreCase(name))
- return type;
- }
- return null;
- }
- }
-}
diff --git a/src/main/java/fr/xephi/authme/commands/EmailCommand.java b/src/main/java/fr/xephi/authme/commands/EmailCommand.java
deleted file mode 100644
index b81627ed..00000000
--- a/src/main/java/fr/xephi/authme/commands/EmailCommand.java
+++ /dev/null
@@ -1,189 +0,0 @@
-package fr.xephi.authme.commands;
-
-import java.security.NoSuchAlgorithmException;
-import java.util.Arrays;
-
-import org.bukkit.command.Command;
-import org.bukkit.command.CommandExecutor;
-import org.bukkit.command.CommandSender;
-import org.bukkit.entity.Player;
-
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.ConsoleLogger;
-import fr.xephi.authme.cache.auth.PlayerAuth;
-import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.security.PasswordSecurity;
-import fr.xephi.authme.security.RandomString;
-import fr.xephi.authme.settings.Messages;
-import fr.xephi.authme.settings.Settings;
-
-/**
- *
- * @author Xephi59
- */
-public class EmailCommand implements CommandExecutor {
-
- public AuthMe plugin;
- private Messages m = Messages.getInstance();
-
- public EmailCommand(AuthMe plugin) {
- this.plugin = plugin;
- }
-
- @Override
- public boolean onCommand(CommandSender sender, Command cmnd, String label,
- String[] args) {
- if (!(sender instanceof Player)) {
- return true;
- }
-
- if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
- m.send(sender, "no_perm");
- return true;
- }
-
- Player player = (Player) sender;
- String name = player.getName();
-
- if (args.length == 0) {
- m.send(player, "usage_email_add");
- m.send(player, "usage_email_change");
- m.send(player, "usage_email_recovery");
- return true;
- }
-
- if (args[0].equalsIgnoreCase("add")) {
- if (args.length != 3) {
- m.send(player, "usage_email_add");
- return true;
- }
- if (Settings.getmaxRegPerEmail > 0) {
- if (!plugin.authmePermissible(sender, "authme.allow2accounts") && plugin.database.getAllAuthsByEmail(args[1]).size() >= Settings.getmaxRegPerEmail) {
- m.send(player, "max_reg");
- return true;
- }
- }
- if (args[1].equals(args[2]) && PlayerCache.getInstance().isAuthenticated(name)) {
- PlayerAuth auth = PlayerCache.getInstance().getAuth(name);
- if (auth.getEmail() == null || (!auth.getEmail().equals("your@email.com") && !auth.getEmail().isEmpty())) {
- m.send(player, "usage_email_change");
- return true;
- }
- if (!Settings.isEmailCorrect(args[1])) {
- m.send(player, "email_invalid");
- return true;
- }
- auth.setEmail(args[1]);
- if (!plugin.database.updateEmail(auth)) {
- m.send(player, "error");
- return true;
- }
- PlayerCache.getInstance().updatePlayer(auth);
- m.send(player, "email_added");
- player.sendMessage(auth.getEmail());
- } else if (PlayerCache.getInstance().isAuthenticated(name)) {
- m.send(player, "email_confirm");
- } else {
- if (!plugin.database.isAuthAvailable(name)) {
- m.send(player, "login_msg");
- } else {
- m.send(player, "reg_email_msg");
- }
- }
- } else if (args[0].equalsIgnoreCase("change")) {
- if (args.length != 3) {
- m.send(player, "usage_email_change");
- return true;
- }
- if (Settings.getmaxRegPerEmail > 0) {
- if (!plugin.authmePermissible(sender, "authme.allow2accounts") && plugin.database.getAllAuthsByEmail(args[2]).size() >= Settings.getmaxRegPerEmail) {
- m.send(player, "max_reg");
- return true;
- }
- }
- if (PlayerCache.getInstance().isAuthenticated(name)) {
- PlayerAuth auth = PlayerCache.getInstance().getAuth(name);
- if (auth.getEmail() == null || auth.getEmail().equals("your@email.com") || auth.getEmail().isEmpty()) {
- m.send(player, "usage_email_add");
- return true;
- }
- if (!args[1].equals(auth.getEmail())) {
- m.send(player, "old_email_invalid");
- return true;
- }
- if (!Settings.isEmailCorrect(args[2])) {
- m.send(player, "new_email_invalid");
- return true;
- }
- auth.setEmail(args[2]);
- if (!plugin.database.updateEmail(auth)) {
- m.send(player, "error");
- return true;
- }
- PlayerCache.getInstance().updatePlayer(auth);
- m.send(player, "email_changed");
- player.sendMessage(Arrays.toString(m.send("email_defined")) + auth.getEmail());
- } else if (PlayerCache.getInstance().isAuthenticated(name)) {
- m.send(player, "email_confirm");
- } else {
- if (!plugin.database.isAuthAvailable(name)) {
- m.send(player, "login_msg");
- } else {
- m.send(player, "reg_email_msg");
- }
- }
- }
- if (args[0].equalsIgnoreCase("recovery")) {
- if (args.length != 2) {
- m.send(player, "usage_email_recovery");
- return true;
- }
- if (plugin.mail == null) {
- m.send(player, "error");
- return true;
- }
- if (plugin.database.isAuthAvailable(name)) {
- if (PlayerCache.getInstance().isAuthenticated(name)) {
- m.send(player, "logged_in");
- return true;
- }
- try {
- RandomString rand = new RandomString(Settings.getRecoveryPassLength);
- String thePass = rand.nextString();
- String hashnew = PasswordSecurity.getHash(Settings.getPasswordHash, thePass, name);
- PlayerAuth auth = null;
- if (PlayerCache.getInstance().isAuthenticated(name)) {
- auth = PlayerCache.getInstance().getAuth(name);
- } else if (plugin.database.isAuthAvailable(name)) {
- auth = plugin.database.getAuth(name);
- } else {
- m.send(player, "unknown_user");
- return true;
- }
- if (Settings.getmailAccount.equals("") || Settings.getmailAccount.isEmpty()) {
- m.send(player, "error");
- return true;
- }
-
- if (!args[1].equalsIgnoreCase(auth.getEmail()) || args[1].equalsIgnoreCase("your@email.com") || auth.getEmail().equalsIgnoreCase("your@email.com")) {
- m.send(player, "email_invalid");
- return true;
- }
- auth.setHash(hashnew);
- plugin.database.updatePassword(auth);
- plugin.mail.main(auth, thePass);
- m.send(player, "email_send");
- } catch (NoSuchAlgorithmException ex) {
- ConsoleLogger.showError(ex.getMessage());
- m.send(sender, "error");
- } catch (NoClassDefFoundError ncdfe) {
- ConsoleLogger.showError(ncdfe.getMessage());
- m.send(sender, "error");
- }
- } else {
- m.send(player, "reg_email_msg");
- }
- }
- return true;
- }
-}
diff --git a/src/main/java/fr/xephi/authme/commands/LoginCommand.java b/src/main/java/fr/xephi/authme/commands/LoginCommand.java
deleted file mode 100644
index b8730929..00000000
--- a/src/main/java/fr/xephi/authme/commands/LoginCommand.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package fr.xephi.authme.commands;
-
-import org.bukkit.command.Command;
-import org.bukkit.command.CommandExecutor;
-import org.bukkit.command.CommandSender;
-import org.bukkit.entity.Player;
-
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.settings.Messages;
-
-public class LoginCommand implements CommandExecutor {
-
- private AuthMe plugin;
- private Messages m = Messages.getInstance();
-
- public LoginCommand(AuthMe plugin) {
- this.plugin = plugin;
- }
-
- @Override
- public boolean onCommand(CommandSender sender, Command cmnd, String label,
- final String[] args) {
- if (!(sender instanceof Player)) {
- return true;
- }
-
- final Player player = (Player) sender;
-
- if (args.length == 0) {
- m.send(player, "usage_log");
- return true;
- }
-
- if (!plugin.authmePermissible(player, "authme." + label.toLowerCase())) {
- m.send(player, "no_perm");
- return true;
- }
- plugin.management.performLogin(player, args[0], false);
- return true;
- }
-}
diff --git a/src/main/java/fr/xephi/authme/commands/LogoutCommand.java b/src/main/java/fr/xephi/authme/commands/LogoutCommand.java
deleted file mode 100644
index 4c21f7f6..00000000
--- a/src/main/java/fr/xephi/authme/commands/LogoutCommand.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package fr.xephi.authme.commands;
-
-import org.bukkit.command.Command;
-import org.bukkit.command.CommandExecutor;
-import org.bukkit.command.CommandSender;
-import org.bukkit.entity.Player;
-
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.settings.Messages;
-
-public class LogoutCommand implements CommandExecutor {
-
- private Messages m = Messages.getInstance();
- private AuthMe plugin;
-
- public LogoutCommand(AuthMe plugin) {
- this.plugin = plugin;
- }
-
- @Override
- public boolean onCommand(CommandSender sender, Command cmnd, String label,
- String[] args) {
- if (!(sender instanceof Player)) {
- return true;
- }
-
- if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
- m.send(sender, "no_perm");
- return true;
- }
-
- final Player player = (Player) sender;
- plugin.management.performLogout(player);
- return true;
- }
-
-}
diff --git a/src/main/java/fr/xephi/authme/commands/PasspartuCommand.java b/src/main/java/fr/xephi/authme/commands/PasspartuCommand.java
deleted file mode 100644
index 0d7b059e..00000000
--- a/src/main/java/fr/xephi/authme/commands/PasspartuCommand.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package fr.xephi.authme.commands;
-
-import org.bukkit.command.Command;
-import org.bukkit.command.CommandExecutor;
-import org.bukkit.command.CommandSender;
-import org.bukkit.entity.Player;
-
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.Utils;
-import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.settings.Messages;
-
-/**
- *
- * @author stefano
- */
-public class PasspartuCommand implements CommandExecutor {
-
- private Utils utils = Utils.getInstance();
- public AuthMe plugin;
- private Messages m = Messages.getInstance();
-
- public PasspartuCommand(AuthMe plugin) {
- this.plugin = plugin;
- }
-
- @Override
- public boolean onCommand(CommandSender sender, Command cmnd, String label,
- String[] args) {
-
- if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
- m.send(sender, "no_perm");
- return true;
- }
-
- if (PlayerCache.getInstance().isAuthenticated(sender.getName().toLowerCase())) {
- return true;
- }
-
- if ((sender instanceof Player) && args.length == 1) {
- if (utils.readToken(args[0])) {
- // bypass login!
- plugin.management.performLogin((Player) sender, "dontneed", true);
- return true;
- }
- sender.sendMessage("Time is expired or Token is Wrong!");
- return true;
- }
- sender.sendMessage("usage: /passpartu token");
- return true;
- }
-}
diff --git a/src/main/java/fr/xephi/authme/commands/RegisterCommand.java b/src/main/java/fr/xephi/authme/commands/RegisterCommand.java
deleted file mode 100644
index 11ab0a12..00000000
--- a/src/main/java/fr/xephi/authme/commands/RegisterCommand.java
+++ /dev/null
@@ -1,72 +0,0 @@
-package fr.xephi.authme.commands;
-
-import org.bukkit.command.Command;
-import org.bukkit.command.CommandExecutor;
-import org.bukkit.command.CommandSender;
-import org.bukkit.entity.Player;
-
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.cache.auth.PlayerAuth;
-import fr.xephi.authme.security.RandomString;
-import fr.xephi.authme.settings.Messages;
-import fr.xephi.authme.settings.Settings;
-
-public class RegisterCommand implements CommandExecutor {
-
- private Messages m = Messages.getInstance();
- public PlayerAuth auth;
- public AuthMe plugin;
-
- public RegisterCommand(AuthMe plugin) {
- this.plugin = plugin;
- }
-
- @Override
- public boolean onCommand(CommandSender sender, Command cmnd, String label,
- String[] args) {
- if (!(sender instanceof Player)) {
- sender.sendMessage("Player Only! Use 'authme register ' instead");
- return true;
- }
- if (args.length == 0) {
- m.send(sender, "usage_reg");
- }
- if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
- m.send(sender, "no_perm");
- return true;
- }
- final Player player = (Player) sender;
- if (Settings.emailRegistration && !Settings.getmailAccount.isEmpty()) {
- if (Settings.doubleEmailCheck) {
- if (args.length < 2) {
- m.send(player, "usage_reg");
- return true;
- }
- if (!args[0].equals(args[1])) {
- m.send(player, "usage_reg");
- return true;
- }
- }
- final String email = args[0];
- if (!Settings.isEmailCorrect(email)) {
- m.send(player, "email_invalid");
- return true;
- }
- RandomString rand = new RandomString(Settings.getRecoveryPassLength);
- final String thePass = rand.nextString();
- plugin.management.performRegister(player, thePass, email);
- return true;
- }
- if (args.length == 0 || (Settings.getEnablePasswordVerifier && args.length < 2)) {
- m.send(player, "usage_reg");
- return true;
- }
- if (args.length > 1 && Settings.getEnablePasswordVerifier)
- if (!args[0].equals(args[1])) {
- m.send(player, "password_error");
- return true;
- }
- plugin.management.performRegister(player, args[0], "");
- return true;
- }
-}
diff --git a/src/main/java/fr/xephi/authme/commands/UnregisterCommand.java b/src/main/java/fr/xephi/authme/commands/UnregisterCommand.java
deleted file mode 100644
index 1361656d..00000000
--- a/src/main/java/fr/xephi/authme/commands/UnregisterCommand.java
+++ /dev/null
@@ -1,133 +0,0 @@
-package fr.xephi.authme.commands;
-
-import java.security.NoSuchAlgorithmException;
-
-import org.bukkit.Location;
-import org.bukkit.command.Command;
-import org.bukkit.command.CommandExecutor;
-import org.bukkit.command.CommandSender;
-import org.bukkit.entity.Player;
-import org.bukkit.inventory.ItemStack;
-import org.bukkit.potion.PotionEffect;
-import org.bukkit.potion.PotionEffectType;
-import org.bukkit.scheduler.BukkitScheduler;
-import org.bukkit.scheduler.BukkitTask;
-
-import fr.xephi.authme.AuthMe;
-import fr.xephi.authme.ConsoleLogger;
-import fr.xephi.authme.Utils;
-import fr.xephi.authme.Utils.groupType;
-import fr.xephi.authme.cache.auth.PlayerCache;
-import fr.xephi.authme.cache.backup.FileCache;
-import fr.xephi.authme.cache.limbo.LimboCache;
-import fr.xephi.authme.events.SpawnTeleportEvent;
-import fr.xephi.authme.security.PasswordSecurity;
-import fr.xephi.authme.settings.Messages;
-import fr.xephi.authme.settings.Settings;
-import fr.xephi.authme.task.MessageTask;
-import fr.xephi.authme.task.TimeoutTask;
-
-public class UnregisterCommand implements CommandExecutor {
-
- private Messages m = Messages.getInstance();
- public AuthMe plugin;
- private FileCache playerCache;
-
- public UnregisterCommand(AuthMe plugin) {
- this.plugin = plugin;
- this.playerCache = new FileCache(plugin);
- }
-
- @Override
- public boolean onCommand(CommandSender sender, Command cmnd, String label,
- String[] args) {
- if (!(sender instanceof Player)) {
- return true;
- }
-
- if (!plugin.authmePermissible(sender, "authme." + label.toLowerCase())) {
- m.send(sender, "no_perm");
- return true;
- }
-
- Player player = (Player) sender;
- String name = player.getName().toLowerCase();
-
- if (!PlayerCache.getInstance().isAuthenticated(name)) {
- m.send(player, "not_logged_in");
- return true;
- }
-
- if (args.length != 1) {
- m.send(player, "usage_unreg");
- return true;
- }
- try {
- if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash(), player.getName())) {
- if (!plugin.database.removeAuth(name)) {
- player.sendMessage("error");
- return true;
- }
- if (Settings.isForcedRegistrationEnabled) {
- if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
- Location spawn = plugin.getSpawnLocation(player);
- SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false);
- plugin.getServer().getPluginManager().callEvent(tpEvent);
- if (!tpEvent.isCancelled()) {
- player.teleport(tpEvent.getTo());
- }
- }
- player.getInventory().setContents(new ItemStack[36]);
- player.getInventory().setArmorContents(new ItemStack[4]);
- player.saveData();
- PlayerCache.getInstance().removePlayer(player.getName().toLowerCase());
- if (!Settings.getRegisteredGroup.isEmpty())
- Utils.getInstance().setGroup(player, groupType.UNREGISTERED);
- LimboCache.getInstance().addLimboPlayer(player);
- int delay = Settings.getRegistrationTimeout * 20;
- int interval = Settings.getWarnMessageInterval;
- BukkitScheduler sched = sender.getServer().getScheduler();
- if (delay != 0) {
- BukkitTask id = sched.runTaskLaterAsynchronously(plugin, new TimeoutTask(plugin, name, player), delay);
- LimboCache.getInstance().getLimboPlayer(name).setTimeoutTaskId(id);
- }
- LimboCache.getInstance().getLimboPlayer(name).setMessageTaskId(sched.runTaskAsynchronously(plugin, new MessageTask(plugin, name, m.send("reg_msg"), interval)));
- m.send(player, "unregistered");
- ConsoleLogger.info(player.getDisplayName() + " unregistered himself");
- return true;
- }
- if (!Settings.unRegisteredGroup.isEmpty()) {
- Utils.getInstance().setGroup(player, Utils.groupType.UNREGISTERED);
- }
- PlayerCache.getInstance().removePlayer(player.getName().toLowerCase());
- // check if Player cache File Exist and delete it, preventing
- // duplication of items
- if (playerCache.doesCacheExist(player)) {
- playerCache.removeCache(player);
- }
- if (Settings.applyBlindEffect)
- player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, Settings.getRegistrationTimeout * 20, 2));
- m.send(player, "unregistered");
- ConsoleLogger.info(player.getDisplayName() + " unregistered himself");
- if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) {
- Location spawn = plugin.getSpawnLocation(player);
- SpawnTeleportEvent tpEvent = new SpawnTeleportEvent(player, player.getLocation(), spawn, false);
- plugin.getServer().getPluginManager().callEvent(tpEvent);
- if (!tpEvent.isCancelled()) {
- if (!tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).isLoaded()) {
- tpEvent.getTo().getWorld().getChunkAt(tpEvent.getTo()).load();
- }
- player.teleport(tpEvent.getTo());
- }
- }
- return true;
- } else {
- m.send(player, "wrong_pwd");
- }
- } catch (NoSuchAlgorithmException ex) {
- ConsoleLogger.showError(ex.getMessage());
- sender.sendMessage("Internal Error please read the server log");
- }
- return true;
- }
-}
diff --git a/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java b/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java
index 0ffae7db..26dcff38 100644
--- a/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java
+++ b/src/main/java/fr/xephi/authme/converter/CrazyLoginConverter.java
@@ -2,7 +2,6 @@ package fr.xephi.authme.converter;
import java.io.BufferedReader;
import java.io.File;
-import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
@@ -15,7 +14,6 @@ import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.settings.Settings;
/**
- *
* @author Xephi59
*/
public class CrazyLoginConverter implements Converter {
@@ -34,22 +32,17 @@ public class CrazyLoginConverter implements Converter {
return this;
}
- private static String fileName;
- private static File source;
-
@Override
public void run() {
- fileName = Settings.crazyloginFileName;
+ String fileName = Settings.crazyloginFileName;
try {
- source = new File(AuthMe.getInstance().getDataFolder() + File.separator + fileName);
+ File source = new File(AuthMe.getInstance().getDataFolder() + File.separator + fileName);
if (!source.exists()) {
sender.sendMessage("Error while trying to import datas, please put " + fileName + " in AuthMe folder!");
return;
}
- source.createNewFile();
- BufferedReader users = null;
String line;
- users = new BufferedReader(new FileReader(source));
+ BufferedReader users = new BufferedReader(new FileReader(source));
while ((line = users.readLine()) != null) {
if (line.contains("|")) {
String[] args = line.split("\\|");
@@ -57,23 +50,19 @@ public class CrazyLoginConverter implements Converter {
continue;
if (args[0].equalsIgnoreCase("name"))
continue;
- String player = args[0].toLowerCase();
+ String playerName = args[0].toLowerCase();
String psw = args[1];
- try {
- if (player != null && psw != null) {
- PlayerAuth auth = new PlayerAuth(player, psw, "127.0.0.1", System.currentTimeMillis(), player);
- database.saveAuth(auth);
- }
- } catch (Exception e) {
+ if (psw != null) {
+ PlayerAuth auth = new PlayerAuth(playerName, psw, "127.0.0.1", System.currentTimeMillis(), playerName);
+ database.saveAuth(auth);
}
}
}
users.close();
ConsoleLogger.info("CrazyLogin database has been imported correctly");
- } catch (FileNotFoundException ex) {
- ConsoleLogger.showError(ex.getMessage());
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
+ ConsoleLogger.showError("Can't open the crazylogin database file! Does it exist?");
}
}
diff --git a/src/main/java/fr/xephi/authme/converter/FlatToSql.java b/src/main/java/fr/xephi/authme/converter/FlatToSql.java
index 03112a60..08641926 100644
--- a/src/main/java/fr/xephi/authme/converter/FlatToSql.java
+++ b/src/main/java/fr/xephi/authme/converter/FlatToSql.java
@@ -3,7 +3,6 @@ package fr.xephi.authme.converter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
-import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
@@ -13,7 +12,6 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.settings.Settings;
/**
- *
* @author Xephi59
*/
public class FlatToSql implements Converter {
@@ -30,8 +28,6 @@ public class FlatToSql implements Converter {
private static String columnEmail;
private static String columnLogged;
private static String columnID;
- private static File source;
- private static File output;
public FlatToSql() {
tableName = Settings.getMySQLTablename;
@@ -51,9 +47,9 @@ public class FlatToSql implements Converter {
@Override
public void run() {
try {
- source = new File(AuthMe.getInstance().getDataFolder() + File.separator + "auths.db");
+ File source = new File(AuthMe.getInstance().getDataFolder() + File.separator + "auths.db");
source.createNewFile();
- output = new File(AuthMe.getInstance().getDataFolder() + File.separator + "authme.sql");
+ File output = new File(AuthMe.getInstance().getDataFolder() + File.separator + "authme.sql");
output.createNewFile();
BufferedReader br = new BufferedReader(new FileReader(source));
BufferedWriter sql = new BufferedWriter(new FileWriter(output));
@@ -79,10 +75,9 @@ public class FlatToSql implements Converter {
sql.close();
br.close();
ConsoleLogger.info("The FlatFile has been converted to authme.sql file");
- } catch (FileNotFoundException ex) {
- ConsoleLogger.showError(ex.getMessage());
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
+ ConsoleLogger.showError("Can't open the flat database file! Does it exist?");
}
}
}
diff --git a/src/main/java/fr/xephi/authme/converter/FlatToSqlite.java b/src/main/java/fr/xephi/authme/converter/FlatToSqlite.java
index 757a9d2d..cc121b82 100644
--- a/src/main/java/fr/xephi/authme/converter/FlatToSqlite.java
+++ b/src/main/java/fr/xephi/authme/converter/FlatToSqlite.java
@@ -2,7 +2,6 @@ package fr.xephi.authme.converter;
import java.io.BufferedReader;
import java.io.File;
-import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
@@ -14,32 +13,38 @@ import java.sql.Statement;
import org.bukkit.command.CommandSender;
-import fr.xephi.authme.AuthMe;
import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.settings.Settings;
public class FlatToSqlite implements Converter {
public CommandSender sender;
-
+ private String tableName;
+ private String columnName;
+ private String columnPassword;
+ private String columnIp;
+ private String columnLastLogin;
+ private String lastlocX;
+ private String lastlocY;
+ private String lastlocZ;
+ private String lastlocWorld;
+ private String columnEmail;
+ private String database;
+ private String columnID;
+ private Connection con;
public FlatToSqlite(CommandSender sender) {
this.sender = sender;
}
- private static String tableName;
- private static String columnName;
- private static String columnPassword;
- private static String columnIp;
- private static String columnLastLogin;
- private static String lastlocX;
- private static String lastlocY;
- private static String lastlocZ;
- private static String lastlocWorld;
- private static String columnEmail;
- private static File source;
- private static String database;
- private static String columnID;
- private static Connection con;
+ private static void close(AutoCloseable o) {
+ if (o != null) {
+ try {
+ o.close();
+ } catch (Exception ex) {
+ ConsoleLogger.showError(ex.getMessage());
+ }
+ }
+ }
@Override
public void run() {
@@ -56,6 +61,12 @@ public class FlatToSqlite implements Converter {
columnEmail = Settings.getMySQLColumnEmail;
columnID = Settings.getMySQLColumnId;
+ File source = new File(Settings.PLUGIN_FOLDER, "auths.db");
+ if (!source.exists()) {
+ sender.sendMessage("Source file for FlatFile database not found... Aborting");
+ return;
+ }
+
try {
connect();
setup();
@@ -63,14 +74,12 @@ public class FlatToSqlite implements Converter {
sender.sendMessage("Some error appeared while trying to setup and connect to sqlite database... Aborting");
return;
}
- try {
- source = new File(AuthMe.getInstance().getDataFolder() + File.separator + "auths.db");
- source.createNewFile();
- BufferedReader br = new BufferedReader(new FileReader(source));
+
+ try (BufferedReader reader = new BufferedReader(new FileReader(source))) {
String line;
int i = 1;
String newline;
- while ((line = br.readLine()) != null) {
+ while ((line = reader.readLine()) != null) {
String[] args = line.split(":");
if (args.length == 4)
newline = "INSERT INTO " + tableName + " VALUES (" + i + ", '" + args[0] + "', '" + args[1] + "', '" + args[2] + "', " + args[3] + ", 0, 0, 0, 'world', 'your@email.com');";
@@ -85,27 +94,23 @@ public class FlatToSqlite implements Converter {
saveAuth(newline);
i = i + 1;
}
- br.close();
- ConsoleLogger.info("The FlatFile has been converted to " + database + ".db file");
- close();
- sender.sendMessage("The FlatFile has been converted to " + database + ".db file");
- return;
- } catch (FileNotFoundException ex) {
- ConsoleLogger.showError(ex.getMessage());
+ String resp = "The FlatFile has been converted to " + database + ".db file";
+ ConsoleLogger.info(resp);
+ sender.sendMessage(resp);
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
+ sender.sendMessage("Can't open the flat database file!");
+ } finally {
+ close(con);
}
- sender.sendMessage("Errors appears while trying to convert to SQLite");
- return;
}
- private synchronized static void connect()
- throws ClassNotFoundException, SQLException {
+ private synchronized void connect() throws ClassNotFoundException, SQLException {
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:plugins/AuthMe/" + database + ".db");
}
- private synchronized static void setup() throws SQLException {
+ private synchronized void setup() throws SQLException {
Statement st = null;
ResultSet rs = null;
try {
@@ -148,7 +153,7 @@ public class FlatToSqlite implements Converter {
}
}
- private static synchronized boolean saveAuth(String s) {
+ private synchronized boolean saveAuth(String s) {
PreparedStatement pst = null;
try {
pst = con.prepareStatement(s);
@@ -161,32 +166,4 @@ public class FlatToSqlite implements Converter {
}
return true;
}
-
- private static void close(Statement st) {
- if (st != null) {
- try {
- st.close();
- } catch (SQLException ex) {
- ConsoleLogger.showError(ex.getMessage());
- }
- }
- }
-
- private static void close(ResultSet rs) {
- if (rs != null) {
- try {
- rs.close();
- } catch (SQLException ex) {
- ConsoleLogger.showError(ex.getMessage());
- }
- }
- }
-
- public synchronized static void close() {
- try {
- con.close();
- } catch (SQLException ex) {
- ConsoleLogger.showError(ex.getMessage());
- }
- }
}
diff --git a/src/main/java/fr/xephi/authme/converter/ForceFlatToSqlite.java b/src/main/java/fr/xephi/authme/converter/ForceFlatToSqlite.java
index 44034a49..2c95d1cd 100644
--- a/src/main/java/fr/xephi/authme/converter/ForceFlatToSqlite.java
+++ b/src/main/java/fr/xephi/authme/converter/ForceFlatToSqlite.java
@@ -5,15 +5,13 @@ import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.datasource.SQLite;
+import fr.xephi.authme.settings.Settings;
public class ForceFlatToSqlite implements Converter {
private DataSource data;
- private AuthMe plugin;
-
public ForceFlatToSqlite(DataSource data, AuthMe plugin) {
this.data = data;
- this.plugin = plugin;
}
@Override
@@ -21,9 +19,11 @@ public class ForceFlatToSqlite implements Converter {
DataSource sqlite = null;
try {
sqlite = new SQLite();
- for (PlayerAuth auth : data.getAllAuths())
+ for (PlayerAuth auth : data.getAllAuths()) {
+ auth.setRealName("Player");
sqlite.saveAuth(auth);
- plugin.getSettings().setValue("DataSource.backend", "sqlite");
+ }
+ Settings.setValue("DataSource.backend", "sqlite");
ConsoleLogger.info("Database successfully converted to sqlite !");
} catch (Exception e) {
ConsoleLogger.showError("An error appeared while trying to convert flatfile to sqlite ...");
diff --git a/src/main/java/fr/xephi/authme/converter/RakamakConverter.java b/src/main/java/fr/xephi/authme/converter/RakamakConverter.java
index 333b6bde..caeaccc7 100644
--- a/src/main/java/fr/xephi/authme/converter/RakamakConverter.java
+++ b/src/main/java/fr/xephi/authme/converter/RakamakConverter.java
@@ -2,7 +2,6 @@ package fr.xephi.authme.converter;
import java.io.BufferedReader;
import java.io.File;
-import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
@@ -20,7 +19,6 @@ import fr.xephi.authme.security.PasswordSecurity;
import fr.xephi.authme.settings.Settings;
/**
- *
* @author Xephi59
*/
public class RakamakConverter implements Converter {
@@ -39,27 +37,19 @@ public class RakamakConverter implements Converter {
return this;
}
- private static Boolean useIP;
- private static String fileName;
- private static String ipFileName;
- private static File source;
- private static File ipfiles;
-
@Override
public void run() {
HashAlgorithm hash = Settings.getPasswordHash;
- useIP = Settings.rakamakUseIp;
- fileName = Settings.rakamakUsers;
- ipFileName = Settings.rakamakUsersIp;
- HashMap playerIP = new HashMap();
- HashMap playerPSW = new HashMap();
+ boolean useIP = Settings.rakamakUseIp;
+ String fileName = Settings.rakamakUsers;
+ String ipFileName = Settings.rakamakUsersIp;
+ File source = new File(Settings.PLUGIN_FOLDER, fileName);
+ File ipfiles = new File(Settings.PLUGIN_FOLDER, ipFileName);
+ HashMap playerIP = new HashMap<>();
+ HashMap playerPSW = new HashMap<>();
try {
- source = new File(AuthMe.getInstance().getDataFolder() + File.separator + fileName);
- ipfiles = new File(AuthMe.getInstance().getDataFolder() + File.separator + ipFileName);
- source.createNewFile();
- ipfiles.createNewFile();
- BufferedReader users = null;
- BufferedReader ipFile = null;
+ BufferedReader users;
+ BufferedReader ipFile;
ipFile = new BufferedReader(new FileReader(ipfiles));
String line;
if (useIP) {
@@ -85,27 +75,24 @@ public class RakamakConverter implements Converter {
}
users.close();
for (Entry m : playerPSW.entrySet()) {
- String player = m.getKey();
- String psw = playerPSW.get(player);
+ String playerName = m.getKey();
+ String psw = playerPSW.get(playerName);
String ip;
if (useIP) {
- ip = playerIP.get(player);
+ ip = playerIP.get(playerName);
} else {
ip = "127.0.0.1";
}
- PlayerAuth auth = new PlayerAuth(player, psw, ip, System.currentTimeMillis(), player);
- if (PasswordSecurity.userSalt.containsKey(player))
- auth.setSalt(PasswordSecurity.userSalt.get(player));
+ PlayerAuth auth = new PlayerAuth(playerName, psw, ip, System.currentTimeMillis(), playerName);
+ if (PasswordSecurity.userSalt.containsKey(playerName))
+ auth.setSalt(PasswordSecurity.userSalt.get(playerName));
database.saveAuth(auth);
}
ConsoleLogger.info("Rakamak database has been imported correctly");
sender.sendMessage("Rakamak database has been imported correctly");
- } catch (FileNotFoundException ex) {
- ConsoleLogger.showError(ex.getMessage());
- sender.sendMessage("Error file not found");
} catch (IOException ex) {
ConsoleLogger.showError(ex.getMessage());
- sender.sendMessage("Error IOException");
+ sender.sendMessage("Can't open the rakamak database file! Does it exist?");
}
}
}
diff --git a/src/main/java/fr/xephi/authme/converter/RoyalAuthConverter.java b/src/main/java/fr/xephi/authme/converter/RoyalAuthConverter.java
index c39984d8..03e27813 100644
--- a/src/main/java/fr/xephi/authme/converter/RoyalAuthConverter.java
+++ b/src/main/java/fr/xephi/authme/converter/RoyalAuthConverter.java
@@ -24,16 +24,17 @@ public class RoyalAuthConverter implements Converter {
for (OfflinePlayer o : plugin.getServer().getOfflinePlayers()) {
try {
String name = o.getName().toLowerCase();
- String separator = File.separator;
- File file = new File("." + separator + "plugins" + separator + "RoyalAuth" + separator + "userdata" + separator + name + ".yml");
+ String sp = File.separator;
+ File file = new File("." + sp + "plugins" + sp + "RoyalAuth" + sp + "userdata" + sp + name + ".yml");
if (data.isAuthAvailable(name))
continue;
if (!file.exists())
continue;
RoyalAuthYamlReader ra = new RoyalAuthYamlReader(file);
- PlayerAuth auth = new PlayerAuth(name, ra.getHash(), "127.0.0.1", ra.getLastLogin(), "your@email.com");
+ PlayerAuth auth = new PlayerAuth(name, ra.getHash(), "127.0.0.1", ra.getLastLogin(), "your@email.com", o.getName());
data.saveAuth(auth);
} catch (Exception e) {
+ ConsoleLogger.writeStackTrace(e);
ConsoleLogger.showError("Error while trying to import " + o.getName() + " RoyalAuth datas");
}
}
diff --git a/src/main/java/fr/xephi/authme/converter/SqlToFlat.java b/src/main/java/fr/xephi/authme/converter/SqlToFlat.java
index 4dccbd43..484d2a6b 100644
--- a/src/main/java/fr/xephi/authme/converter/SqlToFlat.java
+++ b/src/main/java/fr/xephi/authme/converter/SqlToFlat.java
@@ -38,11 +38,9 @@ public class SqlToFlat implements Converter {
}
}
sender.sendMessage("Successfully convert from SQL table to file auths.db");
- return;
} catch (Exception ex) {
ConsoleLogger.showError(ex.getMessage());
Messages.getInstance().send(sender, "error");
- return;
}
}
diff --git a/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java b/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java
index 5b2a0be9..8e2a1fc5 100644
--- a/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java
+++ b/src/main/java/fr/xephi/authme/converter/vAuthFileReader.java
@@ -10,6 +10,7 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import fr.xephi.authme.AuthMe;
+import fr.xephi.authme.ConsoleLogger;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.datasource.DataSource;
@@ -27,33 +28,31 @@ public class vAuthFileReader {
public void convert() throws IOException {
final File file = new File(plugin.getDataFolder().getParent() + "" + File.separator + "vAuth" + File.separator + "passwords.yml");
- Scanner scanner = null;
+ Scanner scanner;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String name = line.split(": ")[0];
String password = line.split(": ")[1];
- PlayerAuth auth = null;
+ PlayerAuth auth;
if (isUUIDinstance(password)) {
- String pname = null;
+ String pname;
try {
pname = Bukkit.getOfflinePlayer(UUID.fromString(name)).getName();
- } catch (Exception e) {
- pname = getName(UUID.fromString(name));
- } catch (NoSuchMethodError e) {
+ } catch (Exception | NoSuchMethodError e) {
pname = getName(UUID.fromString(name));
}
if (pname == null)
continue;
- auth = new PlayerAuth(pname.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com");
+ auth = new PlayerAuth(pname.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com", pname);
} else {
- auth = new PlayerAuth(name.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com");
+ auth = new PlayerAuth(name.toLowerCase(), password, "127.0.0.1", System.currentTimeMillis(), "your@email.com", name);
}
- if (auth != null)
- database.saveAuth(auth);
+ database.saveAuth(auth);
}
} catch (Exception e) {
+ ConsoleLogger.writeStackTrace(e);
}
}
@@ -70,7 +69,7 @@ public class vAuthFileReader {
if (op.getUniqueId().compareTo(uuid) == 0)
return op.getName();
}
- } catch (Exception e) {
+ } catch (Exception ignored) {
}
return null;
}
diff --git a/src/main/java/fr/xephi/authme/converter/xAuthToFlat.java b/src/main/java/fr/xephi/authme/converter/xAuthToFlat.java
index 61be7cb8..df45d80c 100644
--- a/src/main/java/fr/xephi/authme/converter/xAuthToFlat.java
+++ b/src/main/java/fr/xephi/authme/converter/xAuthToFlat.java
@@ -48,7 +48,7 @@ public class xAuthToFlat {
String pl = getIdPlayer(id);
String psw = getPassword(id);
if (psw != null && !psw.isEmpty() && pl != null) {
- PlayerAuth auth = new PlayerAuth(pl, psw, "192.168.0.1", 0, "your@email.com");
+ PlayerAuth auth = new PlayerAuth(pl, psw, "192.168.0.1", 0, "your@email.com", pl);
database.saveAuth(auth);
}
}
@@ -82,7 +82,7 @@ public class xAuthToFlat {
}
public List getXAuthPlayers() {
- List xP = new ArrayList();
+ List xP = new ArrayList<>();
Connection conn = xAuth.getPlugin().getDatabaseController().getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
@@ -95,7 +95,7 @@ public class xAuthToFlat {
}
} catch (SQLException e) {
xAuthLog.severe("Cannot import xAuthPlayers", e);
- return new ArrayList();
+ return new ArrayList<>();
} finally {
xAuth.getPlugin().getDatabaseController().close(conn, ps, rs);
}
diff --git a/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java b/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java
index fb96bc7c..03d1af22 100644
--- a/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java
+++ b/src/main/java/fr/xephi/authme/datasource/CacheDataSource.java
@@ -1,30 +1,45 @@
package fr.xephi.authme.datasource;
+import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
import org.bukkit.entity.Player;
import fr.xephi.authme.AuthMe;
import fr.xephi.authme.cache.auth.PlayerAuth;
import fr.xephi.authme.cache.auth.PlayerCache;
+import fr.xephi.authme.util.Utils;
public class CacheDataSource implements DataSource {
- private DataSource source;
- public AuthMe plugin;
- private ConcurrentHashMap cache = new ConcurrentHashMap();
+ private final DataSource source;
+ private final ExecutorService exec;
+ private final ConcurrentHashMap cache = new ConcurrentHashMap<>();
+
+ public CacheDataSource(final AuthMe pl, DataSource src) {
+ this.source = src;
+ this.exec = Executors.newCachedThreadPool();
+ pl.setCanConnect(false);
- public CacheDataSource(AuthMe plugin, DataSource source) {
- this.plugin = plugin;
- this.source = source;
/*
* We need to load all players in cache ... It will took more time to
* load the server, but it will be much easier to check for an
* isAuthAvailable !
*/
- for (PlayerAuth auth : source.getAllAuths())
- cache.put(auth.getNickname().toLowerCase(), auth);
+ exec.execute(new Runnable() {
+ @Override
+ public void run() {
+ for (PlayerAuth auth : source.getAllAuths()) {
+ cache.put(auth.getNickname().toLowerCase(), auth);
+ }
+ pl.setCanConnect(true);
+ }
+ });
}
@Override
@@ -37,62 +52,114 @@ public class CacheDataSource implements DataSource {
user = user.toLowerCase();
if (cache.containsKey(user)) {
return cache.get(user);
- } else {
- PlayerAuth auth = source.getAuth(user);
- if (auth != null)
- cache.put(user, auth);
- return auth;
}
+ return null;
}
@Override
- public synchronized boolean saveAuth(PlayerAuth auth) {
- if (source.saveAuth(auth)) {
- cache.put(auth.getNickname(), auth);
- return true;
- }
- return false;
- }
-
- @Override
- public synchronized boolean updatePassword(PlayerAuth auth) {
- if (source.updatePassword(auth)) {
- if (cache.containsKey(auth.getNickname()))
- cache.get(auth.getNickname()).setHash(auth.getHash());
- return true;
- }
- return false;
- }
-
- @Override
- public boolean updateSession(PlayerAuth auth) {
- if (source.updateSession(auth)) {
- if (cache.containsKey(auth.getNickname())) {
- cache.get(auth.getNickname()).setIp(auth.getIp());
- cache.get(auth.getNickname()).setLastLogin(auth.getLastLogin());
+ public synchronized boolean saveAuth(final PlayerAuth auth) {
+ cache.put(auth.getNickname(), auth);
+ exec.execute(new Runnable() {
+ @Override
+ public void run() {
+ if (!source.saveAuth(auth)) {
+ cache.remove(auth.getNickname());
+ }
}
- return true;
- }
- return false;
+ });
+ return true;
}
@Override
- public boolean updateQuitLoc(PlayerAuth auth) {
- if (source.updateQuitLoc(auth)) {
- if (cache.containsKey(auth.getNickname())) {
- cache.get(auth.getNickname()).setQuitLocX(auth.getQuitLocX());
- cache.get(auth.getNickname()).setQuitLocY(auth.getQuitLocY());
- cache.get(auth.getNickname()).setQuitLocZ(auth.getQuitLocZ());
- cache.get(auth.getNickname()).setWorld(auth.getWorld());
- }
- return true;
+ public synchronized boolean updatePassword(final PlayerAuth auth) {
+ if (!cache.containsKey(auth.getNickname())) {
+ return false;
}
- return false;
+ final String oldHash = cache.get(auth.getNickname()).getHash();
+ cache.get(auth.getNickname()).setHash(auth.getHash());
+ exec.execute(new Runnable() {
+ @Override
+ public void run() {
+ if (!source.updatePassword(auth)) {
+ if (cache.containsKey(auth.getNickname())) {
+ cache.get(auth.getNickname()).setHash(oldHash);
+ }
+ }
+ }
+ });
+ return true;
+ }
+
+ @Override
+ public boolean updateSession(final PlayerAuth auth) {
+ if (!cache.containsKey(auth.getNickname())) {
+ return false;
+ }
+ PlayerAuth cachedAuth = cache.get(auth.getNickname());
+ final String oldIp = cachedAuth.getIp();
+ final long oldLastLogin = cachedAuth.getLastLogin();
+ final String oldRealName = cachedAuth.getRealName();
+
+ cachedAuth.setIp(auth.getIp());
+ cachedAuth.setLastLogin(auth.getLastLogin());
+ cachedAuth.setRealName(auth.getRealName());
+ exec.execute(new Runnable() {
+ @Override
+ public void run() {
+ if (!source.updateSession(auth)) {
+ if (cache.containsKey(auth.getNickname())) {
+ PlayerAuth cachedAuth = cache.get(auth.getNickname());
+ cachedAuth.setIp(oldIp);
+ cachedAuth.setLastLogin(oldLastLogin);
+ cachedAuth.setRealName(oldRealName);
+ }
+ }
+ }
+ });
+ return true;
+ }
+
+ @Override
+ public boolean updateQuitLoc(final PlayerAuth auth) {
+ if (!cache.containsKey(auth.getNickname())) {
+ return false;
+ }
+ final PlayerAuth cachedAuth = cache.get(auth.getNickname());
+ final double oldX = cachedAuth.getQuitLocX();
+ final double oldY = cachedAuth.getQuitLocY();
+ final double oldZ = cachedAuth.getQuitLocZ();
+ final String oldWorld = cachedAuth.getWorld();
+
+ cachedAuth.setQuitLocX(auth.getQuitLocX());
+ cachedAuth.setQuitLocY(auth.getQuitLocY());
+ cachedAuth.setQuitLocZ(auth.getQuitLocZ());
+ cachedAuth.setWorld(auth.getWorld());
+ exec.execute(new Runnable() {
+ @Override
+ public void run() {
+ if (!source.updateQuitLoc(auth)) {
+ if (cache.containsKey(auth.getNickname())) {
+ PlayerAuth cachedAuth = cache.get(auth.getNickname());
+ cachedAuth.setQuitLocX(oldX);
+ cachedAuth.setQuitLocY(oldY);
+ cachedAuth.setQuitLocZ(oldZ);
+ cachedAuth.setWorld(oldWorld);
+ }
+ }
+ }
+ });
+ return true;
}
@Override
public int getIps(String ip) {
- return source.getIps(ip);
+ int count = 0;
+ for (Map.Entry p : cache.entrySet()) {
+ if (p.getValue().getIp().equals(ip)) {
+ count++;
+ }
+ }
+ return count;
}
@Override
@@ -122,79 +189,121 @@ public class CacheDataSource implements DataSource {
}
@Override
- public synchronized boolean removeAuth(String user) {
- if (source.removeAuth(user)) {
- cache.remove(user);
- return true;
- }
- return false;
+ public synchronized boolean removeAuth(String username) {
+ final String user = username.toLowerCase();
+ final PlayerAuth auth = cache.get(user);
+ cache.remove(user);
+ exec.execute(new Runnable() {
+ @Override
+ public void run() {
+ if (!source.removeAuth(user)) {
+ cache.put(user, auth);
+ }
+ }
+ });
+ return true;
}
@Override
public synchronized void close() {
+ exec.shutdown();
source.close();
}
@Override
public void reload() {
- cache.clear();
- source.reload();
- for (Player player : plugin.getServer().getOnlinePlayers()) {
- String user = player.getName().toLowerCase();
- if (PlayerCache.getInstance().isAuthenticated(user)) {
- try {
- PlayerAuth auth = source.getAuth(user);
- cache.put(user, auth);
- } catch (NullPointerException npe) {
+ exec.execute(new Runnable() {
+ @Override
+ public void run() {
+ cache.clear();
+ source.reload();
+ for (Player player : Utils.getOnlinePlayers()) {
+ String user = player.getName().toLowerCase();
+ if (PlayerCache.getInstance().isAuthenticated(user)) {
+ PlayerAuth auth = source.getAuth(user);
+ cache.put(user, auth);
+ }
}
-
}
+ });
+ }
+
+ @Override
+ public synchronized boolean updateEmail(final PlayerAuth auth) {
+ try {
+ return exec.submit(new Callable() {
+ public Boolean call() {
+ return source.updateEmail(auth);
+ }
+ }).get();
+ } catch (Exception e) {
+ return false;
}
}
@Override
- public synchronized boolean updateEmail(PlayerAuth auth) {
- if (source.updateEmail(auth)) {
- if (cache.containsKey(auth.getNickname()))
- cache.get(auth.getNickname()).setEmail(auth.getEmail());
- return true;
+ public synchronized boolean updateSalt(final PlayerAuth auth) {
+ if (!cache.containsKey(auth.getNickname())) {
+ return false;
}
- return false;
- }
-
- @Override
- public synchronized boolean updateSalt(PlayerAuth auth) {
- if (source.updateSalt(auth)) {
- if (cache.containsKey(auth.getNickname()))
- cache.get(auth.getNickname()).setSalt(auth.getSalt());
- return true;
- }
- return false;
+ PlayerAuth cachedAuth = cache.get(auth.getNickname());
+ final String oldSalt = cachedAuth.getSalt();
+ cachedAuth.setSalt(auth.getSalt());
+ exec.execute(new Runnable() {
+ @Override
+ public void run() {
+ if (!source.updateSalt(auth)) {
+ if (cache.containsKey(auth.getNickname())) {
+ cache.get(auth.getNickname()).setSalt(oldSalt);
+ }
+ }
+ }
+ });
+ return true;
}
@Override
public synchronized List getAllAuthsByName(PlayerAuth auth) {
- return source.getAllAuthsByName(auth);
- }
-
- @Override
- public synchronized List getAllAuthsByIp(String ip) {
- return source.getAllAuthsByIp(ip);
- }
-
- @Override
- public synchronized List getAllAuthsByEmail(String email) {
- return source.getAllAuthsByEmail(email);
- }
-
- @Override
- public synchronized void purgeBanned(List banned) {
- source.purgeBanned(banned);
- for (PlayerAuth auth : cache.values()) {
- if (banned.contains(auth.getNickname())) {
- cache.remove(auth.getNickname());
- }
+ List result = new ArrayList<>();
+ for (Map.Entry stringPlayerAuthEntry : cache.entrySet()) {
+ PlayerAuth p = stringPlayerAuthEntry.getValue();
+ if (p.getIp().equals(auth.getIp()))
+ result.add(p.getNickname());
}
+ return result;
+ }
+
+ @Override
+ public synchronized List getAllAuthsByIp(final String ip) throws Exception {
+ return exec.submit(new Callable>() {
+ public List call() throws Exception {
+ return source.getAllAuthsByIp(ip);
+ }
+ }).get();
+ }
+
+ @Override
+ public synchronized List getAllAuthsByEmail(final String email) throws Exception {
+ return exec.submit(new Callable>() {
+ public List call() throws Exception {
+ return source.getAllAuthsByEmail(email);
+ }
+ }).get();
+ }
+
+ @Override
+ public synchronized void purgeBanned(final List banned) {
+ exec.execute(new Runnable() {
+ @Override
+ public void run() {
+ source.purgeBanned(banned);
+ for (PlayerAuth auth : cache.values()) {
+ if (banned.contains(auth.getNickname())) {
+ cache.remove(auth.getNickname());
+ }
+ }
+ }
+ });
}
@Override
@@ -204,45 +313,66 @@ public class CacheDataSource implements DataSource {
@Override
public boolean isLogged(String user) {
- return source.isLogged(user.toLowerCase());
+ user = user.toLowerCase();
+ return PlayerCache.getInstance().getCache().containsKey(user);
}
@Override
- public void setLogged(String user) {
- source.setLogged(user.toLowerCase());
+ public void setLogged(final String user) {
+ exec.execute(new Runnable() {
+ @Override
+ public void run() {
+ source.setLogged(user.toLowerCase());
+ }
+ });
}
@Override
- public void setUnlogged(String user) {
- source.setUnlogged(user.toLowerCase());
+ public void setUnlogged(final String user) {
+ exec.execute(new Runnable() {
+ @Override
+ public void run() {
+ source.setUnlogged(user.toLowerCase());
+ }
+ });
}
@Override
public void purgeLogged() {
- source.purgeLogged();
+ exec.execute(new Runnable() {
+ @Override
+ public void run() {
+ source.purgeLogged();
+ }
+ });
}
@Override
public int getAccountsRegistered() {
- return source.getAccountsRegistered();
+ return cache.size();
}
@Override
- public void updateName(String oldone, String newone) {
+ public void updateName(final String oldone, final String newone) {
if (cache.containsKey(oldone)) {
cache.put(newone, cache.get(oldone));
cache.remove(oldone);
}
- source.updateName(oldone, newone);
+ exec.execute(new Runnable() {
+ @Override
+ public void run() {
+ source.updateName(oldone, newone);
+ }
+ });
}
@Override
public List getAllAuths() {
- return source.getAllAuths();
+ return new ArrayList<>(cache.values());
}
@Override
public List getLoggedPlayers() {
- return source.getLoggedPlayers();
+ return new ArrayList<>(PlayerCache.getInstance().getCache().values());
}
}
diff --git a/src/main/java/fr/xephi/authme/datasource/DataSource.java b/src/main/java/fr/xephi/authme/datasource/DataSource.java
index ef445dc4..c4fada07 100644
--- a/src/main/java/fr/xephi/authme/datasource/DataSource.java
+++ b/src/main/java/fr/xephi/authme/datasource/DataSource.java
@@ -6,8 +6,7 @@ import fr.xephi.authme.cache.auth.PlayerAuth;
public interface DataSource {
- public enum DataSourceType {
-
+ enum DataSourceType {
MYSQL,
FILE,
SQLITE
@@ -35,9 +34,9 @@ public interface DataSource {
List getAllAuthsByName(PlayerAuth auth);
- List getAllAuthsByIp(String ip);
+ List getAllAuthsByIp(String ip) throws Exception;
- List getAllAuthsByEmail(String email);
+ List getAllAuthsByEmail(String email) throws Exception;
boolean updateEmail(PlayerAuth auth);
diff --git a/src/main/java/fr/xephi/authme/datasource/DatabaseCalls.java b/src/main/java/fr/xephi/authme/datasource/DatabaseCalls.java
index 1b3e0993..5a263b28 100644
--- a/src/main/java/fr/xephi/authme/datasource/DatabaseCalls.java
+++ b/src/main/java/fr/xephi/authme/datasource/DatabaseCalls.java
@@ -3,7 +3,6 @@ package fr.xephi.authme.datasource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -12,56 +11,34 @@ import fr.xephi.authme.cache.auth.PlayerAuth;
public class DatabaseCalls implements DataSource {
private DataSource database;
+ private final ExecutorService exec;
public DatabaseCalls(DataSource database) {
this.database = database;
+ this.exec = Executors.newCachedThreadPool();
}
@Override
public synchronized boolean isAuthAvailable(final String user) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Boolean result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Boolean call() throws Exception {
return database.isAuthAvailable(user);
}
}).get();
- } catch (InterruptedException e1) {
- return false;
- } catch (ExecutionException e1) {
- return false;
- } finally {
- executor.shutdown();
- }
- try {
- return result.booleanValue();
} catch (Exception e) {
- return (false);
+ return false;
}
}
@Override
public synchronized PlayerAuth getAuth(final String user) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- PlayerAuth result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public PlayerAuth call() throws Exception {
return database.getAuth(user);
}
}).get();
- } catch (InterruptedException e1) {
- return null;
- } catch (ExecutionException e1) {
- return null;
- } finally {
- executor.shutdown();
- }
- try {
- return result;
} catch (Exception e) {
return null;
}
@@ -69,331 +46,177 @@ public class DatabaseCalls implements DataSource {
@Override
public synchronized boolean saveAuth(final PlayerAuth auth) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Boolean result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Boolean call() throws Exception {
return database.saveAuth(auth);
}
}).get();
- } catch (InterruptedException e1) {
- return false;
- } catch (ExecutionException e1) {
- return false;
- } finally {
- executor.shutdown();
- }
- try {
- return result.booleanValue();
} catch (Exception e) {
- return (false);
+ return false;
}
}
@Override
public synchronized boolean updateSession(final PlayerAuth auth) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Boolean result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Boolean call() throws Exception {
return database.updateSession(auth);
}
}).get();
- } catch (InterruptedException e1) {
- return false;
- } catch (ExecutionException e1) {
- return false;
- } finally {
- executor.shutdown();
- }
- try {
- return result.booleanValue();
} catch (Exception e) {
- return (false);
+ return false;
}
}
@Override
public synchronized boolean updatePassword(final PlayerAuth auth) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Boolean result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Boolean call() throws Exception {
return database.updatePassword(auth);
}
}).get();
- } catch (InterruptedException e1) {
- return false;
- } catch (ExecutionException e1) {
- return false;
- } finally {
- executor.shutdown();
- }
- try {
- return result.booleanValue();
} catch (Exception e) {
- return (false);
+ return false;
}
}
@Override
public synchronized int purgeDatabase(final long until) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Integer result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Integer call() throws Exception {
return database.purgeDatabase(until);
}
}).get();
- } catch (InterruptedException e1) {
- return 0;
- } catch (ExecutionException e1) {
- return 0;
- } finally {
- executor.shutdown();
- }
- try {
- return result.intValue();
} catch (Exception e) {
- return (0);
+ return -1;
}
}
@Override
public synchronized List autoPurgeDatabase(final long until) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- List result;
try {
- result = executor.submit(new Callable>() {
-
+ return exec.submit(new Callable>() {
public List call() throws Exception {
return database.autoPurgeDatabase(until);
}
}).get();
- } catch (InterruptedException e1) {
- return new ArrayList();
- } catch (ExecutionException e1) {
- return new ArrayList();
- } finally {
- executor.shutdown();
- }
- try {
- return result;
} catch (Exception e) {
- return (new ArrayList());
+ return new ArrayList<>();
}
}
@Override
public synchronized boolean removeAuth(final String user) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Boolean result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Boolean call() throws Exception {
return database.removeAuth(user);
}
}).get();
- } catch (InterruptedException e1) {
- return false;
- } catch (ExecutionException e1) {
- return false;
- } finally {
- executor.shutdown();
- }
- try {
- return result.booleanValue();
} catch (Exception e) {
- return (false);
+ return false;
}
}
@Override
public synchronized boolean updateQuitLoc(final PlayerAuth auth) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Boolean result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Boolean call() throws Exception {
return database.updateQuitLoc(auth);
}
}).get();
- } catch (InterruptedException e1) {
- return false;
- } catch (ExecutionException e1) {
- return false;
- } finally {
- executor.shutdown();
- }
- try {
- return result.booleanValue();
} catch (Exception e) {
- return (false);
+ return false;
}
}
@Override
public synchronized int getIps(final String ip) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Integer result;
try {
- result = executor.submit(new Callable() {
+ return exec.submit(new Callable() {
public Integer call() throws Exception {
return database.getIps(ip);
}
}).get();
- } catch (InterruptedException e1) {
- return 0;
- } catch (ExecutionException e1) {
- return 0;
- } finally {
- executor.shutdown();
- }
- try {
- return result.intValue();
} catch (Exception e) {
- return (0);
+ return -1;
}
}
@Override
public synchronized List getAllAuthsByName(final PlayerAuth auth) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- List result;
try {
- result = executor.submit(new Callable>() {
-
+ return exec.submit(new Callable>() {
public List call() throws Exception {
return database.getAllAuthsByName(auth);
}
}).get();
- } catch (InterruptedException e1) {
- return new ArrayList();
- } catch (ExecutionException e1) {
- return new ArrayList();
- } finally {
- executor.shutdown();
- }
- try {
- return result;
} catch (Exception e) {
- return (new ArrayList());
+ return new ArrayList<>();
}
}
@Override
public synchronized List getAllAuthsByIp(final String ip) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- List result;
try {
- result = executor.submit(new Callable>() {
-
+ return exec.submit(new Callable>() {
public List call() throws Exception {
return database.getAllAuthsByIp(ip);
}
}).get();
- } catch (InterruptedException e1) {
- return new ArrayList();
- } catch (ExecutionException e1) {
- return new ArrayList();
- } finally {
- executor.shutdown();
- }
- try {
- return result;
} catch (Exception e) {
- return (new ArrayList());
+ return new ArrayList<>();
}
}
@Override
public synchronized List getAllAuthsByEmail(final String email) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- List result;
try {
- result = executor.submit(new Callable>() {
-
+ return exec.submit(new Callable>() {
public List call() throws Exception {
return database.getAllAuthsByEmail(email);
}
}).get();
- } catch (InterruptedException e1) {
- return new ArrayList();
- } catch (ExecutionException e1) {
- return new ArrayList();
- } finally {
- executor.shutdown();
- }
- try {
- return result;
} catch (Exception e) {
- return (new ArrayList());
+ return new ArrayList<>();
}
}
@Override
public synchronized boolean updateEmail(final PlayerAuth auth) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Boolean result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable() {
public Boolean call() throws Exception {
return database.updateEmail(auth);
}
}).get();
- } catch (InterruptedException e1) {
- return false;
- } catch (ExecutionException e1) {
- return false;
- } finally {
- executor.shutdown();
- }
- try {
- return result.booleanValue();
} catch (Exception e) {
- return (false);
+ return false;
}
}
@Override
public synchronized boolean updateSalt(final PlayerAuth auth) {
- ExecutorService executor = Executors.newSingleThreadExecutor();
- Boolean result;
try {
- result = executor.submit(new Callable() {
-
+ return exec.submit(new Callable