commit dd5c051eb98314ac18f5840f85ccf0203479611e Author: Ivan Filipov Date: Mon Apr 10 15:14:23 2023 +0300 Initial commit diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e142a52 --- /dev/null +++ b/LICENSE @@ -0,0 +1,625 @@ +GNU GENERAL PUBLIC LICENSE + +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +Preamble + +The GNU General Public License is a free, copyleft license for software and +other kinds of works. + +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. + +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. + +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. + +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. + +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. + +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. + +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. + +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. + +The precise terms and conditions for copying, distribution and modification +follow. + +TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, +such as semiconductor masks. + +"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. + +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. + +A "covered work" means either the unmodified Program or a work based on the +Program. + +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. + +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. + +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. + + 1. Source Code. + +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. + +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. + +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. + +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. + +The Corresponding Source need not include anything that users can regenerate +automatically from other parts of the Corresponding Source. + + The Corresponding Source for a work in source code form is that same work. + + 2. Basic Permissions. + +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. + +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. + + + +Copyright (C) + +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: + + Copyright (C) + +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/README.md b/README.md new file mode 100644 index 0000000..5ceebce --- /dev/null +++ b/README.md @@ -0,0 +1,23 @@ +# Simple WordPress login captcha + +Add captcha on wp-login.php in any Wordpress site. + +**NOTE: Not compatible yet with woocommerce or any other login page.** + +How to install: +1. Unzip downloaded file in ROOT THEME directory(ex. /my_site/wp-content/themes/my_theme/) +2. Make sure that in the root directory of your theme now exist folder “wl_functions” and in it there are: + - wl_captcha (folder) + - AHGBold.ttf + - image.php + - securimage.php + - login.php +3. In the root theme folder, open file functions.php and on top of the page add: + - include ( get_stylesheet_directory() . '/wl_functions/login.php' ); +4. That’s it. Now open your wordpress login page you have integrates captcha. + +**NOTE: If any problems occure, comment or delete the row** + + include ( get_stylesheet_directory() . '/wl_functions/login.php' ); + +**in functions.php in your ROOT THEME directory(ex. /my_site/wp-content/themes/my_theme/functions.php).** diff --git a/wl_functions/login.php b/wl_functions/login.php new file mode 100644 index 0000000..95ba5b0 --- /dev/null +++ b/wl_functions/login.php @@ -0,0 +1,38 @@ +27); // An array of additional HTML tag attributes to pass to the text input tag +// $options['image_id'] = 'captcha_image'; // change the name of the alt text of the image +// $options['image_attributes'] = array('data-id'=>27); //An array of additional HTML tag attributes to pass to the captcha image tag +// $options['error_html'] = '
*Some important text!!!
'; //Optional HTML markup to be shown above the text input field +// $options['namespace'] = 'some_namespace'; //The optional captcha namespace to use for showing the image. Namespaces are for using multiple captchas on the same page. + + echo "
\n"; + echo Securimage::getCaptchaHtml($options); + echo "\n
\n"; +?> + +check($captcha) == false) { + return new WP_Error("Captcha Invalid", __("ERROR: You are a bot. If not, then enable JavaScript")); + }else{ + return $user; + } + +} +add_filter("wp_authenticate_user", "verify_login_captcha", 10, 2); diff --git a/wl_functions/wl_captcha/AHGBold.ttf b/wl_functions/wl_captcha/AHGBold.ttf new file mode 100644 index 0000000..764b23d Binary files /dev/null and b/wl_functions/wl_captcha/AHGBold.ttf differ diff --git a/wl_functions/wl_captcha/image.php b/wl_functions/wl_captcha/image.php new file mode 100644 index 0000000..6336bdc --- /dev/null +++ b/wl_functions/wl_captcha/image.php @@ -0,0 +1,47 @@ + + * @version 3.5.2 (Feb 15, 2014) + * @package Securimage + * + */ + +// Remove the "//" from the following line for debugging problems +// error_reporting(E_ALL); ini_set('display_errors', 1); + +require_once dirname(__FILE__) . '/securimage.php'; + +$img = new Securimage(); + +// You can customize the image by making changes below, some examples are included - remove the "//" to uncomment + +//$img->ttf_file = './Quiff.ttf'; +//$img->captcha_type = Securimage::SI_CAPTCHA_MATHEMATIC; // show a simple math problem instead of text +//$img->captcha_type = Securimage::SI_CAPTCHA_STRING; // show a simple text +//$img->case_sensitive = true; // true to use case sensitve codes - not recommended +//$img->image_height = 90; // height in pixels of the image +//$img->image_width = $img->image_height * M_E; // a good formula for image size based on the height +//$img->perturbation = .75; // 1.0 = high distortion, higher numbers = more distortion +//$img->image_bg_color = new Securimage_Color("#0099CC"); // image background color +//$img->text_color = new Securimage_Color("#EAEAEA"); // captcha text color +//$img->num_lines = 8; // how many lines to draw over the image +//$img->line_color = new Securimage_Color("#0000CC"); // color of lines over the image +//$img->signature_color = new Securimage_Color(rand(0, 64), +// rand(64, 128), +// rand(128, 255)); // random signature color +//$img->image_signature = "Something"; // text of signature, shown in right bottom corner +//$img->code_length = 3; // the length of the displayed text + +// see securimage.php for more options that can be set + +// set namespace if supplied to script via HTTP GET +if (!empty($_GET['namespace'])) $img->setNamespace($_GET['namespace']); + +//$img->captcha_type = Securimage::SI_CAPTCHA_MATHEMATIC; +$img->show(); // outputs the image and content headers to the browser +// alternate use: +// $img->show('/path/to/background_image.jpg'); diff --git a/wl_functions/wl_captcha/securimage.php b/wl_functions/wl_captcha/securimage.php new file mode 100644 index 0000000..46232fd --- /dev/null +++ b/wl_functions/wl_captcha/securimage.php @@ -0,0 +1,1661 @@ + + * @version 3.6.4 (Mar 3, 2016) + * @package Securimage + * + */ + + + +/** + * Securimage CAPTCHA Class. + * + * A class for creating and validating secure CAPTCHA images and audio. + * + * The class contains many options regarding appearance, security, storage of + * captcha data and image/audio generation options. + * + * @version 3.5.2 + * @package Securimage + * @subpackage classes + * @author Drew Phillips + * + */ +class Securimage +{ + // All of the public variables below are securimage options + // They can be passed as an array to the Securimage constructor, set below, + // or set from securimage_show.php and securimage_play.php + + /** + * Constant for rendering captcha as a JPEG image + * @var int + */ + const SI_IMAGE_JPEG = 1; + + /** + * Constant for rendering captcha as a PNG image (default) + * @var int + */ + + const SI_IMAGE_PNG = 2; + /** + * Constant for rendering captcha as a GIF image + * @var int + */ + const SI_IMAGE_GIF = 3; + + /** + * Constant for generating a normal alphanumeric captcha based on the + * character set + * + * @see Securimage::$charset charset property + * @var int + */ + const SI_CAPTCHA_STRING = 0; + + /** + * Constant for generating a captcha consisting of a simple math problem + * + * @var int + */ + const SI_CAPTCHA_MATHEMATIC = 1; + + /** + * Constant for generating a word based captcha using 2 words from a list + * + * @var int + */ + const SI_CAPTCHA_WORDS = 2; + + /** + * getCaptchaHtml() display constant for HTML Captcha Image + * + * @var integer + */ + const HTML_IMG = 1; + + /** + * getCaptchaHtml() display constant for Captcha Input text box + * + * @var integer + */ + const HTML_INPUT = 4; + + /** + * getCaptchaHtml() display constant for Captcha Text HTML label + * + * @var integer + */ + const HTML_INPUT_LABEL = 8; + + /** + * getCaptchaHtml() display constant for all HTML elements (default) + * + * @var integer + */ + const HTML_ALL = 0xffffffff; + + /*%*********************************************************************%*/ + // Properties + + /** + * The width of the captcha image + * @var int + */ + public $image_width = 215; + + /** + * The height of the captcha image + * @var int + */ + public $image_height = 80; + + /** + * Font size is calculated by image height and this ratio. Leave blank for + * default ratio of 0.4. + * + * Valid range: 0.1 - 0.99. + * + * Depending on image_width, values > 0.6 are probably too large and + * values < 0.3 are too small. + * + * @var float + */ + public $font_ratio; + + /** + * The type of the image, default = png + * + * @see Securimage::SI_IMAGE_PNG SI_IMAGE_PNG + * @see Securimage::SI_IMAGE_JPEG SI_IMAGE_JPEG + * @see Securimage::SI_IMAGE_GIF SI_IMAGE_GIF + * @var int + */ + public $image_type = self::SI_IMAGE_PNG; + + /** + * The background color of the captcha + * @var Securimage_Color|string + */ + public $image_bg_color = '#ffffff'; + + /** + * The color of the captcha text + * @var Securimage_Color|string + */ + public $text_color = '#707070'; + + /** + * The color of the lines over the captcha + * @var Securimage_Color|string + */ + public $line_color = '#707070'; + + /** + * The color of the noise that is drawn + * @var Securimage_Color|string + */ + public $noise_color = '#707070'; + + /** + * How transparent to make the text. + * + * 0 = completely opaque, 100 = invisible + * + * @var int + */ + public $text_transparency_percentage = 20; + + /** + * Whether or not to draw the text transparently. + * + * true = use transparency, false = no transparency + * + * @var bool + */ + public $use_transparent_text = true; + + /** + * The length of the captcha code + * @var int + */ + public $code_length = 6; + + /** + * Whether the captcha should be case sensitive or not. + * + * Not recommended, use only for maximum protection. + * + * @var bool + */ + public $case_sensitive = false; + + /** + * The character set to use for generating the captcha code + * @var string + */ + public $charset = 'ABCDEFGHKLMNPRSTUVWYZabcdefghklmnprstuvwyz23456789'; + + /** + * How long in seconds a captcha remains valid, after this time it will be + * considered incorrect. + * + * @var int + */ + public $expiry_time = 900; + + /** + * The session name securimage should use. + * + * Only use if your application uses a custom session name (e.g. Joomla). + * It is recommended to set this value here so it is used by all securimage + * scripts (i.e. securimage_show.php) + * + * @var string + */ + public $session_name = null; + + /** + * true to use the wordlist file, false to generate random captcha codes + * @var bool + */ + public $use_wordlist = false; + + /** + * The level of distortion. + * + * 0.75 = normal, 1.0 = very high distortion + * + * @var double + */ + public $perturbation = 0.85; + + /** + * How many lines to draw over the captcha code to increase security + * @var int + */ + public $num_lines = 5; + + /** + * The level of noise (random dots) to place on the image, 0-10 + * @var int + */ + public $noise_level = 2; + + /** + * The signature text to draw on the bottom corner of the image + * @var string + */ + public $image_signature = ''; + + /** + * The color of the signature text + * @var Securimage_Color|string + */ + public $signature_color = '#707070'; + + /** + * The path to the ttf font file to use for the signature text. + * Defaults to $ttf_file (AHGBold.ttf) + * + * @see Securimage::$ttf_file + * @var string + */ + public $signature_font; + + /** + * The type of captcha to create. + * + * Either alphanumeric based on *charset*, a simple math problem, or an + * image consisting of 2 words from the word list. + * + * @see Securimage::SI_CAPTCHA_STRING SI_CAPTCHA_STRING + * @see Securimage::SI_CAPTCHA_MATHEMATIC SI_CAPTCHA_MATHEMATIC + * @see Securimage::SI_CAPTCHA_WORDS SI_CAPTCHA_WORDS + * @see Securimage::$charset charset property + * @see Securimage::$wordlist_file wordlist_file property + * @var int + */ +// public $captcha_type_arr = [self::SI_CAPTCHA_STRING, self::SI_CAPTCHA_MATHEMATIC, self::SI_CAPTCHA_WORDS]; + public $captcha_type_arr = [self::SI_CAPTCHA_STRING, self::SI_CAPTCHA_MATHEMATIC]; + public $captcha_type = self::SI_CAPTCHA_STRING; // or self::SI_CAPTCHA_MATHEMATIC, or self::SI_CAPTCHA_WORDS; + //public $captcha_type = $this->captcha_type_arr[rand(0, 2)]; // or self::SI_CAPTCHA_MATHEMATIC, or self::SI_CAPTCHA_WORDS; + + /** + * The captcha namespace used for having multiple captchas on a page or + * to separate captchas from differen forms on your site. + * Example: + * + * + * // or manually in securimage_show.php + * $img->setNamespace('contact_form'); + * + * // in form validator + * $img->setNamespace('contact_form'); + * if ($img->check($code) == true) { + * echo "Valid!"; + * } + * + * @var string + */ + public $namespace; + + /** + * The TTF font file to use to draw the captcha code. + * + * Leave blank for default font AHGBold.ttf + * + * @var string + */ + public $ttf_file; + + /** + * Captcha ID if using static captcha + * @var string Unique captcha id + */ + protected static $_captchaId = null; + + /** + * The GD image resource of the captcha image + * + * @var resource + */ + protected $im; + + /** + * A temporary GD image resource of the captcha image for distortion + * + * @var resource + */ + protected $tmpimg; + + /** + * The background image GD resource + * @var string + */ + protected $bgimg; + + /** + * Scale factor for magnification of distorted captcha image + * + * @var int + */ + protected $iscale = 5; + + /** + * Absolute path to securimage directory. + * + * This is calculated at runtime + * + * @var string + */ + public $securimage_path = null; + + /** + * The captcha challenge value. + * + * Either the case-sensitive/insensitive word captcha, or the solution to + * the math captcha. + * + * @var string|bool Captcha challenge value + */ + protected $code; + + /** + * The display value of the captcha to draw on the image + * + * Either the word captcha or the math equation to present to the user + * + * @var string Captcha display value to draw on the image + */ + protected $code_display; + + /** + * Alternate text to draw as the captcha image text + * + * A value that can be passed to the constructor that can be used to + * generate a captcha image with a given value. + * + * This value does not get stored in the session or database and is only + * used when calling Securimage::show(). + * + * If a display_value was passed to the constructor and the captcha image + * is generated, the display_value will be used as the string to draw on + * the captcha image. + * + * Used only if captcha codes are generated and managed by a 3rd party + * app/library + * + * @var string Captcha code value to display on the image + */ + public $display_value; + + /** + * Captcha code supplied by user [set from Securimage::check()] + * + * @var string + */ + protected $captcha_code; + + /** + * Time (in seconds) that the captcha was solved in (correctly or incorrectly). + * + * This is from the time of code creation, to when validation was attempted. + * + * @var int + */ + protected $_timeToSolve = 0; + + /** + * Flag that can be specified telling securimage not to call exit after + * generating a captcha image or audio file + * + * @var bool If true, script will not terminate; if false script will terminate (default) + */ + protected $no_exit; + + /** + * Flag indicating whether or not a PHP session should be started and used + * + * @var bool If true, no session will be started; if false, session will be started and used to store data (default) + */ + protected $no_session; + + /** + * Flag indicating whether or not HTTP headers will be sent when outputting + * captcha image/audio + * + * @var bool If true (default) headers will be sent, if false, no headers are sent + */ + protected $send_headers; + + /** + * PDO connection when a database is used + * + * @var PDO|bool + */ +// protected $pdo_conn; + + /** + * The GD color for the background color + * + * @var int + */ + protected $gdbgcolor; + + /** + * The GD color for the text color + * + * @var int + */ + protected $gdtextcolor; + + /** + * The GD color for the line color + * + * @var int + */ + protected $gdlinecolor; + + /** + * The GD color for the signature text color + * + * @var int + */ + protected $gdsignaturecolor; + + /** + * Create a new securimage object, pass options to set in the constructor. + * + * The object can then be used to display a captcha, play an audible captcha, or validate a submission. + * + * @param array $options Options to initialize the class. May be any class property. + * + * $options = array( + * 'text_color' => new Securimage_Color('#013020'), + * 'code_length' => 5, + * 'num_lines' => 5, + * 'noise_level' => 3, + * 'font_file' => Securimage::getPath() . '/custom.ttf' + * ); + * + * $img = new Securimage($options); + * + */ + public function __construct($options = array()) + { + $this->securimage_path = dirname(__FILE__); + + $this->captcha_type = rand(0,1); //Added by Fill + + if (!is_array($options)) { + trigger_error( + '$options passed to Securimage::__construct() must be an array. ' . + gettype($options) . ' given', + E_USER_WARNING + ); + $options = array(); + } + + // check for and load settings from custom config file + if (file_exists(dirname(__FILE__) . '/config.inc.php')) { + $settings = include dirname(__FILE__) . '/config.inc.php'; + + if (is_array($settings)) { + $options = array_merge($settings, $options); + } + } + + if (is_array($options) && sizeof($options) > 0) { + foreach($options as $prop => $val) { + if ($prop == 'captchaId') { + Securimage::$_captchaId = $val; + } else { + $this->$prop = $val; + } + } + } + + $this->image_bg_color = $this->initColor($this->image_bg_color, '#ffffff'); + $this->text_color = $this->initColor($this->text_color, '#616161'); + $this->line_color = $this->initColor($this->line_color, '#616161'); + $this->noise_color = $this->initColor($this->noise_color, '#616161'); + $this->signature_color = $this->initColor($this->signature_color, '#616161'); + + if (is_null($this->ttf_file)) { + $this->ttf_file = $this->securimage_path . '/AHGBold.ttf'; + } + + $this->signature_font = $this->ttf_file; + + if (is_null($this->code_length) || (int)$this->code_length < 1) { + $this->code_length = 6; + } + + if (is_null($this->perturbation) || !is_numeric($this->perturbation)) { + $this->perturbation = 0.75; + } + + if (is_null($this->namespace) || !is_string($this->namespace)) { + $this->namespace = 'default'; + } + + if (is_null($this->no_exit)) { + $this->no_exit = false; + } + + if (is_null($this->no_session)) { + $this->no_session = false; + } + + if (is_null($this->send_headers)) { + $this->send_headers = true; + } + + if ($this->no_session != true) { + // Initialize session or attach to existing + if ( session_id() == '' || (function_exists('session_status') && PHP_SESSION_NONE == session_status()) ) { // no session has been started yet (or it was previousy closed), which is needed for validation + if (!is_null($this->session_name) && trim($this->session_name) != '') { + session_name(trim($this->session_name)); // set session name if provided + } + session_start(); + } + } + } + + /** + * Return the absolute path to the Securimage directory. + * + * @return string The path to the securimage base directory + */ + public static function getPath() + { + return dirname(__FILE__); + } + + /** + * Generate a new captcha ID or retrieve the current ID (if exists). + * + * @param bool $new If true, generates a new challenge and returns and ID. If false, the existing captcha ID is returned, or null if none exists. + * @param array $options Additional options to be passed to Securimage. + * $options must include database settings if they are not set directly in securimage.php + * + * @return null|string Returns null if no captcha id set and new was false, or the captcha ID + */ + public static function getCaptchaId($new = true, array $options = array()) + { + if (is_null($new) || (bool)$new == true) { + $id = sha1(uniqid($_SERVER['REMOTE_ADDR'], true)); + $opts = array('no_session' => true +// 'use_database' => true + ); + if (sizeof($options) > 0) $opts = array_merge($options, $opts); + $si = new self($opts); + Securimage::$_captchaId = $id; + $si->createCode(); + + return $id; + } else { + return Securimage::$_captchaId; + } + } + + /** + * Validate a captcha code input against a captcha ID + * + * @param string $id The captcha ID to check + * @param string $value The captcha value supplied by the user + * @param array $options Array of options to construct Securimage with. + * Options must include database options if they are not set in securimage.php + * + * @see Securimage::$database_driver + * @return bool true if the code was valid for the given captcha ID, false if not or if database failed to open + */ + public static function checkByCaptchaId($id, $value, array $options = array()) + { + $opts = array('captchaId' => $id, + 'no_session' => true +// 'use_database' => true + ); + + if (sizeof($options) > 0) $opts = array_merge($options, $opts); + + $si = new self($opts); + + return false; + + } + + + /** + * Generates a new challenge and serves a captcha image. + * + * Appropriate headers will be sent to the browser unless the *send_headers* option is false. + * + * @param string $background_image The absolute or relative path to the background image to use as the background of the captcha image. + * + * $img = new Securimage(); + * $img->code_length = 6; + * $img->num_lines = 5; + * $img->noise_level = 5; + * + * $img->show(); // sends the image and appropriate headers to browser + * exit; + */ + public function show($background_image = '') + { + set_error_handler(array(&$this, 'errorHandler')); + + if($background_image != '' && is_readable($background_image)) { + $this->bgimg = $background_image; + } + + $this->doImage(); + } + + /** + * Checks a given code against the correct value from the session and/or database. + * + * @param string $code The captcha code to check + * + * $code = $_POST['code']; + * $img = new Securimage(); + * if ($img->check($code) == true) { + * $captcha_valid = true; + * } else { + * $captcha_valid = false; + * } + * + * @return bool true if the given code was correct, false if not. + */ + public function check($code) + { + $this->code_entered = $code; + $this->validate(); + return $this->correct_code; + } + + /** + * Returns HTML code for displaying the captcha image, audio button, and form text input. + * + * Options can be specified to modify the output of the HTML. Accepted options: + * + * 'securimage_path': + * Optional: The URI to where securimage is installed (e.g. /securimage) + * 'show_image_url': + * Path to the securimage_show.php script (useful when integrating with a framework or moving outside the securimage directory) + * This will be passed as a urlencoded string to the tag for outputting the captcha image + * 'audio_play_url': + * Same as show_image_url, except this indicates the URL of the audio playback script + * 'image_id': + * A string that sets the "id" attribute of the captcha image (default: captcha_image) + * 'image_alt_text': + * The alt text of the captcha image (default: CAPTCHA Image) + * 'show_audio_button': + * true/false Whether or not to show the audio button (default: true) + * 'disable_flash_fallback':) + * Allow only HTML5 audio and disable Flash fallback + * 'show_refresh_button': + * true/false Whether or not to show a button to refresh the image (default: true) + * 'audio_icon_url': + * URL to the image used for showing the HTML5 audio icon + * 'icon_size': + * Size (for both height & width) in pixels of the audio and refresh buttons + * 'show_text_input': + * true/false Whether or not to show the text input for the captcha (default: true) + * 'refresh_alt_text': + * Alt text for the refresh image (default: Refresh Image) + * 'refresh_title_text': + * Title text for the refresh image link (default: Refresh Image) + * 'input_id': + * A string that sets the "id" attribute of the captcha text input (default: captcha_code) + * 'input_name': + * A string that sets the "name" attribute of the captcha text input (default: same as input_id) + * 'input_text': + * A string that sets the text of the label for the captcha text input (default: Type the text:) + * 'input_attributes': + * An array of additional HTML tag attributes to pass to the text input tag (default: empty) + * 'image_attributes': + * An array of additional HTML tag attributes to pass to the captcha image tag (default: empty) + * 'error_html': + * Optional HTML markup to be shown above the text input field + * 'namespace': + * The optional captcha namespace to use for showing the image and playing back the audio. Namespaces are for using multiple captchas on the same page. + * + * @param array $options Array of options for modifying the HTML code. + * @param int $parts Securiage::HTML_* constant controlling what component of the captcha HTML to display + * + * @return string The generated HTML code for displaying the captcha + */ + public static function getCaptchaHtml($options = array(), $parts = Securimage::HTML_ALL) + { + static $javascript_init = false; + + if (!isset($options['securimage_path'])) { + $docroot = (isset($_SERVER['DOCUMENT_ROOT'])) ? $_SERVER['DOCUMENT_ROOT'] : substr($_SERVER['SCRIPT_FILENAME'], 0, -strlen($_SERVER['SCRIPT_NAME'])); + $docroot = realpath($docroot); + $sipath = dirname(__FILE__); + $securimage_path = str_replace($docroot, '', $sipath); + } else { + $securimage_path = $options['securimage_path']; + } + + $show_image_url = (isset($options['show_image_url'])) ? $options['show_image_url'] : null; + $image_id = (isset($options['image_id'])) ? $options['image_id'] : 'captcha_image'; + $image_alt = (isset($options['image_alt_text'])) ? $options['image_alt_text'] : 'CAPTCHA Image'; +// $show_audio_btn = (isset($options['show_audio_button'])) ? (bool)$options['show_audio_button'] : false; +// $disable_flash_fbk = (isset($options['disable_flash_fallback'])) ? (bool)$options['disable_flash_fallback'] : false; +// $show_refresh_btn = (isset($options['show_refresh_button'])) ? (bool)$options['show_refresh_button'] : false; +// $refresh_icon_url = (isset($options['refresh_icon_url'])) ? $options['refresh_icon_url'] : null; +// $audio_but_bg_col = (isset($options['audio_button_bgcol'])) ? $options['audio_button_bgcol'] : '#ffffff'; +// $audio_icon_url = (isset($options['audio_icon_url'])) ? $options['audio_icon_url'] : null; +// $loading_icon_url = (isset($options['loading_icon_url'])) ? $options['loading_icon_url'] : null; +// $icon_size = (isset($options['icon_size'])) ? $options['icon_size'] : 32; +// $audio_play_url = (isset($options['audio_play_url'])) ? $options['audio_play_url'] : null; +// $audio_swf_url = (isset($options['audio_swf_url'])) ? $options['audio_swf_url'] : null; + $show_input = (isset($options['show_text_input'])) ? (bool)$options['show_text_input'] : true; +// $refresh_alt = (isset($options['refresh_alt_text'])) ? $options['refresh_alt_text'] : 'Refresh Image'; +// $refresh_title = (isset($options['refresh_title_text'])) ? $options['refresh_title_text'] : 'Refresh Image'; + $input_text = (isset($options['input_text'])) ? $options['input_text'] : 'Type the text:'; + $input_id = (isset($options['input_id'])) ? $options['input_id'] : 'captcha_code'; + $input_name = (isset($options['input_name'])) ? $options['input_name'] : $input_id; + $input_attrs = (isset($options['input_attributes'])) ? $options['input_attributes'] : array(); + $image_attrs = (isset($options['image_attributes'])) ? $options['image_attributes'] : array(); + $error_html = (isset($options['error_html'])) ? $options['error_html'] : null; + $namespace = (isset($options['namespace'])) ? $options['namespace'] : ''; + + $rand = md5(uniqid($_SERVER['REMOTE_PORT'], true)); + $securimage_path = rtrim($securimage_path, '/\\'); + $securimage_path = str_replace('\\', '/', $securimage_path); + + $image_attr = ''; + if (!is_array($image_attrs)) $image_attrs = array(); + if (!isset($image_attrs['style'])) $image_attrs['style'] = 'float: left; padding-right: 5px'; + $image_attrs['id'] = $image_id; + + $show_path = $securimage_path . '/image.php?'; + if ($show_image_url) { + if (parse_url($show_image_url, PHP_URL_QUERY)) { + $show_path = "{$show_image_url}&"; + } else { + $show_path = "{$show_image_url}?"; + } + } + if (!empty($namespace)) { + $show_path .= sprintf('namespace=%s&', $namespace); + } + $image_attrs['src'] = $show_path . $rand; + + $image_attrs['alt'] = $image_alt; + + foreach($image_attrs as $name => $val) { + $image_attr .= sprintf('%s="%s" ', $name, htmlspecialchars($val)); + } + + $html = ''; + + if ( ($parts & Securimage::HTML_IMG) > 0) { + $html .= sprintf('', $image_attr); + } + + if ($parts == Securimage::HTML_ALL) { + $html .= '
'; + } + + if ( ($parts & Securimage::HTML_INPUT_LABEL) > 0 && $show_input) { + $html .= sprintf(' ', + htmlspecialchars($input_id), + htmlspecialchars($input_text)); + + if (!empty($error_html)) { + $html .= $error_html; + } + } + + if ( ($parts & Securimage::HTML_INPUT) > 0 && $show_input) { + $input_attr = ''; + if (!is_array($input_attrs)) $input_attrs = array(); + $input_attrs['type'] = 'text'; + $input_attrs['name'] = $input_name; + $input_attrs['id'] = $input_id; + + foreach($input_attrs as $name => $val) { + $input_attr .= sprintf('%s="%s" ', $name, htmlspecialchars($val)); + } + + $html .= sprintf('', $input_attr); + } + + return $html; + } + + /** + * Get the time in seconds that it took to solve the captcha. + * + * @return int The time in seconds from when the code was created, to when it was solved + */ + public function getTimeToSolve() + { + return $this->_timeToSolve; + } + + /** + * Set the namespace for the captcha being stored in the session or database. + * + * Namespaces are useful when multiple captchas need to be displayed on a single page. + * + * @param string $namespace Namespace value, String consisting of characters "a-zA-Z0-9_-" + */ + public function setNamespace($namespace) + { + $namespace = preg_replace('/[^a-z0-9-_]/i', '', $namespace); + $namespace = substr($namespace, 0, 64); + + if (!empty($namespace)) { + $this->namespace = $namespace; + } else { + $this->namespace = 'default'; + } + } + + /** + * Return the code from the session or database (if configured). If none exists or was found, an empty string is returned. + * + * @param bool $array true to receive an array containing the code and properties, false to receive just the code. + * @param bool $returnExisting If true, and the class property *code* is set, it will be returned instead of getting the code from the session or database. + * @return array|string Return is an array if $array = true, otherwise a string containing the code + */ + public function getCode($array = false, $returnExisting = false) + { + $code = array(); + + if ($returnExisting && strlen($this->code) > 0) { + if ($array) { + return array( + 'code' => $this->code, + 'display' => $this->code_display, + 'code_display' => $this->code_display, + 'time' => 0); + } else { + return $this->code; + } + } + + if ($this->no_session != true) { + if (isset($_SESSION['secure_code_value'][$this->namespace]) && + trim($_SESSION['secure_code_value'][$this->namespace]) != '') { + if ($this->isCodeExpired( + $_SESSION['secure_code_ctime'][$this->namespace]) == false) { + $code['code'] = $_SESSION['secure_code_value'][$this->namespace]; + $code['time'] = $_SESSION['secure_code_ctime'][$this->namespace]; + $code['display'] = $_SESSION['secure_code_disp'] [$this->namespace]; + } + } + } + + if ($array == true) { + return $code; + } else { + return $code['code']; + } + } + + /** + * The main image drawing routing, responsible for constructing the entire image and serving it + */ + protected function doImage() + { + if( ($this->use_transparent_text == true || $this->bgimg != '') && function_exists('imagecreatetruecolor')) { + $imagecreate = 'imagecreatetruecolor'; + } else { + $imagecreate = 'imagecreate'; + } + + $this->im = $imagecreate($this->image_width, $this->image_height); + $this->tmpimg = $imagecreate($this->image_width * $this->iscale, $this->image_height * $this->iscale); + + $this->allocateColors(); + imagepalettecopy($this->tmpimg, $this->im); + + $this->setBackground(); + + $code = ''; + + if ($this->getCaptchaId(false) !== null) { + // a captcha Id was supplied + + // check to see if a display_value for the captcha image was set + if (is_string($this->display_value) && strlen($this->display_value) > 0) { + $this->code_display = $this->display_value; + $this->code = ($this->case_sensitive) ? + $this->display_value : + strtolower($this->display_value); + $code = $this->code; + } + } + + if ($code == '') { + // if the code was not set using display_value or was not found in + // the database, create a new code + $this->createCode(); + } + + if ($this->noise_level > 0) { + $this->drawNoise(); + } + + $this->drawWord(); + + if ($this->perturbation > 0 && is_readable($this->ttf_file)) { + $this->distortedCopy(); + } + + if ($this->num_lines > 0) { + $this->drawLines(); + } + + if (trim($this->image_signature) != '') { + $this->addSignature(); + } + + $this->output(); + } + + /** + * Allocate the colors to be used for the image + */ + protected function allocateColors() + { + // allocate bg color first for imagecreate + $this->gdbgcolor = imagecolorallocate($this->im, + $this->image_bg_color->r, + $this->image_bg_color->g, + $this->image_bg_color->b); + + $alpha = intval($this->text_transparency_percentage / 100 * 127); + + if ($this->use_transparent_text == true) { + $this->gdtextcolor = imagecolorallocatealpha($this->im, + $this->text_color->r, + $this->text_color->g, + $this->text_color->b, + $alpha); + $this->gdlinecolor = imagecolorallocatealpha($this->im, + $this->line_color->r, + $this->line_color->g, + $this->line_color->b, + $alpha); + $this->gdnoisecolor = imagecolorallocatealpha($this->im, + $this->noise_color->r, + $this->noise_color->g, + $this->noise_color->b, + $alpha); + } else { + $this->gdtextcolor = imagecolorallocate($this->im, + $this->text_color->r, + $this->text_color->g, + $this->text_color->b); + $this->gdlinecolor = imagecolorallocate($this->im, + $this->line_color->r, + $this->line_color->g, + $this->line_color->b); + $this->gdnoisecolor = imagecolorallocate($this->im, + $this->noise_color->r, + $this->noise_color->g, + $this->noise_color->b); + } + + $this->gdsignaturecolor = imagecolorallocate($this->im, + $this->signature_color->r, + $this->signature_color->g, + $this->signature_color->b); + + } + + /** + * The the background color, or background image to be used + */ + protected function setBackground() + { + // set background color of image by drawing a rectangle since imagecreatetruecolor doesn't set a bg color + imagefilledrectangle($this->im, 0, 0, + $this->image_width, $this->image_height, + $this->gdbgcolor); + imagefilledrectangle($this->tmpimg, 0, 0, + $this->image_width * $this->iscale, $this->image_height * $this->iscale, + $this->gdbgcolor); + + if ($this->bgimg == '') { + return; + } + + $dat = @getimagesize($this->bgimg); + if($dat == false) { + return; + } + + switch($dat[2]) { + case 1: $newim = @imagecreatefromgif($this->bgimg); break; + case 2: $newim = @imagecreatefromjpeg($this->bgimg); break; + case 3: $newim = @imagecreatefrompng($this->bgimg); break; + default: return; + } + + if(!$newim) return; + + imagecopyresized($this->im, $newim, 0, 0, 0, 0, + $this->image_width, $this->image_height, + imagesx($newim), imagesy($newim)); + } + + /** + * This method generates a new captcha code. + * + * Generates a random captcha code based on *charset*, math problem, or captcha from the wordlist and saves the value to the session and/or database. + */ + public function createCode() + { + $this->code = false; + + switch($this->captcha_type) { + case self::SI_CAPTCHA_MATHEMATIC: + { + do { + $signs = array('+', '-', 'x'); + $left = mt_rand(1, 10); + $right = mt_rand(1, 5); + $sign = $signs[mt_rand(0, 2)]; + + switch($sign) { + case 'x': $c = $left * $right; break; + case '-': $c = $left - $right; break; + default: $c = $left + $right; break; + } + } while ($c <= 0); // no negative #'s or 0 + + $this->code = "$c"; + $this->code_display = "$left $sign $right"; + break; + } + + + default: + { + if ($this->code == false) { + $this->code = $this->generateCode($this->code_length); + } + + $this->code_display = $this->code; + $this->code = ($this->case_sensitive) ? $this->code : strtolower($this->code); + } // default + } + + $this->saveData(); + } + + /** + * Draws the captcha code on the image + */ + protected function drawWord() + { + $width2 = $this->image_width * $this->iscale; + $height2 = $this->image_height * $this->iscale; + $ratio = ($this->font_ratio) ? $this->font_ratio : 0.4; + + if ((float)$ratio < 0.1 || (float)$ratio >= 1) { + $ratio = 0.4; + } + + if (!is_readable($this->ttf_file)) { + imagestring($this->im, 4, 10, ($this->image_height / 2) - 5, 'Failed to load TTF font file!', $this->gdtextcolor); + } else { + if ($this->perturbation > 0) { + $font_size = $height2 * $ratio; + $bb = imageftbbox($font_size, 0, $this->ttf_file, $this->code_display); + $tx = $bb[4] - $bb[0]; + $ty = $bb[5] - $bb[1]; + $x = floor($width2 / 2 - $tx / 2 - $bb[0]); + $y = round($height2 / 2 - $ty / 2 - $bb[1]); + + imagettftext($this->tmpimg, $font_size, 0, (int)$x, (int)$y, $this->gdtextcolor, $this->ttf_file, $this->code_display); + } else { + $font_size = $this->image_height * $ratio; + $bb = imageftbbox($font_size, 0, $this->ttf_file, $this->code_display); + $tx = $bb[4] - $bb[0]; + $ty = $bb[5] - $bb[1]; + $x = floor($this->image_width / 2 - $tx / 2 - $bb[0]); + $y = round($this->image_height / 2 - $ty / 2 - $bb[1]); + + imagettftext($this->im, $font_size, 0, (int)$x, (int)$y, $this->gdtextcolor, $this->ttf_file, $this->code_display); + } + } + + // DEBUG + //$this->im = $this->tmpimg; + //$this->output(); + + } + + /** + * Copies the captcha image to the final image with distortion applied + */ + protected function distortedCopy() + { + $numpoles = 3; // distortion factor + // make array of poles AKA attractor points + for ($i = 0; $i < $numpoles; ++ $i) { + $px[$i] = mt_rand($this->image_width * 0.2, $this->image_width * 0.8); + $py[$i] = mt_rand($this->image_height * 0.2, $this->image_height * 0.8); + $rad[$i] = mt_rand($this->image_height * 0.2, $this->image_height * 0.8); + $tmp = ((- $this->frand()) * 0.15) - .15; + $amp[$i] = $this->perturbation * $tmp; + } + + $bgCol = imagecolorat($this->tmpimg, 0, 0); + $width2 = $this->iscale * $this->image_width; + $height2 = $this->iscale * $this->image_height; + imagepalettecopy($this->im, $this->tmpimg); // copy palette to final image so text colors come across + // loop over $img pixels, take pixels from $tmpimg with distortion field + for ($ix = 0; $ix < $this->image_width; ++ $ix) { + for ($iy = 0; $iy < $this->image_height; ++ $iy) { + $x = $ix; + $y = $iy; + for ($i = 0; $i < $numpoles; ++ $i) { + $dx = $ix - $px[$i]; + $dy = $iy - $py[$i]; + if ($dx == 0 && $dy == 0) { + continue; + } + $r = sqrt($dx * $dx + $dy * $dy); + if ($r > $rad[$i]) { + continue; + } + $rscale = $amp[$i] * sin(3.14 * $r / $rad[$i]); + $x += $dx * $rscale; + $y += $dy * $rscale; + } + $c = $bgCol; + $x *= $this->iscale; + $y *= $this->iscale; + if ($x >= 0 && $x < $width2 && $y >= 0 && $y < $height2) { + $c = imagecolorat($this->tmpimg, $x, $y); + } + if ($c != $bgCol) { // only copy pixels of letters to preserve any background image + imagesetpixel($this->im, $ix, $iy, $c); + } + } + } + } + + /** + * Draws distorted lines on the image + */ + protected function drawLines() + { + for ($line = 0; $line < $this->num_lines; ++ $line) { + $x = $this->image_width * (1 + $line) / ($this->num_lines + 1); + $x += (0.5 - $this->frand()) * $this->image_width / $this->num_lines; + $y = mt_rand($this->image_height * 0.1, $this->image_height * 0.9); + + $theta = ($this->frand() - 0.5) * M_PI * 0.7; + $w = $this->image_width; + $len = mt_rand($w * 0.4, $w * 0.7); + $lwid = mt_rand(0, 2); + + $k = $this->frand() * 0.6 + 0.2; + $k = $k * $k * 0.5; + $phi = $this->frand() * 6.28; + $step = 0.5; + $dx = $step * cos($theta); + $dy = $step * sin($theta); + $n = $len / $step; + $amp = 1.5 * $this->frand() / ($k + 5.0 / $len); + $x0 = $x - 0.5 * $len * cos($theta); + $y0 = $y - 0.5 * $len * sin($theta); + + $ldx = round(- $dy * $lwid); + $ldy = round($dx * $lwid); + + for ($i = 0; $i < $n; ++ $i) { + $x = $x0 + $i * $dx + $amp * $dy * sin($k * $i * $step + $phi); + $y = $y0 + $i * $dy - $amp * $dx * sin($k * $i * $step + $phi); + imagefilledrectangle($this->im, $x, $y, $x + $lwid, $y + $lwid, $this->gdlinecolor); + } + } + } + + /** + * Draws random noise on the image + */ + protected function drawNoise() + { + if ($this->noise_level > 10) { + $noise_level = 10; + } else { + $noise_level = $this->noise_level; + } + + $t0 = microtime(true); + + $noise_level *= 125; // an arbitrary number that works well on a 1-10 scale + + $points = $this->image_width * $this->image_height * $this->iscale; + $height = $this->image_height * $this->iscale; + $width = $this->image_width * $this->iscale; + for ($i = 0; $i < $noise_level; ++$i) { + $x = mt_rand(10, $width); + $y = mt_rand(10, $height); + $size = mt_rand(7, 10); + if ($x - $size <= 0 && $y - $size <= 0) continue; // dont cover 0,0 since it is used by imagedistortedcopy + imagefilledarc($this->tmpimg, $x, $y, $size, $size, 0, 360, $this->gdnoisecolor, IMG_ARC_PIE); + } + + $t1 = microtime(true); + + $t = $t1 - $t0; + + /* + // DEBUG + imagestring($this->tmpimg, 5, 25, 30, "$t", $this->gdnoisecolor); + header('content-type: image/png'); + imagepng($this->tmpimg); + exit; + */ + } + + /** + * Print signature text on image + */ + protected function addSignature() + { + $bbox = imagettfbbox(10, 0, $this->signature_font, $this->image_signature); + $textlen = $bbox[2] - $bbox[0]; + $x = $this->image_width - $textlen - 5; + $y = $this->image_height - 3; + + imagettftext($this->im, 10, 0, $x, $y, $this->gdsignaturecolor, $this->signature_font, $this->image_signature); + } + + /** + * Sends the appropriate image and cache headers and outputs image to the browser + */ + protected function output() + { + if ($this->canSendHeaders() || $this->send_headers == false) { + if ($this->send_headers) { + // only send the content-type headers if no headers have been output + // this will ease debugging on misconfigured servers where warnings + // may have been output which break the image and prevent easily viewing + // source to see the error. + header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); + header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT"); + header("Cache-Control: no-store, no-cache, must-revalidate"); + header("Cache-Control: post-check=0, pre-check=0", false); + header("Pragma: no-cache"); + } + + switch ($this->image_type) { + case self::SI_IMAGE_JPEG: + if ($this->send_headers) header("Content-Type: image/jpeg"); + imagejpeg($this->im, null, 90); + break; + case self::SI_IMAGE_GIF: + if ($this->send_headers) header("Content-Type: image/gif"); + imagegif($this->im); + break; + default: + if ($this->send_headers) header("Content-Type: image/png"); + imagepng($this->im); + break; + } + } else { + echo '
' + .'Failed to generate captcha image, content has already been ' + .'output.
This is most likely due to misconfiguration or ' + .'a PHP error was sent to the browser.
'; + } + + imagedestroy($this->im); + restore_error_handler(); + + if (!$this->no_exit) exit; + } + + /** + * Generates a random captcha code from the set character set + * + * @see Securimage::$charset Charset option + * @return string A randomly generated CAPTCHA code + */ + protected function generateCode() + { + $code = ''; + + if (function_exists('mb_strlen')) { + for($i = 1, $cslen = mb_strlen($this->charset, 'UTF-8'); $i <= $this->code_length; ++$i) { + $code .= mb_substr($this->charset, mt_rand(0, $cslen - 1), 1, 'UTF-8'); + } + } else { + for($i = 1, $cslen = strlen($this->charset); $i <= $this->code_length; ++$i) { + $code .= substr($this->charset, mt_rand(0, $cslen - 1), 1); + } + } + + return $code; + } + + /** + * Validate a code supplied by the user + * + * Checks the entered code against the value stored in the session and/or database (if configured). Handles case sensitivity. + * Also removes the code from session/database if the code was entered correctly to prevent re-use attack. + * + * This function does not return a value. + * + * @see Securimage::$correct_code 'correct_code' property + */ + protected function validate() + { + if (!is_string($this->code) || strlen($this->code) == 0) { + $code = $this->getCode(true); + // returns stored code, or an empty string if no stored code was found + // checks the session and database if enabled + } else { + $code = $this->code; + } + + if (is_array($code)) { + if (!empty($code)) { + $ctime = $code['time']; + $code = $code['code']; + + $this->_timeToSolve = time() - $ctime; + } else { + $code = ''; + } + } + + if ($this->case_sensitive == false && preg_match('/[A-Z]/', $code)) { + // case sensitive was set from securimage_show.php but not in class + // the code saved in the session has capitals so set case sensitive to true + $this->case_sensitive = true; + } + + $code_entered = trim( (($this->case_sensitive) ? $this->code_entered + : strtolower($this->code_entered)) + ); + $this->correct_code = false; + + if ($code != '') { + if (strpos($code, ' ') !== false) { + // for multi word captchas, remove more than once space from input + $code_entered = preg_replace('/\s+/', ' ', $code_entered); + $code_entered = strtolower($code_entered); + } + + if ((string)$code === (string)$code_entered) { + $this->correct_code = true; + if ($this->no_session != true) { + $_SESSION['secure_code_disp'] [$this->namespace] = ''; + $_SESSION['secure_code_value'][$this->namespace] = ''; + $_SESSION['secure_code_ctime'][$this->namespace] = ''; + $_SESSION['secure_code_audio'][$this->namespace] = ''; + } +// $this->clearCodeFromDatabase(); + } + } + } + + /** + * Save CAPTCHA data to session and database (if configured) + */ + protected function saveData() + { + if ($this->no_session != true) { + if (isset($_SESSION['secure_code_value']) && is_scalar($_SESSION['secure_code_value'])) { + // fix for migration from v2 - v3 + unset($_SESSION['secure_code_value']); + unset($_SESSION['secure_code_ctime']); + } + + $_SESSION['secure_code_disp'] [$this->namespace] = $this->code_display; + $_SESSION['secure_code_value'][$this->namespace] = $this->code; + $_SESSION['secure_code_ctime'][$this->namespace] = time(); + } + + } + + /** + * Checks to see if the captcha code has expired and can no longer be used. + * + * @see Securimage::$expiry_time expiry_time + * @param int $creation_time The Unix timestamp of when the captcha code was created + * @return bool true if the code is expired, false if it is still valid + */ + protected function isCodeExpired($creation_time) + { + $expired = true; + + if (!is_numeric($this->expiry_time) || $this->expiry_time < 1) { + $expired = false; + } else if (time() - $creation_time < $this->expiry_time) { + $expired = false; + } + + return $expired; + } + + /** + * Checks to see if headers can be sent and if any error has been output + * to the browser + * + * @return bool true if it is safe to send headers, false if not + */ + protected function canSendHeaders() + { + if (headers_sent()) { + // output has been flushed and headers have already been sent + return false; + } else if (strlen((string)ob_get_contents()) > 0) { + // headers haven't been sent, but there is data in the buffer that will break image and audio data + return false; + } + + return true; + } + + /** + * Return a random float between 0 and 0.9999 + * + * @return float Random float between 0 and 0.9999 + */ + function frand() + { + return 0.0001 * mt_rand(0,9999); + } + + /** + * Convert an html color code to a Securimage_Color + * @param string $color + * @param Securimage_Color|string $default The defalt color to use if $color is invalid + */ + protected function initColor($color, $default) + { + if ($color == null) { + return new Securimage_Color($default); + } else if (is_string($color)) { + try { + return new Securimage_Color($color); + } catch(Exception $e) { + return new Securimage_Color($default); + } + } else if (is_array($color) && sizeof($color) == 3) { + return new Securimage_Color($color[0], $color[1], $color[2]); + } else { + return new Securimage_Color($default); + } + } + + /** + * The error handling function used when outputting captcha image or audio. + * + * This error handler helps determine if any errors raised would + * prevent captcha image or audio from displaying. If they have + * no effect on the output buffer or headers, true is returned so + * the script can continue processing. + * + * See https://github.com/dapphp/securimage/issues/15 + * + * @param int $errno PHP error number + * @param string $errstr String description of the error + * @param string $errfile File error occurred in + * @param int $errline Line the error occurred on in file + * @param array $errcontext Additional context information + * @return boolean true if the error was handled, false if PHP should handle the error + */ + public function errorHandler($errno, $errstr, $errfile = '', $errline = 0, $errcontext = array()) + { + // get the current error reporting level + $level = error_reporting(); + + // if error was supressed or $errno not set in current error level + if ($level == 0 || ($level & $errno) == 0) { + return true; + } + + return false; + } +} + + +/** + * Color object for Securimage CAPTCHA + * + * @version 3.0 + * @since 2.0 + * @package Securimage + * @subpackage classes + * + */ +class Securimage_Color +{ + /** + * Red value (0-255) + * @var int + */ + public $r; + + /** + * Gree value (0-255) + * @var int + */ + public $g; + + /** + * Blue value (0-255) + * @var int + */ + public $b; + + /** + * Create a new Securimage_Color object. + * + * Constructor expects 1 or 3 arguments. + * + * When passing a single argument, specify the color using HTML hex format. + * + * When passing 3 arguments, specify each RGB component (from 0-255) + * individually. + * + * Examples: + * + * $color = new Securimage_Color('#0080FF'); + * $color = new Securimage_Color(0, 128, 255); + * + * @param string $color The html color code to use + * @throws Exception If any color value is not valid + */ + public function __construct($color = '#ffffff') + { + $args = func_get_args(); + + if (sizeof($args) == 0) { + $this->r = 255; + $this->g = 255; + $this->b = 255; + } else if (sizeof($args) == 1) { + // set based on html code + if (substr($color, 0, 1) == '#') { + $color = substr($color, 1); + } + + if (strlen($color) != 3 && strlen($color) != 6) { + throw new InvalidArgumentException( + 'Invalid HTML color code passed to Securimage_Color' + ); + } + + $this->constructHTML($color); + } else if (sizeof($args) == 3) { + $this->constructRGB($args[0], $args[1], $args[2]); + } else { + throw new InvalidArgumentException( + 'Securimage_Color constructor expects 0, 1 or 3 arguments; ' . sizeof($args) . ' given' + ); + } + } + + /** + * Construct from an rgb triplet + * + * @param int $red The red component, 0-255 + * @param int $green The green component, 0-255 + * @param int $blue The blue component, 0-255 + */ + protected function constructRGB($red, $green, $blue) + { + if ($red < 0) $red = 0; + if ($red > 255) $red = 255; + if ($green < 0) $green = 0; + if ($green > 255) $green = 255; + if ($blue < 0) $blue = 0; + if ($blue > 255) $blue = 255; + + $this->r = $red; + $this->g = $green; + $this->b = $blue; + } + + /** + * Construct from an html hex color code + * + * @param string $color + */ + protected function constructHTML($color) + { + if (strlen($color) == 3) { + $red = str_repeat(substr($color, 0, 1), 2); + $green = str_repeat(substr($color, 1, 1), 2); + $blue = str_repeat(substr($color, 2, 1), 2); + } else { + $red = substr($color, 0, 2); + $green = substr($color, 2, 2); + $blue = substr($color, 4, 2); + } + + $this->r = hexdec($red); + $this->g = hexdec($green); + $this->b = hexdec($blue); + } +}