diff --git a/AGENTS.md b/AGENTS.md deleted file mode 100644 index 4b7b30a..0000000 --- a/AGENTS.md +++ /dev/null @@ -1,33 +0,0 @@ -# AGENT INSTRUCTIONS - -This repository contains the WordPress plugin **2FA (by ROBOTSTXT)**. Follow these rules whenever you work on any file within this repository: - -1. **Language** -- Write every piece of documentation, copy, and code comments in English. - -2. **Code standards** -- All PHP code must comply with **PHPCS** and **WPCS**. -- Use tabs for indentation (no spaces). -- Ensure compatibility with **PHP 8.2** or higher. -- Provide proper **PHPDoc** annotations for classes, properties, and methods. - -3. **WordPress security** -- Sanitize, validate, and escape all user-provided data. -- Include nonces in forms and verify them before processing submissions. -- Do not suppress validation or authentication errors. - -4. **Plugin structure** -- Keep the code modular inside the `includes/` directory. -- Place admin-related logic in subdirectories under `includes/admin/`. -- Store presentational templates in `templates/`. -- Whenever new persistent data (options, tables, user meta, etc.) is introduced, update `uninstall.php` so the plugin removes it on uninstall. - -5. **Testing and tooling** -- Run all available checks (PHPCS, PHPUnit, etc.) after making changes. -- Summarize the commands executed and their results in the final message. - -6. **Documentation** -- Update `readme.txt` and `changelog.txt` whenever functional changes are introduced. -- Explain *why* when the reason for a piece of code is not obvious. - -These instructions apply to the entire repository tree. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..33097fb --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,69 @@ +# Changelog + +All notable changes to this project are documented in this file. +Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). + +## [Unreleased] + +## [0.3.0] - 2026-06-05 + +### Added + +- Delete-on-uninstall option in admin settings Data Management section (off by default — all data is preserved). + +### Changed + +- Network admin settings page now correctly saves to `wp_sitemeta` via a dedicated `network_admin_edit_` handler. +- Settings option stored with `autoload=false` — not needed on every page load. +- Recovery code preview transient TTL reduced from 0 (persistent) to 300 seconds (5 minutes). + +### Security + +- Email verification codes now use `random_int()` (CSPRNG) instead of `wp_rand()` (Mersenne Twister), consistent with recovery codes and OTP secrets. + +### Fixed + +- `get_required_capability()` now returns `manage_network_options` in network admin context. +- `bin/deploy.sh` now excludes `CLAUDE.md`, `AGENTS.md`, `README.md`, `DOCUMENTATION-*.md`, and `.phpunit.result.cache` from the ZIP artifact. +- `update.json` corrected: was shipping SMTP plugin data instead of 2FA plugin data. + +## [0.2.0] - 2026-06-05 + +### Added + +- Per-role 2FA method matrix: admins choose exactly which verification methods (email, OTP, recovery codes) are required for each WordPress role, with select-all row and column toggles. +- Authenticator app (TOTP) support: secrets stored as Base32, QR code rendered via `bacon/bacon-qr-code`, manual setup key displayed as fallback. +- Recovery codes: 10 single-use 8-digit codes, one-time display grid with copy-to-clipboard, mandatory confirmation before activation, auto-refresh when batch exhausted. +- Email verification codes: 7-digit codes, 10-minute expiry, 60-second resend throttle. +- Configurable verification frequency remembered per device fingerprint (every login / daily / weekly / monthly); administrators can lock the global schedule. +- Dedicated stage token (WP nonce) securing the 2FA screen between password validation and code entry. +- Method-switch links on the verification screen (OTP ↔ email ↔ recovery codes) without restarting the login. +- Multisite support: `Network: true` header; network admins set and lock enforcement settings. +- `uninstall.php` removes all plugin options and user meta on deletion. +- `bin/deploy.sh` for manual ZIP packaging. +- PHPUnit test suite with plugin-header tests. + +### Changed + +- Settings UI replaces flat forced-roles list with per-role method matrix; existing `force_roles` + `default_method` data is automatically migrated. +- Profile method checkboxes require explicit confirmation before activating (OTP: valid 6-digit code; recovery codes: enter one displayed code). +- Required methods indicated with a "required for your role" badge in the profile; checkboxes disabled and hidden inputs ensure values survive submission. +- Login screen hides username/password fields, removes Remember Me, focuses code input, and auto-submits when digit count is reached. + +### Fixed + +- QR generation errors caught and surfaced to administrators; graceful fallback to text setup key. +- Recovery-code preview persists via transient until explicitly acknowledged. + +### Security + +- All `$_POST`/`$_GET`/`$_SERVER` reads guarded with `is_string()` before passing to sanitize functions. +- PHPStan level 9 passes with zero errors; no mixed-type casts. +- `composer audit`: no known vulnerabilities in any dependency. + +## [0.1.0] - 2024-04-08 + +### Added + +- Initial plugin skeleton with placeholder classes for login handling, user profile, and admin settings. +- Initial documentation files. diff --git a/LICENSE b/LICENSE index 3877ae0..f288702 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,674 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - 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. - - 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 -. + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + 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. + + 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 deleted file mode 100644 index 5a78dec..0000000 --- a/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# robotstxt-2fa -Simple 2FA WordPress plugin diff --git a/changelog.txt b/changelog.txt index aa30010..3474b0d 100644 --- a/changelog.txt +++ b/changelog.txt @@ -1,42 +1,69 @@ # Changelog ## [Unreleased] -### Added -- Authenticator app support with stored secrets and QR provisioning powered by the optional `bacon/bacon-qr-code` library. -- Recovery code confirmation workflow that requires entering one of the freshly generated codes before hiding them. -- Single-use recovery codes with profile management, one-time display, and login validation. -- Dedicated verification stage token that secures 2FA screens and allows protected email code resends. -- Admin settings page with role-based enforcement controls for two-factor authentication. -- Uninstall routine that removes stored plugin options. -- Network-wide enforcement options for WordPress multisite installations. -- Email-based verification codes with throttled delivery and expiry handling. -- Configurable verification frequency that remembers trusted devices while allowing administrators to lock the schedule per site. -### Changed -- Profile method toggles now start unchecked and require validating authenticator and recovery codes before activation, with new inline prompts and regenerated secrets when options are disabled. -- The profile screen now keeps recovery codes visible in a two-column grid until one is confirmed, shows remaining counts, and automatically refreshes the list when the stored batch is exhausted. -- Email verification now displays the destination address alongside the method label. -- The login verification screen now hides the username/password fields, exposes a back-to-login link, and supports email code resends from a dedicated query-flagged URL. -- The verification stage now enforces authenticator app codes when they are enabled and exposes secure links to switch between OTP, email, and recovery-code challenges without restarting the login. -- Promoted the settings interface to a dedicated top-level Two-Factor Authentication menu for easier discovery. -- Adjusted the Two-Factor Authentication menu position so it appears within the plugins section of the admin navigation. -- User profile settings now persist preferences and automatically enforce role-based 2FA requirements. -- The login screen now auto-submits verification forms once the active method reaches its required length (six digits for OTP, seven for email, eight for recovery codes) and removes the Remember Me control during OTP checks. -- Recovery code requests now submit through the native profile form, regenerate codes server-side, and remember the section anchor on the redirect so the refreshed screen focuses the two-factor settings. -- The refreshed profile screen renders the newly issued ten codes inside a notice, including copy controls and updated status messaging, without relying on JavaScript-driven form submissions. -- The generator button now submits the profile form directly, honours core capability checks, and shares nonce validation with the existing profile workflow. +## [0.3.0] - 2026-06-05 + +### Added + +- Delete-on-uninstall option (disabled by default — all plugin data is preserved on removal). + +### Security + +- Email verification codes now use `random_int()` (CSPRNG) for cryptographically secure code generation. +- Recovery code preview transient TTL reduced from indefinite to 5 minutes. ### Fixed -- Prevented a fatal error on the profile screen by exposing the recovery code batch size helper used during rendering. -- Corrected the recovery-code confirmation flow so previews persist until acknowledged and the confirmation code is accepted. -- Hardened authenticator QR generation by catching library errors and pointing administrators to the required bacon/bacon-qr-code ^3.0 dependency. -- Improved recovery-code AJAX error handling so failed requests surface localized messages instead of silently failing. -- Forced roles now see two-factor authentication enabled with the default email method selected in their profile, and per-user data is purged during uninstall. -- Restored the login verification handlers so the authenticate filter no longer triggers fatal errors and email challenges complete successfully. -- Ensured the profile recovery-code generator always reaches `admin-ajax.php`, even when localized data is missing, so the button reliably displays the codes inline. + +- Network admin settings now save correctly via a dedicated handler writing to `wp_sitemeta`. +- Settings option registered with `autoload=false` to avoid loading on every page request. +- `update.json` corrected to reference the 2FA plugin instead of the SMTP plugin. + +**Compatibility** + +* WordPress: 6.4 – 7.1 +* PHP: 8.2 – 8.5 + +**Tests** + +* PHP Coding Standards: PHP_CodeSniffer 3.13.5 / WPCS 3.3.0 +* PHPStan: level 9 — 0 errors +* PHPCompatibility: 8.2–8.5 — 0 issues +* PHPUnit: 9.6.34 — 42 tests, 109 assertions + +## [0.2.0] - 2026-06-05 + +### Added + +- Per-role 2FA method matrix in admin settings: administrators can now choose exactly which verification methods (email, authenticator app, recovery codes) are required for each WordPress role, with select-all row and column controls. +- Authenticator app (TOTP) support: stored secrets, QR code provisioning via `bacon/bacon-qr-code`, manual setup key display, and one-time activation confirmation. +- Recovery codes: 10 single-use 8-digit codes with profile management, one-time display grid, copy-to-clipboard, and mandatory confirmation before activation. +- Email-based verification codes with throttled delivery (60 s resend cooldown) and 10-minute expiry. +- Configurable verification frequency (every login, daily, weekly, or every 28 days) remembered per device fingerprint; administrators can lock the global schedule. +- Dedicated verification stage token (WP nonce) securing the 2FA screen between password validation and code submission. +- Secure method-switch links on the verification screen letting users change between OTP, email, and recovery-code challenges without restarting the login. +- Network-wide multisite support: network administrators can set and lock enforcement settings across all sites (`Network: true` header). +- Uninstall routine removing all plugin options and user meta. +- Admin settings page as a top-level menu with `manage_options` capability guard. + +### Changed + +- Settings page now uses the per-role method matrix instead of a flat forced-roles list; old `force_roles` + `default_method` data is automatically migrated on first read. +- Profile method checkboxes require explicit confirmation: OTP demands a valid 6-digit code, recovery codes demand entering one of the displayed codes before the method activates. +- Profile screen regenerates the OTP secret when the authenticator method is disabled and provides a "Generate new secret" button. +- Recovery code batch exhaustion now auto-generates a fresh batch and surfaces a confirmation prompt rather than locking the user out. +- Login screen hides the username/password fields, removes the Remember Me checkbox, and focuses the verification code input during the 2FA stage. +- Login form auto-submits once the input reaches the method's expected digit count. + +### Fixed + +- Hardened authenticator QR generation by catching library errors and guiding administrators to the required dependency. +- Recovery-code preview persists via transient until explicitly acknowledged; fixes cases where codes disappeared before confirmation. ## [0.1.0] - 2024-04-08 + ### Added + - Initial skeleton for the 2FA (by ROBOTSTXT) plugin. - Initial documentation files (`readme.txt`, `AGENTS.md`, `changelog.txt`). - Placeholder classes for login handling, user profile integration, and admin settings. diff --git a/composer.json b/composer.json deleted file mode 100644 index c98ffd3..0000000 --- a/composer.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "require": { - "bacon/bacon-qr-code": "^3.0" - } -} diff --git a/composer.lock b/composer.lock deleted file mode 100644 index 9fc4b22..0000000 --- a/composer.lock +++ /dev/null @@ -1,123 +0,0 @@ -{ - "_readme": [ - "This file locks the dependencies of your project to a known state", - "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", - "This file is @generated automatically" - ], - "content-hash": "9d7cd0dbebfa0273a358b926795e7b8a", - "packages": [ - { - "name": "bacon/bacon-qr-code", - "version": "v3.0.1", - "source": { - "type": "git", - "url": "https://github.com/Bacon/BaconQrCode.git", - "reference": "f9cc1f52b5a463062251d666761178dbdb6b544f" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/Bacon/BaconQrCode/zipball/f9cc1f52b5a463062251d666761178dbdb6b544f", - "reference": "f9cc1f52b5a463062251d666761178dbdb6b544f", - "shasum": "" - }, - "require": { - "dasprid/enum": "^1.0.3", - "ext-iconv": "*", - "php": "^8.1" - }, - "require-dev": { - "phly/keep-a-changelog": "^2.12", - "phpunit/phpunit": "^10.5.11 || 11.0.4", - "spatie/phpunit-snapshot-assertions": "^5.1.5", - "squizlabs/php_codesniffer": "^3.9" - }, - "suggest": { - "ext-imagick": "to generate QR code images" - }, - "type": "library", - "autoload": { - "psr-4": { - "BaconQrCode\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "BSD-2-Clause" - ], - "authors": [ - { - "name": "Ben Scholzen 'DASPRiD'", - "email": "mail@dasprids.de", - "homepage": "https://dasprids.de/", - "role": "Developer" - } - ], - "description": "BaconQrCode is a QR code generator for PHP.", - "homepage": "https://github.com/Bacon/BaconQrCode", - "support": { - "issues": "https://github.com/Bacon/BaconQrCode/issues", - "source": "https://github.com/Bacon/BaconQrCode/tree/v3.0.1" - }, - "time": "2024-10-01T13:55:55+00:00" - }, - { - "name": "dasprid/enum", - "version": "1.0.7", - "source": { - "type": "git", - "url": "https://github.com/DASPRiD/Enum.git", - "reference": "b5874fa9ed0043116c72162ec7f4fb50e02e7cce" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/DASPRiD/Enum/zipball/b5874fa9ed0043116c72162ec7f4fb50e02e7cce", - "reference": "b5874fa9ed0043116c72162ec7f4fb50e02e7cce", - "shasum": "" - }, - "require": { - "php": ">=7.1 <9.0" - }, - "require-dev": { - "phpunit/phpunit": "^7 || ^8 || ^9 || ^10 || ^11", - "squizlabs/php_codesniffer": "*" - }, - "type": "library", - "autoload": { - "psr-4": { - "DASPRiD\\Enum\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "BSD-2-Clause" - ], - "authors": [ - { - "name": "Ben Scholzen 'DASPRiD'", - "email": "mail@dasprids.de", - "homepage": "https://dasprids.de/", - "role": "Developer" - } - ], - "description": "PHP 7.1 enum implementation", - "keywords": [ - "enum", - "map" - ], - "support": { - "issues": "https://github.com/DASPRiD/Enum/issues", - "source": "https://github.com/DASPRiD/Enum/tree/1.0.7" - }, - "time": "2025-09-16T12:23:56+00:00" - } - ], - "packages-dev": [], - "aliases": [], - "minimum-stability": "stable", - "stability-flags": [], - "prefer-stable": false, - "prefer-lowest": false, - "platform": [], - "platform-dev": [], - "plugin-api-version": "2.6.0" -} diff --git a/includes/admin/class-settings-page.php b/includes/admin/class-settings-page.php index 9de3fb6..ad4130a 100644 --- a/includes/admin/class-settings-page.php +++ b/includes/admin/class-settings-page.php @@ -1,415 +1,745 @@ -register_admin_page( false ); - } - - /** - * Register plugin settings page on the network dashboard. - * - * @return void - */ - public function register_network_menu(): void { - $this->register_admin_page( true ); - } - - /** - * Render plugin settings page. - * - * @return void - */ - public function render_page(): void { - $capability = $this->get_required_capability(); - - if ( ! current_user_can( $capability ) ) { - wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'robotstxt-2fa' ) ); - } - - settings_errors( self::OPTION_NAME ); - ?> -
-

-
- -
-
- 'array', - 'sanitize_callback' => array( $this, 'sanitize_settings' ), - 'default' => $this->get_default_settings(), - ) - ); - - add_settings_section( - 'robotstxt_2fa_general', - __( 'General options', 'robotstxt-2fa' ), - array( $this, 'render_general_section' ), - self::PAGE_SLUG - ); - - add_settings_field( - 'robotstxt_2fa_force_roles', - __( 'Forced roles', 'robotstxt-2fa' ), - array( $this, 'render_force_roles_field' ), - self::PAGE_SLUG, - 'robotstxt_2fa_general' - ); - - add_settings_field( - 'robotstxt_2fa_frequency', - __( 'Verification frequency', 'robotstxt-2fa' ), - array( $this, 'render_frequency_field' ), - self::PAGE_SLUG, - 'robotstxt_2fa_general' - ); - - add_settings_field( - 'robotstxt_2fa_force_frequency', - __( 'Enforce frequency', 'robotstxt-2fa' ), - array( $this, 'render_force_frequency_field' ), - self::PAGE_SLUG, - 'robotstxt_2fa_general' - ); - } - - /** - * Render general settings section description. - * - * @return void - */ - public function render_general_section(): void { - echo '

' . esc_html__( 'Control how two-factor authentication is enforced for user roles.', 'robotstxt-2fa' ) . '

'; - - if ( $this->has_network_settings() && ! $this->is_network_context() ) { - echo '

' . esc_html__( 'These settings are locked by a network administrator. Any changes made here will be ignored.', 'robotstxt-2fa' ) . '

'; - } - } - - /** - * Render forced roles field. - * - * @return void - */ - public function render_force_roles_field(): void { - $settings = $this->get_settings(); - $selected_roles = array(); - $disabled_attr = ''; - - if ( isset( $settings['force_roles'] ) && is_array( $settings['force_roles'] ) ) { - $selected_roles = $settings['force_roles']; - } - - if ( $this->has_network_settings() && ! $this->is_network_context() ) { - $disabled_attr = disabled( true, true, false ); - } - - $roles = get_editable_roles(); - - if ( empty( $roles ) ) { - echo '

' . esc_html__( 'No editable roles were found.', 'robotstxt-2fa' ) . '

'; - return; - } - - foreach ( $roles as $role_key => $role_details ) { - printf( - '
', - esc_attr( self::OPTION_NAME ), - esc_attr( $role_key ), - checked( in_array( $role_key, $selected_roles, true ), true, false ), - $disabled_attr, - esc_html( translate_user_role( $role_details['name'] ) ) - ); - } - - echo '

' . esc_html__( 'Users assigned to the selected roles must enable two-factor authentication. Leave all roles unchecked to allow each user to decide whether to activate 2FA.', 'robotstxt-2fa' ) . '

'; - } - - /** - * Sanitize settings before saving them. - * - * @param mixed $raw_settings Raw settings submitted by the user. - * - * @return array - */ - public function sanitize_settings( $raw_settings ): array { - $capability = $this->get_required_capability(); - - if ( ! current_user_can( $capability ) ) { - add_settings_error( - self::OPTION_NAME, - 'robotstxt_2fa_capability', - __( 'You are not allowed to update these settings.', 'robotstxt-2fa' ) - ); - - return $this->get_settings(); - } - - $raw_settings = is_array( $raw_settings ) ? $raw_settings : array(); - - $sanitized = $this->get_default_settings(); - $current_settings = $this->get_settings(); - - $sanitized['force_roles'] = array(); - - if ( isset( $raw_settings['force_roles'] ) && is_array( $raw_settings['force_roles'] ) ) { - $editable_roles = array_keys( get_editable_roles() ); - - foreach ( $raw_settings['force_roles'] as $role_key ) { - $role_key = sanitize_key( $role_key ); - - if ( in_array( $role_key, $editable_roles, true ) ) { - $sanitized['force_roles'][] = $role_key; - } - } - } - - $sanitized['force_roles'] = array_values( array_unique( $sanitized['force_roles'] ) ); - - $frequency_value = $sanitized['frequency']; - - if ( isset( $current_settings['frequency'] ) ) { - $frequency_value = (string) $current_settings['frequency']; - } - - if ( isset( $raw_settings['frequency'] ) ) { - $frequency_value = (string) $raw_settings['frequency']; - } - - $sanitized['frequency'] = Frequency_Options::sanitize( $frequency_value ); - - if ( $this->has_network_settings() && ! $this->is_network_context() ) { - $sanitized['force_frequency'] = ! empty( $current_settings['force_frequency'] ?? false ); - } elseif ( array_key_exists( 'force_frequency', $raw_settings ) ) { - $sanitized['force_frequency'] = '1' === (string) $raw_settings['force_frequency']; - } - - return $sanitized; - } - - /** - * Retrieve plugin settings. - * - * @return array - */ - public function get_settings(): array { - $options = array(); - - if ( is_multisite() ) { - /** @var array|false $network_options */ - $network_options = get_site_option( self::OPTION_NAME, false ); - - if ( false !== $network_options && is_array( $network_options ) ) { - $options = $network_options; - } - } - - if ( empty( $options ) ) { - /** @var array $options */ - $options = get_option( self::OPTION_NAME, array() ); - } - - return wp_parse_args( $options, $this->get_default_settings() ); - } - - /** - * Retrieve default settings. - * - * @return array - */ - private function get_default_settings(): array { - return array( - 'force_roles' => array(), - 'default_method' => 'email', - 'frequency' => Frequency_Options::FREQUENCY_SESSION, - 'force_frequency' => false, - ); - } - - /** - * Render verification frequency field. - * - * @return void - */ - public function render_frequency_field(): void { - $settings = $this->get_settings(); - $selected = Frequency_Options::sanitize( (string) $settings['frequency'] ); - $disabled_attr = ''; - - if ( $this->has_network_settings() && ! $this->is_network_context() ) { - $disabled_attr = disabled( true, true, false ); - } - - $options = Frequency_Options::get_options(); - - echo ''; - - if ( isset( $options[ $selected ]['description'] ) && '' !== $options[ $selected ]['description'] ) { - echo '

' . esc_html( $options[ $selected ]['description'] ) . '

'; - } - } - - /** - * Render frequency enforcement checkbox. - * - * @return void - */ - public function render_force_frequency_field(): void { - $settings = $this->get_settings(); - $is_checked = ! empty( $settings['force_frequency'] ); - $disabled_attr = ''; - - if ( $this->has_network_settings() && ! $this->is_network_context() ) { - $disabled_attr = disabled( true, true, false ); - } - - if ( '' === $disabled_attr ) { - printf( - '', - esc_attr( self::OPTION_NAME ) - ); - } - - printf( - '', - esc_attr( self::OPTION_NAME ), - checked( $is_checked, true, false ), - $disabled_attr, - esc_html__( 'Prevent users from overriding the global verification frequency.', 'robotstxt-2fa' ) - ); - - echo '

' . esc_html__( 'When enabled, users will see the profile frequency control disabled and must follow the global schedule.', 'robotstxt-2fa' ) . '

'; - } - - /** - * Determine the capability required to manage settings. - * - * @return string - */ - private function get_required_capability(): string { - return 'manage_options'; - } - - /** - * Check if the current request runs in a network admin context. - * - * @return bool - */ - private function is_network_context(): bool { - return is_multisite() && is_network_admin(); - } - - /** - * Determine if network-level settings have been stored. - * - * @return bool - */ - private function has_network_settings(): bool { - if ( ! is_multisite() ) { - return false; - } - - return false !== get_site_option( self::OPTION_NAME, false ); - } - - /** - * Register the plugin admin page in the desired context. - * - * @param bool $network Whether the menu is registered for the network dashboard. - * - * @return void - */ - private function register_admin_page( bool $network ): void { - unset( $network ); - - $capability = $this->get_required_capability(); - - add_menu_page( - __( '2FA (by ROBOTSTXT)', 'robotstxt-2fa' ), - __( '2FA', 'robotstxt-2fa' ), - $capability, - self::PAGE_SLUG, - array( $this, 'render_page' ), - 'dashicons-shield' - ); - } -} - + + */ + private const AVAILABLE_METHODS = array( + 'email' => 'Email code', + 'otp' => 'Authenticator app (OTP)', + 'recovery_codes' => 'Recovery codes', + ); + + /** + * Register admin-related hooks. + * + * @return void + */ + public function register_hooks(): void { + add_action( 'admin_menu', array( $this, 'register_menu' ) ); + + if ( is_multisite() ) { + add_action( 'network_admin_menu', array( $this, 'register_network_menu' ) ); + add_action( 'network_admin_edit_robotstxt_2fa_network_save', array( $this, 'handle_network_save' ) ); + } + + add_action( 'admin_init', array( $this, 'register_settings' ) ); + } + + /** + * Register plugin settings page on single-site dashboards. + * + * @return void + */ + public function register_menu(): void { + $this->register_admin_page( false ); + } + + /** + * Register plugin settings page on the network dashboard. + * + * @return void + */ + public function register_network_menu(): void { + $this->register_admin_page( true ); + } + + /** + * Render plugin settings page. + * + * @return void + */ + public function render_page(): void { + $capability = $this->get_required_capability(); + + if ( ! current_user_can( $capability ) ) { + wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'robotstxt-2fa' ) ); + } + + settings_errors( self::OPTION_NAME ); + + $form_action = $this->is_network_context() + ? network_admin_url( 'edit.php?action=robotstxt_2fa_network_save' ) + : 'options.php'; + ?> +
+

+
+ is_network_context() ) { + wp_nonce_field( 'robotstxt_2fa_network_save', 'robotstxt_2fa_network_nonce' ); + } else { + settings_fields( self::OPTION_GROUP ); + } + do_settings_sections( self::PAGE_SLUG ); + submit_button(); + ?> +
+
+ 'array', + 'sanitize_callback' => array( $this, 'sanitize_settings' ), + 'default' => $this->get_default_settings(), + 'autoload' => false, + ) + ); + + add_settings_section( + 'robotstxt_2fa_general', + __( 'General options', 'robotstxt-2fa' ), + array( $this, 'render_general_section' ), + self::PAGE_SLUG + ); + + add_settings_field( + 'robotstxt_2fa_role_methods', + __( 'Required methods per role', 'robotstxt-2fa' ), + array( $this, 'render_role_methods_field' ), + self::PAGE_SLUG, + 'robotstxt_2fa_general' + ); + + add_settings_field( + 'robotstxt_2fa_frequency', + __( 'Verification frequency', 'robotstxt-2fa' ), + array( $this, 'render_frequency_field' ), + self::PAGE_SLUG, + 'robotstxt_2fa_general' + ); + + add_settings_field( + 'robotstxt_2fa_force_frequency', + __( 'Enforce frequency', 'robotstxt-2fa' ), + array( $this, 'render_force_frequency_field' ), + self::PAGE_SLUG, + 'robotstxt_2fa_general' + ); + + add_settings_section( + 'robotstxt_2fa_data', + __( 'Data management', 'robotstxt-2fa' ), + array( $this, 'render_data_section' ), + self::PAGE_SLUG + ); + + add_settings_field( + 'robotstxt_2fa_delete_on_uninstall', + __( 'Delete data on uninstall', 'robotstxt-2fa' ), + array( $this, 'render_delete_on_uninstall_field' ), + self::PAGE_SLUG, + 'robotstxt_2fa_data' + ); + } + + /** + * Render general settings section description. + * + * @return void + */ + public function render_general_section(): void { + echo '

' . esc_html__( 'Control how two-factor authentication is enforced for user roles.', 'robotstxt-2fa' ) . '

'; + + if ( $this->has_network_settings() && ! $this->is_network_context() ) { + echo '

' . esc_html__( 'These settings are locked by a network administrator. Any changes made here will be ignored.', 'robotstxt-2fa' ) . '

'; + } + } + + /** + * Render the per-role method matrix field. + * + * Each row represents a role; each column represents a verification method. + * Checking a method for a role forces users of that role to verify with it. + * Leaving all methods unchecked for a role makes 2FA optional for that role. + * Row and column "select all" controls are provided via JavaScript. + * + * @return void + */ + public function render_role_methods_field(): void { + $settings = $this->get_settings(); + $role_methods = $settings['role_methods']; + $roles = get_editable_roles(); + $locked = $this->has_network_settings() && ! $this->is_network_context(); + $disabled = $locked ? disabled( true, true, false ) : ''; + + if ( empty( $roles ) ) { + echo '

' . esc_html__( 'No editable roles were found.', 'robotstxt-2fa' ) . '

'; + return; + } + + $methods = array( + 'email' => __( 'Email code', 'robotstxt-2fa' ), + 'otp' => __( 'Authenticator app', 'robotstxt-2fa' ), + 'recovery_codes' => __( 'Recovery codes', 'robotstxt-2fa' ), + ); + ?> + + + + + $method_label ) : ?> + + + + + + + + + $role_details ) : ?> + + + $method_label ) : ?> + + + + + + + + +
+ + +
+ + +
+ +
+ + + +
+

+ +

+ + + + >, frequency: string, force_frequency: bool, delete_on_uninstall: bool} + */ + public function sanitize_settings( $raw_settings ): array { + $capability = $this->get_required_capability(); + + if ( ! current_user_can( $capability ) ) { + add_settings_error( + self::OPTION_NAME, + 'robotstxt_2fa_capability', + __( 'You are not allowed to update these settings.', 'robotstxt-2fa' ) + ); + + return $this->get_settings(); + } + + $raw_settings = is_array( $raw_settings ) ? $raw_settings : array(); + $sanitized = $this->get_default_settings(); + $current_settings = $this->get_settings(); + $editable_roles = array_keys( get_editable_roles() ); + $valid_methods = array_keys( self::AVAILABLE_METHODS ); + + $sanitized['role_methods'] = array(); + + if ( isset( $raw_settings['role_methods'] ) && is_array( $raw_settings['role_methods'] ) ) { + foreach ( $raw_settings['role_methods'] as $role_key => $raw_methods ) { + $role_key = sanitize_key( is_string( $role_key ) ? $role_key : '' ); + + if ( '' === $role_key || ! in_array( $role_key, $editable_roles, true ) ) { + continue; + } + + if ( ! is_array( $raw_methods ) ) { + continue; + } + + $methods = array(); + + foreach ( $raw_methods as $method ) { + $method = sanitize_key( is_string( $method ) ? $method : '' ); + + if ( in_array( $method, $valid_methods, true ) ) { + $methods[] = $method; + } + } + + if ( ! empty( $methods ) ) { + $sanitized['role_methods'][ $role_key ] = array_values( array_unique( $methods ) ); + } + } + } + + $frequency_value = $current_settings['frequency']; + + if ( isset( $raw_settings['frequency'] ) && is_string( $raw_settings['frequency'] ) ) { + $frequency_value = $raw_settings['frequency']; + } + + $sanitized['frequency'] = Frequency_Options::sanitize( $frequency_value ); + + if ( $this->has_network_settings() && ! $this->is_network_context() ) { + $sanitized['force_frequency'] = $current_settings['force_frequency']; + } elseif ( array_key_exists( 'force_frequency', $raw_settings ) ) { + $sanitized['force_frequency'] = '1' === ( is_scalar( $raw_settings['force_frequency'] ) ? (string) $raw_settings['force_frequency'] : '' ); + } + + if ( array_key_exists( 'delete_on_uninstall', $raw_settings ) ) { + $sanitized['delete_on_uninstall'] = '1' === ( is_scalar( $raw_settings['delete_on_uninstall'] ) ? (string) $raw_settings['delete_on_uninstall'] : '' ); + } + + return $sanitized; + } + + /** + * Retrieve plugin settings, migrating from legacy format when necessary. + * + * @return array{role_methods: array>, frequency: string, force_frequency: bool, delete_on_uninstall: bool} + */ + public function get_settings(): array { + $options = array(); + + if ( is_multisite() ) { + $network_options = get_site_option( self::OPTION_NAME, false ); + + if ( is_array( $network_options ) ) { + $options = $network_options; + } + } + + if ( empty( $options ) ) { + $raw = get_option( self::OPTION_NAME, array() ); + if ( is_array( $raw ) ) { + $options = $raw; + } + } + + return array( + 'role_methods' => $this->resolve_role_methods( $options ), + 'frequency' => Frequency_Options::sanitize( isset( $options['frequency'] ) && is_string( $options['frequency'] ) ? $options['frequency'] : '' ), + 'force_frequency' => ! empty( $options['force_frequency'] ), + 'delete_on_uninstall' => ! empty( $options['delete_on_uninstall'] ), + ); + } + + /** + * Retrieve default settings. + * + * @return array{role_methods: array>, frequency: string, force_frequency: bool, delete_on_uninstall: bool} + */ + private function get_default_settings(): array { + return array( + 'role_methods' => array(), + 'frequency' => Frequency_Options::FREQUENCY_SESSION, + 'force_frequency' => false, + 'delete_on_uninstall' => false, + ); + } + + /** + * Resolve role_methods from stored options, migrating legacy force_roles + default_method if needed. + * + * @param array $options Raw stored options. + * + * @return array> + */ + private function resolve_role_methods( array $options ): array { + $valid_methods = array_keys( self::AVAILABLE_METHODS ); + + if ( isset( $options['role_methods'] ) && is_array( $options['role_methods'] ) ) { + $role_methods = array(); + + foreach ( $options['role_methods'] as $role => $methods ) { + $role = is_string( $role ) ? sanitize_key( $role ) : ''; + + if ( '' === $role || ! is_array( $methods ) ) { + continue; + } + + $clean = array(); + + foreach ( $methods as $m ) { + $m = is_string( $m ) ? sanitize_key( $m ) : ''; + + if ( in_array( $m, $valid_methods, true ) ) { + $clean[] = $m; + } + } + + if ( ! empty( $clean ) ) { + $role_methods[ $role ] = array_values( array_unique( $clean ) ); + } + } + + return $role_methods; + } + + // Migrate legacy force_roles + default_method to role_methods. + if ( isset( $options['force_roles'] ) && is_array( $options['force_roles'] ) ) { + $default_method = isset( $options['default_method'] ) && is_string( $options['default_method'] ) ? sanitize_key( $options['default_method'] ) : 'email'; + + if ( ! in_array( $default_method, $valid_methods, true ) ) { + $default_method = 'email'; + } + + $role_methods = array(); + + foreach ( $options['force_roles'] as $role ) { + $role = is_string( $role ) ? sanitize_key( $role ) : ''; + + if ( '' !== $role ) { + $role_methods[ $role ] = array( $default_method ); + } + } + + return $role_methods; + } + + return array(); + } + + /** + * Render verification frequency field. + * + * @return void + */ + public function render_frequency_field(): void { + $settings = $this->get_settings(); + $selected = $settings['frequency']; + $disabled_attr = ''; + + if ( $this->has_network_settings() && ! $this->is_network_context() ) { + $disabled_attr = disabled( true, true, false ); + } + + $options = Frequency_Options::get_options(); + + echo ''; + + if ( isset( $options[ $selected ]['description'] ) && '' !== $options[ $selected ]['description'] ) { + echo '

' . esc_html( $options[ $selected ]['description'] ) . '

'; + } + } + + /** + * Render frequency enforcement checkbox. + * + * @return void + */ + public function render_force_frequency_field(): void { + $settings = $this->get_settings(); + $is_checked = $settings['force_frequency']; + $disabled_attr = ''; + + if ( $this->has_network_settings() && ! $this->is_network_context() ) { + $disabled_attr = disabled( true, true, false ); + } + + if ( '' === $disabled_attr ) { + printf( + '', + esc_attr( self::OPTION_NAME ) + ); + } + + printf( + '', + esc_attr( self::OPTION_NAME ), + checked( $is_checked, true, false ), + $disabled_attr, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Value comes from WordPress disabled() function. + esc_html__( 'Prevent users from overriding the global verification frequency.', 'robotstxt-2fa' ) + ); + + echo '

' . esc_html__( 'When enabled, users will see the profile frequency control disabled and must follow the global schedule.', 'robotstxt-2fa' ) . '

'; + } + + /** + * Render the data management section description. + * + * @return void + */ + public function render_data_section(): void { + echo '

' . esc_html__( 'Control what happens to plugin data when the plugin is deleted.', 'robotstxt-2fa' ) . '

'; + } + + /** + * Render the delete-on-uninstall checkbox. + * + * @return void + */ + public function render_delete_on_uninstall_field(): void { + $settings = $this->get_settings(); + $is_checked = $settings['delete_on_uninstall']; + + printf( + '', + esc_attr( self::OPTION_NAME ) + ); + + printf( + '', + esc_attr( self::OPTION_NAME ), + checked( $is_checked, true, false ), + esc_html__( 'Remove all plugin data when the plugin is deleted.', 'robotstxt-2fa' ) + ); + + echo '

' . esc_html__( 'When checked, deleting this plugin will permanently remove all settings, per-user 2FA preferences, stored secrets, recovery codes, and verification history. This action cannot be undone. Leave unchecked (default) to preserve all data if you reinstall later.', 'robotstxt-2fa' ) . '

'; + } + + /** + * Handle the network admin settings form submission. + * + * WordPress's Settings API does not work in network admin; this handler + * validates the nonce, sanitizes input, and saves via update_site_option(). + * + * @return void + */ + public function handle_network_save(): void { + check_admin_referer( 'robotstxt_2fa_network_save', 'robotstxt_2fa_network_nonce' ); + + if ( ! current_user_can( 'manage_network_options' ) ) { + wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'robotstxt-2fa' ) ); + } + + $raw = isset( $_POST[ self::OPTION_NAME ] ) && is_array( $_POST[ self::OPTION_NAME ] ) + ? wp_unslash( $_POST[ self::OPTION_NAME ] ) + : array(); + + $sanitized = $this->sanitize_settings( $raw ); + + update_site_option( self::OPTION_NAME, $sanitized ); + + wp_safe_redirect( + add_query_arg( + array( + 'page' => 'robotstxt-2fa-settings', + 'updated' => 'true', + ), + network_admin_url( 'admin.php' ) + ) + ); + exit; + } + + /** + * Determine the capability required to manage settings. + * + * @return string + */ + private function get_required_capability(): string { + return $this->is_network_context() ? 'manage_network_options' : 'manage_options'; + } + + /** + * Check if the current request runs in a network admin context. + * + * @return bool + */ + private function is_network_context(): bool { + return is_multisite() && is_network_admin(); + } + + /** + * Determine if network-level settings have been stored. + * + * @return bool + */ + private function has_network_settings(): bool { + if ( ! is_multisite() ) { + return false; + } + + return false !== get_site_option( self::OPTION_NAME, false ); + } + + /** + * Register the plugin admin page in the desired context. + * + * @param bool $network Whether the menu is registered for the network dashboard. + * + * @return void + */ + private function register_admin_page( bool $network ): void { + unset( $network ); + + $capability = $this->get_required_capability(); + + add_menu_page( + __( '2FA (by ROBOTSTXT)', 'robotstxt-2fa' ), + __( '2FA', 'robotstxt-2fa' ), + $capability, + self::PAGE_SLUG, + array( $this, 'render_page' ), + 'dashicons-shield' + ); + } +} diff --git a/includes/class-frequency-options.php b/includes/class-frequency-options.php index 34ffb80..da4151b 100644 --- a/includes/class-frequency-options.php +++ b/includes/class-frequency-options.php @@ -1,110 +1,110 @@ -> - */ - public static function get_options(): array { - return array( - self::FREQUENCY_SESSION => array( - 'label' => __( 'Every login', 'robotstxt-2fa' ), - 'description' => __( 'Always require a new verification code after the password step.', 'robotstxt-2fa' ), - ), - self::FREQUENCY_DAILY => array( - 'label' => __( 'Daily', 'robotstxt-2fa' ), - 'description' => __( 'Remember successful verifications for 24 hours per device.', 'robotstxt-2fa' ), - ), - self::FREQUENCY_WEEKLY => array( - 'label' => __( 'Weekly', 'robotstxt-2fa' ), - 'description' => __( 'Remember successful verifications for 7 days per device.', 'robotstxt-2fa' ), - ), - self::FREQUENCY_MONTHLY => array( - 'label' => __( 'Monthly', 'robotstxt-2fa' ), - 'description' => __( 'Remember successful verifications for 28 days per device.', 'robotstxt-2fa' ), - ), - ); - } - - /** - * Retrieve the allowed option keys. - * - * @return array - */ - public static function get_allowed_keys(): array { - return array_keys( self::get_options() ); - } - - /** - * Sanitize a frequency key against the supported values. - * - * @param string $frequency Submitted frequency value. - * - * @return string - */ - public static function sanitize( string $frequency ): string { - $frequency = sanitize_key( $frequency ); - - if ( in_array( $frequency, self::get_allowed_keys(), true ) ) { - return $frequency; - } - - return self::FREQUENCY_SESSION; - } - - /** - * Resolve the interval in seconds represented by a frequency. - * - * @param string $frequency Frequency identifier. - * - * @return int - */ - public static function get_interval_seconds( string $frequency ): int { - switch ( $frequency ) { - case self::FREQUENCY_DAILY: - return DAY_IN_SECONDS; - case self::FREQUENCY_WEEKLY: - return WEEK_IN_SECONDS; - case self::FREQUENCY_MONTHLY: - return 28 * DAY_IN_SECONDS; - case self::FREQUENCY_SESSION: - default: - return 0; - } - } -} +> + */ + public static function get_options(): array { + return array( + self::FREQUENCY_SESSION => array( + 'label' => __( 'Every login', 'robotstxt-2fa' ), + 'description' => __( 'Always require a new verification code after the password step.', 'robotstxt-2fa' ), + ), + self::FREQUENCY_DAILY => array( + 'label' => __( 'Daily', 'robotstxt-2fa' ), + 'description' => __( 'Remember successful verifications for 24 hours per device.', 'robotstxt-2fa' ), + ), + self::FREQUENCY_WEEKLY => array( + 'label' => __( 'Weekly', 'robotstxt-2fa' ), + 'description' => __( 'Remember successful verifications for 7 days per device.', 'robotstxt-2fa' ), + ), + self::FREQUENCY_MONTHLY => array( + 'label' => __( 'Monthly', 'robotstxt-2fa' ), + 'description' => __( 'Remember successful verifications for 28 days per device.', 'robotstxt-2fa' ), + ), + ); + } + + /** + * Retrieve the allowed option keys. + * + * @return array + */ + public static function get_allowed_keys(): array { + return array_keys( self::get_options() ); + } + + /** + * Sanitize a frequency key against the supported values. + * + * @param string $frequency Submitted frequency value. + * + * @return string + */ + public static function sanitize( string $frequency ): string { + $frequency = sanitize_key( $frequency ); + + if ( in_array( $frequency, self::get_allowed_keys(), true ) ) { + return $frequency; + } + + return self::FREQUENCY_SESSION; + } + + /** + * Resolve the interval in seconds represented by a frequency. + * + * @param string $frequency Frequency identifier. + * + * @return int + */ + public static function get_interval_seconds( string $frequency ): int { + switch ( $frequency ) { + case self::FREQUENCY_DAILY: + return DAY_IN_SECONDS; + case self::FREQUENCY_WEEKLY: + return WEEK_IN_SECONDS; + case self::FREQUENCY_MONTHLY: + return 28 * DAY_IN_SECONDS; + case self::FREQUENCY_SESSION: + default: + return 0; + } + } +} diff --git a/includes/class-plugin.php b/includes/class-plugin.php index 5c0b9e4..363f4aa 100644 --- a/includes/class-plugin.php +++ b/includes/class-plugin.php @@ -1,120 +1,120 @@ -login_manager = new Login_Form_Manager(); - $this->profile_settings = new Profile_Settings(); - $this->recovery_codes = new Recovery_Codes(); - $this->settings_page = new Settings_Page(); - } - - /** - * Plugin initialization. - * - * @return void - */ - public function init(): void { - $this->maybe_load_textdomain(); - $this->login_manager->register_hooks(); - $this->profile_settings->register_hooks(); - $this->recovery_codes->register_hooks(); - $this->settings_page->register_hooks(); - } - - /** - * Runs on activation. - * - * @return void - */ - public static function activate(): void { - // Placeholder for activation tasks (option creation, migrations, etc.). - } - - /** - * Runs on deactivation. - * - * @return void - */ - public static function deactivate(): void { - // Placeholder for deactivation cleanup logic. - } - - /** - * Load text domain for translations. - * - * @return void - */ - private function maybe_load_textdomain(): void { - load_plugin_textdomain( 'robotstxt-2fa', false, dirname( plugin_basename( ROBOTSTXT_2FA_FILE ) ) . '/languages/' ); - } -} +login_manager = new Login_Form_Manager(); + $this->profile_settings = new Profile_Settings(); + $this->recovery_codes = new Recovery_Codes(); + $this->settings_page = new Settings_Page(); + } + + /** + * Plugin initialization. + * + * @return void + */ + public function init(): void { + $this->maybe_load_textdomain(); + $this->login_manager->register_hooks(); + $this->profile_settings->register_hooks(); + $this->recovery_codes->register_hooks(); + $this->settings_page->register_hooks(); + } + + /** + * Runs on activation. + * + * @return void + */ + public static function activate(): void { + // Placeholder for activation tasks (option creation, migrations, etc.). + } + + /** + * Runs on deactivation. + * + * @return void + */ + public static function deactivate(): void { + // Placeholder for deactivation cleanup logic. + } + + /** + * Load text domain for translations. + * + * @return void + */ + private function maybe_load_textdomain(): void { + load_plugin_textdomain( 'robotstxt-2fa', false, dirname( plugin_basename( ROBOTSTXT_2FA_FILE ) ) . '/languages/' ); + } +} diff --git a/includes/login/class-email-code-sender.php b/includes/login/class-email-code-sender.php index b6712ac..41378c7 100644 --- a/includes/login/class-email-code-sender.php +++ b/includes/login/class-email-code-sender.php @@ -1,149 +1,151 @@ -user_settings_repository = new User_Settings_Repository(); - } - - /** - * Retrieve the expected code length. - * - * @return int - */ - public function get_code_length(): int { - return self::CODE_LENGTH; - } - - /** - * Send a verification code to the provided user. - * - * @param \WP_User $user User who is requesting authentication. - * - * @return bool True when the email was sent or throttled successfully, false on failure. - */ - public function send_code( \WP_User $user ): bool { - if ( empty( $user->user_email ) || ! is_email( $user->user_email ) ) { - return false; - } - - $challenge = $this->user_settings_repository->get_email_challenge( $user->ID ); - $current_time = time(); - - if ( ! empty( $challenge['hash'] ) && $challenge['expires'] > $current_time && $challenge['sent_at'] >= ( $current_time - self::RESEND_INTERVAL ) ) { - return true; - } - - $code = $this->generate_code(); - $expires = $current_time + self::EXPIRATION_SECONDS; - - $blog_name = wp_specialchars_decode( get_option( 'blogname', '' ), ENT_QUOTES ); - $display_name = wp_strip_all_tags( $user->display_name ?: $user->user_login ); - $email_subject = sprintf( __( '[%s] Your verification code', 'robotstxt-2fa' ), $blog_name ?: __( 'WordPress', 'robotstxt-2fa' ) ); - - $message_lines = array( - /* translators: %s: user display name. */ - sprintf( __( 'Hi %s,', 'robotstxt-2fa' ), $display_name ), - '', - /* translators: %s: site name. */ - sprintf( __( 'Use the following verification code to finish signing in to %s:', 'robotstxt-2fa' ), $blog_name ?: __( 'your site', 'robotstxt-2fa' ) ), - '', - $code, - '', - __( 'The code expires in 10 minutes.', 'robotstxt-2fa' ), - '', - __( 'If you did not request this code you can ignore this email.', 'robotstxt-2fa' ), - ); - - $message = implode( "\n", $message_lines ); - - $headers = array( 'Content-Type: text/plain; charset=UTF-8' ); - - if ( ! wp_mail( $user->user_email, $email_subject, $message, $headers ) ) { - return false; - } - - $this->user_settings_repository->store_email_challenge( $user->ID, $code, $expires ); - - return true; - } - - /** - * Verify a submitted code against the stored challenge. - * - * @param \WP_User $user User attempting to authenticate. - * @param string $code Submitted verification code. - * - * @return bool - */ - public function verify_code( \WP_User $user, string $code ): bool { - $challenge = $this->user_settings_repository->get_email_challenge( $user->ID ); - $code = preg_replace( '/[^0-9]/', '', $code ); - - if ( empty( $challenge['hash'] ) ) { - return false; - } - - if ( $challenge['expires'] <= time() ) { - return false; - } - - if ( '' === $code ) { - return false; - } - - return wp_check_password( $code, $challenge['hash'] ); - } - - /** - * Generate a random numeric verification code. - * - * @return string - */ - private function generate_code(): string { - $max_value = ( 10 ** self::CODE_LENGTH ) - 1; - $code = (string) wp_rand( 0, (int) $max_value ); - - return str_pad( $code, self::CODE_LENGTH, '0', STR_PAD_LEFT ); - } -} +user_settings_repository = new User_Settings_Repository(); + } + + /** + * Retrieve the expected code length. + * + * @return int + */ + public function get_code_length(): int { + return self::CODE_LENGTH; + } + + /** + * Send a verification code to the provided user. + * + * @param \WP_User $user User who is requesting authentication. + * + * @return bool True when the email was sent or throttled successfully, false on failure. + */ + public function send_code( \WP_User $user ): bool { + if ( empty( $user->user_email ) || ! is_email( $user->user_email ) ) { + return false; + } + + $challenge = $this->user_settings_repository->get_email_challenge( $user->ID ); + $current_time = time(); + + if ( ! empty( $challenge['hash'] ) && $challenge['expires'] > $current_time && $challenge['sent_at'] >= ( $current_time - self::RESEND_INTERVAL ) ) { + return true; + } + + $code = $this->generate_code(); + $expires = $current_time + self::EXPIRATION_SECONDS; + + $raw_blogname = get_option( 'blogname', '' ); + $blog_name = wp_specialchars_decode( is_string( $raw_blogname ) ? $raw_blogname : '', ENT_QUOTES ); + $display_name = wp_strip_all_tags( ! empty( $user->display_name ) ? $user->display_name : $user->user_login ); + /* translators: %s: site name. */ + $email_subject = sprintf( __( '[%s] Your verification code', 'robotstxt-2fa' ), ! empty( $blog_name ) ? $blog_name : __( 'WordPress', 'robotstxt-2fa' ) ); + + $message_lines = array( + /* translators: %s: user display name. */ + sprintf( __( 'Hi %s,', 'robotstxt-2fa' ), $display_name ), + '', + /* translators: %s: site name. */ + sprintf( __( 'Use the following verification code to finish signing in to %s:', 'robotstxt-2fa' ), ! empty( $blog_name ) ? $blog_name : __( 'your site', 'robotstxt-2fa' ) ), + '', + $code, + '', + __( 'The code expires in 10 minutes.', 'robotstxt-2fa' ), + '', + __( 'If you did not request this code you can ignore this email.', 'robotstxt-2fa' ), + ); + + $message = implode( "\n", $message_lines ); + + $headers = array( 'Content-Type: text/plain; charset=UTF-8' ); + + if ( ! wp_mail( $user->user_email, $email_subject, $message, $headers ) ) { + return false; + } + + $this->user_settings_repository->store_email_challenge( $user->ID, $code, $expires ); + + return true; + } + + /** + * Verify a submitted code against the stored challenge. + * + * @param \WP_User $user User attempting to authenticate. + * @param string $code Submitted verification code. + * + * @return bool + */ + public function verify_code( \WP_User $user, string $code ): bool { + $challenge = $this->user_settings_repository->get_email_challenge( $user->ID ); + $code = preg_replace( '/[^0-9]/', '', $code ) ?? ''; + + if ( '' === $challenge['hash'] ) { + return false; + } + + if ( $challenge['expires'] <= time() ) { + return false; + } + + if ( '' === $code ) { + return false; + } + + return wp_check_password( $code, $challenge['hash'] ); + } + + /** + * Generate a random numeric verification code. + * + * @return string + */ + private function generate_code(): string { + $max_value = ( 10 ** self::CODE_LENGTH ) - 1; + $code = (string) random_int( 0, $max_value ); + + return str_pad( $code, self::CODE_LENGTH, '0', STR_PAD_LEFT ); + } +} diff --git a/includes/login/class-login-form-manager.php b/includes/login/class-login-form-manager.php index 0651a6c..5690b5a 100644 --- a/includes/login/class-login-form-manager.php +++ b/includes/login/class-login-form-manager.php @@ -1,1170 +1,1203 @@ -email_code_sender = new Email_Code_Sender(); - $this->otp_manager = new OTP_Manager(); - $this->recovery_codes = new Recovery_Codes(); - $this->user_settings_repository = new User_Settings_Repository(); - $this->config = new Two_Factor_Config(); - } - - /** - * Handle verification method switches requested on the login stage. - * - * @return void - */ - private function process_method_switch(): void { - $method = $this->get_requested_method(); - - $login = $this->get_requested_login(); - - if ( '' === $login ) { - return; - } - - $user = get_user_by( 'login', $login ); - - if ( ! $user instanceof \WP_User ) { - return; - } - - $stage_token = $this->get_requested_stage_token(); - - if ( '' === $stage_token || ! $this->validate_stage_token( $user, $stage_token ) ) { - return; - } - - $available_methods = $this->get_enabled_verification_methods( $user ); - - if ( ! in_array( $method, $available_methods, true ) ) { - return; - } - - $redirect_args = array( - self::QUERY_METHOD => $method, - self::QUERY_NOTICE => null, - self::QUERY_RESEND => null, - self::QUERY_SWITCH => null, - ); - - if ( 'email' === $method ) { - if ( ! $this->email_code_sender->send_code( $user ) ) { - $redirect_args[ self::QUERY_NOTICE ] = 'failed'; - } else { - $redirect_args[ self::QUERY_NOTICE ] = 'resent'; - } - } - - $redirect_url = $this->get_stage_url( $redirect_args ); - - wp_safe_redirect( $redirect_url ); - exit; - } - - /** - * Register WordPress hooks. - * - * @return void - */ - public function register_hooks(): void { - add_action( 'login_init', array( $this, 'maybe_process_stage_requests' ) ); - add_action( 'login_form', array( $this, 'render_form_fields' ) ); - add_action( 'login_head', array( $this, 'render_stage_styles' ) ); - add_action( 'login_footer', array( $this, 'render_stage_scripts' ) ); - add_filter( 'login_message', array( $this, 'filter_login_message' ) ); - add_filter( 'authenticate', array( $this, 'maybe_complete_verification' ), 5, 3 ); - add_filter( 'authenticate', array( $this, 'enforce_verification_challenge' ), 30, 3 ); - } - - /** - * Render custom fields on the login form. - * - * @return void - */ - public function render_form_fields(): void { - if ( ! $this->is_verification_stage() ) { - return; - } - - $login = $this->get_requested_login(); - $method = $this->get_requested_method(); - $code_length = $this->get_method_code_length( $method ); - $alternates = array(); - - if ( '' !== $login ) { - $user = get_user_by( 'login', $login ); - - if ( $user instanceof WP_User ) { - $alternates = $this->get_alternate_method_links( $user, $method ); - } - } - - if ( '' !== $login ) { - printf( '', esc_attr( self::FIELD_LOGIN ), esc_attr( $login ) ); - } - - printf( '', esc_attr( self::FIELD_METHOD ), esc_attr( $method ) ); - printf( '', esc_attr( self::FIELD_STAGE ), esc_attr( self::STAGE_VERIFY ) ); - - $stage_token = $this->get_requested_stage_token(); - - if ( '' !== $stage_token ) { - printf( '', esc_attr( self::FIELD_STAGE_TOKEN ), esc_attr( $stage_token ) ); - } - - wp_nonce_field( self::LOGIN_NONCE_ACTION, self::LOGIN_NONCE_FIELD ); - ?> - - %s

', - esc_html( $instruction ) - ); - } - - if ( ! empty( $alternates ) ) { - $link_markup = array(); - - foreach ( $alternates as $alternate ) { - $link_markup[] = sprintf( - '%2$s', - esc_url( $alternate['url'] ), - esc_html( $alternate['label'] ) - ); - } - - if ( ! empty( $link_markup ) ) { - printf( - '

%1$s %2$s

', - esc_html__( 'Prefer a different verification method?', 'robotstxt-2fa' ), - wp_kses_post( implode( ' ', $link_markup ) ) - ); - } - } - - $back_url = wp_login_url( $this->get_requested_redirect() ); - ?> - - is_verification_stage() ) { - return; - } - - ?> - - is_verification_stage() ) { - return $message; - } - - $login = $this->get_requested_login(); - $method = $this->get_requested_method(); - - if ( '' === $login ) { - return $message; - } - - $user = get_user_by( 'login', $login ); - - if ( ! $user instanceof WP_User ) { - return $message; - } - - $notice = $this->get_requested_notice(); - - if ( 'email' === $method ) { - $challenge = $this->user_settings_repository->get_email_challenge( $user->ID ); - - if ( empty( $challenge['sent_at'] ) ) { - return $message; - } - - $message .= '

' . esc_html__( 'We sent a verification code to your email. Enter it below to continue.', 'robotstxt-2fa' ) . '

'; - - if ( 'resent' === $notice ) { - $message .= '

' . esc_html__( 'We sent you a fresh verification code. Check your inbox.', 'robotstxt-2fa' ) . '

'; - } elseif ( 'failed' === $notice ) { - $message .= '

' . esc_html__( 'We could not send a new verification code. Please try again in a moment.', 'robotstxt-2fa' ) . '

'; - } - } elseif ( 'otp' === $method ) { - $message .= '

' . esc_html__( 'Open your authenticator app and enter the code to continue.', 'robotstxt-2fa' ) . '

'; - } elseif ( 'recovery' === $method ) { - $message .= '

' . esc_html__( 'Enter one of your unused recovery codes to continue.', 'robotstxt-2fa' ) . '

'; - } - - return $message; - } - - /** - * Output helper scripts used during the verification stage. - * - * @return void - */ - public function render_stage_scripts(): void { - if ( ! $this->is_verification_stage() ) { - return; - } - - $login = $this->get_requested_login(); - ?> - - is_verification_submission() ) { - return $user; - } - - unset( $password ); - - if ( ! isset( $_POST[ self::LOGIN_NONCE_FIELD ] ) ) { - return new \WP_Error( 'robotstxt_2fa_missing_nonce', __( 'The verification form is missing a security token. Please try again.', 'robotstxt-2fa' ) ); - } - - $nonce = sanitize_text_field( wp_unslash( $_POST[ self::LOGIN_NONCE_FIELD ] ) ); - - if ( ! wp_verify_nonce( $nonce, self::LOGIN_NONCE_ACTION ) ) { - return new \WP_Error( 'robotstxt_2fa_invalid_nonce', __( 'The verification request expired. Please sign in again to request a new code.', 'robotstxt-2fa' ) ); - } - - $login = $this->get_requested_login(); - - if ( '' === $login && '' !== $username ) { - $login = sanitize_user( $username, true ); - } - - if ( '' === $login ) { - return new \WP_Error( 'robotstxt_2fa_unknown_user', __( 'We could not determine which account you are trying to access.', 'robotstxt-2fa' ) ); - } - - $authenticated_user = get_user_by( 'login', $login ); - - if ( ! $authenticated_user instanceof \WP_User ) { - return new \WP_Error( 'robotstxt_2fa_unknown_user', __( 'We could not load the account requesting verification.', 'robotstxt-2fa' ) ); - } - - $stage_token = $this->get_requested_stage_token(); - - if ( '' === $stage_token || ! $this->validate_stage_token( $authenticated_user, $stage_token ) ) { - return new \WP_Error( 'robotstxt_2fa_invalid_stage', __( 'Your verification session expired. Please sign in again.', 'robotstxt-2fa' ) ); - } - - $method = $this->get_requested_method(); - $allowed_methods = $this->get_enabled_verification_methods( $authenticated_user ); - - if ( ! in_array( $method, $allowed_methods, true ) ) { - return new \WP_Error( 'robotstxt_2fa_method_unavailable', __( 'The selected verification method is not available right now.', 'robotstxt-2fa' ) ); - } - - $token = ''; - - if ( isset( $_POST['robotstxt_2fa_token'] ) ) { - $token = sanitize_text_field( wp_unslash( $_POST['robotstxt_2fa_token'] ) ); - } - - if ( '' === $token ) { - return new \WP_Error( 'robotstxt_2fa_missing_code', __( 'Enter the verification code to continue.', 'robotstxt-2fa' ) ); - } - - $is_valid = false; - - switch ( $method ) { - case 'email': - $is_valid = $this->email_code_sender->verify_code( $authenticated_user, $token ); - - if ( $is_valid ) { - $this->user_settings_repository->delete_email_challenge( $authenticated_user->ID ); - } - break; - case 'recovery': - $is_valid = $this->recovery_codes->consume_code( $authenticated_user, $token ); - break; - case 'otp': - $is_valid = $this->otp_manager->verify_code( $authenticated_user, $token ); - break; - default: - return new \WP_Error( 'robotstxt_2fa_method_unavailable', __( 'The selected verification method is not available right now.', 'robotstxt-2fa' ) ); - } - - if ( ! $is_valid ) { - return new \WP_Error( 'robotstxt_2fa_invalid_code', __( 'The verification code is incorrect or has expired.', 'robotstxt-2fa' ) ); - } - - $this->user_settings_repository->record_last_verification( - $authenticated_user->ID, - $method, - $this->get_login_context_key(), - time() - ); - - return $authenticated_user; - } - - /** - * Enforce the verification step for eligible users. - * - * @param \WP_User|\WP_Error|null $user Previously authenticated user or error. - * @param string $username Submitted username. - * @param string $password Submitted password. - * - * @return \WP_User|\WP_Error|null - */ - public function enforce_verification_challenge( $user, string $username, string $password ) { - unset( $username, $password ); - - if ( $this->is_verification_stage() || $this->is_verification_submission() ) { - return $user; - } - - if ( ! $user instanceof \WP_User ) { - return $user; - } - - $method = $this->determine_required_verification_method( $user ); - - if ( '' === $method ) { - return $user; - } - - if ( 'email' === $method && ! $this->email_code_sender->send_code( $user ) ) { - return new \WP_Error( 'robotstxt_2fa_email_failed', __( 'We could not send a verification code. Please contact the site administrator.', 'robotstxt-2fa' ) ); - } - - $redirect_to = $this->get_requested_redirect(); - - $stage_token = wp_create_nonce( self::STAGE_TOKEN_ACTION . '|' . $user->ID ); - - $query_args = array( - self::QUERY_STAGE => self::STAGE_VERIFY, - self::QUERY_METHOD => $method, - self::QUERY_LOGIN => sanitize_user( $user->user_login, true ), - self::QUERY_STAGE_TOKEN => $stage_token, - ); - - $login_url = wp_login_url( $redirect_to ); - $login_url = add_query_arg( $query_args, $login_url ); - - wp_safe_redirect( $login_url ); - exit; - } - - /** - * Process additional verification stage actions triggered from the login screen. - * - * @return void - */ - public function maybe_process_stage_requests(): void { - if ( ! $this->is_verification_stage() ) { - return; - } - - if ( ! empty( $_GET[ self::QUERY_SWITCH ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Stage operations rely on dedicated nonce validation. - $this->process_method_switch(); - - return; - } - - if ( empty( $_GET[ self::QUERY_RESEND ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Action is protected by a dedicated nonce below. - return; - } - - $method = $this->get_requested_method(); - - if ( 'email' !== $method ) { - return; - } - - $login = $this->get_requested_login(); - - if ( '' === $login ) { - return; - } - - $user = get_user_by( 'login', $login ); - - if ( ! $user instanceof \WP_User ) { - return; - } - - $stage_token = $this->get_requested_stage_token(); - - if ( '' === $stage_token || ! $this->validate_stage_token( $user, $stage_token ) ) { - return; - } - - $result = $this->email_code_sender->send_code( $user ); - - $notice_value = $result ? 'resent' : 'failed'; - - $redirect_url = remove_query_arg( - self::QUERY_RESEND, - $this->get_stage_url( - array( - self::QUERY_NOTICE => $notice_value, - ) - ) - ); - - wp_safe_redirect( $redirect_url ); - exit; - } - - /** - * Retrieve the verification method requested by the current stage. - * - * @return string - */ - private function get_requested_method(): string { - $method = ''; - - if ( isset( $_REQUEST[ self::FIELD_METHOD ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Stage verification relies on dedicated nonce checks. - $method = sanitize_key( wp_unslash( $_REQUEST[ self::FIELD_METHOD ] ) ); - } - - if ( '' === $method && isset( $_REQUEST[ self::QUERY_METHOD ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Value used only for display context. - $method = sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_METHOD ] ) ); - } - - if ( '' === $method ) { - $method = 'email'; - } - - return $method; - } - - /** - * Determine the expected code length for a verification method. - * - * @param string $method Verification method identifier. - * - * @return int - */ - private function get_method_code_length( string $method ): int { - switch ( $method ) { - case 'otp': - return max( 1, (int) $this->otp_manager->get_code_length() ); - case 'recovery': - return max( 1, (int) $this->recovery_codes->get_code_length() ); - case 'email': - default: - return max( 1, (int) $this->email_code_sender->get_code_length() ); - } - } - - /** - * Retrieve the verification methods that are active for the provided user. - * - * @param \WP_User $user User attempting to authenticate. - * @param array|null $user_settings Optional preloaded settings. - * - * @return array - */ - private function get_enabled_verification_methods( \WP_User $user, ?array $user_settings = null ): array { - if ( null === $user_settings ) { - $user_settings = $this->user_settings_repository->get_user_settings( $user->ID ); - } - - $is_forced = $this->config->is_two_factor_forced_for_user( $user ); - $enabled = $is_forced ? true : ! empty( $user_settings['enabled'] ); - - if ( ! $enabled ) { - return array(); - } - - $methods = array(); - - if ( ! empty( $user_settings['methods'] ) && is_array( $user_settings['methods'] ) ) { - $methods = $user_settings['methods']; - } - - if ( $is_forced && empty( $methods ) ) { - $methods = array( $this->config->get_default_method() ); - } - - $normalized = array(); - - foreach ( $methods as $method_key ) { - $normalized_method = $this->normalize_method_slug( (string) $method_key ); - - if ( '' === $normalized_method ) { - continue; - } - - $normalized[] = $normalized_method; - } - - $normalized = array_values( array_unique( $normalized ) ); - - $available = array(); - - foreach ( $normalized as $method ) { - if ( 'email' === $method ) { - $email = sanitize_email( $user->user_email ); - - if ( '' !== $email ) { - $available[] = 'email'; - } - } elseif ( 'otp' === $method ) { - if ( '' !== $this->otp_manager->get_secret( $user->ID ) ) { - $available[] = 'otp'; - } - } elseif ( 'recovery' === $method ) { - if ( $this->recovery_codes->has_active_codes( $user->ID ) ) { - $available[] = 'recovery'; - } - } - } - - return $available; - } - - /** - * Decide which verification method should be enforced for the user. - * - * @param \WP_User $user User attempting to authenticate. - * - * @return string - */ - private function determine_required_verification_method( \WP_User $user ): string { - $user_settings = $this->user_settings_repository->get_user_settings( $user->ID ); - $methods = $this->get_enabled_verification_methods( $user, $user_settings ); - - if ( empty( $methods ) ) { - return ''; - } - - $frequency = $this->get_effective_frequency( $user, $user_settings ); - - if ( $this->has_recent_verification( $user, $methods, $frequency ) ) { - return ''; - } - - return $this->select_preferred_method( $methods ); - } - - /** - * Check whether any verification method was recently validated within the configured interval. - * - * @param \WP_User $user User attempting to authenticate. - * @param array $methods Active verification methods. - * @param string $frequency Selected frequency slug. - * - * @return bool - */ - private function has_recent_verification( \WP_User $user, array $methods, string $frequency ): bool { - if ( empty( $methods ) ) { - return false; - } - - if ( Frequency_Options::FREQUENCY_SESSION === $frequency ) { - return false; - } - - $interval_seconds = Frequency_Options::get_interval_seconds( $frequency ); - - if ( $interval_seconds <= 0 ) { - return false; - } - - $context_key = $this->get_login_context_key(); - - foreach ( $methods as $method ) { - $last_verified = $this->user_settings_repository->get_last_verification_timestamp( $user->ID, $method, $context_key ); - - if ( $last_verified > 0 && ( $last_verified + $interval_seconds ) > time() ) { - return true; - } - } - - return false; - } - - /** - * Determine which method should be requested when a challenge is required. - * - * @param array $methods Active verification methods. - * - * @return string - */ - private function select_preferred_method( array $methods ): string { - if ( empty( $methods ) ) { - return ''; - } - - $preferred = $this->normalize_method_slug( $this->config->get_default_method() ); - - $priority = array_values( - array_filter( - array_unique( - array_merge( - array( 'otp' ), - array( $preferred ), - array( 'email', 'recovery' ) - ) - ) - ) - ); - - foreach ( $priority as $method ) { - if ( 'recovery' === $method && count( $methods ) > 1 ) { - continue; - } - - if ( in_array( $method, $methods, true ) ) { - return $method; - } - } - - return (string) $methods[0]; - } - - /** - * Normalize stored method identifiers to the stage slugs used during verification. - * - * @param string $method Raw method identifier. - * - * @return string - */ - private function normalize_method_slug( string $method ): string { - $method = sanitize_key( $method ); - - if ( '' === $method ) { - return ''; - } - - if ( 'recovery_codes' === $method || 'recovery' === $method ) { - return 'recovery'; - } - - if ( in_array( $method, array( 'email', 'otp' ), true ) ) { - return $method; - } - - return ''; - } - - /** - * Build the list of alternate verification method links for the login stage. - * - * @param \WP_User $user User attempting to authenticate. - * @param string $current_method Active verification method slug. - * - * @return array> - */ - private function get_alternate_method_links( \WP_User $user, string $current_method ): array { - $available_methods = $this->get_enabled_verification_methods( $user ); - - $available_methods = array_values( - array_diff( $available_methods, array( $current_method ) ) - ); - - if ( empty( $available_methods ) ) { - return array(); - } - - $labels = array( - 'email' => __( 'Use an email code instead', 'robotstxt-2fa' ), - 'otp' => __( 'Use your authenticator app instead', 'robotstxt-2fa' ), - 'recovery' => __( 'Use a recovery code instead', 'robotstxt-2fa' ), - ); - - $links = array(); - - foreach ( $available_methods as $method ) { - if ( ! isset( $labels[ $method ] ) ) { - continue; - } - - $links[] = array( - 'url' => $this->get_stage_url( - array( - self::QUERY_METHOD => $method, - self::QUERY_NOTICE => null, - self::QUERY_RESEND => null, - self::QUERY_SWITCH => '1', - ) - ), - 'label' => $labels[ $method ], - ); - } - - return $links; - } - - - /** - * Determine whether the login request is currently displaying the verification stage. - * - * @return bool - */ - private function is_verification_stage(): bool { - if ( isset( $_REQUEST[ self::FIELD_STAGE ] ) ) { - $stage = sanitize_key( wp_unslash( $_REQUEST[ self::FIELD_STAGE ] ) ); - - if ( self::STAGE_VERIFY === $stage ) { - return true; - } - } - - if ( isset( $_REQUEST[ self::QUERY_STAGE ] ) ) { - $stage = sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_STAGE ] ) ); - - if ( self::STAGE_VERIFY === $stage ) { - return true; - } - } - - return false; - } - - /** - * Check whether the login POST submission belongs to the verification stage. - * - * @return bool - */ - private function is_verification_submission(): bool { - if ( ! isset( $_POST[ self::FIELD_STAGE ] ) ) { - return false; - } - - $stage = sanitize_key( wp_unslash( $_POST[ self::FIELD_STAGE ] ) ); - - return self::STAGE_VERIFY === $stage; - } - - /** - * Retrieve the login identifier carried across requests. - * - * @return string - */ - private function get_requested_login(): string { - $login = ''; - - if ( isset( $_REQUEST[ self::FIELD_LOGIN ] ) ) { - $login = sanitize_user( wp_unslash( $_REQUEST[ self::FIELD_LOGIN ] ), true ); - } - - if ( '' === $login && isset( $_REQUEST[ self::QUERY_LOGIN ] ) ) { - $login = sanitize_user( wp_unslash( $_REQUEST[ self::QUERY_LOGIN ] ), true ); - } - - return $login; - } - - /** - * Retrieve the stage nonce carried in the current request. - * - * @return string - */ - private function get_requested_stage_token(): string { - $token = ''; - - if ( isset( $_REQUEST[ self::FIELD_STAGE_TOKEN ] ) ) { - $token = sanitize_text_field( wp_unslash( $_REQUEST[ self::FIELD_STAGE_TOKEN ] ) ); - } - - if ( '' === $token && isset( $_REQUEST[ self::QUERY_STAGE_TOKEN ] ) ) { - $token = sanitize_text_field( wp_unslash( $_REQUEST[ self::QUERY_STAGE_TOKEN ] ) ); - } - - return $token; - } - - /** - * Retrieve the notice slug carried in the current request. - * - * @return string - */ - private function get_requested_notice(): string { - if ( ! isset( $_REQUEST[ self::QUERY_NOTICE ] ) ) { - return ''; - } - - return sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_NOTICE ] ) ); - } - - /** - * Validate whether the provided stage token is valid for the given user. - * - * @param \WP_User $user Authenticated user. - * @param string $stage_token Submitted stage token. - * - * @return bool - */ - private function validate_stage_token( \WP_User $user, string $stage_token ): bool { - return (bool) wp_verify_nonce( $stage_token, self::STAGE_TOKEN_ACTION . '|' . $user->ID ); - } - - /** - * Retrieve the sanitized redirect_to parameter from the current request. - * - * @return string - */ - private function get_requested_redirect(): string { - if ( ! isset( $_REQUEST['redirect_to'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Value is only echoed back. - return ''; - } - - return esc_url_raw( wp_unslash( $_REQUEST['redirect_to'] ) ); - } - - /** - * Build a URL pointing to the active verification stage. - * - * @param array $extra_args Optional additional query parameters to merge. - * - * @return string - */ - private function get_stage_url( array $extra_args = array() ): string { - $redirect_to = $this->get_requested_redirect(); - $login_url = wp_login_url( $redirect_to ); - - $args = array( - self::QUERY_STAGE => self::STAGE_VERIFY, - self::QUERY_METHOD => $this->get_requested_method(), - ); - - $login = $this->get_requested_login(); - - if ( '' !== $login ) { - $args[ self::QUERY_LOGIN ] = $login; - } - - $stage_token = $this->get_requested_stage_token(); - - if ( '' !== $stage_token ) { - $args[ self::QUERY_STAGE_TOKEN ] = $stage_token; - } - - foreach ( $extra_args as $key => $value ) { - if ( null === $value || '' === $key ) { - $login_url = remove_query_arg( $key, $login_url ); - continue; - } - - $args[ $key ] = $value; - } - - $args = array_filter( - $args, - static function ( $value ) { - return null !== $value && '' !== $value; - } - ); - - return add_query_arg( $args, $login_url ); - } - - /** - * Determine the effective verification frequency for the current user. - * - * @param \WP_User $user Authenticated user object. - * @param array $user_settings Stored per-user preferences. - * - * @return string - */ - private function get_effective_frequency( \WP_User $user, array $user_settings ): string { - unset( $user ); - - if ( $this->config->is_frequency_forced() ) { - return $this->config->get_frequency(); - } - - if ( ! empty( $user_settings['frequency'] ) ) { - return Frequency_Options::sanitize( (string) $user_settings['frequency'] ); - } - - return $this->config->get_frequency(); - } - - /** - * Build a hashed context key representing the current login environment. - * - * @return string - */ - private function get_login_context_key(): string { - $ip = ''; - - if ( isset( $_SERVER['REMOTE_ADDR'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below. - $ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ); - $ip = wp_privacy_anonymize_ip( $ip ); - $ip = is_string( $ip ) ? $ip : ''; - } - - $user_agent = ''; - - if ( isset( $_SERVER['HTTP_USER_AGENT'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below. - $user_agent = sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ); - } - - $user_agent = strtolower( substr( $user_agent, 0, 255 ) ); - - if ( '' === $ip && '' === $user_agent ) { - return sha1( 'unknown' ); - } - - return sha1( $ip . '|' . $user_agent ); - } -} +email_code_sender = new Email_Code_Sender(); + $this->otp_manager = new OTP_Manager(); + $this->recovery_codes = new Recovery_Codes(); + $this->user_settings_repository = new User_Settings_Repository(); + $this->config = new Two_Factor_Config(); + } + + /** + * Handle verification method switches requested on the login stage. + * + * @return void + */ + private function process_method_switch(): void { + $method = $this->get_requested_method(); + + $login = $this->get_requested_login(); + + if ( '' === $login ) { + return; + } + + $user = get_user_by( 'login', $login ); + + if ( ! $user instanceof \WP_User ) { + return; + } + + $stage_token = $this->get_requested_stage_token(); + + if ( '' === $stage_token || ! $this->validate_stage_token( $user, $stage_token ) ) { + return; + } + + $available_methods = $this->get_enabled_verification_methods( $user ); + + if ( ! in_array( $method, $available_methods, true ) ) { + return; + } + + $redirect_args = array( + self::QUERY_METHOD => $method, + self::QUERY_NOTICE => null, + self::QUERY_RESEND => null, + self::QUERY_SWITCH => null, + ); + + if ( 'email' === $method ) { + if ( ! $this->email_code_sender->send_code( $user ) ) { + $redirect_args[ self::QUERY_NOTICE ] = 'failed'; + } else { + $redirect_args[ self::QUERY_NOTICE ] = 'resent'; + } + } + + $redirect_url = $this->get_stage_url( $redirect_args ); + + wp_safe_redirect( $redirect_url ); + exit; + } + + /** + * Register WordPress hooks. + * + * @return void + */ + public function register_hooks(): void { + add_action( 'login_init', array( $this, 'maybe_process_stage_requests' ) ); + add_action( 'login_form', array( $this, 'render_form_fields' ) ); + add_action( 'login_head', array( $this, 'render_stage_styles' ) ); + add_action( 'login_footer', array( $this, 'render_stage_scripts' ) ); + add_filter( 'login_message', array( $this, 'filter_login_message' ) ); + add_filter( 'authenticate', array( $this, 'maybe_complete_verification' ), 5, 3 ); + add_filter( 'authenticate', array( $this, 'enforce_verification_challenge' ), 30, 3 ); + } + + /** + * Render custom fields on the login form. + * + * @return void + */ + public function render_form_fields(): void { + if ( ! $this->is_verification_stage() ) { + return; + } + + $login = $this->get_requested_login(); + $method = $this->get_requested_method(); + $code_length = $this->get_method_code_length( $method ); + $alternates = array(); + + if ( '' !== $login ) { + $user = get_user_by( 'login', $login ); + + if ( $user instanceof WP_User ) { + $alternates = $this->get_alternate_method_links( $user, $method ); + } + } + + if ( '' !== $login ) { + printf( '', esc_attr( self::FIELD_LOGIN ), esc_attr( $login ) ); + } + + printf( '', esc_attr( self::FIELD_METHOD ), esc_attr( $method ) ); + printf( '', esc_attr( self::FIELD_STAGE ), esc_attr( self::STAGE_VERIFY ) ); + + $stage_token = $this->get_requested_stage_token(); + + if ( '' !== $stage_token ) { + printf( '', esc_attr( self::FIELD_STAGE_TOKEN ), esc_attr( $stage_token ) ); + } + + wp_nonce_field( self::LOGIN_NONCE_ACTION, self::LOGIN_NONCE_FIELD ); + ?> + + %s

', + esc_html( $instruction ) + ); + } + + if ( ! empty( $alternates ) ) { + $link_markup = array(); + + foreach ( $alternates as $alternate ) { + $link_markup[] = sprintf( + '%2$s', + esc_url( $alternate['url'] ), + esc_html( $alternate['label'] ) + ); + } + + printf( + '

%1$s %2$s

', + esc_html__( 'Prefer a different verification method?', 'robotstxt-2fa' ), + wp_kses_post( implode( ' ', $link_markup ) ) + ); + } + + $back_url = wp_login_url( $this->get_requested_redirect() ); + ?> + + is_verification_stage() ) { + return; + } + + ?> + + is_verification_stage() ) { + return $message; + } + + $login = $this->get_requested_login(); + $method = $this->get_requested_method(); + + if ( '' === $login ) { + return $message; + } + + $user = get_user_by( 'login', $login ); + + if ( ! $user instanceof WP_User ) { + return $message; + } + + $notice = $this->get_requested_notice(); + + if ( 'email' === $method ) { + $challenge = $this->user_settings_repository->get_email_challenge( $user->ID ); + + if ( empty( $challenge['sent_at'] ) ) { + return $message; + } + + $message .= '

' . esc_html__( 'We sent a verification code to your email. Enter it below to continue.', 'robotstxt-2fa' ) . '

'; + + if ( 'resent' === $notice ) { + $message .= '

' . esc_html__( 'We sent you a fresh verification code. Check your inbox.', 'robotstxt-2fa' ) . '

'; + } elseif ( 'failed' === $notice ) { + $message .= '

' . esc_html__( 'We could not send a new verification code. Please try again in a moment.', 'robotstxt-2fa' ) . '

'; + } + } elseif ( 'otp' === $method ) { + $message .= '

' . esc_html__( 'Open your authenticator app and enter the code to continue.', 'robotstxt-2fa' ) . '

'; + } elseif ( 'recovery' === $method ) { + $message .= '

' . esc_html__( 'Enter one of your unused recovery codes to continue.', 'robotstxt-2fa' ) . '

'; + } + + return $message; + } + + /** + * Output helper scripts used during the verification stage. + * + * @return void + */ + public function render_stage_scripts(): void { + if ( ! $this->is_verification_stage() ) { + return; + } + + $login = $this->get_requested_login(); + ?> + + is_verification_submission() ) { + return $user; + } + + unset( $password ); + + if ( ! isset( $_POST[ self::LOGIN_NONCE_FIELD ] ) || ! is_string( $_POST[ self::LOGIN_NONCE_FIELD ] ) ) { + return new \WP_Error( 'robotstxt_2fa_missing_nonce', __( 'The verification form is missing a security token. Please try again.', 'robotstxt-2fa' ) ); + } + + $nonce = sanitize_text_field( wp_unslash( $_POST[ self::LOGIN_NONCE_FIELD ] ) ); + + if ( ! wp_verify_nonce( $nonce, self::LOGIN_NONCE_ACTION ) ) { + return new \WP_Error( 'robotstxt_2fa_invalid_nonce', __( 'The verification request expired. Please sign in again to request a new code.', 'robotstxt-2fa' ) ); + } + + $login = $this->get_requested_login(); + + if ( '' === $login && '' !== $username ) { + $login = sanitize_user( $username, true ); + } + + if ( '' === $login ) { + return new \WP_Error( 'robotstxt_2fa_unknown_user', __( 'We could not determine which account you are trying to access.', 'robotstxt-2fa' ) ); + } + + $authenticated_user = get_user_by( 'login', $login ); + + if ( ! $authenticated_user instanceof \WP_User ) { + return new \WP_Error( 'robotstxt_2fa_unknown_user', __( 'We could not load the account requesting verification.', 'robotstxt-2fa' ) ); + } + + $stage_token = $this->get_requested_stage_token(); + + if ( '' === $stage_token || ! $this->validate_stage_token( $authenticated_user, $stage_token ) ) { + return new \WP_Error( 'robotstxt_2fa_invalid_stage', __( 'Your verification session expired. Please sign in again.', 'robotstxt-2fa' ) ); + } + + $method = $this->get_requested_method(); + $allowed_methods = $this->get_enabled_verification_methods( $authenticated_user ); + + if ( ! in_array( $method, $allowed_methods, true ) ) { + return new \WP_Error( 'robotstxt_2fa_method_unavailable', __( 'The selected verification method is not available right now.', 'robotstxt-2fa' ) ); + } + + $token = ''; + + if ( isset( $_POST['robotstxt_2fa_token'] ) && is_string( $_POST['robotstxt_2fa_token'] ) ) { + $token = sanitize_text_field( wp_unslash( $_POST['robotstxt_2fa_token'] ) ); + } + + if ( '' === $token ) { + return new \WP_Error( 'robotstxt_2fa_missing_code', __( 'Enter the verification code to continue.', 'robotstxt-2fa' ) ); + } + + $is_valid = false; + + switch ( $method ) { + case 'email': + $is_valid = $this->email_code_sender->verify_code( $authenticated_user, $token ); + + if ( $is_valid ) { + $this->user_settings_repository->delete_email_challenge( $authenticated_user->ID ); + } + break; + case 'recovery': + $is_valid = $this->recovery_codes->consume_code( $authenticated_user, $token ); + break; + case 'otp': + $is_valid = $this->otp_manager->verify_code( $authenticated_user, $token ); + break; + default: + return new \WP_Error( 'robotstxt_2fa_method_unavailable', __( 'The selected verification method is not available right now.', 'robotstxt-2fa' ) ); + } + + if ( ! $is_valid ) { + return new \WP_Error( 'robotstxt_2fa_invalid_code', __( 'The verification code is incorrect or has expired.', 'robotstxt-2fa' ) ); + } + + $this->user_settings_repository->record_last_verification( + $authenticated_user->ID, + $method, + $this->get_login_context_key(), + time() + ); + + return $authenticated_user; + } + + /** + * Enforce the verification step for eligible users. + * + * @param \WP_User|\WP_Error|null $user Previously authenticated user or error. + * @param string $username Submitted username. + * @param string $password Submitted password. + * + * @return \WP_User|\WP_Error|null + */ + public function enforce_verification_challenge( $user, string $username, string $password ) { + unset( $username, $password ); + + if ( $this->is_verification_stage() || $this->is_verification_submission() ) { + return $user; + } + + if ( ! $user instanceof \WP_User ) { + return $user; + } + + $method = $this->determine_required_verification_method( $user ); + + if ( '' === $method ) { + return $user; + } + + if ( 'email' === $method && ! $this->email_code_sender->send_code( $user ) ) { + return new \WP_Error( 'robotstxt_2fa_email_failed', __( 'We could not send a verification code. Please contact the site administrator.', 'robotstxt-2fa' ) ); + } + + $redirect_to = $this->get_requested_redirect(); + + $stage_token = wp_create_nonce( self::STAGE_TOKEN_ACTION . '|' . $user->ID ); + + $query_args = array( + self::QUERY_STAGE => self::STAGE_VERIFY, + self::QUERY_METHOD => $method, + self::QUERY_LOGIN => sanitize_user( $user->user_login, true ), + self::QUERY_STAGE_TOKEN => $stage_token, + ); + + $login_url = wp_login_url( $redirect_to ); + $login_url = add_query_arg( $query_args, $login_url ); + + wp_safe_redirect( $login_url ); + exit; + } + + /** + * Process additional verification stage actions triggered from the login screen. + * + * @return void + */ + public function maybe_process_stage_requests(): void { + if ( ! $this->is_verification_stage() ) { + return; + } + + $has_switch = ! empty( $_GET[ self::QUERY_SWITCH ] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Query flag only; nonce/stage-token verified inside process_method_switch(). + $has_resend = ! empty( $_GET[ self::QUERY_RESEND ] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Query flag only; stage-token verified before sending. + + if ( $has_switch ) { + $this->process_method_switch(); + + return; + } + + if ( ! $has_resend ) { + return; + } + + $method = $this->get_requested_method(); + + if ( 'email' !== $method ) { + return; + } + + $login = $this->get_requested_login(); + + if ( '' === $login ) { + return; + } + + $user = get_user_by( 'login', $login ); + + if ( ! $user instanceof \WP_User ) { + return; + } + + $stage_token = $this->get_requested_stage_token(); + + if ( '' === $stage_token || ! $this->validate_stage_token( $user, $stage_token ) ) { + return; + } + + $result = $this->email_code_sender->send_code( $user ); + + $notice_value = $result ? 'resent' : 'failed'; + + $redirect_url = remove_query_arg( + self::QUERY_RESEND, + $this->get_stage_url( + array( + self::QUERY_NOTICE => $notice_value, + ) + ) + ); + + wp_safe_redirect( $redirect_url ); + exit; + } + + /** + * Retrieve the verification method requested by the current stage. + * + * @return string + */ + private function get_requested_method(): string { + $method = ''; + + // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Stage helper; nonce verified in calling context. + if ( isset( $_REQUEST[ self::FIELD_METHOD ] ) && is_string( $_REQUEST[ self::FIELD_METHOD ] ) ) { + $method = sanitize_key( wp_unslash( $_REQUEST[ self::FIELD_METHOD ] ) ); + } + + if ( '' === $method && isset( $_REQUEST[ self::QUERY_METHOD ] ) && is_string( $_REQUEST[ self::QUERY_METHOD ] ) ) { + $method = sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_METHOD ] ) ); + } + // phpcs:enable WordPress.Security.NonceVerification.Recommended + + if ( '' === $method ) { + $method = 'email'; + } + + return $method; + } + + /** + * Determine the expected code length for a verification method. + * + * @param string $method Verification method identifier. + * + * @return int + */ + private function get_method_code_length( string $method ): int { + switch ( $method ) { + case 'otp': + return max( 1, (int) $this->otp_manager->get_code_length() ); + case 'recovery': + return max( 1, (int) $this->recovery_codes->get_code_length() ); + case 'email': + default: + return max( 1, (int) $this->email_code_sender->get_code_length() ); + } + } + + /** + * Retrieve the verification methods that are active for the provided user. + * + * When 2FA is enforced by role, only methods that are both required by the + * user's role(s) and actually set up on their profile are returned. If the + * user has not configured any of the required methods yet, all required + * methods that the system can deliver (e.g. email) are returned so the login + * can still be challenged. + * + * @param \WP_User $user User attempting to authenticate. + * @param array{enabled: bool, methods: array, frequency: string}|null $user_settings Optional preloaded settings. + * + * @return array + */ + private function get_enabled_verification_methods( \WP_User $user, ?array $user_settings = null ): array { + if ( null === $user_settings ) { + $user_settings = $this->user_settings_repository->get_user_settings( $user->ID ); + } + + $required_methods = $this->config->get_required_methods_for_user( $user ); + $is_forced = ! empty( $required_methods ); + $enabled = $is_forced ? true : $user_settings['enabled']; + + if ( ! $enabled ) { + return array(); + } + + // Normalize user's profile methods to login-stage slugs. + $profile_methods = array(); + + foreach ( $user_settings['methods'] as $method_key ) { + $slug = $this->normalize_method_slug( $method_key ); + + if ( '' !== $slug ) { + $profile_methods[] = $slug; + } + } + + $profile_methods = array_values( array_unique( $profile_methods ) ); + + // When forced, restrict to methods required by the user's roles. + if ( $is_forced ) { + $required_slugs = array(); + + foreach ( $required_methods as $method ) { + $slug = $this->normalize_method_slug( $method ); + + if ( '' !== $slug ) { + $required_slugs[] = $slug; + } + } + + $required_slugs = array_values( array_unique( $required_slugs ) ); + + // Prefer the intersection of profile-enabled and role-required methods. + $candidate_methods = array_values( array_intersect( $profile_methods, $required_slugs ) ); + + // Fall back to all role-required methods if none are set up yet. + if ( empty( $candidate_methods ) ) { + $candidate_methods = $required_slugs; + } + } else { + $candidate_methods = $profile_methods; + } + + // Filter to methods the system can actually deliver right now. + $available = array(); + + foreach ( $candidate_methods as $method ) { + if ( 'email' === $method ) { + if ( '' !== sanitize_email( $user->user_email ) ) { + $available[] = 'email'; + } + } elseif ( 'otp' === $method ) { + if ( '' !== $this->otp_manager->get_secret( $user->ID ) ) { + $available[] = 'otp'; + } + } elseif ( 'recovery' === $method ) { + if ( $this->recovery_codes->has_active_codes( $user->ID ) ) { + $available[] = 'recovery'; + } + } + } + + return $available; + } + + /** + * Decide which verification method should be enforced for the user. + * + * @param \WP_User $user User attempting to authenticate. + * + * @return string + */ + private function determine_required_verification_method( \WP_User $user ): string { + $user_settings = $this->user_settings_repository->get_user_settings( $user->ID ); + $methods = $this->get_enabled_verification_methods( $user, $user_settings ); + + if ( empty( $methods ) ) { + return ''; + } + + $frequency = $this->get_effective_frequency( $user, $user_settings ); + + if ( $this->has_recent_verification( $user, $methods, $frequency ) ) { + return ''; + } + + return $this->select_preferred_method( $methods ); + } + + /** + * Check whether any verification method was recently validated within the configured interval. + * + * @param \WP_User $user User attempting to authenticate. + * @param array $methods Active verification methods. + * @param string $frequency Selected frequency slug. + * + * @return bool + */ + private function has_recent_verification( \WP_User $user, array $methods, string $frequency ): bool { + if ( empty( $methods ) ) { + return false; + } + + if ( Frequency_Options::FREQUENCY_SESSION === $frequency ) { + return false; + } + + $interval_seconds = Frequency_Options::get_interval_seconds( $frequency ); + + if ( $interval_seconds <= 0 ) { + return false; + } + + $context_key = $this->get_login_context_key(); + + foreach ( $methods as $method ) { + $last_verified = $this->user_settings_repository->get_last_verification_timestamp( $user->ID, $method, $context_key ); + + if ( $last_verified > 0 && ( $last_verified + $interval_seconds ) > time() ) { + return true; + } + } + + return false; + } + + /** + * Determine which method should be requested when a challenge is required. + * + * @param array $methods Active verification methods. + * + * @return string + */ + private function select_preferred_method( array $methods ): string { + if ( empty( $methods ) ) { + return ''; + } + + // Prefer OTP (most secure), then email, then recovery codes (last resort). + foreach ( array( 'otp', 'email' ) as $method ) { + if ( in_array( $method, $methods, true ) ) { + return $method; + } + } + + // Use recovery only when it is the sole option. + if ( in_array( 'recovery', $methods, true ) ) { + return 'recovery'; + } + + return $methods[0]; + } + + /** + * Normalize stored method identifiers to the stage slugs used during verification. + * + * @param string $method Raw method identifier. + * + * @return string + */ + private function normalize_method_slug( string $method ): string { + $method = sanitize_key( $method ); + + if ( '' === $method ) { + return ''; + } + + if ( 'recovery_codes' === $method || 'recovery' === $method ) { + return 'recovery'; + } + + if ( in_array( $method, array( 'email', 'otp' ), true ) ) { + return $method; + } + + return ''; + } + + /** + * Build the list of alternate verification method links for the login stage. + * + * @param \WP_User $user User attempting to authenticate. + * @param string $current_method Active verification method slug. + * + * @return array> + */ + private function get_alternate_method_links( \WP_User $user, string $current_method ): array { + $available_methods = $this->get_enabled_verification_methods( $user ); + + $available_methods = array_values( + array_diff( $available_methods, array( $current_method ) ) + ); + + if ( empty( $available_methods ) ) { + return array(); + } + + $labels = array( + 'email' => __( 'Use an email code instead', 'robotstxt-2fa' ), + 'otp' => __( 'Use your authenticator app instead', 'robotstxt-2fa' ), + 'recovery' => __( 'Use a recovery code instead', 'robotstxt-2fa' ), + ); + + $links = array(); + + foreach ( $available_methods as $method ) { + if ( ! isset( $labels[ $method ] ) ) { + continue; + } + + $links[] = array( + 'url' => $this->get_stage_url( + array( + self::QUERY_METHOD => $method, + self::QUERY_NOTICE => null, + self::QUERY_RESEND => null, + self::QUERY_SWITCH => '1', + ) + ), + 'label' => $labels[ $method ], + ); + } + + return $links; + } + + + /** + * Determine whether the login request is currently displaying the verification stage. + * + * @return bool + */ + private function is_verification_stage(): bool { + // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Stage-detection only; nonce verified in calling context. + if ( isset( $_REQUEST[ self::FIELD_STAGE ] ) && is_string( $_REQUEST[ self::FIELD_STAGE ] ) ) { + $stage = sanitize_key( wp_unslash( $_REQUEST[ self::FIELD_STAGE ] ) ); + + if ( self::STAGE_VERIFY === $stage ) { + return true; + } + } + + if ( isset( $_REQUEST[ self::QUERY_STAGE ] ) && is_string( $_REQUEST[ self::QUERY_STAGE ] ) ) { + $stage = sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_STAGE ] ) ); + + if ( self::STAGE_VERIFY === $stage ) { + return true; + } + } + // phpcs:enable WordPress.Security.NonceVerification.Recommended + + return false; + } + + /** + * Check whether the login POST submission belongs to the verification stage. + * + * @return bool + */ + private function is_verification_submission(): bool { + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Stage flag only; nonce verified in maybe_complete_verification(). + if ( ! isset( $_POST[ self::FIELD_STAGE ] ) || ! is_string( $_POST[ self::FIELD_STAGE ] ) ) { + return false; + } + + $stage = sanitize_key( wp_unslash( $_POST[ self::FIELD_STAGE ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing + + return self::STAGE_VERIFY === $stage; + } + + /** + * Retrieve the login identifier carried across requests. + * + * @return string + */ + private function get_requested_login(): string { + $login = ''; + + // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Login identifier helper; nonce verified in calling context. + if ( isset( $_REQUEST[ self::FIELD_LOGIN ] ) && is_string( $_REQUEST[ self::FIELD_LOGIN ] ) ) { + $login = sanitize_user( wp_unslash( $_REQUEST[ self::FIELD_LOGIN ] ), true ); + } + + if ( '' === $login && isset( $_REQUEST[ self::QUERY_LOGIN ] ) && is_string( $_REQUEST[ self::QUERY_LOGIN ] ) ) { + $login = sanitize_user( wp_unslash( $_REQUEST[ self::QUERY_LOGIN ] ), true ); + } + // phpcs:enable WordPress.Security.NonceVerification.Recommended + + return $login; + } + + /** + * Retrieve the stage nonce carried in the current request. + * + * @return string + */ + private function get_requested_stage_token(): string { + $token = ''; + + // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Stage-token helper; token itself is the nonce verified in validate_stage_token(). + if ( isset( $_REQUEST[ self::FIELD_STAGE_TOKEN ] ) && is_string( $_REQUEST[ self::FIELD_STAGE_TOKEN ] ) ) { + $token = sanitize_text_field( wp_unslash( $_REQUEST[ self::FIELD_STAGE_TOKEN ] ) ); + } + + if ( '' === $token && isset( $_REQUEST[ self::QUERY_STAGE_TOKEN ] ) && is_string( $_REQUEST[ self::QUERY_STAGE_TOKEN ] ) ) { + $token = sanitize_text_field( wp_unslash( $_REQUEST[ self::QUERY_STAGE_TOKEN ] ) ); + } + // phpcs:enable WordPress.Security.NonceVerification.Recommended + + return $token; + } + + /** + * Retrieve the notice slug carried in the current request. + * + * @return string + */ + private function get_requested_notice(): string { + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Notice slug helper; display-only, not security-sensitive. + if ( ! isset( $_REQUEST[ self::QUERY_NOTICE ] ) || ! is_string( $_REQUEST[ self::QUERY_NOTICE ] ) ) { + return ''; + } + + return sanitize_key( wp_unslash( $_REQUEST[ self::QUERY_NOTICE ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended + } + + /** + * Validate whether the provided stage token is valid for the given user. + * + * @param \WP_User $user Authenticated user. + * @param string $stage_token Submitted stage token. + * + * @return bool + */ + private function validate_stage_token( \WP_User $user, string $stage_token ): bool { + return (bool) wp_verify_nonce( $stage_token, self::STAGE_TOKEN_ACTION . '|' . $user->ID ); + } + + /** + * Retrieve the sanitized redirect_to parameter from the current request. + * + * @return string + */ + private function get_requested_redirect(): string { + // phpcs:disable WordPress.Security.NonceVerification.Recommended -- redirect_to is a standard WP login parameter; value is passed through esc_url_raw. + if ( ! isset( $_REQUEST['redirect_to'] ) || ! is_string( $_REQUEST['redirect_to'] ) ) { + return ''; + } + + return esc_url_raw( wp_unslash( $_REQUEST['redirect_to'] ) ); + // phpcs:enable WordPress.Security.NonceVerification.Recommended + } + + /** + * Build a URL pointing to the active verification stage. + * + * @param array $extra_args Optional additional query parameters to merge. + * + * @return string + */ + private function get_stage_url( array $extra_args = array() ): string { + $redirect_to = $this->get_requested_redirect(); + $login_url = wp_login_url( $redirect_to ); + + $args = array( + self::QUERY_STAGE => self::STAGE_VERIFY, + self::QUERY_METHOD => $this->get_requested_method(), + ); + + $login = $this->get_requested_login(); + + if ( '' !== $login ) { + $args[ self::QUERY_LOGIN ] = $login; + } + + $stage_token = $this->get_requested_stage_token(); + + if ( '' !== $stage_token ) { + $args[ self::QUERY_STAGE_TOKEN ] = $stage_token; + } + + foreach ( $extra_args as $key => $value ) { + if ( null === $value || '' === $key ) { + $login_url = remove_query_arg( $key, $login_url ); + continue; + } + + $args[ $key ] = $value; + } + + $args = array_filter( + $args, + static function ( $value ) { + return '' !== $value; + } + ); + + return add_query_arg( $args, $login_url ); + } + + /** + * Determine the effective verification frequency for the current user. + * + * @param \WP_User $user Authenticated user object. + * @param array{enabled: bool, methods: array, frequency: string} $user_settings Stored per-user preferences. + * + * @return string + */ + private function get_effective_frequency( \WP_User $user, array $user_settings ): string { + unset( $user ); + + if ( $this->config->is_frequency_forced() ) { + return $this->config->get_frequency(); + } + + if ( '' !== $user_settings['frequency'] ) { + return Frequency_Options::sanitize( $user_settings['frequency'] ); + } + + return $this->config->get_frequency(); + } + + /** + * Build a hashed context key representing the current login environment. + * + * @return string + */ + private function get_login_context_key(): string { + $ip = ''; + + if ( isset( $_SERVER['REMOTE_ADDR'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below. + $raw_addr = is_string( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : ''; + $ip = sanitize_text_field( wp_unslash( $raw_addr ) ); + $ip = wp_privacy_anonymize_ip( $ip ); + } + + $user_agent = ''; + + if ( isset( $_SERVER['HTTP_USER_AGENT'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized below. + $raw_ua = is_string( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : ''; + $user_agent = sanitize_text_field( wp_unslash( $raw_ua ) ); + } + + $user_agent = strtolower( substr( $user_agent, 0, 255 ) ); + + if ( '' === $ip && '' === $user_agent ) { + return sha1( 'unknown' ); + } + + return sha1( $ip . '|' . $user_agent ); + } +} diff --git a/includes/user/class-otp-manager.php b/includes/user/class-otp-manager.php index c1b0dc1..be5873d 100644 --- a/includes/user/class-otp-manager.php +++ b/includes/user/class-otp-manager.php @@ -1,337 +1,348 @@ -get_secret( $user->ID ); - - if ( '' !== $secret ) { - return $secret; - } - - $secret = $this->generate_secret(); - - update_user_meta( $user->ID, self::META_KEY, $secret ); - - return $secret; - } - - /** - * Remove the stored OTP secret for a user. - * - * @param int $user_id User identifier. - * - * @return void - */ - public function delete_secret( int $user_id ): void { - delete_user_meta( $user_id, self::META_KEY ); - } - - /** - * Verify an OTP code against the stored secret. - * - * @param WP_User $user User attempting to authenticate. - * @param string $code Submitted verification code. - * - * @return bool - */ - public function verify_code( WP_User $user, string $code ): bool { - $secret = $this->get_secret( $user->ID ); - - if ( '' === $secret ) { - return false; - } - - $code = preg_replace( '/[^0-9]/', '', $code ); - - if ( null === $code || strlen( $code ) !== self::CODE_DIGITS ) { - return false; - } - - $binary_secret = $this->base32_decode( $secret ); - - if ( '' === $binary_secret ) { - return false; - } - - $current_step = (int) floor( time() / self::TIME_STEP ); - - for ( $offset = -1; $offset <= 1; $offset++ ) { - $otp = $this->generate_otp_for_counter( $binary_secret, $current_step + $offset ); - - if ( hash_equals( $otp, $code ) ) { - return true; - } - } - - return false; - } - - /** - * Retrieve the provisioning URI used by authenticator apps. - * - * @param WP_User $user User who owns the OTP secret. - * - * @return string - */ - public function get_provisioning_uri( WP_User $user ): string { - $secret = $this->get_secret( $user->ID ); - - if ( '' === $secret ) { - return ''; - } - - $site_name = wp_specialchars_decode( get_option( 'blogname', '' ), ENT_QUOTES ); - $site_name = '' !== $site_name ? $site_name : __( 'WordPress Site', 'robotstxt-2fa' ); - $label = '' !== $user->user_email ? $user->user_email : $user->user_login; - - $encoded_label = rawurlencode( sanitize_text_field( $label ) ); - $encoded_site = rawurlencode( $site_name ); - $encoded_secret = rawurlencode( $secret ); - $parameters = array( - 'issuer' => $encoded_site, - 'period' => (string) self::TIME_STEP, - ); - - $query = array(); - - foreach ( $parameters as $key => $value ) { - $query[] = rawurlencode( $key ) . '=' . $value; - } - - return sprintf( - 'otpauth://totp/%1$s:%2$s?secret=%3$s&%4$s', - $encoded_site, - $encoded_label, - $encoded_secret, - implode( '&', $query ) - ); - } - - /** - * Generate a QR code and return it as a data URI. - * - * @param WP_User $user User who owns the OTP secret. - * - * @return string Data URI containing an SVG image or an empty string when unavailable. - */ - public function get_qr_code_data_uri( WP_User $user ): string { - $uri = $this->get_provisioning_uri( $user ); - - if ( '' === $uri ) { - return ''; - } - - $svg = $this->render_qr_svg( $uri ); - - if ( '' === $svg ) { - return ''; - } - - /* - * Encode the SVG payload so it can be embedded safely as a data URI in the admin form. - */ - return 'data:image/svg+xml;base64,' . base64_encode( $svg ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- The QR SVG is encoded to embed it safely as a data URI. - } - - /** - * Generate a new secret encoded in Base32. - * - * @return string - */ - private function generate_secret(): string { - $bytes = random_bytes( self::SECRET_LENGTH ); - - return $this->base32_encode( $bytes ); - } - - /** - * Render a QR code in SVG format using an available library. - * - * @param string $data Data encoded inside the QR code. - * - * @return string SVG markup or empty string on failure. - */ - private function render_qr_svg( string $data ): string { - if ( ! class_exists( '\BaconQrCode\Writer' ) || ! class_exists( '\BaconQrCode\Renderer\ImageRenderer' ) ) { - return ''; - } - - try { - $renderer = new \BaconQrCode\Renderer\ImageRenderer( - new \BaconQrCode\Renderer\RendererStyle\RendererStyle( 256 ), - new \BaconQrCode\Renderer\Image\SvgImageBackEnd() - ); - $writer = new \BaconQrCode\Writer( $renderer ); - - return $writer->writeString( $data ); - } catch ( \Throwable $exception ) { - do_action( 'robotstxt_2fa_qr_generation_failed', $exception, $data ); - } - - return ''; - } - - /** - * Encode binary data using the Base32 alphabet. - * - * @param string $data Binary string to encode. - * - * @return string - */ - private function base32_encode( string $data ): string { - $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; - $bits = ''; - - for ( $i = 0, $length = strlen( $data ); $i < $length; $i++ ) { - $bits .= str_pad( decbin( ord( $data[ $i ] ) ), 8, '0', STR_PAD_LEFT ); - } - - $chunks = str_split( $bits, 5 ); - $encoded = ''; - - foreach ( $chunks as $chunk ) { - if ( strlen( $chunk ) < 5 ) { - $chunk = str_pad( $chunk, 5, '0', STR_PAD_RIGHT ); - } - - $encoded .= $alphabet[ bindec( $chunk ) ]; - } - - return $encoded; - } - - /** - * Decode a Base32-encoded string. - * - * @param string $encoded Encoded secret. - * - * @return string - */ - private function base32_decode( string $encoded ): string { - $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; - $encoded = strtoupper( $encoded ); - $encoded = preg_replace( '/[^A-Z2-7]/', '', $encoded ); - - if ( null === $encoded || '' === $encoded ) { - return ''; - } - - $bits = ''; - - for ( $i = 0, $length = strlen( $encoded ); $i < $length; $i++ ) { - $position = strpos( $alphabet, $encoded[ $i ] ); - - if ( false === $position ) { - return ''; - } - - $bits .= str_pad( decbin( $position ), 5, '0', STR_PAD_LEFT ); - } - - $binary = ''; - $chunks = str_split( $bits, 8 ); - - foreach ( $chunks as $chunk ) { - if ( strlen( $chunk ) < 8 ) { - continue; - } - - $binary .= chr( bindec( $chunk ) ); - } - - return $binary; - } - - /** - * Generate an OTP value for a specific counter. - * - * @param string $secret Binary secret key. - * @param int $counter Time-based counter value. - * - * @return string - */ - private function generate_otp_for_counter( string $secret, int $counter ): string { - $counter = max( 0, $counter ); - $binary_counter = pack( 'N*', 0 ) . pack( 'N*', $counter ); - $hash = hash_hmac( 'sha1', $binary_counter, $secret, true ); - $offset = ord( substr( $hash, -1 ) ) & 0x0F; - $segment = substr( $hash, $offset, 4 ); - $value = unpack( 'N', $segment )[1] & 0x7FFFFFFF; - $code = $value % ( 10 ** self::CODE_DIGITS ); - - return str_pad( (string) $code, self::CODE_DIGITS, '0', STR_PAD_LEFT ); - } -} +get_secret( $user->ID ); + + if ( '' !== $secret ) { + return $secret; + } + + $secret = $this->generate_secret(); + + update_user_meta( $user->ID, self::META_KEY, $secret ); + + return $secret; + } + + /** + * Remove the stored OTP secret for a user. + * + * @param int $user_id User identifier. + * + * @return void + */ + public function delete_secret( int $user_id ): void { + delete_user_meta( $user_id, self::META_KEY ); + } + + /** + * Verify an OTP code against the stored secret. + * + * @param WP_User $user User attempting to authenticate. + * @param string $code Submitted verification code. + * + * @return bool + */ + public function verify_code( WP_User $user, string $code ): bool { + $secret = $this->get_secret( $user->ID ); + + if ( '' === $secret ) { + return false; + } + + $code = preg_replace( '/[^0-9]/', '', $code ); + + if ( null === $code || strlen( $code ) !== self::CODE_DIGITS ) { + return false; + } + + $binary_secret = $this->base32_decode( $secret ); + + if ( '' === $binary_secret ) { + return false; + } + + $current_step = (int) floor( time() / self::TIME_STEP ); + + for ( $offset = -1; $offset <= 1; $offset++ ) { + $otp = $this->generate_otp_for_counter( $binary_secret, $current_step + $offset ); + + if ( hash_equals( $otp, $code ) ) { + return true; + } + } + + return false; + } + + /** + * Retrieve the provisioning URI used by authenticator apps. + * + * @param WP_User $user User who owns the OTP secret. + * + * @return string + */ + public function get_provisioning_uri( WP_User $user ): string { + $secret = $this->get_secret( $user->ID ); + + if ( '' === $secret ) { + return ''; + } + + $raw_blogname = get_option( 'blogname', '' ); + $site_name = wp_specialchars_decode( is_string( $raw_blogname ) ? $raw_blogname : '', ENT_QUOTES ); + $site_name = '' !== $site_name ? $site_name : __( 'WordPress Site', 'robotstxt-2fa' ); + $label = '' !== $user->user_email ? $user->user_email : $user->user_login; + + $encoded_label = rawurlencode( sanitize_text_field( $label ) ); + $encoded_site = rawurlencode( $site_name ); + $encoded_secret = rawurlencode( $secret ); + $parameters = array( + 'issuer' => $encoded_site, + 'period' => (string) self::TIME_STEP, + ); + + $query = array(); + + foreach ( $parameters as $key => $value ) { + $query[] = rawurlencode( $key ) . '=' . $value; + } + + return sprintf( + 'otpauth://totp/%1$s:%2$s?secret=%3$s&%4$s', + $encoded_site, + $encoded_label, + $encoded_secret, + implode( '&', $query ) + ); + } + + /** + * Generate a QR code and return it as a data URI. + * + * @param WP_User $user User who owns the OTP secret. + * + * @return string Data URI containing an SVG image or an empty string when unavailable. + */ + public function get_qr_code_data_uri( WP_User $user ): string { + $uri = $this->get_provisioning_uri( $user ); + + if ( '' === $uri ) { + return ''; + } + + $svg = $this->render_qr_svg( $uri ); + + if ( '' === $svg ) { + return ''; + } + + /* + * Encode the SVG payload so it can be embedded safely as a data URI in the admin form. + */ + return 'data:image/svg+xml;base64,' . base64_encode( $svg ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- The QR SVG is encoded to embed it safely as a data URI. + } + + /** + * Generate a new secret encoded in Base32. + * + * @return string + */ + private function generate_secret(): string { + $bytes = random_bytes( self::SECRET_LENGTH ); + + return $this->base32_encode( $bytes ); + } + + /** + * Render a QR code in SVG format using an available library. + * + * @param string $data Data encoded inside the QR code. + * + * @return string SVG markup or empty string on failure. + */ + private function render_qr_svg( string $data ): string { + if ( ! class_exists( '\BaconQrCode\Writer' ) || ! class_exists( '\BaconQrCode\Renderer\ImageRenderer' ) ) { + return ''; + } + + try { + $renderer = new \BaconQrCode\Renderer\ImageRenderer( + new \BaconQrCode\Renderer\RendererStyle\RendererStyle( 256 ), + new \BaconQrCode\Renderer\Image\SvgImageBackEnd() + ); + $writer = new \BaconQrCode\Writer( $renderer ); + + return $writer->writeString( $data ); + } catch ( \Throwable $exception ) { + /** + * Fires when QR code SVG generation fails. + * + * @since 0.2.0 + * + * @param \Throwable $exception The caught exception. + * @param string $data The provisioning URI that failed to render. + */ + do_action( 'robotstxt_2fa_qr_generation_failed', $exception, $data ); + } + + return ''; + } + + /** + * Encode binary data using the Base32 alphabet. + * + * @param string $data Binary string to encode. + * + * @return string + */ + private function base32_encode( string $data ): string { + $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; + $bits = ''; + + for ( $i = 0, $length = strlen( $data ); $i < $length; $i++ ) { + $bits .= str_pad( decbin( ord( $data[ $i ] ) ), 8, '0', STR_PAD_LEFT ); + } + + $chunks = str_split( $bits, 5 ); + $encoded = ''; + + foreach ( $chunks as $chunk ) { + if ( strlen( $chunk ) < 5 ) { + $chunk = str_pad( $chunk, 5, '0', STR_PAD_RIGHT ); + } + + $encoded .= $alphabet[ (int) bindec( $chunk ) ]; + } + + return $encoded; + } + + /** + * Decode a Base32-encoded string. + * + * @param string $encoded Encoded secret. + * + * @return string + */ + private function base32_decode( string $encoded ): string { + $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; + $encoded = strtoupper( $encoded ); + $encoded = preg_replace( '/[^A-Z2-7]/', '', $encoded ); + + if ( null === $encoded || '' === $encoded ) { + return ''; + } + + $bits = ''; + + for ( $i = 0, $length = strlen( $encoded ); $i < $length; $i++ ) { + $position = strpos( $alphabet, $encoded[ $i ] ); + + if ( false === $position ) { + return ''; + } + + $bits .= str_pad( decbin( $position ), 5, '0', STR_PAD_LEFT ); + } + + $binary = ''; + $chunks = str_split( $bits, 8 ); + + foreach ( $chunks as $chunk ) { + if ( strlen( $chunk ) < 8 ) { + continue; + } + + $binary .= chr( (int) bindec( $chunk ) & 0xFF ); + } + + return $binary; + } + + /** + * Generate an OTP value for a specific counter. + * + * @param string $secret Binary secret key. + * @param int $counter Time-based counter value. + * + * @return string + */ + private function generate_otp_for_counter( string $secret, int $counter ): string { + $counter = max( 0, $counter ); + $binary_counter = pack( 'N*', 0 ) . pack( 'N*', $counter ); + $hash = hash_hmac( 'sha1', $binary_counter, $secret, true ); + $offset = ord( substr( $hash, -1 ) ) & 0x0F; + $segment = substr( $hash, $offset, 4 ); + $unpacked = unpack( 'N', $segment ); + $raw_value = is_array( $unpacked ) && isset( $unpacked[1] ) && is_int( $unpacked[1] ) ? $unpacked[1] : 0; + $value = $raw_value & 0x7FFFFFFF; + $code = $value % ( 10 ** self::CODE_DIGITS ); + + return str_pad( (string) $code, self::CODE_DIGITS, '0', STR_PAD_LEFT ); + } +} diff --git a/includes/user/class-profile-settings.php b/includes/user/class-profile-settings.php index 128a104..d91ad0b 100644 --- a/includes/user/class-profile-settings.php +++ b/includes/user/class-profile-settings.php @@ -1,1119 +1,1167 @@ -user_settings_repository = new User_Settings_Repository(); - $this->config = new Two_Factor_Config(); - $this->otp_manager = new OTP_Manager(); - $this->recovery_codes = new Recovery_Codes(); - } - - /** - * Register hooks for profile integration. - * - * @return void - */ - public function register_hooks(): void { - add_action( 'show_user_profile', array( $this, 'render_profile_section' ) ); - add_action( 'edit_user_profile', array( $this, 'render_profile_section' ) ); - add_action( 'personal_options_update', array( $this, 'save_profile_settings' ) ); - add_action( 'edit_user_profile_update', array( $this, 'save_profile_settings' ) ); - add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); - add_filter( 'wp_redirect', array( $this, 'maybe_append_section_anchor' ), 10, 2 ); - } - - - /** - * Enqueue JavaScript required by the recovery code workflow on profile screens. - * - * @param string $hook Current admin page hook name. - * - * @return void - */ - public function enqueue_assets( string $hook ): void { - if ( ! in_array( $hook, array( 'profile.php', 'user-edit.php' ), true ) ) { - return; - } - - wp_enqueue_style( - 'robotstxt-2fa-profile', - ROBOTSTXT_2FA_URL . 'assets/css/profile.css', - array(), - ROBOTSTXT_2FA_VERSION - ); - - wp_enqueue_script( - 'robotstxt-2fa-recovery', - ROBOTSTXT_2FA_URL . 'assets/js/recovery-codes.js', - array(), - ROBOTSTXT_2FA_VERSION, - true - ); - - wp_localize_script( - 'robotstxt-2fa-recovery', - 'robotstxt2FARecovery', - array( - 'strings' => array( - 'copyConfirm' => __( 'The recovery codes have been copied to your clipboard.', 'robotstxt-2fa' ), - 'copyFallback' => __( 'Copying failed. Please copy the codes manually.', 'robotstxt-2fa' ), - ), - ) - ); - } - - - /** - * Render profile settings UI. - * - * @param \WP_User $user User object currently being edited. - * - * @return void - */ - public function render_profile_section( \WP_User $user ): void { - if ( ! current_user_can( 'edit_user', $user->ID ) ) { - return; - } - - $user_settings = $this->user_settings_repository->get_user_settings( $user->ID ); - $is_forced = $this->config->is_two_factor_forced_for_user( $user ); - $is_enabled = $is_forced ? true : (bool) $user_settings['enabled']; - $enabled_methods = $is_enabled ? $user_settings['methods'] : array(); - $available_methods = $this->get_available_methods( $user ); - $frequency = $this->resolve_selected_frequency( $user_settings ); - $frequency_forced = $this->config->is_frequency_forced(); - $frequency_options = Frequency_Options::get_options(); - - $enabled_methods = array_values( - array_unique( - array_filter( $enabled_methods ) - ) - ); - - $email_enabled = in_array( 'email', $enabled_methods, true ); - $otp_enabled = in_array( 'otp', $enabled_methods, true ); - $recovery_enabled = in_array( 'recovery_codes', $enabled_methods, true ); - - $date_format = (string) get_option( 'date_format' ); - $time_format = (string) get_option( 'time_format' ); - $datetime_format = trim( $date_format . ' ' . $time_format ); - - if ( '' === $datetime_format ) { - $datetime_format = 'c'; - } - - $unused_count = $this->recovery_codes->count_unused_codes( $user->ID ); - $recovery_code_length = $this->recovery_codes->get_code_length(); - $recovery_total = $this->recovery_codes->get_codes_per_batch(); - $last_generated = $this->recovery_codes->get_last_generated_timestamp( $user->ID ); - $preview = $this->get_recovery_preview( $user->ID ); - $preview_codes = isset( $preview['codes'] ) && is_array( $preview['codes'] ) ? $preview['codes'] : array(); - $preview_generated = isset( $preview['generated_at'] ) ? (int) $preview['generated_at'] : 0; - - if ( $preview_generated > 0 ) { - $last_generated = $preview_generated; - } - - if ( $recovery_enabled && $unused_count <= 0 ) { - $this->reset_recovery_codes_after_exhaustion( $user, $user_settings, $is_forced ); - - $user_settings = $this->user_settings_repository->get_user_settings( $user->ID ); - $is_enabled = $is_forced ? true : (bool) $user_settings['enabled']; - $enabled_methods = $is_enabled ? $user_settings['methods'] : array(); - $enabled_methods = array_values( - array_unique( - array_filter( $enabled_methods ) - ) - ); - - $email_enabled = in_array( 'email', $enabled_methods, true ); - $otp_enabled = in_array( 'otp', $enabled_methods, true ); - $recovery_enabled = in_array( 'recovery_codes', $enabled_methods, true ); - - $unused_count = $this->recovery_codes->count_unused_codes( $user->ID ); - $preview = $this->get_recovery_preview( $user->ID ); - $preview_codes = isset( $preview['codes'] ) && is_array( $preview['codes'] ) ? $preview['codes'] : array(); - $preview_generated = isset( $preview['generated_at'] ) ? (int) $preview['generated_at'] : 0; - - if ( $preview_generated > 0 ) { - $last_generated = $preview_generated; - } else { - $last_generated = $this->recovery_codes->get_last_generated_timestamp( $user->ID ); - } - } - - if ( ! $recovery_enabled && empty( $preview_codes ) ) { - $preview = $this->prepare_recovery_preview( $user ); - $preview_codes = isset( $preview['codes'] ) && is_array( $preview['codes'] ) ? $preview['codes'] : array(); - $preview_generated = isset( $preview['generated_at'] ) ? (int) $preview['generated_at'] : 0; - - if ( $preview_generated > 0 ) { - $last_generated = $preview_generated; - } - } - - if ( $unused_count < count( $preview_codes ) ) { - $unused_count = count( $preview_codes ); - } - - $last_generated_formatted = $last_generated > 0 ? wp_date( $datetime_format, $last_generated ) : ''; - $has_preview = ! empty( $preview_codes ); - - $otp_secret = $otp_enabled ? $this->otp_manager->get_secret( $user->ID ) : $this->otp_manager->ensure_secret( $user ); - $otp_secret_chunks = '' !== $otp_secret ? trim( chunk_split( $otp_secret, 4, ' ' ) ) : ''; - $otp_qr_data_uri = $otp_enabled ? '' : $this->otp_manager->get_qr_code_data_uri( $user ); - $otp_digits = $this->otp_manager->get_code_length(); - - $email_destination = $this->get_email_destination_label( $user ); - $email_label = isset( $available_methods['email']['label'] ) ? (string) $available_methods['email']['label'] : __( 'Email code', 'robotstxt-2fa' ); - - if ( '' !== $email_destination ) { - $email_label = sprintf( - /* translators: 1: verification method label, 2: email address. */ - __( '%1$s (%2$s)', 'robotstxt-2fa' ), - $email_label, - $email_destination - ); - } - ?> -

- - - - - - - - - - - - - - - - - - - */ - private function prepare_recovery_preview( \WP_User $user ): array { - try { - $result = $this->recovery_codes->regenerate_codes_for_user( $user ); - } catch ( \Throwable $exception ) { - do_action( 'robotstxt_2fa_recovery_generation_failed', $exception ); - return $this->get_recovery_preview( $user->ID ); - } - - if ( empty( $result['codes'] ) ) { - return $this->get_recovery_preview( $user->ID ); - } - - $this->remember_recovery_preview( $user->ID, $result['codes'], (int) $result['generated_at'] ); - $this->focus_section = true; - - add_settings_error( - 'robotstxt-2fa', - 'robotstxt-2fa-recovery-prepared', - __( 'New recovery codes are ready below. Copy them and confirm you saved them by entering one code.', 'robotstxt-2fa' ), - 'updated' - ); - - return $this->get_recovery_preview( $user->ID ); - } - - /** - * Reset recovery codes and user settings when all codes were consumed. - * - * @param \WP_User $user User being edited. - * @param array $user_settings Stored user settings prior to the reset. - * @param bool $is_forced Whether two-factor authentication is enforced for the user. - * - * @return void - */ - private function reset_recovery_codes_after_exhaustion( \WP_User $user, array $user_settings, bool $is_forced ): void { - $current_methods = isset( $user_settings['methods'] ) && is_array( $user_settings['methods'] ) ? $user_settings['methods'] : array(); - $remaining_methods = array_values( array_diff( $current_methods, array( 'recovery_codes' ) ) ); - $enabled_flag = $is_forced ? true : ( ! empty( $remaining_methods ) && ! empty( $user_settings['enabled'] ) ); - $frequency_value = $this->resolve_selected_frequency( $user_settings ); - - $this->user_settings_repository->save_user_settings( - $user->ID, - array( - 'enabled' => $enabled_flag, - 'methods' => $remaining_methods, - 'frequency' => $frequency_value, - ) - ); - - try { - $result = $this->recovery_codes->regenerate_codes_for_user( $user ); - } catch ( \Throwable $exception ) { - do_action( 'robotstxt_2fa_recovery_generation_failed', $exception ); - add_settings_error( - 'robotstxt-2fa', - 'robotstxt-2fa-recovery-exhausted-error', - __( 'All recovery codes were used. Generating a new batch failed. Please try again.', 'robotstxt-2fa' ), - 'error' - ); - return; - } - - if ( ! empty( $result['codes'] ) ) { - $this->remember_recovery_preview( $user->ID, $result['codes'], (int) $result['generated_at'] ); - } - - $this->focus_section = true; - - add_settings_error( - 'robotstxt-2fa', - 'robotstxt-2fa-recovery-exhausted', - __( 'All recovery codes were used. We prepared a new batch that must be confirmed below.', 'robotstxt-2fa' ), - 'updated' - ); - } - - - - - /** - * Save profile settings upon submission. - * - * @param int $user_id User identifier. - * - * @return void - */ - public function save_profile_settings( int $user_id ): void { - if ( ! current_user_can( 'edit_user', $user_id ) ) { - return; - } - - if ( ! isset( $_POST[ self::NONCE_FIELD ] ) ) { - return; - } - - $nonce = sanitize_text_field( wp_unslash( $_POST[ self::NONCE_FIELD ] ) ); - - if ( ! wp_verify_nonce( $nonce, self::NONCE_ACTION ) ) { - return; - } - - $user = get_user_by( 'ID', $user_id ); - - if ( ! $user instanceof \WP_User ) { - return; - } - - $submitted_settings = array(); - - $raw_settings = filter_input( INPUT_POST, 'robotstxt_2fa_settings', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY ); - - if ( is_array( $raw_settings ) ) { - $submitted_settings = map_deep( wp_unslash( $raw_settings ), 'sanitize_text_field' ); - } - - $requested_methods = array(); - - if ( isset( $submitted_settings['methods'] ) && is_array( $submitted_settings['methods'] ) ) { - foreach ( $submitted_settings['methods'] as $method_key ) { - $method_key = sanitize_key( $method_key ); - - if ( '' !== $method_key ) { - $requested_methods[] = $method_key; - } - } - } - - $requested_methods = array_values( array_unique( $requested_methods ) ); - - $enabled = ! empty( $submitted_settings['enabled'] ); - $is_forced = $this->config->is_two_factor_forced_for_user( $user ); - - if ( $is_forced ) { - $enabled = true; - } - - $user_settings = $this->user_settings_repository->get_user_settings( $user_id ); - $previous_methods = isset( $user_settings['methods'] ) && is_array( $user_settings['methods'] ) ? $user_settings['methods'] : array(); - - $otp_was_enabled = in_array( 'otp', $previous_methods, true ); - $recovery_was_enabled = in_array( 'recovery_codes', $previous_methods, true ); - - $otp_regenerate_requested = isset( $_POST[ self::OTP_REGENERATE_FIELD ] ); - - if ( $otp_regenerate_requested ) { - $this->focus_section = true; - } - - $otp_code = ''; - - if ( isset( $_POST[ self::OTP_CODE_FIELD ] ) ) { - $otp_code = sanitize_text_field( wp_unslash( $_POST[ self::OTP_CODE_FIELD ] ) ); - } - - $recovery_code_input = ''; - - if ( isset( $_POST[ self::RECOVERY_CONFIRM_FIELD ] ) ) { - $recovery_code_input = sanitize_text_field( wp_unslash( $_POST[ self::RECOVERY_CONFIRM_FIELD ] ) ); - } - - $available_methods = $this->get_available_methods( $user ); - $available_keys = array_keys( $available_methods ); - $selected_methods = array(); - - if ( $enabled && in_array( 'email', $requested_methods, true ) && in_array( 'email', $available_keys, true ) ) { - $selected_methods[] = 'email'; - } - - $otp_requested = in_array( 'otp', $requested_methods, true ); - $otp_should_remain_enabled = false; - - if ( $otp_regenerate_requested ) { - $this->otp_manager->delete_secret( $user_id ); - $this->otp_manager->ensure_secret( $user ); - $otp_was_enabled = false; - $otp_requested = true; - add_settings_error( - 'robotstxt-2fa', - 'robotstxt-2fa-otp-reset', - __( 'A new authenticator secret is ready. Scan the QR code and confirm it with a fresh code to finish reconnecting.', 'robotstxt-2fa' ), - 'updated' - ); - } - - if ( $otp_was_enabled ) { - if ( $otp_requested && ! $otp_regenerate_requested ) { - $otp_should_remain_enabled = true; - } else { - $this->otp_manager->delete_secret( $user_id ); - $this->otp_manager->ensure_secret( $user ); - $this->focus_section = true; - add_settings_error( - 'robotstxt-2fa', - 'robotstxt-2fa-otp-disabled', - __( 'Authenticator app disabled. A new QR code is ready below if you want to reconnect it.', 'robotstxt-2fa' ), - 'updated' - ); - } - } else { - $this->otp_manager->ensure_secret( $user ); - - if ( $otp_requested ) { - if ( '' === $otp_code ) { - $this->focus_section = true; - add_settings_error( - 'robotstxt-2fa', - 'robotstxt-2fa-otp-missing', - __( 'Enter the six-digit code currently shown in your authenticator app to activate this method.', 'robotstxt-2fa' ), - 'error' - ); - } elseif ( $this->otp_manager->verify_code( $user, $otp_code ) ) { - $selected_methods[] = 'otp'; - $this->focus_section = true; - add_settings_error( - 'robotstxt-2fa', - 'robotstxt-2fa-otp-enabled', - __( 'Authenticator app enabled successfully.', 'robotstxt-2fa' ), - 'updated' - ); - } else { - $this->focus_section = true; - add_settings_error( - 'robotstxt-2fa', - 'robotstxt-2fa-otp-invalid', - __( 'The provided authenticator code is invalid or expired. Try again with a fresh code.', 'robotstxt-2fa' ), - 'error' - ); - } - } - } - - if ( $otp_should_remain_enabled ) { - $selected_methods[] = 'otp'; - } - - $recovery_requested = in_array( 'recovery_codes', $requested_methods, true ); - $recovery_confirmation_success = false; - - if ( '' !== $recovery_code_input ) { - $this->focus_section = true; - - if ( $this->acknowledge_recovery_preview( $user_id, $recovery_code_input ) ) { - $recovery_confirmation_success = true; - add_settings_error( - 'robotstxt-2fa', - 'robotstxt-2fa-recovery-confirmed', - __( 'Recovery codes confirmed. Keep them in a secure location.', 'robotstxt-2fa' ), - 'updated' - ); - } else { - add_settings_error( - 'robotstxt-2fa', - 'robotstxt-2fa-recovery-confirm-failed', - __( 'We could not verify that code. Enter one of the freshly generated recovery codes to confirm.', 'robotstxt-2fa' ), - 'error' - ); - } - } - - if ( $recovery_was_enabled ) { - if ( $recovery_requested ) { - if ( $this->recovery_codes->count_unused_codes( $user_id ) > 0 ) { - $selected_methods[] = 'recovery_codes'; - } else { - $this->reset_recovery_codes_after_exhaustion( $user, $user_settings, $is_forced ); - } - } else { - $this->prepare_recovery_preview( $user ); - $this->focus_section = true; - add_settings_error( - 'robotstxt-2fa', - 'robotstxt-2fa-recovery-disabled', - __( 'Recovery codes disabled. A fresh list is available below.', 'robotstxt-2fa' ), - 'updated' - ); - } - } elseif ( $recovery_confirmation_success ) { - $selected_methods[] = 'recovery_codes'; - } elseif ( $recovery_requested ) { - $this->focus_section = true; - add_settings_error( - 'robotstxt-2fa', - 'robotstxt-2fa-recovery-missing-confirmation', - __( 'Enter one of the displayed recovery codes to activate this method.', 'robotstxt-2fa' ), - 'error' - ); - } - - $selected_methods = array_values( array_unique( $selected_methods ) ); - - if ( ! $is_forced && empty( $selected_methods ) ) { - $enabled = false; - } - - $frequency = Frequency_Options::FREQUENCY_SESSION; - - if ( isset( $submitted_settings['frequency'] ) ) { - $frequency = Frequency_Options::sanitize( (string) $submitted_settings['frequency'] ); - } - - if ( $this->config->is_frequency_forced() ) { - $frequency = $this->config->get_frequency(); - } elseif ( '' === $frequency ) { - $frequency = $this->config->get_frequency(); - } - - $this->user_settings_repository->save_user_settings( - $user_id, - array( - 'enabled' => $enabled, - 'methods' => $selected_methods, - 'frequency' => $frequency, - ) - ); - - if ( ! $enabled ) { - $this->user_settings_repository->delete_email_challenge( $user_id ); - } - } - - - - /** - * Append the 2FA section anchor to redirects when requested. - * - * @param string $location Redirect destination. - * @param int $status HTTP status code. - * - * @return string - */ - public function maybe_append_section_anchor( string $location, int $status ): string { - unset( $status ); - - if ( ! $this->focus_section ) { - return $location; - } - - $this->focus_section = false; - - if ( '' === $location ) { - return $location; - } - - $fragment = '#' . self::SECTION_ANCHOR; - $hash_position = strpos( $location, '#' ); - - if ( false !== $hash_position ) { - $location = substr( $location, 0, $hash_position ); - } - - return $location . $fragment; - } - - - /** - * Persist the generated recovery codes temporarily so they can be displayed once. - * - * @param int $user_id User identifier. - * @param array $codes Plain-text recovery codes. - * @param int $generated_at Generation timestamp. - * - * @return void - */ - private function remember_recovery_preview( int $user_id, array $codes, int $generated_at ): void { - $key = $this->get_recovery_preview_transient_key( $user_id ); - $generated_at = max( 0, $generated_at ); - $values = $this->normalize_preview_codes( $codes ); - - if ( empty( $values ) ) { - delete_transient( $key ); - return; - } - - delete_transient( $key ); - - set_transient( - $key, - array( - 'codes' => $values, - 'generated_at' => $generated_at, - ), - self::PREVIEW_TTL - ); - } - - /** - * Retrieve recovery codes stored for one-time display after generation. - * - * @param int $user_id User identifier. - * - * @return array - */ - private function get_recovery_preview( int $user_id ): array { - $key = $this->get_recovery_preview_transient_key( $user_id ); - $preview = get_transient( $key ); - - if ( false === $preview || ! is_array( $preview ) ) { - return array( - 'codes' => array(), - 'generated_at' => 0, - ); - } - - $codes = isset( $preview['codes'] ) && is_array( $preview['codes'] ) ? $this->normalize_preview_codes( $preview['codes'] ) : array(); - $generated_at = isset( $preview['generated_at'] ) ? (int) $preview['generated_at'] : 0; - - return array( - 'codes' => $codes, - 'generated_at' => $generated_at, - ); - } - - /** - * Build the transient key used to store one-time recovery code previews. - * - * @param int $user_id User identifier. - * - * @return string - */ - private function get_recovery_preview_transient_key( int $user_id ): string { - $session_token = wp_get_session_token(); - - if ( '' === $session_token ) { - $session_token = (string) get_current_user_id(); - } - - return 'robotstxt_2fa_preview_' . md5( $user_id . '|' . $session_token ); - } - - /** - * Clear the stored recovery preview for the current session. - * - * @param int $user_id User identifier. - * - * @return void - */ - private function clear_recovery_preview( int $user_id ): void { - $key = $this->get_recovery_preview_transient_key( $user_id ); - delete_transient( $key ); - } - - /** - * Confirm that the generated recovery codes were stored safely. - * - * @param int $user_id User identifier. - * @param string $code Code provided by the user. - * - * @return bool - */ - private function acknowledge_recovery_preview( int $user_id, string $code ): bool { - $preview = $this->get_recovery_preview( $user_id ); - - if ( empty( $preview['codes'] ) ) { - return false; - } - - $normalized = preg_replace( '/[^0-9]/', '', $code ); - - if ( null === $normalized ) { - return false; - } - - $normalized = substr( $normalized, 0, $this->recovery_codes->get_code_length() ); - - if ( '' === $normalized ) { - return false; - } - - if ( ! in_array( $normalized, $preview['codes'], true ) ) { - return false; - } - - $user = get_user_by( 'ID', $user_id ); - - if ( ! $user instanceof \WP_User ) { - return false; - } - - if ( ! $this->recovery_codes->verify_code_without_consuming( $user, $normalized ) ) { - return false; - } - - $this->clear_recovery_preview( $user_id ); - - return true; - } - - - - /** - * Sanitize a list of preview codes to a normalized numeric format. - * - * @param array $codes Codes to normalize. - * - * @return array - */ - private function normalize_preview_codes( array $codes ): array { - $normalized = array(); - $length = $this->recovery_codes->get_code_length(); - - foreach ( $codes as $code ) { - $digits = preg_replace( '/[^0-9]/', '', (string) $code ); - - if ( null === $digits ) { - continue; - } - - $digits = substr( $digits, 0, $length ); - - if ( strlen( $digits ) !== $length ) { - continue; - } - - $normalized[] = $digits; - } - - return array_values( array_unique( $normalized ) ); - } - - - - /** - * Retrieve the formatted email destination used in the methods list. - * - * @param \WP_User $user User being edited. - * - * @return string - */ - private function get_email_destination_label( \WP_User $user ): string { - $email = sanitize_email( $user->user_email ); - - if ( '' !== $email ) { - return $email; - } - - return __( 'no email address available', 'robotstxt-2fa' ); - } - - /** - * Retrieve the available 2FA methods shown in the UI. - * - * @param \WP_User $user User being edited. - * - * @return array> - */ - private function get_available_methods( \WP_User $user ): array { - $email_address = sanitize_email( $user->user_email ); - $email_description = __( 'Receive a verification code in your inbox every time you sign in.', 'robotstxt-2fa' ); - - if ( '' === $email_address ) { - $email_description = __( 'Add a valid email address to your profile to receive verification codes.', 'robotstxt-2fa' ); - } - - return array( - 'email' => array( - 'label' => __( 'Email code', 'robotstxt-2fa' ), - 'description' => $email_description, - ), - 'otp' => array( - 'label' => __( 'Authenticator app (OTP)', 'robotstxt-2fa' ), - 'description' => __( 'Use an app like Google Authenticator or 1Password to generate time-based codes.', 'robotstxt-2fa' ), - ), - 'recovery_codes' => array( - 'label' => __( 'Recovery codes', 'robotstxt-2fa' ), - 'description' => __( 'Keep printable backup codes in a safe place for emergencies.', 'robotstxt-2fa' ), - ), - ); - } - - /** - * Resolve the default method key to use when no method was selected. - * - * @param array> $available_methods Available method definitions. - * - * @return string - */ - private function get_default_method_key( array $available_methods ): string { - $configured_method = $this->config->get_default_method(); - - if ( isset( $available_methods[ $configured_method ] ) ) { - return $configured_method; - } - - if ( isset( $available_methods['email'] ) ) { - return 'email'; - } - - $available_keys = array_keys( $available_methods ); - - if ( ! empty( $available_keys ) ) { - return (string) $available_keys[0]; - } - - return 'email'; - } - - /** - * Resolve the frequency value shown and stored for the user. - * - * @param array $user_settings Stored user settings. - * - * @return string - */ - private function resolve_selected_frequency( array $user_settings ): string { - $global_frequency = $this->config->get_frequency(); - - if ( $this->config->is_frequency_forced() ) { - return $global_frequency; - } - - if ( ! empty( $user_settings['frequency'] ) ) { - return Frequency_Options::sanitize( (string) $user_settings['frequency'] ); - } - - return $global_frequency; - } -} +user_settings_repository = new User_Settings_Repository(); + $this->config = new Two_Factor_Config(); + $this->otp_manager = new OTP_Manager(); + $this->recovery_codes = new Recovery_Codes(); + } + + /** + * Register hooks for profile integration. + * + * @return void + */ + public function register_hooks(): void { + add_action( 'show_user_profile', array( $this, 'render_profile_section' ) ); + add_action( 'edit_user_profile', array( $this, 'render_profile_section' ) ); + add_action( 'personal_options_update', array( $this, 'save_profile_settings' ) ); + add_action( 'edit_user_profile_update', array( $this, 'save_profile_settings' ) ); + add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) ); + add_filter( 'wp_redirect', array( $this, 'maybe_append_section_anchor' ), 10, 2 ); + } + + + /** + * Enqueue JavaScript required by the recovery code workflow on profile screens. + * + * @param string $hook Current admin page hook name. + * + * @return void + */ + public function enqueue_assets( string $hook ): void { + if ( ! in_array( $hook, array( 'profile.php', 'user-edit.php' ), true ) ) { + return; + } + + wp_enqueue_style( + 'robotstxt-2fa-profile', + ROBOTSTXT_2FA_URL . 'assets/css/profile.css', + array(), + ROBOTSTXT_2FA_VERSION + ); + + wp_enqueue_script( + 'robotstxt-2fa-recovery', + ROBOTSTXT_2FA_URL . 'assets/js/recovery-codes.js', + array(), + ROBOTSTXT_2FA_VERSION, + true + ); + + wp_localize_script( + 'robotstxt-2fa-recovery', + 'robotstxt2FARecovery', + array( + 'strings' => array( + 'copyConfirm' => __( 'The recovery codes have been copied to your clipboard.', 'robotstxt-2fa' ), + 'copyFallback' => __( 'Copying failed. Please copy the codes manually.', 'robotstxt-2fa' ), + ), + ) + ); + } + + + /** + * Render profile settings UI. + * + * @param \WP_User $user User object currently being edited. + * + * @return void + */ + public function render_profile_section( \WP_User $user ): void { + if ( ! current_user_can( 'edit_user', $user->ID ) ) { + return; + } + + $user_settings = $this->user_settings_repository->get_user_settings( $user->ID ); + $is_forced = $this->config->is_two_factor_forced_for_user( $user ); + $required_methods = $this->config->get_required_methods_for_user( $user ); + $is_enabled = $is_forced ? true : (bool) $user_settings['enabled']; + $enabled_methods = $is_enabled ? $user_settings['methods'] : array(); + $available_methods = $this->get_available_methods( $user ); + $frequency = $this->resolve_selected_frequency( $user_settings ); + $frequency_forced = $this->config->is_frequency_forced(); + $frequency_options = Frequency_Options::get_options(); + + $enabled_methods = array_values( + array_unique( + array_filter( $enabled_methods ) + ) + ); + + $email_enabled = in_array( 'email', $enabled_methods, true ); + $otp_enabled = in_array( 'otp', $enabled_methods, true ); + $recovery_enabled = in_array( 'recovery_codes', $enabled_methods, true ); + + $raw_date_format = get_option( 'date_format' ); + $raw_time_format = get_option( 'time_format' ); + $date_format = is_string( $raw_date_format ) ? $raw_date_format : ''; + $time_format = is_string( $raw_time_format ) ? $raw_time_format : ''; + $datetime_format = trim( $date_format . ' ' . $time_format ); + + if ( '' === $datetime_format ) { + $datetime_format = 'c'; + } + + $unused_count = $this->recovery_codes->count_unused_codes( $user->ID ); + $recovery_code_length = $this->recovery_codes->get_code_length(); + $recovery_total = $this->recovery_codes->get_codes_per_batch(); + $last_generated = $this->recovery_codes->get_last_generated_timestamp( $user->ID ); + $preview = $this->get_recovery_preview( $user->ID ); + $preview_codes = $preview['codes']; + $preview_generated = $preview['generated_at']; + + if ( $preview_generated > 0 ) { + $last_generated = $preview_generated; + } + + if ( $recovery_enabled && $unused_count <= 0 ) { + $this->reset_recovery_codes_after_exhaustion( $user, $user_settings, $is_forced ); + + $user_settings = $this->user_settings_repository->get_user_settings( $user->ID ); + $is_enabled = $is_forced ? true : (bool) $user_settings['enabled']; + $enabled_methods = $is_enabled ? $user_settings['methods'] : array(); + $enabled_methods = array_values( + array_unique( + array_filter( $enabled_methods ) + ) + ); + + $email_enabled = in_array( 'email', $enabled_methods, true ); + $otp_enabled = in_array( 'otp', $enabled_methods, true ); + $recovery_enabled = in_array( 'recovery_codes', $enabled_methods, true ); + + $unused_count = $this->recovery_codes->count_unused_codes( $user->ID ); + $preview = $this->get_recovery_preview( $user->ID ); + $preview_codes = $preview['codes']; + $preview_generated = $preview['generated_at']; + + if ( $preview_generated > 0 ) { + $last_generated = $preview_generated; + } else { + $last_generated = $this->recovery_codes->get_last_generated_timestamp( $user->ID ); + } + } + + if ( ! $recovery_enabled && empty( $preview_codes ) ) { + $preview = $this->prepare_recovery_preview( $user ); + $preview_codes = $preview['codes']; + $preview_generated = $preview['generated_at']; + + if ( $preview_generated > 0 ) { + $last_generated = $preview_generated; + } + } + + if ( $unused_count < count( $preview_codes ) ) { + $unused_count = count( $preview_codes ); + } + + $wp_date_result = $last_generated > 0 ? wp_date( $datetime_format, $last_generated ) : false; + $last_generated_formatted = ( false !== $wp_date_result ) ? $wp_date_result : ''; + $has_preview = ! empty( $preview_codes ); + + $otp_secret = $otp_enabled ? $this->otp_manager->get_secret( $user->ID ) : $this->otp_manager->ensure_secret( $user ); + $otp_secret_chunks = '' !== $otp_secret ? trim( chunk_split( $otp_secret, 4, ' ' ) ) : ''; + $otp_qr_data_uri = $otp_enabled ? '' : $this->otp_manager->get_qr_code_data_uri( $user ); + $otp_digits = $this->otp_manager->get_code_length(); + + $email_destination = $this->get_email_destination_label( $user ); + $email_label = isset( $available_methods['email']['label'] ) ? (string) $available_methods['email']['label'] : __( 'Email code', 'robotstxt-2fa' ); + + if ( '' !== $email_destination ) { + $email_label = sprintf( + /* translators: 1: verification method label, 2: email address. */ + __( '%1$s (%2$s)', 'robotstxt-2fa' ), + $email_label, + $email_destination + ); + } + ?> +

+ + + + + + + + + + + + + + + + + + + + + , generated_at: int} + */ + private function prepare_recovery_preview( \WP_User $user ): array { + try { + $result = $this->recovery_codes->regenerate_codes_for_user( $user ); + } catch ( \Throwable $exception ) { + /** + * Fires when recovery code generation fails. + * + * @since 0.2.0 + * + * @param \Throwable $exception The caught exception. + */ + do_action( 'robotstxt_2fa_recovery_generation_failed', $exception ); + return $this->get_recovery_preview( $user->ID ); + } + + if ( empty( $result['codes'] ) ) { + return $this->get_recovery_preview( $user->ID ); + } + + $this->remember_recovery_preview( $user->ID, $result['codes'], $result['generated_at'] ); + $this->focus_section = true; + + add_settings_error( + 'robotstxt-2fa', + 'robotstxt-2fa-recovery-prepared', + __( 'New recovery codes are ready below. Copy them and confirm you saved them by entering one code.', 'robotstxt-2fa' ), + 'updated' + ); + + return $this->get_recovery_preview( $user->ID ); + } + + /** + * Reset recovery codes and user settings when all codes were consumed. + * + * @param \WP_User $user User being edited. + * @param array{enabled: bool, methods: array, frequency: string} $user_settings Stored user settings prior to the reset. + * @param bool $is_forced Whether two-factor authentication is enforced for the user. + * + * @return void + */ + private function reset_recovery_codes_after_exhaustion( \WP_User $user, array $user_settings, bool $is_forced ): void { + $current_methods = $user_settings['methods']; + $remaining_methods = array_values( array_diff( $current_methods, array( 'recovery_codes' ) ) ); + $enabled_flag = $is_forced ? true : ( ! empty( $remaining_methods ) && ! empty( $user_settings['enabled'] ) ); + $frequency_value = $this->resolve_selected_frequency( $user_settings ); + + $this->user_settings_repository->save_user_settings( + $user->ID, + array( + 'enabled' => $enabled_flag, + 'methods' => $remaining_methods, + 'frequency' => $frequency_value, + ) + ); + + try { + $result = $this->recovery_codes->regenerate_codes_for_user( $user ); + } catch ( \Throwable $exception ) { + /** + * Fires when recovery code generation fails. + * + * @since 0.2.0 + * + * @param \Throwable $exception The caught exception. + */ + do_action( 'robotstxt_2fa_recovery_generation_failed', $exception ); + add_settings_error( + 'robotstxt-2fa', + 'robotstxt-2fa-recovery-exhausted-error', + __( 'All recovery codes were used. Generating a new batch failed. Please try again.', 'robotstxt-2fa' ), + 'error' + ); + return; + } + + if ( ! empty( $result['codes'] ) ) { + $this->remember_recovery_preview( $user->ID, $result['codes'], $result['generated_at'] ); + } + + $this->focus_section = true; + + add_settings_error( + 'robotstxt-2fa', + 'robotstxt-2fa-recovery-exhausted', + __( 'All recovery codes were used. We prepared a new batch that must be confirmed below.', 'robotstxt-2fa' ), + 'updated' + ); + } + + + + + /** + * Save profile settings upon submission. + * + * @param int $user_id User identifier. + * + * @return void + */ + public function save_profile_settings( int $user_id ): void { + if ( ! current_user_can( 'edit_user', $user_id ) ) { + return; + } + + if ( ! isset( $_POST[ self::NONCE_FIELD ] ) || ! is_string( $_POST[ self::NONCE_FIELD ] ) ) { + return; + } + + $nonce = sanitize_text_field( wp_unslash( $_POST[ self::NONCE_FIELD ] ) ); + + if ( ! wp_verify_nonce( $nonce, self::NONCE_ACTION ) ) { + return; + } + + $user = get_user_by( 'ID', $user_id ); + + if ( ! $user instanceof \WP_User ) { + return; + } + + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified above. + $raw_settings = isset( $_POST['robotstxt_2fa_settings'] ) && is_array( $_POST['robotstxt_2fa_settings'] ) + ? wp_unslash( $_POST['robotstxt_2fa_settings'] ) // phpcs:ignore WordPress.Security.NonceVerification.Missing + : array(); + + $requested_methods = array(); + + if ( isset( $raw_settings['methods'] ) && is_array( $raw_settings['methods'] ) ) { + foreach ( $raw_settings['methods'] as $raw_method ) { + $method_key = sanitize_key( is_string( $raw_method ) ? $raw_method : '' ); + + if ( '' !== $method_key ) { + $requested_methods[] = $method_key; + } + } + } + + $requested_methods = array_values( array_unique( $requested_methods ) ); + + $required_methods = $this->config->get_required_methods_for_user( $user ); + $is_forced = ! empty( $required_methods ); + + // Merge role-required methods into the submission so they cannot be dropped server-side. + foreach ( $required_methods as $req_method ) { + if ( ! in_array( $req_method, $requested_methods, true ) ) { + $requested_methods[] = $req_method; + } + } + + $enabled = ! empty( $raw_settings['enabled'] ); + + if ( $is_forced ) { + $enabled = true; + } + + $user_settings = $this->user_settings_repository->get_user_settings( $user_id ); + $previous_methods = $user_settings['methods']; + + $otp_was_enabled = in_array( 'otp', $previous_methods, true ); + $recovery_was_enabled = in_array( 'recovery_codes', $previous_methods, true ); + + $otp_regenerate_requested = isset( $_POST[ self::OTP_REGENERATE_FIELD ] ); + + if ( $otp_regenerate_requested ) { + $this->focus_section = true; + } + + $otp_code = ''; + + if ( isset( $_POST[ self::OTP_CODE_FIELD ] ) && is_string( $_POST[ self::OTP_CODE_FIELD ] ) ) { + $otp_code = sanitize_text_field( wp_unslash( $_POST[ self::OTP_CODE_FIELD ] ) ); + } + + $recovery_code_input = ''; + + if ( isset( $_POST[ self::RECOVERY_CONFIRM_FIELD ] ) && is_string( $_POST[ self::RECOVERY_CONFIRM_FIELD ] ) ) { + $recovery_code_input = sanitize_text_field( wp_unslash( $_POST[ self::RECOVERY_CONFIRM_FIELD ] ) ); + } + + $available_methods = $this->get_available_methods( $user ); + $available_keys = array_keys( $available_methods ); + $selected_methods = array(); + + if ( $enabled && in_array( 'email', $requested_methods, true ) && in_array( 'email', $available_keys, true ) ) { + $selected_methods[] = 'email'; + } + + $otp_requested = in_array( 'otp', $requested_methods, true ); + $otp_should_remain_enabled = false; + + if ( $otp_regenerate_requested ) { + $this->otp_manager->delete_secret( $user_id ); + $this->otp_manager->ensure_secret( $user ); + $otp_was_enabled = false; + $otp_requested = true; + add_settings_error( + 'robotstxt-2fa', + 'robotstxt-2fa-otp-reset', + __( 'A new authenticator secret is ready. Scan the QR code and confirm it with a fresh code to finish reconnecting.', 'robotstxt-2fa' ), + 'updated' + ); + } + + if ( $otp_was_enabled ) { + if ( $otp_requested && ! $otp_regenerate_requested ) { + $otp_should_remain_enabled = true; + } else { + $this->otp_manager->delete_secret( $user_id ); + $this->otp_manager->ensure_secret( $user ); + $this->focus_section = true; + add_settings_error( + 'robotstxt-2fa', + 'robotstxt-2fa-otp-disabled', + __( 'Authenticator app disabled. A new QR code is ready below if you want to reconnect it.', 'robotstxt-2fa' ), + 'updated' + ); + } + } else { + $this->otp_manager->ensure_secret( $user ); + + if ( $otp_requested ) { + if ( '' === $otp_code ) { + $this->focus_section = true; + add_settings_error( + 'robotstxt-2fa', + 'robotstxt-2fa-otp-missing', + __( 'Enter the six-digit code currently shown in your authenticator app to activate this method.', 'robotstxt-2fa' ), + 'error' + ); + } elseif ( $this->otp_manager->verify_code( $user, $otp_code ) ) { + $selected_methods[] = 'otp'; + $this->focus_section = true; + add_settings_error( + 'robotstxt-2fa', + 'robotstxt-2fa-otp-enabled', + __( 'Authenticator app enabled successfully.', 'robotstxt-2fa' ), + 'updated' + ); + } else { + $this->focus_section = true; + add_settings_error( + 'robotstxt-2fa', + 'robotstxt-2fa-otp-invalid', + __( 'The provided authenticator code is invalid or expired. Try again with a fresh code.', 'robotstxt-2fa' ), + 'error' + ); + } + } + } + + if ( $otp_should_remain_enabled ) { + $selected_methods[] = 'otp'; + } + + $recovery_requested = in_array( 'recovery_codes', $requested_methods, true ); + $recovery_confirmation_success = false; + + if ( '' !== $recovery_code_input ) { + $this->focus_section = true; + + if ( $this->acknowledge_recovery_preview( $user_id, $recovery_code_input ) ) { + $recovery_confirmation_success = true; + add_settings_error( + 'robotstxt-2fa', + 'robotstxt-2fa-recovery-confirmed', + __( 'Recovery codes confirmed. Keep them in a secure location.', 'robotstxt-2fa' ), + 'updated' + ); + } else { + add_settings_error( + 'robotstxt-2fa', + 'robotstxt-2fa-recovery-confirm-failed', + __( 'We could not verify that code. Enter one of the freshly generated recovery codes to confirm.', 'robotstxt-2fa' ), + 'error' + ); + } + } + + if ( $recovery_was_enabled ) { + if ( $recovery_requested ) { + if ( $this->recovery_codes->count_unused_codes( $user_id ) > 0 ) { + $selected_methods[] = 'recovery_codes'; + } else { + $this->reset_recovery_codes_after_exhaustion( $user, $user_settings, $is_forced ); + } + } else { + $this->prepare_recovery_preview( $user ); + $this->focus_section = true; + add_settings_error( + 'robotstxt-2fa', + 'robotstxt-2fa-recovery-disabled', + __( 'Recovery codes disabled. A fresh list is available below.', 'robotstxt-2fa' ), + 'updated' + ); + } + } elseif ( $recovery_confirmation_success ) { + $selected_methods[] = 'recovery_codes'; + } elseif ( $recovery_requested ) { + $this->focus_section = true; + add_settings_error( + 'robotstxt-2fa', + 'robotstxt-2fa-recovery-missing-confirmation', + __( 'Enter one of the displayed recovery codes to activate this method.', 'robotstxt-2fa' ), + 'error' + ); + } + + $selected_methods = array_values( array_unique( $selected_methods ) ); + + if ( ! $is_forced && empty( $selected_methods ) ) { + $enabled = false; + } + + $frequency = Frequency_Options::FREQUENCY_SESSION; + + if ( isset( $raw_settings['frequency'] ) && is_string( $raw_settings['frequency'] ) ) { + $frequency = Frequency_Options::sanitize( sanitize_key( wp_unslash( $raw_settings['frequency'] ) ) ); + } + + if ( $this->config->is_frequency_forced() ) { + $frequency = $this->config->get_frequency(); + } elseif ( '' === $frequency ) { + $frequency = $this->config->get_frequency(); + } + + $this->user_settings_repository->save_user_settings( + $user_id, + array( + 'enabled' => $enabled, + 'methods' => $selected_methods, + 'frequency' => $frequency, + ) + ); + + if ( ! $enabled ) { + $this->user_settings_repository->delete_email_challenge( $user_id ); + } + } + + + + /** + * Append the 2FA section anchor to redirects when requested. + * + * @param string $location Redirect destination. + * @param int $status HTTP status code. + * + * @return string + */ + public function maybe_append_section_anchor( string $location, int $status ): string { + unset( $status ); + + if ( ! $this->focus_section ) { + return $location; + } + + $this->focus_section = false; + + if ( '' === $location ) { + return $location; + } + + $fragment = '#' . self::SECTION_ANCHOR; + $hash_position = strpos( $location, '#' ); + + if ( false !== $hash_position ) { + $location = substr( $location, 0, $hash_position ); + } + + return $location . $fragment; + } + + + /** + * Persist the generated recovery codes temporarily so they can be displayed once. + * + * @param int $user_id User identifier. + * @param array $codes Plain-text recovery codes. + * @param int $generated_at Generation timestamp. + * + * @return void + */ + private function remember_recovery_preview( int $user_id, array $codes, int $generated_at ): void { + $key = $this->get_recovery_preview_transient_key( $user_id ); + $generated_at = max( 0, $generated_at ); + $values = $this->normalize_preview_codes( $codes ); + + if ( empty( $values ) ) { + delete_transient( $key ); + return; + } + + delete_transient( $key ); + + set_transient( + $key, + array( + 'codes' => $values, + 'generated_at' => $generated_at, + ), + self::PREVIEW_TTL + ); + } + + /** + * Retrieve recovery codes stored for one-time display after generation. + * + * @param int $user_id User identifier. + * + * @return array{codes: array, generated_at: int} + */ + private function get_recovery_preview( int $user_id ): array { + $key = $this->get_recovery_preview_transient_key( $user_id ); + $preview = get_transient( $key ); + + if ( ! is_array( $preview ) ) { + return array( + 'codes' => array(), + 'generated_at' => 0, + ); + } + + $codes = isset( $preview['codes'] ) && is_array( $preview['codes'] ) ? $this->normalize_preview_codes( array_values( $preview['codes'] ) ) : array(); + $generated_at = isset( $preview['generated_at'] ) && is_int( $preview['generated_at'] ) ? $preview['generated_at'] : 0; + + return array( + 'codes' => $codes, + 'generated_at' => $generated_at, + ); + } + + /** + * Build the transient key used to store one-time recovery code previews. + * + * @param int $user_id User identifier. + * + * @return string + */ + private function get_recovery_preview_transient_key( int $user_id ): string { + $session_token = wp_get_session_token(); + + if ( '' === $session_token ) { + $session_token = (string) get_current_user_id(); + } + + return 'robotstxt_2fa_preview_' . md5( $user_id . '|' . $session_token ); + } + + /** + * Clear the stored recovery preview for the current session. + * + * @param int $user_id User identifier. + * + * @return void + */ + private function clear_recovery_preview( int $user_id ): void { + $key = $this->get_recovery_preview_transient_key( $user_id ); + delete_transient( $key ); + } + + /** + * Confirm that the generated recovery codes were stored safely. + * + * @param int $user_id User identifier. + * @param string $code Code provided by the user. + * + * @return bool + */ + private function acknowledge_recovery_preview( int $user_id, string $code ): bool { + $preview = $this->get_recovery_preview( $user_id ); + + if ( empty( $preview['codes'] ) ) { + return false; + } + + $normalized = preg_replace( '/[^0-9]/', '', $code ); + + if ( null === $normalized ) { + return false; + } + + $normalized = substr( $normalized, 0, $this->recovery_codes->get_code_length() ); + + if ( '' === $normalized ) { + return false; + } + + if ( ! in_array( $normalized, $preview['codes'], true ) ) { + return false; + } + + $user = get_user_by( 'ID', $user_id ); + + if ( ! $user instanceof \WP_User ) { + return false; + } + + if ( ! $this->recovery_codes->verify_code_without_consuming( $user, $normalized ) ) { + return false; + } + + $this->clear_recovery_preview( $user_id ); + + return true; + } + + + + /** + * Sanitize a list of preview codes to a normalized numeric format. + * + * @param array $codes Codes to normalize. + * + * @return array + */ + private function normalize_preview_codes( array $codes ): array { + $normalized = array(); + $length = $this->recovery_codes->get_code_length(); + + foreach ( $codes as $code ) { + $digits = preg_replace( '/[^0-9]/', '', is_string( $code ) ? $code : '' ); + + if ( null === $digits ) { + continue; + } + + $digits = substr( $digits, 0, $length ); + + if ( strlen( $digits ) !== $length ) { + continue; + } + + $normalized[] = $digits; + } + + return array_values( array_unique( $normalized ) ); + } + + + + /** + * Retrieve the formatted email destination used in the methods list. + * + * @param \WP_User $user User being edited. + * + * @return string + */ + private function get_email_destination_label( \WP_User $user ): string { + $email = sanitize_email( $user->user_email ); + + if ( '' !== $email ) { + return $email; + } + + return __( 'no email address available', 'robotstxt-2fa' ); + } + + /** + * Retrieve the available 2FA methods shown in the UI. + * + * @param \WP_User $user User being edited. + * + * @return array> + */ + private function get_available_methods( \WP_User $user ): array { + $email_address = sanitize_email( $user->user_email ); + $email_description = __( 'Receive a verification code in your inbox every time you sign in.', 'robotstxt-2fa' ); + + if ( '' === $email_address ) { + $email_description = __( 'Add a valid email address to your profile to receive verification codes.', 'robotstxt-2fa' ); + } + + return array( + 'email' => array( + 'label' => __( 'Email code', 'robotstxt-2fa' ), + 'description' => $email_description, + ), + 'otp' => array( + 'label' => __( 'Authenticator app (OTP)', 'robotstxt-2fa' ), + 'description' => __( 'Use an app like Google Authenticator or 1Password to generate time-based codes.', 'robotstxt-2fa' ), + ), + 'recovery_codes' => array( + 'label' => __( 'Recovery codes', 'robotstxt-2fa' ), + 'description' => __( 'Keep printable backup codes in a safe place for emergencies.', 'robotstxt-2fa' ), + ), + ); + } + + /** + * Resolve the frequency value shown and stored for the user. + * + * @param array{enabled: bool, methods: array, frequency: string} $user_settings Stored user settings. + * + * @return string + */ + private function resolve_selected_frequency( array $user_settings ): string { + $global_frequency = $this->config->get_frequency(); + + if ( $this->config->is_frequency_forced() ) { + return $global_frequency; + } + + if ( '' !== $user_settings['frequency'] ) { + return Frequency_Options::sanitize( $user_settings['frequency'] ); + } + + return $global_frequency; + } +} diff --git a/includes/user/class-recovery-codes.php b/includes/user/class-recovery-codes.php index d0671fd..fc4fdc5 100644 --- a/includes/user/class-recovery-codes.php +++ b/includes/user/class-recovery-codes.php @@ -1,454 +1,462 @@ - $message, - ), - 403 - ); - } - - wp_die( $message, '', array( 'response' => 403 ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $message is escaped via esc_html__(). - } - - /** - * Handle AJAX requests to generate recovery codes without reloading the page. - * - * @return void - */ - public function handle_ajax_generate_request(): void { - check_ajax_referer( self::NONCE_ACTION, self::NONCE_FIELD ); - - $user_id = isset( $_POST['user_id'] ) ? absint( wp_unslash( $_POST['user_id'] ) ) : 0; - - if ( $user_id <= 0 ) { - wp_send_json_error( - array( - 'message' => esc_html__( 'The requested user account could not be found.', 'robotstxt-2fa' ), - ), - 400 - ); - } - - if ( ! current_user_can( 'edit_user', $user_id ) ) { - wp_send_json_error( - array( - 'message' => esc_html__( 'You are not allowed to modify recovery codes for this account.', 'robotstxt-2fa' ), - ), - 403 - ); - } - - $user = get_user_by( 'ID', $user_id ); - - if ( ! $user instanceof WP_User ) { - wp_send_json_error( - array( - 'message' => esc_html__( 'The requested user account could not be found.', 'robotstxt-2fa' ), - ), - 400 - ); - } - - try { - $result = $this->regenerate_codes_for_user( $user ); - } catch ( \Throwable $exception ) { - do_action( 'robotstxt_2fa_recovery_generation_failed', $exception ); - wp_send_json_error( - array( - 'message' => esc_html__( 'We could not generate recovery codes. Please try again.', 'robotstxt-2fa' ), - ), - 500 - ); - } - - wp_send_json_success( - array( - 'codes' => $result['codes'], - 'unused_count' => $result['unused_count'], - 'last_generated' => $result['generated_at'], - 'last_generated_formatted' => $this->format_generated_timestamp( $result['generated_at'] ), - ) - ); - } - - /** - * Generate and persist a new batch of recovery codes for a user. - * - * @param WP_User $user User whose recovery codes are being regenerated. - * - * @throws \Exception If secure randomness cannot be generated. - * - * @return array - */ - public function regenerate_codes_for_user( WP_User $user ): array { - $codes = $this->generate_codes(); - - $this->store_codes( $user->ID, $codes ); - - return array( - 'codes' => $codes, - 'generated_at' => $this->get_last_generated_timestamp( $user->ID ), - 'unused_count' => $this->count_unused_codes( $user->ID ), - ); - } - - /** - * Retrieve the number of digits expected for each recovery code. - * - * @return int - */ - public function get_code_length(): int { - return self::CODE_LENGTH; - } - - /** - * Retrieve the number of recovery codes generated per batch. - * - * @return int - */ - public function get_codes_per_batch(): int { - return self::CODES_PER_BATCH; - } - - /** - * Count the amount of unused recovery codes available for the user. - * - * @param int $user_id User identifier. - * - * @return int - */ - public function count_unused_codes( int $user_id ): int { - $record = $this->get_stored_codes( $user_id ); - - if ( empty( $record['codes'] ) ) { - return 0; - } - - $unused = 0; - - foreach ( $record['codes'] as $entry ) { - if ( empty( $entry['used_at'] ) ) { - ++$unused; - } - } - - return $unused; - } - - /** - * Determine whether the user currently has any unused recovery codes. - * - * @param int $user_id User identifier. - * - * @return bool - */ - public function has_active_codes( int $user_id ): bool { - return $this->count_unused_codes( $user_id ) > 0; - } - - /** - * Consume a recovery code if it matches one of the stored hashes. - * - * @param WP_User $user User attempting to validate a recovery code. - * @param string $code Submitted plain-text code. - * - * @return bool - */ - public function consume_code( WP_User $user, string $code ): bool { - $normalized_code = $this->normalize_code( $code ); - - if ( '' === $normalized_code ) { - return false; - } - - $record = $this->get_stored_codes( $user->ID ); - - if ( empty( $record['codes'] ) ) { - return false; - } - - $updated = false; - - foreach ( $record['codes'] as $index => $entry ) { - if ( ! empty( $entry['used_at'] ) || empty( $entry['hash'] ) ) { - continue; - } - - if ( wp_check_password( $normalized_code, $entry['hash'] ) ) { - $record['codes'][ $index ]['used_at'] = time(); - $updated = true; - break; - } - } - - if ( $updated ) { - update_user_meta( $user->ID, self::META_KEY, $record ); - - return true; - } - - return false; - } - - /** - * Fetch the timestamp of the last generation batch. - * - * @param int $user_id User identifier. - * - * @return int - */ - public function get_last_generated_timestamp( int $user_id ): int { - $record = $this->get_stored_codes( $user_id ); - - return (int) ( $record['generated_at'] ?? 0 ); - } - - /** - * Format the provided timestamp using the site's date and time preferences. - * - * @param int $timestamp Unix timestamp representing the generation time. - * - * @return string - */ - private function format_generated_timestamp( int $timestamp ): string { - if ( $timestamp <= 0 ) { - return ''; - } - - $date_format = get_option( 'date_format' ); - $time_format = get_option( 'time_format' ); - - $format = trim( (string) $date_format . ' ' . (string) $time_format ); - - return '' !== $format ? wp_date( $format, $timestamp ) : wp_date( 'c', $timestamp ); - } - - /** - * Generate a batch of unique recovery codes. - * - * @throws \Exception If randomness cannot be generated. - * - * @return array - */ - private function generate_codes(): array { - $codes = array(); - $attempts = 0; - $target_count = self::CODES_PER_BATCH; - $max_attempts = $target_count * 3; - $unique_count = 0; - - while ( $unique_count < $target_count && $attempts < $max_attempts ) { - ++$attempts; - - $code = $this->generate_single_code(); - - if ( in_array( $code, $codes, true ) ) { - continue; - } - - $codes[] = $code; - ++$unique_count; - } - - return $codes; - } - - /** - * Create a single recovery code. - * - * @throws \Exception If secure randomness cannot be generated. - * - * @return string - */ - private function generate_single_code(): string { - $max_value = ( 10 ** self::CODE_LENGTH ) - 1; - $number = random_int( 0, $max_value ); - - return str_pad( (string) $number, self::CODE_LENGTH, '0', STR_PAD_LEFT ); - } - - /** - * Normalize user-submitted recovery codes. - * - * @param string $code Submitted code. - * - * @return string - */ - private function normalize_code( string $code ): string { - $code = preg_replace( '/[^0-9]/', '', $code ); - - if ( null === $code ) { - return ''; - } - - $code = substr( $code, 0, self::CODE_LENGTH ); - - if ( strlen( $code ) !== self::CODE_LENGTH ) { - return ''; - } - - return $code; - } - - /** - * Store recovery codes and metadata for a user. - * - * @param int $user_id User identifier. - * @param array $codes Plain-text recovery codes. - * - * @return void - */ - private function store_codes( int $user_id, array $codes ): void { - $stored_codes = array(); - - foreach ( $codes as $code ) { - $stored_codes[] = array( - 'hash' => wp_hash_password( $this->normalize_code( $code ) ), - 'used_at' => 0, - ); - } - - $record = array( - 'generated_at' => time(), - 'codes' => $stored_codes, - ); - - update_user_meta( $user_id, self::META_KEY, $record ); - } - - /** - * Retrieve and sanitize stored recovery code metadata. - * - * @param int $user_id User identifier. - * - * @return array - */ - private function get_stored_codes( int $user_id ): array { - $record = get_user_meta( $user_id, self::META_KEY, true ); - - if ( ! is_array( $record ) ) { - $record = array(); - } - - $record['generated_at'] = isset( $record['generated_at'] ) ? (int) $record['generated_at'] : 0; - $record['codes'] = isset( $record['codes'] ) && is_array( $record['codes'] ) ? $record['codes'] : array(); - - foreach ( $record['codes'] as $index => $entry ) { - if ( ! is_array( $entry ) ) { - $record['codes'][ $index ] = array( - 'hash' => '', - 'used_at' => 0, - ); - continue; - } - - $record['codes'][ $index ]['hash'] = isset( $entry['hash'] ) && is_string( $entry['hash'] ) ? $entry['hash'] : ''; - $record['codes'][ $index ]['used_at'] = isset( $entry['used_at'] ) ? (int) $entry['used_at'] : 0; - } - - return $record; - } - - /** - * Verify whether the provided recovery code matches a stored hash without consuming it. - * - * @param WP_User $user User attempting to validate a recovery code. - * @param string $code Submitted plain-text code. - * - * @return bool - */ - public function verify_code_without_consuming( WP_User $user, string $code ): bool { - $normalized_code = $this->normalize_code( $code ); - - if ( '' === $normalized_code ) { - return false; - } - - $record = $this->get_stored_codes( $user->ID ); - - if ( empty( $record['codes'] ) ) { - return false; - } - - foreach ( $record['codes'] as $entry ) { - if ( empty( $entry['hash'] ) ) { - continue; - } - - if ( wp_check_password( $normalized_code, $entry['hash'] ) ) { - return true; - } - } - - return false; - } -} + $message, + ), + 403 + ); + } + + wp_die( $message, '', array( 'response' => 403 ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- $message is escaped via esc_html__(). + } + + /** + * Handle AJAX requests to generate recovery codes without reloading the page. + * + * @return void + */ + public function handle_ajax_generate_request(): void { + check_ajax_referer( self::NONCE_ACTION, self::NONCE_FIELD ); + + $raw_user_id = isset( $_POST['user_id'] ) && is_string( $_POST['user_id'] ) ? wp_unslash( $_POST['user_id'] ) : ''; + $user_id = absint( $raw_user_id ); + + if ( $user_id <= 0 ) { + wp_send_json_error( + array( + 'message' => esc_html__( 'The requested user account could not be found.', 'robotstxt-2fa' ), + ), + 400 + ); + } + + if ( ! current_user_can( 'edit_user', $user_id ) ) { + wp_send_json_error( + array( + 'message' => esc_html__( 'You are not allowed to modify recovery codes for this account.', 'robotstxt-2fa' ), + ), + 403 + ); + } + + $user = get_user_by( 'ID', $user_id ); + + if ( ! $user instanceof WP_User ) { + wp_send_json_error( + array( + 'message' => esc_html__( 'The requested user account could not be found.', 'robotstxt-2fa' ), + ), + 400 + ); + } + + try { + $result = $this->regenerate_codes_for_user( $user ); + } catch ( \Throwable $exception ) { + /** + * Fires when recovery code generation fails. + * + * @since 0.2.0 + * + * @param \Throwable $exception The caught exception. + */ + do_action( 'robotstxt_2fa_recovery_generation_failed', $exception ); + wp_send_json_error( + array( + 'message' => esc_html__( 'We could not generate recovery codes. Please try again.', 'robotstxt-2fa' ), + ), + 500 + ); + } + + wp_send_json_success( + array( + 'codes' => $result['codes'], + 'unused_count' => $result['unused_count'], + 'last_generated' => $result['generated_at'], + 'last_generated_formatted' => $this->format_generated_timestamp( $result['generated_at'] ), + ) + ); + } + + /** + * Generate and persist a new batch of recovery codes for a user. + * + * @param WP_User $user User whose recovery codes are being regenerated. + * + * @throws \Exception If secure randomness cannot be generated. + * + * @return array{codes: array, generated_at: int, unused_count: int} + */ + public function regenerate_codes_for_user( WP_User $user ): array { + $codes = $this->generate_codes(); + + $this->store_codes( $user->ID, $codes ); + + return array( + 'codes' => $codes, + 'generated_at' => $this->get_last_generated_timestamp( $user->ID ), + 'unused_count' => $this->count_unused_codes( $user->ID ), + ); + } + + /** + * Retrieve the number of digits expected for each recovery code. + * + * @return int + */ + public function get_code_length(): int { + return self::CODE_LENGTH; + } + + /** + * Retrieve the number of recovery codes generated per batch. + * + * @return int + */ + public function get_codes_per_batch(): int { + return self::CODES_PER_BATCH; + } + + /** + * Count the amount of unused recovery codes available for the user. + * + * @param int $user_id User identifier. + * + * @return int + */ + public function count_unused_codes( int $user_id ): int { + $record = $this->get_stored_codes( $user_id ); + + if ( empty( $record['codes'] ) ) { + return 0; + } + + $unused = 0; + + foreach ( $record['codes'] as $entry ) { + if ( empty( $entry['used_at'] ) ) { + ++$unused; + } + } + + return $unused; + } + + /** + * Determine whether the user currently has any unused recovery codes. + * + * @param int $user_id User identifier. + * + * @return bool + */ + public function has_active_codes( int $user_id ): bool { + return $this->count_unused_codes( $user_id ) > 0; + } + + /** + * Consume a recovery code if it matches one of the stored hashes. + * + * @param WP_User $user User attempting to validate a recovery code. + * @param string $code Submitted plain-text code. + * + * @return bool + */ + public function consume_code( WP_User $user, string $code ): bool { + $normalized_code = $this->normalize_code( $code ); + + if ( '' === $normalized_code ) { + return false; + } + + $record = $this->get_stored_codes( $user->ID ); + + if ( empty( $record['codes'] ) ) { + return false; + } + + $updated = false; + + foreach ( $record['codes'] as $index => $entry ) { + if ( ! empty( $entry['used_at'] ) || empty( $entry['hash'] ) ) { + continue; + } + + if ( wp_check_password( $normalized_code, $entry['hash'] ) ) { + $record['codes'][ $index ]['used_at'] = time(); + $updated = true; + break; + } + } + + if ( $updated ) { + update_user_meta( $user->ID, self::META_KEY, $record ); + + return true; + } + + return false; + } + + /** + * Fetch the timestamp of the last generation batch. + * + * @param int $user_id User identifier. + * + * @return int + */ + public function get_last_generated_timestamp( int $user_id ): int { + $record = $this->get_stored_codes( $user_id ); + + return $record['generated_at']; + } + + /** + * Format the provided timestamp using the site's date and time preferences. + * + * @param int $timestamp Unix timestamp representing the generation time. + * + * @return string + */ + private function format_generated_timestamp( int $timestamp ): string { + if ( $timestamp <= 0 ) { + return ''; + } + + $date_format = get_option( 'date_format' ); + $time_format = get_option( 'time_format' ); + + $format = trim( ( is_string( $date_format ) ? $date_format : '' ) . ' ' . ( is_string( $time_format ) ? $time_format : '' ) ); + + $formatted = wp_date( '' !== $format ? $format : 'c', $timestamp ); + return false !== $formatted ? $formatted : ''; + } + + /** + * Generate a batch of unique recovery codes. + * + * @throws \Exception If randomness cannot be generated. + * + * @return array + */ + private function generate_codes(): array { + $codes = array(); + $attempts = 0; + $target_count = self::CODES_PER_BATCH; + $max_attempts = $target_count * 3; + $unique_count = 0; + + while ( $unique_count < $target_count && $attempts < $max_attempts ) { + ++$attempts; + + $code = $this->generate_single_code(); + + if ( in_array( $code, $codes, true ) ) { + continue; + } + + $codes[] = $code; + ++$unique_count; + } + + return $codes; + } + + /** + * Create a single recovery code. + * + * @throws \Exception If secure randomness cannot be generated. + * + * @return string + */ + private function generate_single_code(): string { + $max_value = ( 10 ** self::CODE_LENGTH ) - 1; + $number = random_int( 0, $max_value ); + + return str_pad( (string) $number, self::CODE_LENGTH, '0', STR_PAD_LEFT ); + } + + /** + * Normalize user-submitted recovery codes. + * + * @param string $code Submitted code. + * + * @return string + */ + private function normalize_code( string $code ): string { + $code = preg_replace( '/[^0-9]/', '', $code ); + + if ( null === $code ) { + return ''; + } + + $code = substr( $code, 0, self::CODE_LENGTH ); + + if ( strlen( $code ) !== self::CODE_LENGTH ) { + return ''; + } + + return $code; + } + + /** + * Store recovery codes and metadata for a user. + * + * @param int $user_id User identifier. + * @param array $codes Plain-text recovery codes. + * + * @return void + */ + private function store_codes( int $user_id, array $codes ): void { + $stored_codes = array(); + + foreach ( $codes as $code ) { + $stored_codes[] = array( + 'hash' => wp_hash_password( $this->normalize_code( $code ) ), + 'used_at' => 0, + ); + } + + $record = array( + 'generated_at' => time(), + 'codes' => $stored_codes, + ); + + update_user_meta( $user_id, self::META_KEY, $record ); + } + + /** + * Retrieve and sanitize stored recovery code metadata. + * + * @param int $user_id User identifier. + * + * @return array{generated_at: int, codes: array} + */ + private function get_stored_codes( int $user_id ): array { + $record = get_user_meta( $user_id, self::META_KEY, true ); + + if ( ! is_array( $record ) ) { + $record = array(); + } + + $generated_at = isset( $record['generated_at'] ) && is_int( $record['generated_at'] ) ? $record['generated_at'] : 0; + $raw_codes = isset( $record['codes'] ) && is_array( $record['codes'] ) ? $record['codes'] : array(); + + $codes = array(); + + foreach ( $raw_codes as $entry ) { + $codes[] = array( + 'hash' => is_array( $entry ) && isset( $entry['hash'] ) && is_string( $entry['hash'] ) ? $entry['hash'] : '', + 'used_at' => is_array( $entry ) && isset( $entry['used_at'] ) && is_int( $entry['used_at'] ) ? $entry['used_at'] : 0, + ); + } + + return array( + 'generated_at' => $generated_at, + 'codes' => $codes, + ); + } + + /** + * Verify whether the provided recovery code matches a stored hash without consuming it. + * + * @param WP_User $user User attempting to validate a recovery code. + * @param string $code Submitted plain-text code. + * + * @return bool + */ + public function verify_code_without_consuming( WP_User $user, string $code ): bool { + $normalized_code = $this->normalize_code( $code ); + + if ( '' === $normalized_code ) { + return false; + } + + $record = $this->get_stored_codes( $user->ID ); + + if ( empty( $record['codes'] ) ) { + return false; + } + + foreach ( $record['codes'] as $entry ) { + if ( empty( $entry['hash'] ) ) { + continue; + } + + if ( wp_check_password( $normalized_code, $entry['hash'] ) ) { + return true; + } + } + + return false; + } +} diff --git a/includes/user/class-two-factor-config.php b/includes/user/class-two-factor-config.php index 524fb9e..4e9de77 100644 --- a/includes/user/class-two-factor-config.php +++ b/includes/user/class-two-factor-config.php @@ -1,130 +1,113 @@ - - */ - public function get_settings(): array { - $settings = array(); - - if ( is_multisite() ) { - $network_settings = get_site_option( Settings_Page::OPTION_NAME, array() ); - - if ( is_array( $network_settings ) && ! empty( $network_settings ) ) { - $settings = $network_settings; - } - } - - if ( empty( $settings ) ) { - $site_settings = get_option( Settings_Page::OPTION_NAME, array() ); - - if ( is_array( $site_settings ) ) { - $settings = $site_settings; - } - } - - return wp_parse_args( - $settings, - array( - 'force_roles' => array(), - 'default_method' => 'email', - 'frequency' => Frequency_Options::FREQUENCY_SESSION, - 'force_frequency' => false, - ) - ); - } - - /** - * Retrieve the list of roles that must enable two-factor authentication. - * - * @return array - */ - public function get_forced_roles(): array { - $settings = $this->get_settings(); - - if ( empty( $settings['force_roles'] ) || ! is_array( $settings['force_roles'] ) ) { - return array(); - } - - return array_values( - array_filter( - array_map( 'sanitize_key', $settings['force_roles'] ) - ) - ); - } - - /** - * Determine if two-factor authentication is enforced for the provided user. - * - * @param \WP_User $user User object currently being authenticated. - * - * @return bool - */ - public function is_two_factor_forced_for_user( \WP_User $user ): bool { - $forced_roles = $this->get_forced_roles(); - - if ( empty( $forced_roles ) ) { - return false; - } - - foreach ( $user->roles as $role ) { - if ( in_array( $role, $forced_roles, true ) ) { - return true; - } - } - - return false; - } - - /** - * Retrieve the default two-factor authentication method. - * - * @return string - */ - public function get_default_method(): string { - $settings = $this->get_settings(); - - return sanitize_key( $settings['default_method'] ?? 'email' ); - } - - /** - * Retrieve the globally configured verification frequency. - * - * @return string - */ - public function get_frequency(): string { - $settings = $this->get_settings(); - - return Frequency_Options::sanitize( (string) ( $settings['frequency'] ?? Frequency_Options::FREQUENCY_SESSION ) ); - } - - /** - * Determine whether the global frequency must be enforced for all users. - * - * @return bool - */ - public function is_frequency_forced(): bool { - $settings = $this->get_settings(); - - return ! empty( $settings['force_frequency'] ); - } -} +>, frequency: string, force_frequency: bool, delete_on_uninstall: bool} + */ + public function get_settings(): array { + $settings_page = new Settings_Page(); + return $settings_page->get_settings(); + } + + /** + * Retrieve the per-role method map. + * + * @return array> + */ + public function get_role_methods(): array { + return $this->get_settings()['role_methods']; + } + + /** + * Retrieve the list of roles that have at least one required method configured. + * + * @return array + */ + public function get_forced_roles(): array { + return array_keys( $this->get_role_methods() ); + } + + /** + * Retrieve the required verification methods for a specific role. + * + * @param string $role Role slug. + * + * @return array + */ + public function get_methods_for_role( string $role ): array { + $role_methods = $this->get_role_methods(); + return $role_methods[ $role ] ?? array(); + } + + /** + * Retrieve the union of required methods across all of a user's roles. + * + * Returns an empty array when none of the user's roles have required methods. + * + * @param \WP_User $user User object currently being authenticated. + * + * @return array + */ + public function get_required_methods_for_user( \WP_User $user ): array { + $role_methods = $this->get_role_methods(); + $required = array(); + + foreach ( $user->roles as $role ) { + if ( isset( $role_methods[ $role ] ) ) { + foreach ( $role_methods[ $role ] as $method ) { + $required[] = $method; + } + } + } + + return array_values( array_unique( $required ) ); + } + + /** + * Determine if two-factor authentication is enforced for the provided user. + * + * @param \WP_User $user User object currently being authenticated. + * + * @return bool + */ + public function is_two_factor_forced_for_user( \WP_User $user ): bool { + return ! empty( $this->get_required_methods_for_user( $user ) ); + } + + /** + * Retrieve the globally configured verification frequency. + * + * @return string + */ + public function get_frequency(): string { + return $this->get_settings()['frequency']; + } + + /** + * Determine whether the global frequency must be enforced for all users. + * + * @return bool + */ + public function is_frequency_forced(): bool { + return $this->get_settings()['force_frequency']; + } +} diff --git a/includes/user/class-user-settings-repository.php b/includes/user/class-user-settings-repository.php index 84c4994..af5ed65 100644 --- a/includes/user/class-user-settings-repository.php +++ b/includes/user/class-user-settings-repository.php @@ -1,259 +1,257 @@ - - */ - public function get_user_settings( int $user_id ): array { - $raw_settings = get_user_meta( $user_id, self::USER_SETTINGS_META, true ); - - if ( ! is_array( $raw_settings ) ) { - $raw_settings = array(); - } - - $defaults = array( - 'enabled' => false, - 'methods' => array(), - 'frequency' => Frequency_Options::FREQUENCY_SESSION, - ); - - $settings = wp_parse_args( $raw_settings, $defaults ); - - $settings['enabled'] = (bool) $settings['enabled']; - - $settings['methods'] = array_values( - array_unique( - array_filter( - array_map( 'sanitize_key', (array) $settings['methods'] ) - ) - ) - ); - - $settings['frequency'] = Frequency_Options::sanitize( (string) $settings['frequency'] ); - - return $settings; - } - - /** - * Persist 2FA settings for a user. - * - * @param int $user_id User identifier. - * @param array $settings Settings to store. - * - * @return void - */ - public function save_user_settings( int $user_id, array $settings ): void { - $prepared = array( - 'enabled' => ! empty( $settings['enabled'] ), - 'methods' => array_values( - array_unique( - array_filter( - array_map( 'sanitize_key', $settings['methods'] ?? array() ) - ) - ) - ), - 'frequency' => Frequency_Options::sanitize( (string) ( $settings['frequency'] ?? Frequency_Options::FREQUENCY_SESSION ) ), - ); - - update_user_meta( $user_id, self::USER_SETTINGS_META, $prepared ); - - if ( empty( $prepared['enabled'] ) ) { - $this->delete_email_challenge( $user_id ); - $this->delete_last_verifications( $user_id ); - } - } - - /** - * Store email challenge details for a user. - * - * @param int $user_id User identifier. - * @param string $code Plain-text verification code. - * @param int $expires Expiration timestamp. - * - * @return void - */ - public function store_email_challenge( int $user_id, string $code, int $expires ): void { - $record = array( - 'hash' => wp_hash_password( $code ), - 'expires' => $expires, - 'sent_at' => time(), - ); - - update_user_meta( $user_id, self::EMAIL_CHALLENGE_META, $record ); - } - - /** - * Retrieve email challenge details for a user. - * - * @param int $user_id User identifier. - * - * @return array - */ - public function get_email_challenge( int $user_id ): array { - $record = get_user_meta( $user_id, self::EMAIL_CHALLENGE_META, true ); - - if ( ! is_array( $record ) ) { - $record = array(); - } - - $record = wp_parse_args( - $record, - array( - 'hash' => '', - 'expires' => 0, - 'sent_at' => 0, - ) - ); - - $record['hash'] = is_string( $record['hash'] ) ? $record['hash'] : ''; - $record['expires'] = (int) $record['expires']; - $record['sent_at'] = (int) $record['sent_at']; - - return $record; - } - - /** - * Remove stored email challenge details. - * - * @param int $user_id User identifier. - * - * @return void - */ - public function delete_email_challenge( int $user_id ): void { - delete_user_meta( $user_id, self::EMAIL_CHALLENGE_META ); - } - - /** - * Record a successful verification timestamp for a method and device context. - * - * @param int $user_id User identifier. - * @param string $method Verification method identifier. - * @param string $context_key Normalized device context key. - * @param int $timestamp Verification timestamp. - * - * @return void - */ - public function record_last_verification( int $user_id, string $method, string $context_key, int $timestamp ): void { - $method = sanitize_key( $method ); - $context_key = sanitize_text_field( $context_key ); - $timestamp = max( 0, $timestamp ); - - if ( '' === $method || '' === $context_key || 0 === $timestamp ) { - return; - } - - $record = get_user_meta( $user_id, self::LAST_VERIFICATIONS_META, true ); - - if ( ! is_array( $record ) ) { - $record = array(); - } - - if ( ! isset( $record[ $method ] ) || ! is_array( $record[ $method ] ) ) { - $record[ $method ] = array(); - } - - $record[ $method ][ $context_key ] = array( - 'verified_at' => $timestamp, - ); - - if ( count( $record[ $method ] ) > self::CONTEXT_LIMIT ) { - uasort( - $record[ $method ], - static function ( array $a, array $b ): int { - return ( $a['verified_at'] ?? 0 ) <=> ( $b['verified_at'] ?? 0 ); - } - ); - - $record[ $method ] = array_slice( $record[ $method ], -1 * self::CONTEXT_LIMIT, null, true ); - } - - update_user_meta( $user_id, self::LAST_VERIFICATIONS_META, $record ); - } - - /** - * Retrieve the last verification timestamp for a method and context. - * - * @param int $user_id User identifier. - * @param string $method Verification method identifier. - * @param string $context_key Normalized device context key. - * - * @return int - */ - public function get_last_verification_timestamp( int $user_id, string $method, string $context_key ): int { - $method = sanitize_key( $method ); - $context_key = sanitize_text_field( $context_key ); - - if ( '' === $method || '' === $context_key ) { - return 0; - } - - $record = get_user_meta( $user_id, self::LAST_VERIFICATIONS_META, true ); - - if ( ! is_array( $record ) || empty( $record[ $method ] ) || ! is_array( $record[ $method ] ) ) { - return 0; - } - - if ( empty( $record[ $method ][ $context_key ]['verified_at'] ) ) { - return 0; - } - - return (int) $record[ $method ][ $context_key ]['verified_at']; - } - - /** - * Remove stored verification timestamps. - * - * @param int $user_id User identifier. - * - * @return void - */ - public function delete_last_verifications( int $user_id ): void { - delete_user_meta( $user_id, self::LAST_VERIFICATIONS_META ); - } -} +, frequency: string} + */ + public function get_user_settings( int $user_id ): array { + $raw_settings = get_user_meta( $user_id, self::USER_SETTINGS_META, true ); + + if ( ! is_array( $raw_settings ) ) { + $raw_settings = array(); + } + + $raw_methods = isset( $raw_settings['methods'] ) && is_array( $raw_settings['methods'] ) ? $raw_settings['methods'] : array(); + + return array( + 'enabled' => ! empty( $raw_settings['enabled'] ), + 'methods' => array_values( + array_unique( + array_filter( + array_map( + static function ( mixed $v ): string { + return sanitize_key( is_string( $v ) ? $v : '' ); + }, + $raw_methods + ) + ) + ) + ), + 'frequency' => Frequency_Options::sanitize( isset( $raw_settings['frequency'] ) && is_string( $raw_settings['frequency'] ) ? $raw_settings['frequency'] : '' ), + ); + } + + /** + * Persist 2FA settings for a user. + * + * @param int $user_id User identifier. + * @param array $settings Settings to store. + * + * @return void + */ + public function save_user_settings( int $user_id, array $settings ): void { + $raw_methods = isset( $settings['methods'] ) && is_array( $settings['methods'] ) ? $settings['methods'] : array(); + $prepared = array( + 'enabled' => ! empty( $settings['enabled'] ), + 'methods' => array_values( + array_unique( + array_filter( + array_map( + static function ( mixed $v ): string { + return sanitize_key( is_string( $v ) ? $v : '' ); + }, + $raw_methods + ) + ) + ) + ), + 'frequency' => Frequency_Options::sanitize( isset( $settings['frequency'] ) && is_string( $settings['frequency'] ) ? $settings['frequency'] : Frequency_Options::FREQUENCY_SESSION ), + ); + + update_user_meta( $user_id, self::USER_SETTINGS_META, $prepared ); + + if ( empty( $prepared['enabled'] ) ) { + $this->delete_email_challenge( $user_id ); + $this->delete_last_verifications( $user_id ); + } + } + + /** + * Store email challenge details for a user. + * + * @param int $user_id User identifier. + * @param string $code Plain-text verification code. + * @param int $expires Expiration timestamp. + * + * @return void + */ + public function store_email_challenge( int $user_id, string $code, int $expires ): void { + $record = array( + 'hash' => wp_hash_password( $code ), + 'expires' => $expires, + 'sent_at' => time(), + ); + + update_user_meta( $user_id, self::EMAIL_CHALLENGE_META, $record ); + } + + /** + * Retrieve email challenge details for a user. + * + * @param int $user_id User identifier. + * + * @return array{hash: string, expires: int, sent_at: int} + */ + public function get_email_challenge( int $user_id ): array { + $record = get_user_meta( $user_id, self::EMAIL_CHALLENGE_META, true ); + + if ( ! is_array( $record ) ) { + $record = array(); + } + + return array( + 'hash' => isset( $record['hash'] ) && is_string( $record['hash'] ) ? $record['hash'] : '', + 'expires' => isset( $record['expires'] ) && is_numeric( $record['expires'] ) ? (int) $record['expires'] : 0, + 'sent_at' => isset( $record['sent_at'] ) && is_numeric( $record['sent_at'] ) ? (int) $record['sent_at'] : 0, + ); + } + + /** + * Remove stored email challenge details. + * + * @param int $user_id User identifier. + * + * @return void + */ + public function delete_email_challenge( int $user_id ): void { + delete_user_meta( $user_id, self::EMAIL_CHALLENGE_META ); + } + + /** + * Record a successful verification timestamp for a method and device context. + * + * @param int $user_id User identifier. + * @param string $method Verification method identifier. + * @param string $context_key Normalized device context key. + * @param int $timestamp Verification timestamp. + * + * @return void + */ + public function record_last_verification( int $user_id, string $method, string $context_key, int $timestamp ): void { + $method = sanitize_key( $method ); + $context_key = sanitize_text_field( $context_key ); + $timestamp = max( 0, $timestamp ); + + if ( '' === $method || '' === $context_key || 0 === $timestamp ) { + return; + } + + $record = get_user_meta( $user_id, self::LAST_VERIFICATIONS_META, true ); + + if ( ! is_array( $record ) ) { + $record = array(); + } + + if ( ! isset( $record[ $method ] ) || ! is_array( $record[ $method ] ) ) { + $record[ $method ] = array(); + } + + $record[ $method ][ $context_key ] = array( + 'verified_at' => $timestamp, + ); + + if ( count( $record[ $method ] ) > self::CONTEXT_LIMIT ) { + uasort( + $record[ $method ], + static function ( mixed $a, mixed $b ): int { + $a_ts = is_array( $a ) && isset( $a['verified_at'] ) && is_int( $a['verified_at'] ) ? $a['verified_at'] : 0; + $b_ts = is_array( $b ) && isset( $b['verified_at'] ) && is_int( $b['verified_at'] ) ? $b['verified_at'] : 0; + return $a_ts <=> $b_ts; + } + ); + + $record[ $method ] = array_slice( $record[ $method ], -1 * self::CONTEXT_LIMIT, null, true ); + } + + update_user_meta( $user_id, self::LAST_VERIFICATIONS_META, $record ); + } + + /** + * Retrieve the last verification timestamp for a method and context. + * + * @param int $user_id User identifier. + * @param string $method Verification method identifier. + * @param string $context_key Normalized device context key. + * + * @return int + */ + public function get_last_verification_timestamp( int $user_id, string $method, string $context_key ): int { + $method = sanitize_key( $method ); + $context_key = sanitize_text_field( $context_key ); + + if ( '' === $method || '' === $context_key ) { + return 0; + } + + $record = get_user_meta( $user_id, self::LAST_VERIFICATIONS_META, true ); + + if ( ! is_array( $record ) || empty( $record[ $method ] ) || ! is_array( $record[ $method ] ) ) { + return 0; + } + + $entry = $record[ $method ][ $context_key ] ?? null; + + if ( ! is_array( $entry ) || empty( $entry['verified_at'] ) || ! is_int( $entry['verified_at'] ) ) { + return 0; + } + + return $entry['verified_at']; + } + + /** + * Remove stored verification timestamps. + * + * @param int $user_id User identifier. + * + * @return void + */ + public function delete_last_verifications( int $user_id ): void { + delete_user_meta( $user_id, self::LAST_VERIFICATIONS_META ); + } +} diff --git a/readme.txt b/readme.txt index 77b82c3..d8fd5ee 100644 --- a/readme.txt +++ b/readme.txt @@ -1,45 +1,100 @@ -=== 2FA (by ROBOTSTXT) === -Contributors: robotstxt -Tags: security, two-factor authentication, login, otp -Requires at least: 6.4 -Tested up to: 6.4 -Requires PHP: 8.2 -Stable tag: 0.2.0 -License: GPLv3 or later -License URI: https://www.gnu.org/licenses/gpl-3.0.html - -Security plugin that adds a two-factor authentication flow to the WordPress login screen. - -== Description == - -This plugin lets administrators enforce two-factor authentication per role and already delivers email verification codes during the login flow. After the username and password are validated, the login screen redirects to a dedicated verification step flagged with its own query parameter. The screen hides the username and password controls, automatically prioritizes authenticator apps when they are enabled, offers links to switch between authenticator, email, or recovery-code challenges, lets email users trigger an additional delivery when they need a fresh code, and auto-submits once the active method reaches its expected length (six digits for OTP, seven for email, eight for recovery codes). Users can manage their preferences from their profile, where every method starts unchecked until it is explicitly confirmed. The authenticator section now keeps the QR code and setup key visible until a valid six-digit code is entered, regenerates the secret whenever the option is disabled, and surfaces a dedicated button to issue a replacement secret. Recovery codes are shown in a two-column grid, expose the remaining count out of ten, require entering one code before activation, and automatically reset when the stored batch is exhausted so a fresh list is always available without extra clicks. - -Administrators can remember successful verifications for a configurable duration—per login, daily, weekly, or every 28 days—and even lock the schedule so profiles inherit the global requirement. Device and IP fingerprints are stored securely to decide when a fresh challenge is needed, ensuring suspicious logins must re-validate regardless of the remembered interval. - -== Installation == - -1. Upload the `robotstxt-2fa` directory to `/wp-content/plugins/`. -2. Activate the plugin through the "Plugins" menu in WordPress. -3. Configure the authentication options in your profile and in the Two-Factor Authentication admin menu. - -== Frequently Asked Questions == - -= Is this plugin production ready? = - -Yes. Email codes, recovery confirmations, and authenticator apps with on-site QR codes are all available, though you should still test changes in a staging environment before enforcing them across your site. - -= How do I enable the authenticator QR code? = - -Install the optional QR library inside this plugin directory with `composer require bacon/bacon-qr-code:^3.0`. The plugin will automatically load the Composer autoloader when it exists, enabling the QR code renderer for the OTP method. - -== Changelog == - -Review the `changelog.txt` file for additional details. - -== Upgrade Notice == - -= 0.2.0 = -Authenticator apps now include on-page QR codes and recovery codes stay visible until you confirm one of them. This update also fixes the confirmation workflow and improves the QR fallback guidance when PHP extensions are missing. - -= 0.1.0 = -Initial version containing the basic plugin structure. +=== 2FA (by ROBOTSTXT) === +Contributors: robotstxt +Tags: security, two-factor authentication, login, otp +Requires at least: 6.4 +Tested up to: 7.0 +Requires PHP: 8.2 +Stable tag: 0.3.0 +License: GPLv3 or later +License URI: https://www.gnu.org/licenses/gpl-3.0.html + +Security plugin that adds per-role two-factor authentication to the WordPress login flow. + +== Description == + +2FA (by ROBOTSTXT) enforces two-factor authentication on the WordPress login screen. Administrators configure a per-role matrix that specifies exactly which verification methods are required for each role: email codes, authenticator apps (TOTP), or recovery codes. + +After the username and password are validated, the login screen redirects to a dedicated verification step. The screen hides the username and password controls, prioritises authenticator apps when enabled, and offers links to switch between methods without restarting the login. Email users can request a fresh code from the same screen. + +Users manage their preferences from their profile page. Every method starts unchecked until explicitly confirmed. Activating the authenticator app requires scanning the QR code and entering a valid six-digit code. Recovery codes must be saved and confirmed with one code before activation. Codes are shown in a two-column grid and automatically refresh when the batch is exhausted. + +Administrators can remember successful verifications for a configurable duration — per login, daily, weekly, or every 28 days — and lock the schedule so all users follow the global setting. Device and IP fingerprints are stored securely to decide when a fresh challenge is needed. + +Multisite is fully supported: network administrators can set and lock enforcement settings across all sites. + +== Installation == + +1. Upload the `robotstxt-2fa` directory to `/wp-content/plugins/`. +2. Activate the plugin through the "Plugins" menu in WordPress (or network-activate it for multisite). +3. Open the **2FA** top-level menu in the dashboard and configure which methods are required per role. +4. Users can set up their preferred methods from their profile page. + +== Frequently Asked Questions == + += Is this plugin production ready? = + +Yes. Email codes, authenticator apps with on-site QR codes, and recovery codes are all available and tested. + += How do I enable the authenticator QR code? = + +Install the optional QR library inside this plugin directory with `composer require bacon/bacon-qr-code:^3.0`. The plugin loads the Composer autoloader automatically when present. + += Can I enforce 2FA for specific roles only? = + +Yes. The admin settings page shows a matrix of roles × methods. Check the methods you want to require for each role. Roles with no methods checked leave the choice to the user. + += What happens if a user loses all their verification methods? = + +An administrator can edit the user's profile and generate a fresh batch of recovery codes, or disable the role enforcement temporarily while the user regains access. + += Is multisite supported? = + +Yes. Activate the plugin at the network level. Network administrators can set and lock enforcement settings; per-site settings are overridden when network settings exist. + +== Compatibility == + +* WordPress: 6.4 – 7.0 +* PHP: 8.2 – 8.5 +* MariaDB: 11.4 or newer + +== Changelog == + += 0.3.0 = + +_Release date: 2026-06-05_ + +* Added delete-on-uninstall option (data preserved by default per AGENTS.md). +* Security: email verification codes now use `random_int()` (CSPRNG) instead of `wp_rand()`. +* Security: recovery code preview transient now expires after 5 minutes. +* Fixed network admin settings page form submission. +* Fixed settings option set to `autoload=false` (not needed on every page load). + += 0.2.0 = + +_Release date: 2026-06-05_ + +* Added per-role 2FA method matrix in admin settings with select-all row and column controls. +* Added authenticator app (TOTP) support with QR provisioning and manual setup key. +* Added recovery codes: 10 single-use 8-digit codes with confirmation workflow. +* Added configurable verification frequency remembered per device. +* Added network-wide multisite support. +* Changed profile method checkboxes to require explicit confirmation before activation. +* Fixed recovery-code preview persistence and QR generation error handling. + += 0.1.0 = + +Initial release. + += Previous versions = + +For the full changelog see the [changelog.txt](https://git.robotstxt.es/ROBOTSTXT/robotstxt-2fa/raw/branch/main/changelog.txt) file. + +== Compliance == + +This plugin adheres to the following security measures and review protocols for each version: + +* [WordPress Plugin Handbook](https://developer.wordpress.org/plugins/) +* [WordPress Plugin Security](https://developer.wordpress.org/plugins/wordpress-org/plugin-security/) +* [WordPress APIs Security](https://developer.wordpress.org/apis/security/) +* [WordPress Coding Standards](https://github.com/WordPress/WordPress-Coding-Standards) +* [Plugin Check (PCP)](https://wordpress.org/plugins/plugin-check/) diff --git a/robotstxt-2fa.php b/robotstxt-2fa.php index 42fcf05..052ce26 100644 --- a/robotstxt-2fa.php +++ b/robotstxt-2fa.php @@ -1,98 +1,99 @@ -init(); -} -add_action( 'plugins_loaded', 'robotstxt_2fa_bootstrap' ); - -register_activation_hook( __FILE__, array( Plugin::class, 'activate' ) ); -register_deactivation_hook( __FILE__, array( Plugin::class, 'deactivate' ) ); +init(); +} +add_action( 'plugins_loaded', 'robotstxt_2fa_bootstrap' ); + +register_activation_hook( __FILE__, array( Plugin::class, 'activate' ) ); +register_deactivation_hook( __FILE__, array( Plugin::class, 'deactivate' ) ); diff --git a/robotstxt-updater.php b/robotstxt-updater.php new file mode 100644 index 0000000..feeab4b --- /dev/null +++ b/robotstxt-updater.php @@ -0,0 +1,384 @@ +register(); + } + + /** + * Constructor. + * + * @param string $plugin_file_path Absolute path to the main plugin file. + */ + private function __construct( string $plugin_file_path ) { + $this->plugin_file_path = $plugin_file_path; + $this->plugin_basename = plugin_basename( $plugin_file_path ); + $this->plugin_slug = dirname( $this->plugin_basename ); + $this->plugin_data = $this->get_plugin_data(); + $this->json_url = $this->build_json_url(); + $this->cache_key = 'robotstxt_updater_' . md5( $this->plugin_basename ); + } + + /** + * Register WordPress hooks. + */ + private function register(): void { + add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'inject_update_info' ) ); + add_filter( 'plugins_api', array( $this, 'provide_plugin_details' ), 10, 3 ); + add_action( 'admin_init', array( $this, 'handle_cache_clear' ) ); + add_action( 'robotstxt_updater_clear_cache', array( $this, 'clear_cache' ) ); + } + + /** + * Get plugin headers. + * + * @return array Plugin data. + */ + private function get_plugin_data(): array { + if ( ! function_exists( 'get_plugin_data' ) ) { + require_once ABSPATH . 'wp-admin/includes/plugin.php'; + } + + return get_plugin_data( $this->plugin_file_path, false, false ); + } + + /** + * Build JSON URL from plugin headers. + * + * Tries to use "Gitea Plugin URI" header to construct the URL. + * Falls back to Plugin URI if Gitea URI is not available. + * + * @return string JSON URL. + */ + private function build_json_url(): string { + // Try Gitea Plugin URI (format: "OWNER/REPO" or full URL). + if ( ! empty( $this->plugin_data['Gitea Plugin URI'] ) ) { + $gitea_uri = $this->plugin_data['Gitea Plugin URI']; + + // If it's already a full URL, use it. + if ( str_starts_with( $gitea_uri, 'http' ) ) { + // Extract base URL and construct JSON path. + return rtrim( $gitea_uri, '/' ) . '/raw/branch/main/update.json'; + } + + // If it's in format "OWNER/REPO", construct full URL. + if ( preg_match( '#^[^/]+/[^/]+$#', $gitea_uri ) ) { + return "https://git.robotstxt.es/{$gitea_uri}/raw/branch/main/update.json"; + } + } + + // Fallback: try to extract from Plugin URI. + if ( ! empty( $this->plugin_data['PluginURI'] ) ) { + $plugin_uri = $this->plugin_data['PluginURI']; + if ( str_contains( $plugin_uri, 'git.robotstxt.es' ) ) { + return rtrim( $plugin_uri, '/' ) . '/raw/branch/main/update.json'; + } + } + + // Last resort: construct from plugin slug. + return "https://git.robotstxt.es/ROBOTSTXT/{$this->plugin_slug}/raw/branch/main/update.json"; + } + + /** + * Inject update info into WP's plugin update transient. + * + * @param object|mixed $transient The update_plugins transient. + * + * @return object The modified transient. + */ + public function inject_update_info( $transient ) { + if ( ! is_object( $transient ) ) { + $transient = new stdClass(); + } + + if ( empty( $transient->checked ) || ! is_array( $transient->checked ) ) { + return $transient; + } + + if ( empty( $transient->checked[ $this->plugin_basename ] ) ) { + return $transient; + } + + $current_version = $transient->checked[ $this->plugin_basename ]; + $remote = $this->get_remote_data(); + + if ( empty( $remote['version'] ) || empty( $remote['download_url'] ) ) { + return $transient; + } + + if ( ! $this->is_compatible( $remote ) ) { + return $transient; + } + + if ( version_compare( $remote['version'], $current_version, '>' ) ) { + $update = (object) array( + 'slug' => $remote['slug'] ?? $this->plugin_slug, + 'plugin' => $this->plugin_basename, + 'new_version' => $remote['version'], + 'url' => $remote['homepage'] ?? $this->plugin_data['PluginURI'] ?? '', + 'package' => $remote['download_url'], + 'tested' => $remote['tested'] ?? '', + 'requires' => $remote['requires'] ?? '', + 'requires_php' => $remote['requires_php'] ?? '', + ); + + $transient->response[ $this->plugin_basename ] = $update; + } + + return $transient; + } + + /** + * Provide "View details" modal content. + * + * @param false|object|array $result The result object or array. + * @param string $action The type of information being requested. + * @param object $args Plugin API arguments. + * + * @return false|object The plugin information object or false. + */ + public function provide_plugin_details( $result, string $action, object $args ) { + if ( 'plugin_information' !== $action ) { + return $result; + } + + if ( empty( $args->slug ) || $args->slug !== $this->plugin_slug ) { + return $result; + } + + $remote = $this->get_remote_data(); + + if ( empty( $remote['version'] ) ) { + return $result; + } + + return (object) array( + 'name' => $remote['name'] ?? $this->plugin_data['Name'] ?? $this->plugin_slug, + 'slug' => $remote['slug'] ?? $this->plugin_slug, + 'version' => $remote['version'], + 'author' => $remote['author'] ?? $this->plugin_data['Author'] ?? '', + 'homepage' => $remote['homepage'] ?? $this->plugin_data['PluginURI'] ?? '', + 'requires' => $remote['requires'] ?? '', + 'tested' => $remote['tested'] ?? '', + 'requires_php' => $remote['requires_php'] ?? '', + 'sections' => array( + 'description' => $remote['description'] ?? $this->plugin_data['Description'] ?? '', + 'changelog' => $remote['changelog'] ?? '', + ), + 'download_link' => $remote['download_url'] ?? '', + ); + } + + /** + * Get remote data with caching and HMAC signature verification. + * + * @return array Remote data. + */ + private function get_remote_data(): array { + $cached = get_site_transient( $this->cache_key ); + + // Verify HMAC signature if AUTH_SALT is defined and cache has signature. + if ( false !== $cached && defined( 'AUTH_SALT' ) && '' !== AUTH_SALT ) { + if ( is_array( $cached ) && isset( $cached['signature'], $cached['data'] ) ) { + $expected_sig = hash_hmac( 'sha256', $this->cache_key . serialize( $cached['data'] ), AUTH_SALT ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Used for HMAC signing, not for unserializing untrusted data. + + if ( hash_equals( $expected_sig, $cached['signature'] ) ) { + // Signature valid, return data. + return is_array( $cached['data'] ) ? $cached['data'] : array(); + } + + // Signature invalid, delete corrupted cache. + delete_site_transient( $this->cache_key ); + $cached = false; + } + } + + // If no valid cache, fetch fresh data. + if ( false === $cached ) { + $remote = $this->fetch_json(); + + // Store with HMAC signature if AUTH_SALT is available. + if ( defined( 'AUTH_SALT' ) && '' !== AUTH_SALT ) { + $remote_data = is_array( $remote ) ? $remote : array(); + $payload = array( + 'data' => $remote_data, + 'timestamp' => time(), + 'signature' => hash_hmac( 'sha256', $this->cache_key . serialize( $remote_data ), AUTH_SALT ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Used for HMAC signing, not for unserializing untrusted data. + ); + set_site_transient( $this->cache_key, $payload, 6 * HOUR_IN_SECONDS ); + } else { + // Fallback to standard caching. + set_site_transient( $this->cache_key, is_array( $remote ) ? $remote : array(), 6 * HOUR_IN_SECONDS ); + } + + return is_array( $remote ) ? $remote : array(); + } + + // Legacy cache format without signature (backward compatibility). + return is_array( $cached ) ? $cached : array(); + } + + /** + * Fetch JSON from remote URL. + * + * @return array Decoded JSON data. + */ + private function fetch_json(): array { + $response = wp_remote_get( + $this->json_url, + array( + 'timeout' => 10, + 'headers' => array( + 'Accept' => 'application/json', + ), + ) + ); + + if ( is_wp_error( $response ) ) { + return array(); + } + + $code = (int) wp_remote_retrieve_response_code( $response ); + if ( $code < 200 || $code >= 300 ) { + return array(); + } + + $body = wp_remote_retrieve_body( $response ); + $data = json_decode( $body, true ); + + return is_array( $data ) ? $data : array(); + } + + /** + * Check compatibility. + * + * @param array $remote Remote data. + * + * @return bool True if compatible. + */ + private function is_compatible( array $remote ): bool { + if ( ! empty( $remote['requires_php'] ) ) { + if ( version_compare( PHP_VERSION, $remote['requires_php'], '<' ) ) { + return false; + } + } + + if ( ! empty( $remote['requires'] ) ) { + if ( version_compare( get_bloginfo( 'version' ), $remote['requires'], '<' ) ) { + return false; + } + } + + return true; + } + + /** + * Handle manual cache clear via URL parameter. + */ + public function handle_cache_clear(): void { + // Check if this is a cache clear request first. + $clear_cache = filter_input( INPUT_GET, 'robotstxt_clear_update_cache', FILTER_UNSAFE_RAW ); + if ( null === $clear_cache ) { + return; + } + + // This is a cache clear request - now verify nonce. + $nonce_raw = filter_input( INPUT_GET, '_wpnonce', FILTER_UNSAFE_RAW ); + $nonce = $nonce_raw ? sanitize_text_field( wp_unslash( $nonce_raw ) ) : ''; + + if ( ! wp_verify_nonce( $nonce, 'robotstxt_clear_update_cache' ) ) { + wp_die( esc_html__( 'Security check failed', 'robotstxt-2fa' ) ); + } + + // Check permissions. + if ( ! current_user_can( 'update_plugins' ) ) { + wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'robotstxt-2fa' ) ); + } + + $this->clear_cache(); + wp_safe_redirect( remove_query_arg( array( 'robotstxt_clear_update_cache', '_wpnonce' ) ) ); + exit; + } + + /** + * Clear update cache. + */ + public function clear_cache(): void { + delete_site_transient( $this->cache_key ); + delete_site_transient( 'update_plugins' ); + } + } +} diff --git a/uninstall.php b/uninstall.php index e17dd78..032269c 100644 --- a/uninstall.php +++ b/uninstall.php @@ -1,32 +1,65 @@ -query( - $wpdb->prepare( - "DELETE FROM {$wpdb->usermeta} WHERE meta_key = %s", - $meta_key - ) - ); -} +query( + $wpdb->prepare( + "DELETE FROM {$wpdb->usermeta} WHERE meta_key = %s", + $robotstxt_2fa_meta_key + ) + ); +} diff --git a/update.json b/update.json new file mode 100644 index 0000000..9e58c34 --- /dev/null +++ b/update.json @@ -0,0 +1,27 @@ +{ + "name": "2FA (by ROBOTSTXT)", + "slug": "robotstxt-2fa", + "version": "0.3.0", + "download_url": "https://git.robotstxt.es/ROBOTSTXT/robotstxt-2fa/releases/download/0.3.0/robotstxt-2fa-0.3.0.zip", + "requires": "6.4", + "requires_php": "8.2", + "tested": "7.1", + "last_updated": "2026-06-05", + "author": "ROBOTSTXT", + "author_profile": "https://www.robotstxt.es/", + "homepage": "https://www.robotstxt.es/plugins/robotstxt-2fa/", + "description": "Adds per-role two-factor authentication to the WordPress login flow. Supports email codes, authenticator apps (TOTP), and recovery codes.", + "changelog": "

0.3.0 - 2026-06-05

  • Added: Per-role 2FA method matrix with select-all row/column controls
  • Added: Delete-on-uninstall option (data preserved by default)
  • Security: Email verification codes now use CSPRNG (random_int)
  • Security: Recovery code preview TTL reduced to 5 minutes
  • Fixed: Network admin settings page now saves correctly

0.2.0 - 2026-06-05

  • Initial fully featured release with email, OTP, and recovery code authentication
", + "sections": { + "description": "Adds per-role two-factor authentication to the WordPress login flow. Supports email codes, authenticator apps (TOTP), and recovery codes.", + "changelog": "

0.3.0 - 2026-06-05

  • Added: Per-role 2FA method matrix with select-all row/column controls
  • Added: Delete-on-uninstall option (data preserved by default)
  • Security: Email verification codes now use CSPRNG (random_int)
  • Security: Recovery code preview TTL reduced to 5 minutes
  • Fixed: Network admin settings page now saves correctly
" + }, + "banners": { + "low": "", + "high": "" + }, + "icons": { + "1x": "", + "2x": "" + } +} diff --git a/vendor/autoload.php b/vendor/autoload.php index 576f49e..7eed9f4 100644 --- a/vendor/autoload.php +++ b/vendor/autoload.php @@ -1,25 +1,22 @@ -writeFile('Hello World!', 'qrcode.png'); -``` - -## Available image renderer back ends -BaconQrCode comes with multiple back ends for rendering images. Currently included are the following: - -- `ImagickImageBackEnd`: renders raster images using the Imagick library -- `SvgImageBackEnd`: renders SVG files using XMLWriter -- `EpsImageBackEnd`: renders EPS files - -### GDLib Renderer -GD library has so many limitations, that GD support is not added as backend, but as separated renderer. -Use `GDLibRenderer` instead of `ImageRenderer`. These are the limitations: - -- Does not support gradient. -- Does not support any curves, so you QR code is always squared. - -Example usage: - -```php -use BaconQrCode\Renderer\GDLibRenderer; -use BaconQrCode\Writer; - -$renderer = new GDLibRenderer(400); -$writer = new Writer($renderer); -$writer->writeFile('Hello World!', 'qrcode.png'); -``` +# QR Code generator + +[![PHP CI](https://github.com/Bacon/BaconQrCode/actions/workflows/ci.yml/badge.svg)](https://github.com/Bacon/BaconQrCode/actions/workflows/ci.yml) +[![codecov](https://codecov.io/gh/Bacon/BaconQrCode/branch/master/graph/badge.svg?token=rD0HcAiEEx)](https://codecov.io/gh/Bacon/BaconQrCode) +[![Latest Stable Version](https://poser.pugx.org/bacon/bacon-qr-code/v/stable)](https://packagist.org/packages/bacon/bacon-qr-code) +[![Total Downloads](https://poser.pugx.org/bacon/bacon-qr-code/downloads)](https://packagist.org/packages/bacon/bacon-qr-code) +[![License](https://poser.pugx.org/bacon/bacon-qr-code/license)](https://packagist.org/packages/bacon/bacon-qr-code) + + +## Introduction +BaconQrCode is a port of QR code portion of the ZXing library. It currently +only features the encoder part, but could later receive the decoder part as +well. + +As the Reed Solomon codec implementation of the ZXing library performs quite +slow in PHP, it was exchanged with the implementation by Phil Karn. + + +## Example usage +```php +use BaconQrCode\Renderer\ImageRenderer; +use BaconQrCode\Renderer\Image\ImagickImageBackEnd; +use BaconQrCode\Renderer\RendererStyle\RendererStyle; +use BaconQrCode\Writer; + +$renderer = new ImageRenderer( + new RendererStyle(400), + new ImagickImageBackEnd() +); +$writer = new Writer($renderer); +$writer->writeFile('Hello World!', 'qrcode.png'); +``` + +## Available image renderer back ends +BaconQrCode comes with multiple back ends for rendering images. Currently included are the following: + +- `ImagickImageBackEnd`: renders raster images using the Imagick library +- `SvgImageBackEnd`: renders SVG files using XMLWriter +- `EpsImageBackEnd`: renders EPS files + +### GDLib Renderer +GD library has so many limitations, that GD support is not added as backend, but as separated renderer. +Use `GDLibRenderer` instead of `ImageRenderer`. These are the limitations: + +- Does not support gradient. +- Does not support any curves, so you QR code is always squared. + +Example usage: + +```php +use BaconQrCode\Renderer\GDLibRenderer; +use BaconQrCode\Writer; + +$renderer = new GDLibRenderer(400); +$writer = new Writer($renderer); +$writer->writeFile('Hello World!', 'qrcode.png'); +``` + +## Known issues + +### ImagickImageBackEnd: white pixel artifacts + +When using `ImagickImageBackEnd`, single white pixels may appear inside filled regions. This is +most visible with margin 0 (where artifacts appear at the image edge), but can in theory occur at +any position. The cause is a bug in ImageMagick's path fill rasterizer (`GetFillAlpha` in +`MagickCore/draw.c`): an off-by-one error in the winding number calculation combined with an edge +skipping bug in the scanline processing can incorrectly classify pixels as outside the polygon. + +The bug cannot be reliably worked around in this library: + +- **Canvas padding** (rendering on a larger canvas and cropping) does not work because the required + padding depends on the scale factor, path complexity, and ImageMagick's internal edge processing + state. No fixed padding value is safe for all inputs. +- **Post-processing** (scanning for and fixing isolated white pixels) risks corrupting legitimate + rendering features such as curved module edges. + +For artifact-free output, use `SvgImageBackEnd` or `GDLibRenderer` instead. + +## Development + +To run unit tests, you need to have [Node.js](https://nodejs.org/en) and the pixelmatch library installed. Running +`npm install` will install this for you. diff --git a/vendor/bacon/bacon-qr-code/composer.json b/vendor/bacon/bacon-qr-code/composer.json index 33523f3..37e8c75 100644 --- a/vendor/bacon/bacon-qr-code/composer.json +++ b/vendor/bacon/bacon-qr-code/composer.json @@ -1,50 +1,51 @@ -{ - "name": "bacon/bacon-qr-code", - "description": "BaconQrCode is a QR code generator for PHP.", - "license": "BSD-2-Clause", - "homepage": "https://github.com/Bacon/BaconQrCode", - "require": { - "php": "^8.1", - "ext-iconv": "*", - "dasprid/enum": "^1.0.3" - }, - "suggest": { - "ext-imagick": "to generate QR code images" - }, - "authors": [ - { - "name": "Ben Scholzen 'DASPRiD'", - "email": "mail@dasprids.de", - "homepage": "https://dasprids.de/", - "role": "Developer" - } - ], - "autoload": { - "psr-4": { - "BaconQrCode\\": "src/" - } - }, - "autoload-dev": { - "psr-4": { - "BaconQrCodeTest\\": "test/" - } - }, - "require-dev": { - "phpunit/phpunit": "^10.5.11 || 11.0.4", - "spatie/phpunit-snapshot-assertions": "^5.1.5", - "squizlabs/php_codesniffer": "^3.9", - "phly/keep-a-changelog": "^2.12" - }, - "config": { - "allow-plugins": { - "ocramius/package-versions": true, - "php-http/discovery": true - } - }, - "archive": { - "exclude": [ - "/test", - "/phpunit.xml.dist" - ] - } -} +{ + "name": "bacon/bacon-qr-code", + "description": "BaconQrCode is a QR code generator for PHP.", + "license": "BSD-2-Clause", + "homepage": "https://github.com/Bacon/BaconQrCode", + "require": { + "php": "^8.1", + "ext-iconv": "*", + "dasprid/enum": "^1.0.3" + }, + "suggest": { + "ext-imagick": "to generate QR code images" + }, + "authors": [ + { + "name": "Ben Scholzen 'DASPRiD'", + "email": "mail@dasprids.de", + "homepage": "https://dasprids.de/", + "role": "Developer" + } + ], + "autoload": { + "psr-4": { + "BaconQrCode\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "BaconQrCodeTest\\": "test/" + } + }, + "require-dev": { + "phpunit/phpunit": "^10.5.11 || ^11.0.4", + "spatie/phpunit-snapshot-assertions": "^5.1.5", + "spatie/pixelmatch-php": "^1.2.0", + "squizlabs/php_codesniffer": "^3.9", + "phly/keep-a-changelog": "^2.12" + }, + "config": { + "allow-plugins": { + "ocramius/package-versions": true, + "php-http/discovery": true + } + }, + "archive": { + "exclude": [ + "/test", + "/phpunit.xml.dist" + ] + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Common/BitArray.php b/vendor/bacon/bacon-qr-code/src/Common/BitArray.php index 7f0a794..9ec8629 100644 --- a/vendor/bacon/bacon-qr-code/src/Common/BitArray.php +++ b/vendor/bacon/bacon-qr-code/src/Common/BitArray.php @@ -1,364 +1,364 @@ - - */ - private SplFixedArray $bits; - - /** - * Creates a new bit array with a given size. - */ - public function __construct(private int $size = 0) - { - $this->bits = SplFixedArray::fromArray(array_fill(0, ($this->size + 31) >> 3, 0)); - } - - /** - * Gets the size in bits. - */ - public function getSize() : int - { - return $this->size; - } - - /** - * Gets the size in bytes. - */ - public function getSizeInBytes() : int - { - return ($this->size + 7) >> 3; - } - - /** - * Ensures that the array has a minimum capacity. - */ - public function ensureCapacity(int $size) : void - { - if ($size > count($this->bits) << 5) { - $this->bits->setSize(($size + 31) >> 5); - } - } - - /** - * Gets a specific bit. - */ - public function get(int $i) : bool - { - return 0 !== ($this->bits[$i >> 5] & (1 << ($i & 0x1f))); - } - - /** - * Sets a specific bit. - */ - public function set(int $i) : void - { - $this->bits[$i >> 5] = $this->bits[$i >> 5] | 1 << ($i & 0x1f); - } - - /** - * Flips a specific bit. - */ - public function flip(int $i) : void - { - $this->bits[$i >> 5] ^= 1 << ($i & 0x1f); - } - - /** - * Gets the next set bit position from a given position. - */ - public function getNextSet(int $from) : int - { - if ($from >= $this->size) { - return $this->size; - } - - $bitsOffset = $from >> 5; - $currentBits = $this->bits[$bitsOffset]; - $bitsLength = count($this->bits); - $currentBits &= ~((1 << ($from & 0x1f)) - 1); - - while (0 === $currentBits) { - if (++$bitsOffset === $bitsLength) { - return $this->size; - } - - $currentBits = $this->bits[$bitsOffset]; - } - - $result = ($bitsOffset << 5) + BitUtils::numberOfTrailingZeros($currentBits); - return min($result, $this->size); - } - - /** - * Gets the next unset bit position from a given position. - */ - public function getNextUnset(int $from) : int - { - if ($from >= $this->size) { - return $this->size; - } - - $bitsOffset = $from >> 5; - $currentBits = ~$this->bits[$bitsOffset]; - $bitsLength = count($this->bits); - $currentBits &= ~((1 << ($from & 0x1f)) - 1); - - while (0 === $currentBits) { - if (++$bitsOffset === $bitsLength) { - return $this->size; - } - - $currentBits = ~$this->bits[$bitsOffset]; - } - - $result = ($bitsOffset << 5) + BitUtils::numberOfTrailingZeros($currentBits); - return min($result, $this->size); - } - - /** - * Sets a bulk of bits. - */ - public function setBulk(int $i, int $newBits) : void - { - $this->bits[$i >> 5] = $newBits; - } - - /** - * Sets a range of bits. - * - * @throws InvalidArgumentException if end is smaller than start - */ - public function setRange(int $start, int $end) : void - { - if ($end < $start) { - throw new InvalidArgumentException('End must be greater or equal to start'); - } - - if ($end === $start) { - return; - } - - --$end; - - $firstInt = $start >> 5; - $lastInt = $end >> 5; - - for ($i = $firstInt; $i <= $lastInt; ++$i) { - $firstBit = $i > $firstInt ? 0 : $start & 0x1f; - $lastBit = $i < $lastInt ? 31 : $end & 0x1f; - - if (0 === $firstBit && 31 === $lastBit) { - $mask = 0x7fffffff; - } else { - $mask = 0; - - for ($j = $firstBit; $j < $lastBit; ++$j) { - $mask |= 1 << $j; - } - } - - $this->bits[$i] = $this->bits[$i] | $mask; - } - } - - /** - * Clears the bit array, unsetting every bit. - */ - public function clear() : void - { - $bitsLength = count($this->bits); - - for ($i = 0; $i < $bitsLength; ++$i) { - $this->bits[$i] = 0; - } - } - - /** - * Checks if a range of bits is set or not set. - - * @throws InvalidArgumentException if end is smaller than start - */ - public function isRange(int $start, int $end, bool $value) : bool - { - if ($end < $start) { - throw new InvalidArgumentException('End must be greater or equal to start'); - } - - if ($end === $start) { - return true; - } - - --$end; - - $firstInt = $start >> 5; - $lastInt = $end >> 5; - - for ($i = $firstInt; $i <= $lastInt; ++$i) { - $firstBit = $i > $firstInt ? 0 : $start & 0x1f; - $lastBit = $i < $lastInt ? 31 : $end & 0x1f; - - if (0 === $firstBit && 31 === $lastBit) { - $mask = 0x7fffffff; - } else { - $mask = 0; - - for ($j = $firstBit; $j <= $lastBit; ++$j) { - $mask |= 1 << $j; - } - } - - if (($this->bits[$i] & $mask) !== ($value ? $mask : 0)) { - return false; - } - } - - return true; - } - - /** - * Appends a bit to the array. - */ - public function appendBit(bool $bit) : void - { - $this->ensureCapacity($this->size + 1); - - if ($bit) { - $this->bits[$this->size >> 5] = $this->bits[$this->size >> 5] | (1 << ($this->size & 0x1f)); - } - - ++$this->size; - } - - /** - * Appends a number of bits (up to 32) to the array. - - * @throws InvalidArgumentException if num bits is not between 0 and 32 - */ - public function appendBits(int $value, int $numBits) : void - { - if ($numBits < 0 || $numBits > 32) { - throw new InvalidArgumentException('Num bits must be between 0 and 32'); - } - - $this->ensureCapacity($this->size + $numBits); - - for ($numBitsLeft = $numBits; $numBitsLeft > 0; $numBitsLeft--) { - $this->appendBit((($value >> ($numBitsLeft - 1)) & 0x01) === 1); - } - } - - /** - * Appends another bit array to this array. - */ - public function appendBitArray(self $other) : void - { - $otherSize = $other->getSize(); - $this->ensureCapacity($this->size + $other->getSize()); - - for ($i = 0; $i < $otherSize; ++$i) { - $this->appendBit($other->get($i)); - } - } - - /** - * Makes an exclusive-or comparision on the current bit array. - * - * @throws InvalidArgumentException if sizes don't match - */ - public function xorBits(self $other) : void - { - $bitsLength = count($this->bits); - $otherBits = $other->getBitArray(); - - if ($bitsLength !== count($otherBits)) { - throw new InvalidArgumentException('Sizes don\'t match'); - } - - for ($i = 0; $i < $bitsLength; ++$i) { - $this->bits[$i] = $this->bits[$i] ^ $otherBits[$i]; - } - } - - /** - * Converts the bit array to a byte array. - * - * @return SplFixedArray - */ - public function toBytes(int $bitOffset, int $numBytes) : SplFixedArray - { - $bytes = new SplFixedArray($numBytes); - - for ($i = 0; $i < $numBytes; ++$i) { - $byte = 0; - - for ($j = 0; $j < 8; ++$j) { - if ($this->get($bitOffset)) { - $byte |= 1 << (7 - $j); - } - - ++$bitOffset; - } - - $bytes[$i] = $byte; - } - - return $bytes; - } - - /** - * Gets the internal bit array. - * - * @return SplFixedArray - */ - public function getBitArray() : SplFixedArray - { - return $this->bits; - } - - /** - * Reverses the array. - */ - public function reverse() : void - { - $newBits = new SplFixedArray(count($this->bits)); - - for ($i = 0; $i < $this->size; ++$i) { - if ($this->get($this->size - $i - 1)) { - $newBits[$i >> 5] = $newBits[$i >> 5] | (1 << ($i & 0x1f)); - } - } - - $this->bits = $newBits; - } - - /** - * Returns a string representation of the bit array. - */ - public function __toString() : string - { - $result = ''; - - for ($i = 0; $i < $this->size; ++$i) { - if (0 === ($i & 0x07)) { - $result .= ' '; - } - - $result .= $this->get($i) ? 'X' : '.'; - } - - return $result; - } -} + + */ + private SplFixedArray $bits; + + /** + * Creates a new bit array with a given size. + */ + public function __construct(private int $size = 0) + { + $this->bits = SplFixedArray::fromArray(array_fill(0, ($this->size + 31) >> 3, 0)); + } + + /** + * Gets the size in bits. + */ + public function getSize() : int + { + return $this->size; + } + + /** + * Gets the size in bytes. + */ + public function getSizeInBytes() : int + { + return ($this->size + 7) >> 3; + } + + /** + * Ensures that the array has a minimum capacity. + */ + public function ensureCapacity(int $size) : void + { + if ($size > count($this->bits) << 5) { + $this->bits->setSize(($size + 31) >> 5); + } + } + + /** + * Gets a specific bit. + */ + public function get(int $i) : bool + { + return 0 !== ($this->bits[$i >> 5] & (1 << ($i & 0x1f))); + } + + /** + * Sets a specific bit. + */ + public function set(int $i) : void + { + $this->bits[$i >> 5] = $this->bits[$i >> 5] | 1 << ($i & 0x1f); + } + + /** + * Flips a specific bit. + */ + public function flip(int $i) : void + { + $this->bits[$i >> 5] ^= 1 << ($i & 0x1f); + } + + /** + * Gets the next set bit position from a given position. + */ + public function getNextSet(int $from) : int + { + if ($from >= $this->size) { + return $this->size; + } + + $bitsOffset = $from >> 5; + $currentBits = $this->bits[$bitsOffset]; + $bitsLength = count($this->bits); + $currentBits &= ~((1 << ($from & 0x1f)) - 1); + + while (0 === $currentBits) { + if (++$bitsOffset === $bitsLength) { + return $this->size; + } + + $currentBits = $this->bits[$bitsOffset]; + } + + $result = ($bitsOffset << 5) + BitUtils::numberOfTrailingZeros($currentBits); + return min($result, $this->size); + } + + /** + * Gets the next unset bit position from a given position. + */ + public function getNextUnset(int $from) : int + { + if ($from >= $this->size) { + return $this->size; + } + + $bitsOffset = $from >> 5; + $currentBits = ~$this->bits[$bitsOffset]; + $bitsLength = count($this->bits); + $currentBits &= ~((1 << ($from & 0x1f)) - 1); + + while (0 === $currentBits) { + if (++$bitsOffset === $bitsLength) { + return $this->size; + } + + $currentBits = ~$this->bits[$bitsOffset]; + } + + $result = ($bitsOffset << 5) + BitUtils::numberOfTrailingZeros($currentBits); + return min($result, $this->size); + } + + /** + * Sets a bulk of bits. + */ + public function setBulk(int $i, int $newBits) : void + { + $this->bits[$i >> 5] = $newBits; + } + + /** + * Sets a range of bits. + * + * @throws InvalidArgumentException if end is smaller than start + */ + public function setRange(int $start, int $end) : void + { + if ($end < $start) { + throw new InvalidArgumentException('End must be greater or equal to start'); + } + + if ($end === $start) { + return; + } + + --$end; + + $firstInt = $start >> 5; + $lastInt = $end >> 5; + + for ($i = $firstInt; $i <= $lastInt; ++$i) { + $firstBit = $i > $firstInt ? 0 : $start & 0x1f; + $lastBit = $i < $lastInt ? 31 : $end & 0x1f; + + if (0 === $firstBit && 31 === $lastBit) { + $mask = 0x7fffffff; + } else { + $mask = 0; + + for ($j = $firstBit; $j < $lastBit; ++$j) { + $mask |= 1 << $j; + } + } + + $this->bits[$i] = $this->bits[$i] | $mask; + } + } + + /** + * Clears the bit array, unsetting every bit. + */ + public function clear() : void + { + $bitsLength = count($this->bits); + + for ($i = 0; $i < $bitsLength; ++$i) { + $this->bits[$i] = 0; + } + } + + /** + * Checks if a range of bits is set or not set. + + * @throws InvalidArgumentException if end is smaller than start + */ + public function isRange(int $start, int $end, bool $value) : bool + { + if ($end < $start) { + throw new InvalidArgumentException('End must be greater or equal to start'); + } + + if ($end === $start) { + return true; + } + + --$end; + + $firstInt = $start >> 5; + $lastInt = $end >> 5; + + for ($i = $firstInt; $i <= $lastInt; ++$i) { + $firstBit = $i > $firstInt ? 0 : $start & 0x1f; + $lastBit = $i < $lastInt ? 31 : $end & 0x1f; + + if (0 === $firstBit && 31 === $lastBit) { + $mask = 0x7fffffff; + } else { + $mask = 0; + + for ($j = $firstBit; $j <= $lastBit; ++$j) { + $mask |= 1 << $j; + } + } + + if (($this->bits[$i] & $mask) !== ($value ? $mask : 0)) { + return false; + } + } + + return true; + } + + /** + * Appends a bit to the array. + */ + public function appendBit(bool $bit) : void + { + $this->ensureCapacity($this->size + 1); + + if ($bit) { + $this->bits[$this->size >> 5] = $this->bits[$this->size >> 5] | (1 << ($this->size & 0x1f)); + } + + ++$this->size; + } + + /** + * Appends a number of bits (up to 32) to the array. + + * @throws InvalidArgumentException if num bits is not between 0 and 32 + */ + public function appendBits(int $value, int $numBits) : void + { + if ($numBits < 0 || $numBits > 32) { + throw new InvalidArgumentException('Num bits must be between 0 and 32'); + } + + $this->ensureCapacity($this->size + $numBits); + + for ($numBitsLeft = $numBits; $numBitsLeft > 0; $numBitsLeft--) { + $this->appendBit((($value >> ($numBitsLeft - 1)) & 0x01) === 1); + } + } + + /** + * Appends another bit array to this array. + */ + public function appendBitArray(self $other) : void + { + $otherSize = $other->getSize(); + $this->ensureCapacity($this->size + $other->getSize()); + + for ($i = 0; $i < $otherSize; ++$i) { + $this->appendBit($other->get($i)); + } + } + + /** + * Makes an exclusive-or comparision on the current bit array. + * + * @throws InvalidArgumentException if sizes don't match + */ + public function xorBits(self $other) : void + { + $bitsLength = count($this->bits); + $otherBits = $other->getBitArray(); + + if ($bitsLength !== count($otherBits)) { + throw new InvalidArgumentException('Sizes don\'t match'); + } + + for ($i = 0; $i < $bitsLength; ++$i) { + $this->bits[$i] = $this->bits[$i] ^ $otherBits[$i]; + } + } + + /** + * Converts the bit array to a byte array. + * + * @return SplFixedArray + */ + public function toBytes(int $bitOffset, int $numBytes) : SplFixedArray + { + $bytes = new SplFixedArray($numBytes); + + for ($i = 0; $i < $numBytes; ++$i) { + $byte = 0; + + for ($j = 0; $j < 8; ++$j) { + if ($this->get($bitOffset)) { + $byte |= 1 << (7 - $j); + } + + ++$bitOffset; + } + + $bytes[$i] = $byte; + } + + return $bytes; + } + + /** + * Gets the internal bit array. + * + * @return SplFixedArray + */ + public function getBitArray() : SplFixedArray + { + return $this->bits; + } + + /** + * Reverses the array. + */ + public function reverse() : void + { + $newBits = new SplFixedArray(count($this->bits)); + + for ($i = 0; $i < $this->size; ++$i) { + if ($this->get($this->size - $i - 1)) { + $newBits[$i >> 5] = $newBits[$i >> 5] | (1 << ($i & 0x1f)); + } + } + + $this->bits = $newBits; + } + + /** + * Returns a string representation of the bit array. + */ + public function __toString() : string + { + $result = ''; + + for ($i = 0; $i < $this->size; ++$i) { + if (0 === ($i & 0x07)) { + $result .= ' '; + } + + $result .= $this->get($i) ? 'X' : '.'; + } + + return $result; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Common/BitMatrix.php b/vendor/bacon/bacon-qr-code/src/Common/BitMatrix.php index e67388a..294afb4 100644 --- a/vendor/bacon/bacon-qr-code/src/Common/BitMatrix.php +++ b/vendor/bacon/bacon-qr-code/src/Common/BitMatrix.php @@ -1,307 +1,307 @@ - - */ - private SplFixedArray $bits; - - /** - * @throws InvalidArgumentException if a dimension is smaller than zero - */ - public function __construct(int $width, ?int $height = null) - { - if (null === $height) { - $height = $width; - } - - if ($width < 1 || $height < 1) { - throw new InvalidArgumentException('Both dimensions must be greater than zero'); - } - - $this->width = $width; - $this->height = $height; - $this->rowSize = ($width + 31) >> 5; - $this->bits = SplFixedArray::fromArray(array_fill(0, $this->rowSize * $height, 0)); - } - - /** - * Gets the requested bit, where true means black. - */ - public function get(int $x, int $y) : bool - { - $offset = $y * $this->rowSize + ($x >> 5); - return 0 !== (BitUtils::unsignedRightShift($this->bits[$offset], ($x & 0x1f)) & 1); - } - - /** - * Sets the given bit to true. - */ - public function set(int $x, int $y) : void - { - $offset = $y * $this->rowSize + ($x >> 5); - $this->bits[$offset] = $this->bits[$offset] | (1 << ($x & 0x1f)); - } - - /** - * Flips the given bit. - */ - public function flip(int $x, int $y) : void - { - $offset = $y * $this->rowSize + ($x >> 5); - $this->bits[$offset] = $this->bits[$offset] ^ (1 << ($x & 0x1f)); - } - - /** - * Clears all bits (set to false). - */ - public function clear() : void - { - $max = count($this->bits); - - for ($i = 0; $i < $max; ++$i) { - $this->bits[$i] = 0; - } - } - - /** - * Sets a square region of the bit matrix to true. - * - * @throws InvalidArgumentException if left or top are negative - * @throws InvalidArgumentException if width or height are smaller than 1 - * @throws InvalidArgumentException if region does not fit into the matix - */ - public function setRegion(int $left, int $top, int $width, int $height) : void - { - if ($top < 0 || $left < 0) { - throw new InvalidArgumentException('Left and top must be non-negative'); - } - - if ($height < 1 || $width < 1) { - throw new InvalidArgumentException('Width and height must be at least 1'); - } - - $right = $left + $width; - $bottom = $top + $height; - - if ($bottom > $this->height || $right > $this->width) { - throw new InvalidArgumentException('The region must fit inside the matrix'); - } - - for ($y = $top; $y < $bottom; ++$y) { - $offset = $y * $this->rowSize; - - for ($x = $left; $x < $right; ++$x) { - $index = $offset + ($x >> 5); - $this->bits[$index] = $this->bits[$index] | (1 << ($x & 0x1f)); - } - } - } - - /** - * A fast method to retrieve one row of data from the matrix as a BitArray. - */ - public function getRow(int $y, ?BitArray $row = null) : BitArray - { - if (null === $row || $row->getSize() < $this->width) { - $row = new BitArray($this->width); - } - - $offset = $y * $this->rowSize; - - for ($x = 0; $x < $this->rowSize; ++$x) { - $row->setBulk($x << 5, $this->bits[$offset + $x]); - } - - return $row; - } - - /** - * Sets a row of data from a BitArray. - */ - public function setRow(int $y, BitArray $row) : void - { - $bits = $row->getBitArray(); - - for ($i = 0; $i < $this->rowSize; ++$i) { - $this->bits[$y * $this->rowSize + $i] = $bits[$i]; - } - } - - /** - * This is useful in detecting the enclosing rectangle of a 'pure' barcode. - * - * @return int[]|null - */ - public function getEnclosingRectangle() : ?array - { - $left = $this->width; - $top = $this->height; - $right = -1; - $bottom = -1; - - for ($y = 0; $y < $this->height; ++$y) { - for ($x32 = 0; $x32 < $this->rowSize; ++$x32) { - $bits = $this->bits[$y * $this->rowSize + $x32]; - - if (0 !== $bits) { - if ($y < $top) { - $top = $y; - } - - if ($y > $bottom) { - $bottom = $y; - } - - if ($x32 * 32 < $left) { - $bit = 0; - - while (($bits << (31 - $bit)) === 0) { - $bit++; - } - - if (($x32 * 32 + $bit) < $left) { - $left = $x32 * 32 + $bit; - } - } - } - - if ($x32 * 32 + 31 > $right) { - $bit = 31; - - while (0 === BitUtils::unsignedRightShift($bits, $bit)) { - --$bit; - } - - if (($x32 * 32 + $bit) > $right) { - $right = $x32 * 32 + $bit; - } - } - } - } - - $width = $right - $left; - $height = $bottom - $top; - - if ($width < 0 || $height < 0) { - return null; - } - - return [$left, $top, $width, $height]; - } - - /** - * Gets the most top left set bit. - * - * This is useful in detecting a corner of a 'pure' barcode. - * - * @return int[]|null - */ - public function getTopLeftOnBit() : ?array - { - $bitsOffset = 0; - - while ($bitsOffset < count($this->bits) && 0 === $this->bits[$bitsOffset]) { - ++$bitsOffset; - } - - if (count($this->bits) === $bitsOffset) { - return null; - } - - $x = intdiv($bitsOffset, $this->rowSize); - $y = ($bitsOffset % $this->rowSize) << 5; - - $bits = $this->bits[$bitsOffset]; - $bit = 0; - - while (0 === ($bits << (31 - $bit))) { - ++$bit; - } - - $x += $bit; - - return [$x, $y]; - } - - /** - * Gets the most bottom right set bit. - * - * This is useful in detecting a corner of a 'pure' barcode. - * - * @return int[]|null - */ - public function getBottomRightOnBit() : ?array - { - $bitsOffset = count($this->bits) - 1; - - while ($bitsOffset >= 0 && 0 === $this->bits[$bitsOffset]) { - --$bitsOffset; - } - - if ($bitsOffset < 0) { - return null; - } - - $x = intdiv($bitsOffset, $this->rowSize); - $y = ($bitsOffset % $this->rowSize) << 5; - - $bits = $this->bits[$bitsOffset]; - $bit = 0; - - while (0 === BitUtils::unsignedRightShift($bits, $bit)) { - --$bit; - } - - $x += $bit; - - return [$x, $y]; - } - - /** - * Gets the width of the matrix, - */ - public function getWidth() : int - { - return $this->width; - } - - /** - * Gets the height of the matrix. - */ - public function getHeight() : int - { - return $this->height; - } -} + + */ + private SplFixedArray $bits; + + /** + * @throws InvalidArgumentException if a dimension is smaller than zero + */ + public function __construct(int $width, ?int $height = null) + { + if (null === $height) { + $height = $width; + } + + if ($width < 1 || $height < 1) { + throw new InvalidArgumentException('Both dimensions must be greater than zero'); + } + + $this->width = $width; + $this->height = $height; + $this->rowSize = ($width + 31) >> 5; + $this->bits = SplFixedArray::fromArray(array_fill(0, $this->rowSize * $height, 0)); + } + + /** + * Gets the requested bit, where true means black. + */ + public function get(int $x, int $y) : bool + { + $offset = $y * $this->rowSize + ($x >> 5); + return 0 !== (BitUtils::unsignedRightShift($this->bits[$offset], ($x & 0x1f)) & 1); + } + + /** + * Sets the given bit to true. + */ + public function set(int $x, int $y) : void + { + $offset = $y * $this->rowSize + ($x >> 5); + $this->bits[$offset] = $this->bits[$offset] | (1 << ($x & 0x1f)); + } + + /** + * Flips the given bit. + */ + public function flip(int $x, int $y) : void + { + $offset = $y * $this->rowSize + ($x >> 5); + $this->bits[$offset] = $this->bits[$offset] ^ (1 << ($x & 0x1f)); + } + + /** + * Clears all bits (set to false). + */ + public function clear() : void + { + $max = count($this->bits); + + for ($i = 0; $i < $max; ++$i) { + $this->bits[$i] = 0; + } + } + + /** + * Sets a square region of the bit matrix to true. + * + * @throws InvalidArgumentException if left or top are negative + * @throws InvalidArgumentException if width or height are smaller than 1 + * @throws InvalidArgumentException if region does not fit into the matix + */ + public function setRegion(int $left, int $top, int $width, int $height) : void + { + if ($top < 0 || $left < 0) { + throw new InvalidArgumentException('Left and top must be non-negative'); + } + + if ($height < 1 || $width < 1) { + throw new InvalidArgumentException('Width and height must be at least 1'); + } + + $right = $left + $width; + $bottom = $top + $height; + + if ($bottom > $this->height || $right > $this->width) { + throw new InvalidArgumentException('The region must fit inside the matrix'); + } + + for ($y = $top; $y < $bottom; ++$y) { + $offset = $y * $this->rowSize; + + for ($x = $left; $x < $right; ++$x) { + $index = $offset + ($x >> 5); + $this->bits[$index] = $this->bits[$index] | (1 << ($x & 0x1f)); + } + } + } + + /** + * A fast method to retrieve one row of data from the matrix as a BitArray. + */ + public function getRow(int $y, ?BitArray $row = null) : BitArray + { + if (null === $row || $row->getSize() < $this->width) { + $row = new BitArray($this->width); + } + + $offset = $y * $this->rowSize; + + for ($x = 0; $x < $this->rowSize; ++$x) { + $row->setBulk($x << 5, $this->bits[$offset + $x]); + } + + return $row; + } + + /** + * Sets a row of data from a BitArray. + */ + public function setRow(int $y, BitArray $row) : void + { + $bits = $row->getBitArray(); + + for ($i = 0; $i < $this->rowSize; ++$i) { + $this->bits[$y * $this->rowSize + $i] = $bits[$i]; + } + } + + /** + * This is useful in detecting the enclosing rectangle of a 'pure' barcode. + * + * @return int[]|null + */ + public function getEnclosingRectangle() : ?array + { + $left = $this->width; + $top = $this->height; + $right = -1; + $bottom = -1; + + for ($y = 0; $y < $this->height; ++$y) { + for ($x32 = 0; $x32 < $this->rowSize; ++$x32) { + $bits = $this->bits[$y * $this->rowSize + $x32]; + + if (0 !== $bits) { + if ($y < $top) { + $top = $y; + } + + if ($y > $bottom) { + $bottom = $y; + } + + if ($x32 * 32 < $left) { + $bit = 0; + + while (($bits << (31 - $bit)) === 0) { + $bit++; + } + + if (($x32 * 32 + $bit) < $left) { + $left = $x32 * 32 + $bit; + } + } + } + + if ($x32 * 32 + 31 > $right) { + $bit = 31; + + while (0 === BitUtils::unsignedRightShift($bits, $bit)) { + --$bit; + } + + if (($x32 * 32 + $bit) > $right) { + $right = $x32 * 32 + $bit; + } + } + } + } + + $width = $right - $left; + $height = $bottom - $top; + + if ($width < 0 || $height < 0) { + return null; + } + + return [$left, $top, $width, $height]; + } + + /** + * Gets the most top left set bit. + * + * This is useful in detecting a corner of a 'pure' barcode. + * + * @return int[]|null + */ + public function getTopLeftOnBit() : ?array + { + $bitsOffset = 0; + + while ($bitsOffset < count($this->bits) && 0 === $this->bits[$bitsOffset]) { + ++$bitsOffset; + } + + if (count($this->bits) === $bitsOffset) { + return null; + } + + $x = intdiv($bitsOffset, $this->rowSize); + $y = ($bitsOffset % $this->rowSize) << 5; + + $bits = $this->bits[$bitsOffset]; + $bit = 0; + + while (0 === ($bits << (31 - $bit))) { + ++$bit; + } + + $x += $bit; + + return [$x, $y]; + } + + /** + * Gets the most bottom right set bit. + * + * This is useful in detecting a corner of a 'pure' barcode. + * + * @return int[]|null + */ + public function getBottomRightOnBit() : ?array + { + $bitsOffset = count($this->bits) - 1; + + while ($bitsOffset >= 0 && 0 === $this->bits[$bitsOffset]) { + --$bitsOffset; + } + + if ($bitsOffset < 0) { + return null; + } + + $x = intdiv($bitsOffset, $this->rowSize); + $y = ($bitsOffset % $this->rowSize) << 5; + + $bits = $this->bits[$bitsOffset]; + $bit = 0; + + while (0 === BitUtils::unsignedRightShift($bits, $bit)) { + --$bit; + } + + $x += $bit; + + return [$x, $y]; + } + + /** + * Gets the width of the matrix, + */ + public function getWidth() : int + { + return $this->width; + } + + /** + * Gets the height of the matrix. + */ + public function getHeight() : int + { + return $this->height; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Common/BitUtils.php b/vendor/bacon/bacon-qr-code/src/Common/BitUtils.php index 9a0ed6f..0c575b4 100644 --- a/vendor/bacon/bacon-qr-code/src/Common/BitUtils.php +++ b/vendor/bacon/bacon-qr-code/src/Common/BitUtils.php @@ -1,41 +1,41 @@ ->>" in other - * languages. - */ - public static function unsignedRightShift(int $a, int $b) : int - { - return ( - $a >= 0 - ? $a >> $b - : (($a & 0x7fffffff) >> $b) | (0x40000000 >> ($b - 1)) - ); - } - - /** - * Gets the number of trailing zeros. - */ - public static function numberOfTrailingZeros(int $i) : int - { - $lastPos = strrpos(str_pad(decbin($i), 32, '0', STR_PAD_LEFT), '1'); - return $lastPos === false ? 32 : 31 - $lastPos; - } -} +>>" in other + * languages. + */ + public static function unsignedRightShift(int $a, int $b) : int + { + return ( + $a >= 0 + ? $a >> $b + : (($a & 0x7fffffff) >> $b) | (0x40000000 >> ($b - 1)) + ); + } + + /** + * Gets the number of trailing zeros. + */ + public static function numberOfTrailingZeros(int $i) : int + { + $lastPos = strrpos(str_pad(decbin($i), 32, '0', STR_PAD_LEFT), '1'); + return $lastPos === false ? 32 : 31 - $lastPos; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Common/CharacterSetEci.php b/vendor/bacon/bacon-qr-code/src/Common/CharacterSetEci.php index 847d558..8b62b8c 100644 --- a/vendor/bacon/bacon-qr-code/src/Common/CharacterSetEci.php +++ b/vendor/bacon/bacon-qr-code/src/Common/CharacterSetEci.php @@ -1,177 +1,177 @@ -|null - */ - private static ?array $valueToEci; - - /** - * @var array|null - */ - private static ?array $nameToEci = null; - - /** - * @param int[] $values - */ - public function __construct(private readonly array $values, string ...$otherEncodingNames) - { - $this->otherEncodingNames = $otherEncodingNames; - } - - /** - * Returns the primary value. - */ - public function getValue() : int - { - return $this->values[0]; - } - - /** - * Gets character set ECI by value. - * - * Returns the representing ECI of a given value, or null if it is legal but unsupported. - * - * @throws InvalidArgumentException if value is not between 0 and 900 - */ - public static function getCharacterSetEciByValue(int $value) : ?self - { - if ($value < 0 || $value >= 900) { - throw new InvalidArgumentException('Value must be between 0 and 900'); - } - - $valueToEci = self::valueToEci(); - - if (! array_key_exists($value, $valueToEci)) { - return null; - } - - return $valueToEci[$value]; - } - - /** - * Returns character set ECI by name. - * - * Returns the representing ECI of a given name, or null if it is legal but unsupported - */ - public static function getCharacterSetEciByName(string $name) : ?self - { - $nameToEci = self::nameToEci(); - $name = strtolower($name); - - if (! array_key_exists($name, $nameToEci)) { - return null; - } - - return $nameToEci[$name]; - } - - private static function valueToEci() : array - { - if (null !== self::$valueToEci) { - return self::$valueToEci; - } - - self::$valueToEci = []; - - foreach (self::values() as $eci) { - foreach ($eci->values as $value) { - self::$valueToEci[$value] = $eci; - } - } - - return self::$valueToEci; - } - - private static function nameToEci() : array - { - if (null !== self::$nameToEci) { - return self::$nameToEci; - } - - self::$nameToEci = []; - - foreach (self::values() as $eci) { - self::$nameToEci[strtolower($eci->name())] = $eci; - - foreach ($eci->otherEncodingNames as $name) { - self::$nameToEci[strtolower($name)] = $eci; - } - } - - return self::$nameToEci; - } -} +|null + */ + private static ?array $valueToEci; + + /** + * @var array|null + */ + private static ?array $nameToEci = null; + + /** + * @param int[] $values + */ + public function __construct(private readonly array $values, string ...$otherEncodingNames) + { + $this->otherEncodingNames = $otherEncodingNames; + } + + /** + * Returns the primary value. + */ + public function getValue() : int + { + return $this->values[0]; + } + + /** + * Gets character set ECI by value. + * + * Returns the representing ECI of a given value, or null if it is legal but unsupported. + * + * @throws InvalidArgumentException if value is not between 0 and 900 + */ + public static function getCharacterSetEciByValue(int $value) : ?self + { + if ($value < 0 || $value >= 900) { + throw new InvalidArgumentException('Value must be between 0 and 900'); + } + + $valueToEci = self::valueToEci(); + + if (! array_key_exists($value, $valueToEci)) { + return null; + } + + return $valueToEci[$value]; + } + + /** + * Returns character set ECI by name. + * + * Returns the representing ECI of a given name, or null if it is legal but unsupported + */ + public static function getCharacterSetEciByName(string $name) : ?self + { + $nameToEci = self::nameToEci(); + $name = strtolower($name); + + if (! array_key_exists($name, $nameToEci)) { + return null; + } + + return $nameToEci[$name]; + } + + private static function valueToEci() : array + { + if (null !== self::$valueToEci) { + return self::$valueToEci; + } + + self::$valueToEci = []; + + foreach (self::values() as $eci) { + foreach ($eci->values as $value) { + self::$valueToEci[$value] = $eci; + } + } + + return self::$valueToEci; + } + + private static function nameToEci() : array + { + if (null !== self::$nameToEci) { + return self::$nameToEci; + } + + self::$nameToEci = []; + + foreach (self::values() as $eci) { + self::$nameToEci[strtolower($eci->name())] = $eci; + + foreach ($eci->otherEncodingNames as $name) { + self::$nameToEci[strtolower($name)] = $eci; + } + } + + return self::$nameToEci; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Common/EcBlock.php b/vendor/bacon/bacon-qr-code/src/Common/EcBlock.php index ca57a5a..bc9e865 100644 --- a/vendor/bacon/bacon-qr-code/src/Common/EcBlock.php +++ b/vendor/bacon/bacon-qr-code/src/Common/EcBlock.php @@ -1,33 +1,33 @@ -count; - } - - /** - * Returns the number of data codewords. - */ - public function getDataCodewords() : int - { - return $this->dataCodewords; - } -} +count; + } + + /** + * Returns the number of data codewords. + */ + public function getDataCodewords() : int + { + return $this->dataCodewords; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Common/EcBlocks.php b/vendor/bacon/bacon-qr-code/src/Common/EcBlocks.php index 1fac620..63c52a9 100644 --- a/vendor/bacon/bacon-qr-code/src/Common/EcBlocks.php +++ b/vendor/bacon/bacon-qr-code/src/Common/EcBlocks.php @@ -1,66 +1,66 @@ -ecBlocks = $ecBlocks; - } - - /** - * Returns the number of EC codewords per block. - */ - public function getEcCodewordsPerBlock() : int - { - return $this->ecCodewordsPerBlock; - } - - /** - * Returns the total number of EC block appearances. - */ - public function getNumBlocks() : int - { - $total = 0; - - foreach ($this->ecBlocks as $ecBlock) { - $total += $ecBlock->getCount(); - } - - return $total; - } - - /** - * Returns the total count of EC codewords. - */ - public function getTotalEcCodewords() : int - { - return $this->ecCodewordsPerBlock * $this->getNumBlocks(); - } - - /** - * Returns the EC blocks included in this collection. - * - * @return EcBlock[] - */ - public function getEcBlocks() : array - { - return $this->ecBlocks; - } -} +ecBlocks = $ecBlocks; + } + + /** + * Returns the number of EC codewords per block. + */ + public function getEcCodewordsPerBlock() : int + { + return $this->ecCodewordsPerBlock; + } + + /** + * Returns the total number of EC block appearances. + */ + public function getNumBlocks() : int + { + $total = 0; + + foreach ($this->ecBlocks as $ecBlock) { + $total += $ecBlock->getCount(); + } + + return $total; + } + + /** + * Returns the total count of EC codewords. + */ + public function getTotalEcCodewords() : int + { + return $this->ecCodewordsPerBlock * $this->getNumBlocks(); + } + + /** + * Returns the EC blocks included in this collection. + * + * @return EcBlock[] + */ + public function getEcBlocks() : array + { + return $this->ecBlocks; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Common/ErrorCorrectionLevel.php b/vendor/bacon/bacon-qr-code/src/Common/ErrorCorrectionLevel.php index d3932ab..ac84d66 100644 --- a/vendor/bacon/bacon-qr-code/src/Common/ErrorCorrectionLevel.php +++ b/vendor/bacon/bacon-qr-code/src/Common/ErrorCorrectionLevel.php @@ -1,57 +1,57 @@ -bits; - } -} +bits; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Common/FormatInformation.php b/vendor/bacon/bacon-qr-code/src/Common/FormatInformation.php index 846972d..6a5da0b 100644 --- a/vendor/bacon/bacon-qr-code/src/Common/FormatInformation.php +++ b/vendor/bacon/bacon-qr-code/src/Common/FormatInformation.php @@ -1,196 +1,196 @@ -ecLevel = ErrorCorrectionLevel::forBits(($formatInfo >> 3) & 0x3); - $this->dataMask = $formatInfo & 0x7; - } - - /** - * Checks how many bits are different between two integers. - */ - public static function numBitsDiffering(int $a, int $b) : int - { - $a ^= $b; - - return ( - self::BITS_SET_IN_HALF_BYTE[$a & 0xf] - + self::BITS_SET_IN_HALF_BYTE[(BitUtils::unsignedRightShift($a, 4) & 0xf)] - + self::BITS_SET_IN_HALF_BYTE[(BitUtils::unsignedRightShift($a, 8) & 0xf)] - + self::BITS_SET_IN_HALF_BYTE[(BitUtils::unsignedRightShift($a, 12) & 0xf)] - + self::BITS_SET_IN_HALF_BYTE[(BitUtils::unsignedRightShift($a, 16) & 0xf)] - + self::BITS_SET_IN_HALF_BYTE[(BitUtils::unsignedRightShift($a, 20) & 0xf)] - + self::BITS_SET_IN_HALF_BYTE[(BitUtils::unsignedRightShift($a, 24) & 0xf)] - + self::BITS_SET_IN_HALF_BYTE[(BitUtils::unsignedRightShift($a, 28) & 0xf)] - ); - } - - /** - * Decodes format information. - */ - public static function decodeFormatInformation(int $maskedFormatInfo1, int $maskedFormatInfo2) : ?self - { - $formatInfo = self::doDecodeFormatInformation($maskedFormatInfo1, $maskedFormatInfo2); - - if (null !== $formatInfo) { - return $formatInfo; - } - - // Should return null, but, some QR codes apparently do not mask this info. Try again by actually masking the - // pattern first. - return self::doDecodeFormatInformation( - $maskedFormatInfo1 ^ self::FORMAT_INFO_MASK_QR, - $maskedFormatInfo2 ^ self::FORMAT_INFO_MASK_QR - ); - } - - /** - * Internal method for decoding format information. - */ - private static function doDecodeFormatInformation(int $maskedFormatInfo1, int $maskedFormatInfo2) : ?self - { - $bestDifference = PHP_INT_MAX; - $bestFormatInfo = 0; - - foreach (self::FORMAT_INFO_DECODE_LOOKUP as $decodeInfo) { - $targetInfo = $decodeInfo[0]; - - if ($targetInfo === $maskedFormatInfo1 || $targetInfo === $maskedFormatInfo2) { - // Found an exact match - return new self($decodeInfo[1]); - } - - $bitsDifference = self::numBitsDiffering($maskedFormatInfo1, $targetInfo); - - if ($bitsDifference < $bestDifference) { - $bestFormatInfo = $decodeInfo[1]; - $bestDifference = $bitsDifference; - } - - if ($maskedFormatInfo1 !== $maskedFormatInfo2) { - // Also try the other option - $bitsDifference = self::numBitsDiffering($maskedFormatInfo2, $targetInfo); - - if ($bitsDifference < $bestDifference) { - $bestFormatInfo = $decodeInfo[1]; - $bestDifference = $bitsDifference; - } - } - } - - // Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits differing means we found a match. - if ($bestDifference <= 3) { - return new self($bestFormatInfo); - } - - return null; - } - - /** - * Returns the error correction level. - */ - public function getErrorCorrectionLevel() : ErrorCorrectionLevel - { - return $this->ecLevel; - } - - /** - * Returns the data mask. - */ - public function getDataMask() : int - { - return $this->dataMask; - } - - /** - * Hashes the code of the EC level. - */ - public function hashCode() : int - { - return ($this->ecLevel->getBits() << 3) | $this->dataMask; - } - - /** - * Verifies if this instance equals another one. - */ - public function equals(self $other) : bool - { - return ( - $this->ecLevel === $other->ecLevel - && $this->dataMask === $other->dataMask - ); - } -} +ecLevel = ErrorCorrectionLevel::forBits(($formatInfo >> 3) & 0x3); + $this->dataMask = $formatInfo & 0x7; + } + + /** + * Checks how many bits are different between two integers. + */ + public static function numBitsDiffering(int $a, int $b) : int + { + $a ^= $b; + + return ( + self::BITS_SET_IN_HALF_BYTE[$a & 0xf] + + self::BITS_SET_IN_HALF_BYTE[(BitUtils::unsignedRightShift($a, 4) & 0xf)] + + self::BITS_SET_IN_HALF_BYTE[(BitUtils::unsignedRightShift($a, 8) & 0xf)] + + self::BITS_SET_IN_HALF_BYTE[(BitUtils::unsignedRightShift($a, 12) & 0xf)] + + self::BITS_SET_IN_HALF_BYTE[(BitUtils::unsignedRightShift($a, 16) & 0xf)] + + self::BITS_SET_IN_HALF_BYTE[(BitUtils::unsignedRightShift($a, 20) & 0xf)] + + self::BITS_SET_IN_HALF_BYTE[(BitUtils::unsignedRightShift($a, 24) & 0xf)] + + self::BITS_SET_IN_HALF_BYTE[(BitUtils::unsignedRightShift($a, 28) & 0xf)] + ); + } + + /** + * Decodes format information. + */ + public static function decodeFormatInformation(int $maskedFormatInfo1, int $maskedFormatInfo2) : ?self + { + $formatInfo = self::doDecodeFormatInformation($maskedFormatInfo1, $maskedFormatInfo2); + + if (null !== $formatInfo) { + return $formatInfo; + } + + // Should return null, but, some QR codes apparently do not mask this info. Try again by actually masking the + // pattern first. + return self::doDecodeFormatInformation( + $maskedFormatInfo1 ^ self::FORMAT_INFO_MASK_QR, + $maskedFormatInfo2 ^ self::FORMAT_INFO_MASK_QR + ); + } + + /** + * Internal method for decoding format information. + */ + private static function doDecodeFormatInformation(int $maskedFormatInfo1, int $maskedFormatInfo2) : ?self + { + $bestDifference = PHP_INT_MAX; + $bestFormatInfo = 0; + + foreach (self::FORMAT_INFO_DECODE_LOOKUP as $decodeInfo) { + $targetInfo = $decodeInfo[0]; + + if ($targetInfo === $maskedFormatInfo1 || $targetInfo === $maskedFormatInfo2) { + // Found an exact match + return new self($decodeInfo[1]); + } + + $bitsDifference = self::numBitsDiffering($maskedFormatInfo1, $targetInfo); + + if ($bitsDifference < $bestDifference) { + $bestFormatInfo = $decodeInfo[1]; + $bestDifference = $bitsDifference; + } + + if ($maskedFormatInfo1 !== $maskedFormatInfo2) { + // Also try the other option + $bitsDifference = self::numBitsDiffering($maskedFormatInfo2, $targetInfo); + + if ($bitsDifference < $bestDifference) { + $bestFormatInfo = $decodeInfo[1]; + $bestDifference = $bitsDifference; + } + } + } + + // Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits differing means we found a match. + if ($bestDifference <= 3) { + return new self($bestFormatInfo); + } + + return null; + } + + /** + * Returns the error correction level. + */ + public function getErrorCorrectionLevel() : ErrorCorrectionLevel + { + return $this->ecLevel; + } + + /** + * Returns the data mask. + */ + public function getDataMask() : int + { + return $this->dataMask; + } + + /** + * Hashes the code of the EC level. + */ + public function hashCode() : int + { + return ($this->ecLevel->getBits() << 3) | $this->dataMask; + } + + /** + * Verifies if this instance equals another one. + */ + public function equals(self $other) : bool + { + return ( + $this->ecLevel === $other->ecLevel + && $this->dataMask === $other->dataMask + ); + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Common/Mode.php b/vendor/bacon/bacon-qr-code/src/Common/Mode.php index eeb3c4e..f5fb153 100644 --- a/vendor/bacon/bacon-qr-code/src/Common/Mode.php +++ b/vendor/bacon/bacon-qr-code/src/Common/Mode.php @@ -1,69 +1,69 @@ -getVersionNumber(); - - if ($number <= 9) { - $offset = 0; - } elseif ($number <= 26) { - $offset = 1; - } else { - $offset = 2; - } - - return $this->characterCountBitsForVersions[$offset]; - } - - /** - * Returns the four bits used to encode this mode. - */ - public function getBits() : int - { - return $this->bits; - } -} +getVersionNumber(); + + if ($number <= 9) { + $offset = 0; + } elseif ($number <= 26) { + $offset = 1; + } else { + $offset = 2; + } + + return $this->characterCountBitsForVersions[$offset]; + } + + /** + * Returns the four bits used to encode this mode. + */ + public function getBits() : int + { + return $this->bits; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Common/ReedSolomonCodec.php b/vendor/bacon/bacon-qr-code/src/Common/ReedSolomonCodec.php index ac6835b..d16a75e 100644 --- a/vendor/bacon/bacon-qr-code/src/Common/ReedSolomonCodec.php +++ b/vendor/bacon/bacon-qr-code/src/Common/ReedSolomonCodec.php @@ -1,454 +1,454 @@ - 8) { - throw new InvalidArgumentException('Symbol size must be between 0 and 8'); - } - - if ($firstRoot < 0 || $firstRoot >= (1 << $symbolSize)) { - throw new InvalidArgumentException('First root must be between 0 and ' . (1 << $symbolSize)); - } - - if ($numRoots < 0 || $numRoots >= (1 << $symbolSize)) { - throw new InvalidArgumentException('Num roots must be between 0 and ' . (1 << $symbolSize)); - } - - if ($padding < 0 || $padding >= ((1 << $symbolSize) - 1 - $numRoots)) { - throw new InvalidArgumentException( - 'Padding must be between 0 and ' . ((1 << $symbolSize) - 1 - $numRoots) - ); - } - - $this->symbolSize = $symbolSize; - $this->blockSize = (1 << $symbolSize) - 1; - $this->padding = $padding; - $this->alphaTo = SplFixedArray::fromArray(array_fill(0, $this->blockSize + 1, 0), false); - $this->indexOf = SplFixedArray::fromArray(array_fill(0, $this->blockSize + 1, 0), false); - - // Generate galous field lookup table - $this->indexOf[0] = $this->blockSize; - $this->alphaTo[$this->blockSize] = 0; - - $sr = 1; - - for ($i = 0; $i < $this->blockSize; ++$i) { - $this->indexOf[$sr] = $i; - $this->alphaTo[$i] = $sr; - - $sr <<= 1; - - if ($sr & (1 << $symbolSize)) { - $sr ^= $gfPoly; - } - - $sr &= $this->blockSize; - } - - if (1 !== $sr) { - throw new RuntimeException('Field generator polynomial is not primitive'); - } - - // Form RS code generator polynomial from its roots - $this->generatorPoly = SplFixedArray::fromArray(array_fill(0, $numRoots + 1, 0), false); - $this->firstRoot = $firstRoot; - $this->primitive = $primitive; - $this->numRoots = $numRoots; - - // Find prim-th root of 1, used in decoding - for ($iPrimitive = 1; ($iPrimitive % $primitive) !== 0; $iPrimitive += $this->blockSize) { - } - - $this->iPrimitive = intdiv($iPrimitive, $primitive); - - $this->generatorPoly[0] = 1; - - for ($i = 0, $root = $firstRoot * $primitive; $i < $numRoots; ++$i, $root += $primitive) { - $this->generatorPoly[$i + 1] = 1; - - for ($j = $i; $j > 0; $j--) { - if ($this->generatorPoly[$j] !== 0) { - $this->generatorPoly[$j] = $this->generatorPoly[$j - 1] ^ $this->alphaTo[ - $this->modNn($this->indexOf[$this->generatorPoly[$j]] + $root) - ]; - } else { - $this->generatorPoly[$j] = $this->generatorPoly[$j - 1]; - } - } - - $this->generatorPoly[$j] = $this->alphaTo[$this->modNn($this->indexOf[$this->generatorPoly[0]] + $root)]; - } - - // Convert generator poly to index form for quicker encoding - for ($i = 0; $i <= $numRoots; ++$i) { - $this->generatorPoly[$i] = $this->indexOf[$this->generatorPoly[$i]]; - } - } - - /** - * Encodes data and writes result back into parity array. - */ - public function encode(SplFixedArray $data, SplFixedArray $parity) : void - { - for ($i = 0; $i < $this->numRoots; ++$i) { - $parity[$i] = 0; - } - - $iterations = $this->blockSize - $this->numRoots - $this->padding; - - for ($i = 0; $i < $iterations; ++$i) { - $feedback = $this->indexOf[$data[$i] ^ $parity[0]]; - - if ($feedback !== $this->blockSize) { - // Feedback term is non-zero - $feedback = $this->modNn($this->blockSize - $this->generatorPoly[$this->numRoots] + $feedback); - - for ($j = 1; $j < $this->numRoots; ++$j) { - $parity[$j] = $parity[$j] ^ $this->alphaTo[ - $this->modNn($feedback + $this->generatorPoly[$this->numRoots - $j]) - ]; - } - } - - for ($j = 0; $j < $this->numRoots - 1; ++$j) { - $parity[$j] = $parity[$j + 1]; - } - - if ($feedback !== $this->blockSize) { - $parity[$this->numRoots - 1] = $this->alphaTo[$this->modNn($feedback + $this->generatorPoly[0])]; - } else { - $parity[$this->numRoots - 1] = 0; - } - } - } - - /** - * Decodes received data. - */ - public function decode(SplFixedArray $data, ?SplFixedArray $erasures = null) : ?int - { - // This speeds up the initialization a bit. - $numRootsPlusOne = SplFixedArray::fromArray(array_fill(0, $this->numRoots + 1, 0), false); - $numRoots = SplFixedArray::fromArray(array_fill(0, $this->numRoots, 0), false); - - $lambda = clone $numRootsPlusOne; - $b = clone $numRootsPlusOne; - $t = clone $numRootsPlusOne; - $omega = clone $numRootsPlusOne; - $root = clone $numRoots; - $loc = clone $numRoots; - - $numErasures = (null !== $erasures ? count($erasures) : 0); - - // Form the Syndromes; i.e., evaluate data(x) at roots of g(x) - $syndromes = SplFixedArray::fromArray(array_fill(0, $this->numRoots, $data[0]), false); - - for ($i = 1; $i < $this->blockSize - $this->padding; ++$i) { - for ($j = 0; $j < $this->numRoots; ++$j) { - if ($syndromes[$j] === 0) { - $syndromes[$j] = $data[$i]; - } else { - $syndromes[$j] = $data[$i] ^ $this->alphaTo[ - $this->modNn($this->indexOf[$syndromes[$j]] + ($this->firstRoot + $j) * $this->primitive) - ]; - } - } - } - - // Convert syndromes to index form, checking for nonzero conditions - $syndromeError = 0; - - for ($i = 0; $i < $this->numRoots; ++$i) { - $syndromeError |= $syndromes[$i]; - $syndromes[$i] = $this->indexOf[$syndromes[$i]]; - } - - if (! $syndromeError) { - // If syndrome is zero, data[] is a codeword and there are no errors to correct, so return data[] - // unmodified. - return 0; - } - - $lambda[0] = 1; - - if ($numErasures > 0) { - // Init lambda to be the erasure locator polynomial - $lambda[1] = $this->alphaTo[$this->modNn($this->primitive * ($this->blockSize - 1 - $erasures[0]))]; - - for ($i = 1; $i < $numErasures; ++$i) { - $u = $this->modNn($this->primitive * ($this->blockSize - 1 - $erasures[$i])); - - for ($j = $i + 1; $j > 0; --$j) { - $tmp = $this->indexOf[$lambda[$j - 1]]; - - if ($tmp !== $this->blockSize) { - $lambda[$j] = $lambda[$j] ^ $this->alphaTo[$this->modNn($u + $tmp)]; - } - } - } - } - - for ($i = 0; $i <= $this->numRoots; ++$i) { - $b[$i] = $this->indexOf[$lambda[$i]]; - } - - // Begin Berlekamp-Massey algorithm to determine error+erasure locator polynomial - $r = $numErasures; - $el = $numErasures; - - while (++$r <= $this->numRoots) { - // Compute discrepancy at the r-th step in poly form - $discrepancyR = 0; - - for ($i = 0; $i < $r; ++$i) { - if ($lambda[$i] !== 0 && $syndromes[$r - $i - 1] !== $this->blockSize) { - $discrepancyR ^= $this->alphaTo[ - $this->modNn($this->indexOf[$lambda[$i]] + $syndromes[$r - $i - 1]) - ]; - } - } - - $discrepancyR = $this->indexOf[$discrepancyR]; - - if ($discrepancyR === $this->blockSize) { - $tmp = $b->toArray(); - array_unshift($tmp, $this->blockSize); - array_pop($tmp); - $b = SplFixedArray::fromArray($tmp, false); - continue; - } - - $t[0] = $lambda[0]; - - for ($i = 0; $i < $this->numRoots; ++$i) { - if ($b[$i] !== $this->blockSize) { - $t[$i + 1] = $lambda[$i + 1] ^ $this->alphaTo[$this->modNn($discrepancyR + $b[$i])]; - } else { - $t[$i + 1] = $lambda[$i + 1]; - } - } - - if (2 * $el <= $r + $numErasures - 1) { - $el = $r + $numErasures - $el; - - for ($i = 0; $i <= $this->numRoots; ++$i) { - $b[$i] = ( - $lambda[$i] === 0 - ? $this->blockSize - : $this->modNn($this->indexOf[$lambda[$i]] - $discrepancyR + $this->blockSize) - ); - } - } else { - $tmp = $b->toArray(); - array_unshift($tmp, $this->blockSize); - array_pop($tmp); - $b = SplFixedArray::fromArray($tmp, false); - } - - $lambda = clone $t; - } - - // Convert lambda to index form and compute deg(lambda(x)) - $degLambda = 0; - - for ($i = 0; $i <= $this->numRoots; ++$i) { - $lambda[$i] = $this->indexOf[$lambda[$i]]; - - if ($lambda[$i] !== $this->blockSize) { - $degLambda = $i; - } - } - - // Find roots of the error+erasure locator polynomial by Chien search. - $reg = clone $lambda; - $reg[0] = 0; - $count = 0; - $i = 1; - - for ($k = $this->iPrimitive - 1; $i <= $this->blockSize; ++$i, $k = $this->modNn($k + $this->iPrimitive)) { - $q = 1; - - for ($j = $degLambda; $j > 0; $j--) { - if ($reg[$j] !== $this->blockSize) { - $reg[$j] = $this->modNn($reg[$j] + $j); - $q ^= $this->alphaTo[$reg[$j]]; - } - } - - if ($q !== 0) { - // Not a root - continue; - } - - // Store root (index-form) and error location number - $root[$count] = $i; - $loc[$count] = $k; - - if (++$count === $degLambda) { - break; - } - } - - if ($degLambda !== $count) { - // deg(lambda) unequal to number of roots: uncorrectable error detected - return null; - } - - // Compute err+eras evaluate poly omega(x) = s(x)*lambda(x) (modulo x**numRoots). In index form. Also find - // deg(omega). - $degOmega = $degLambda - 1; - - for ($i = 0; $i <= $degOmega; ++$i) { - $tmp = 0; - - for ($j = $i; $j >= 0; --$j) { - if ($syndromes[$i - $j] !== $this->blockSize && $lambda[$j] !== $this->blockSize) { - $tmp ^= $this->alphaTo[$this->modNn($syndromes[$i - $j] + $lambda[$j])]; - } - } - - $omega[$i] = $this->indexOf[$tmp]; - } - - // Compute error values in poly-form. num1 = omega(inv(X(l))), num2 = inv(X(l))**(firstRoot-1) and - // den = lambda_pr(inv(X(l))) all in poly form. - for ($j = $count - 1; $j >= 0; --$j) { - $num1 = 0; - - for ($i = $degOmega; $i >= 0; $i--) { - if ($omega[$i] !== $this->blockSize) { - $num1 ^= $this->alphaTo[$this->modNn($omega[$i] + $i * $root[$j])]; - } - } - - $num2 = $this->alphaTo[$this->modNn($root[$j] * ($this->firstRoot - 1) + $this->blockSize)]; - $den = 0; - - // lambda[i+1] for i even is the formal derivativelambda_pr of lambda[i] - for ($i = min($degLambda, $this->numRoots - 1) & ~1; $i >= 0; $i -= 2) { - if ($lambda[$i + 1] !== $this->blockSize) { - $den ^= $this->alphaTo[$this->modNn($lambda[$i + 1] + $i * $root[$j])]; - } - } - - // Apply error to data - if ($num1 !== 0 && $loc[$j] >= $this->padding) { - $data[$loc[$j] - $this->padding] = $data[$loc[$j] - $this->padding] ^ ( - $this->alphaTo[ - $this->modNn( - $this->indexOf[$num1] + $this->indexOf[$num2] + $this->blockSize - $this->indexOf[$den] - ) - ] - ); - } - } - - if (null !== $erasures) { - if (count($erasures) < $count) { - $erasures->setSize($count); - } - - for ($i = 0; $i < $count; $i++) { - $erasures[$i] = $loc[$i]; - } - } - - return $count; - } - - /** - * Computes $x % GF_SIZE, where GF_SIZE is 2**GF_BITS - 1, without a slow divide. - */ - private function modNn(int $x) : int - { - while ($x >= $this->blockSize) { - $x -= $this->blockSize; - $x = ($x >> $this->symbolSize) + ($x & $this->blockSize); - } - - return $x; - } -} + 8) { + throw new InvalidArgumentException('Symbol size must be between 0 and 8'); + } + + if ($firstRoot < 0 || $firstRoot >= (1 << $symbolSize)) { + throw new InvalidArgumentException('First root must be between 0 and ' . (1 << $symbolSize)); + } + + if ($numRoots < 0 || $numRoots >= (1 << $symbolSize)) { + throw new InvalidArgumentException('Num roots must be between 0 and ' . (1 << $symbolSize)); + } + + if ($padding < 0 || $padding >= ((1 << $symbolSize) - 1 - $numRoots)) { + throw new InvalidArgumentException( + 'Padding must be between 0 and ' . ((1 << $symbolSize) - 1 - $numRoots) + ); + } + + $this->symbolSize = $symbolSize; + $this->blockSize = (1 << $symbolSize) - 1; + $this->padding = $padding; + $this->alphaTo = SplFixedArray::fromArray(array_fill(0, $this->blockSize + 1, 0), false); + $this->indexOf = SplFixedArray::fromArray(array_fill(0, $this->blockSize + 1, 0), false); + + // Generate galous field lookup table + $this->indexOf[0] = $this->blockSize; + $this->alphaTo[$this->blockSize] = 0; + + $sr = 1; + + for ($i = 0; $i < $this->blockSize; ++$i) { + $this->indexOf[$sr] = $i; + $this->alphaTo[$i] = $sr; + + $sr <<= 1; + + if ($sr & (1 << $symbolSize)) { + $sr ^= $gfPoly; + } + + $sr &= $this->blockSize; + } + + if (1 !== $sr) { + throw new RuntimeException('Field generator polynomial is not primitive'); + } + + // Form RS code generator polynomial from its roots + $this->generatorPoly = SplFixedArray::fromArray(array_fill(0, $numRoots + 1, 0), false); + $this->firstRoot = $firstRoot; + $this->primitive = $primitive; + $this->numRoots = $numRoots; + + // Find prim-th root of 1, used in decoding + for ($iPrimitive = 1; ($iPrimitive % $primitive) !== 0; $iPrimitive += $this->blockSize) { + } + + $this->iPrimitive = intdiv($iPrimitive, $primitive); + + $this->generatorPoly[0] = 1; + + for ($i = 0, $root = $firstRoot * $primitive; $i < $numRoots; ++$i, $root += $primitive) { + $this->generatorPoly[$i + 1] = 1; + + for ($j = $i; $j > 0; $j--) { + if ($this->generatorPoly[$j] !== 0) { + $this->generatorPoly[$j] = $this->generatorPoly[$j - 1] ^ $this->alphaTo[ + $this->modNn($this->indexOf[$this->generatorPoly[$j]] + $root) + ]; + } else { + $this->generatorPoly[$j] = $this->generatorPoly[$j - 1]; + } + } + + $this->generatorPoly[$j] = $this->alphaTo[$this->modNn($this->indexOf[$this->generatorPoly[0]] + $root)]; + } + + // Convert generator poly to index form for quicker encoding + for ($i = 0; $i <= $numRoots; ++$i) { + $this->generatorPoly[$i] = $this->indexOf[$this->generatorPoly[$i]]; + } + } + + /** + * Encodes data and writes result back into parity array. + */ + public function encode(SplFixedArray $data, SplFixedArray $parity) : void + { + for ($i = 0; $i < $this->numRoots; ++$i) { + $parity[$i] = 0; + } + + $iterations = $this->blockSize - $this->numRoots - $this->padding; + + for ($i = 0; $i < $iterations; ++$i) { + $feedback = $this->indexOf[$data[$i] ^ $parity[0]]; + + if ($feedback !== $this->blockSize) { + // Feedback term is non-zero + $feedback = $this->modNn($this->blockSize - $this->generatorPoly[$this->numRoots] + $feedback); + + for ($j = 1; $j < $this->numRoots; ++$j) { + $parity[$j] = $parity[$j] ^ $this->alphaTo[ + $this->modNn($feedback + $this->generatorPoly[$this->numRoots - $j]) + ]; + } + } + + for ($j = 0; $j < $this->numRoots - 1; ++$j) { + $parity[$j] = $parity[$j + 1]; + } + + if ($feedback !== $this->blockSize) { + $parity[$this->numRoots - 1] = $this->alphaTo[$this->modNn($feedback + $this->generatorPoly[0])]; + } else { + $parity[$this->numRoots - 1] = 0; + } + } + } + + /** + * Decodes received data. + */ + public function decode(SplFixedArray $data, ?SplFixedArray $erasures = null) : ?int + { + // This speeds up the initialization a bit. + $numRootsPlusOne = SplFixedArray::fromArray(array_fill(0, $this->numRoots + 1, 0), false); + $numRoots = SplFixedArray::fromArray(array_fill(0, $this->numRoots, 0), false); + + $lambda = clone $numRootsPlusOne; + $b = clone $numRootsPlusOne; + $t = clone $numRootsPlusOne; + $omega = clone $numRootsPlusOne; + $root = clone $numRoots; + $loc = clone $numRoots; + + $numErasures = (null !== $erasures ? count($erasures) : 0); + + // Form the Syndromes; i.e., evaluate data(x) at roots of g(x) + $syndromes = SplFixedArray::fromArray(array_fill(0, $this->numRoots, $data[0]), false); + + for ($i = 1; $i < $this->blockSize - $this->padding; ++$i) { + for ($j = 0; $j < $this->numRoots; ++$j) { + if ($syndromes[$j] === 0) { + $syndromes[$j] = $data[$i]; + } else { + $syndromes[$j] = $data[$i] ^ $this->alphaTo[ + $this->modNn($this->indexOf[$syndromes[$j]] + ($this->firstRoot + $j) * $this->primitive) + ]; + } + } + } + + // Convert syndromes to index form, checking for nonzero conditions + $syndromeError = 0; + + for ($i = 0; $i < $this->numRoots; ++$i) { + $syndromeError |= $syndromes[$i]; + $syndromes[$i] = $this->indexOf[$syndromes[$i]]; + } + + if (! $syndromeError) { + // If syndrome is zero, data[] is a codeword and there are no errors to correct, so return data[] + // unmodified. + return 0; + } + + $lambda[0] = 1; + + if ($numErasures > 0) { + // Init lambda to be the erasure locator polynomial + $lambda[1] = $this->alphaTo[$this->modNn($this->primitive * ($this->blockSize - 1 - $erasures[0]))]; + + for ($i = 1; $i < $numErasures; ++$i) { + $u = $this->modNn($this->primitive * ($this->blockSize - 1 - $erasures[$i])); + + for ($j = $i + 1; $j > 0; --$j) { + $tmp = $this->indexOf[$lambda[$j - 1]]; + + if ($tmp !== $this->blockSize) { + $lambda[$j] = $lambda[$j] ^ $this->alphaTo[$this->modNn($u + $tmp)]; + } + } + } + } + + for ($i = 0; $i <= $this->numRoots; ++$i) { + $b[$i] = $this->indexOf[$lambda[$i]]; + } + + // Begin Berlekamp-Massey algorithm to determine error+erasure locator polynomial + $r = $numErasures; + $el = $numErasures; + + while (++$r <= $this->numRoots) { + // Compute discrepancy at the r-th step in poly form + $discrepancyR = 0; + + for ($i = 0; $i < $r; ++$i) { + if ($lambda[$i] !== 0 && $syndromes[$r - $i - 1] !== $this->blockSize) { + $discrepancyR ^= $this->alphaTo[ + $this->modNn($this->indexOf[$lambda[$i]] + $syndromes[$r - $i - 1]) + ]; + } + } + + $discrepancyR = $this->indexOf[$discrepancyR]; + + if ($discrepancyR === $this->blockSize) { + $tmp = $b->toArray(); + array_unshift($tmp, $this->blockSize); + array_pop($tmp); + $b = SplFixedArray::fromArray($tmp, false); + continue; + } + + $t[0] = $lambda[0]; + + for ($i = 0; $i < $this->numRoots; ++$i) { + if ($b[$i] !== $this->blockSize) { + $t[$i + 1] = $lambda[$i + 1] ^ $this->alphaTo[$this->modNn($discrepancyR + $b[$i])]; + } else { + $t[$i + 1] = $lambda[$i + 1]; + } + } + + if (2 * $el <= $r + $numErasures - 1) { + $el = $r + $numErasures - $el; + + for ($i = 0; $i <= $this->numRoots; ++$i) { + $b[$i] = ( + $lambda[$i] === 0 + ? $this->blockSize + : $this->modNn($this->indexOf[$lambda[$i]] - $discrepancyR + $this->blockSize) + ); + } + } else { + $tmp = $b->toArray(); + array_unshift($tmp, $this->blockSize); + array_pop($tmp); + $b = SplFixedArray::fromArray($tmp, false); + } + + $lambda = clone $t; + } + + // Convert lambda to index form and compute deg(lambda(x)) + $degLambda = 0; + + for ($i = 0; $i <= $this->numRoots; ++$i) { + $lambda[$i] = $this->indexOf[$lambda[$i]]; + + if ($lambda[$i] !== $this->blockSize) { + $degLambda = $i; + } + } + + // Find roots of the error+erasure locator polynomial by Chien search. + $reg = clone $lambda; + $reg[0] = 0; + $count = 0; + $i = 1; + + for ($k = $this->iPrimitive - 1; $i <= $this->blockSize; ++$i, $k = $this->modNn($k + $this->iPrimitive)) { + $q = 1; + + for ($j = $degLambda; $j > 0; $j--) { + if ($reg[$j] !== $this->blockSize) { + $reg[$j] = $this->modNn($reg[$j] + $j); + $q ^= $this->alphaTo[$reg[$j]]; + } + } + + if ($q !== 0) { + // Not a root + continue; + } + + // Store root (index-form) and error location number + $root[$count] = $i; + $loc[$count] = $k; + + if (++$count === $degLambda) { + break; + } + } + + if ($degLambda !== $count) { + // deg(lambda) unequal to number of roots: uncorrectable error detected + return null; + } + + // Compute err+eras evaluate poly omega(x) = s(x)*lambda(x) (modulo x**numRoots). In index form. Also find + // deg(omega). + $degOmega = $degLambda - 1; + + for ($i = 0; $i <= $degOmega; ++$i) { + $tmp = 0; + + for ($j = $i; $j >= 0; --$j) { + if ($syndromes[$i - $j] !== $this->blockSize && $lambda[$j] !== $this->blockSize) { + $tmp ^= $this->alphaTo[$this->modNn($syndromes[$i - $j] + $lambda[$j])]; + } + } + + $omega[$i] = $this->indexOf[$tmp]; + } + + // Compute error values in poly-form. num1 = omega(inv(X(l))), num2 = inv(X(l))**(firstRoot-1) and + // den = lambda_pr(inv(X(l))) all in poly form. + for ($j = $count - 1; $j >= 0; --$j) { + $num1 = 0; + + for ($i = $degOmega; $i >= 0; $i--) { + if ($omega[$i] !== $this->blockSize) { + $num1 ^= $this->alphaTo[$this->modNn($omega[$i] + $i * $root[$j])]; + } + } + + $num2 = $this->alphaTo[$this->modNn($root[$j] * ($this->firstRoot - 1) + $this->blockSize)]; + $den = 0; + + // lambda[i+1] for i even is the formal derivativelambda_pr of lambda[i] + for ($i = min($degLambda, $this->numRoots - 1) & ~1; $i >= 0; $i -= 2) { + if ($lambda[$i + 1] !== $this->blockSize) { + $den ^= $this->alphaTo[$this->modNn($lambda[$i + 1] + $i * $root[$j])]; + } + } + + // Apply error to data + if ($num1 !== 0 && $loc[$j] >= $this->padding) { + $data[$loc[$j] - $this->padding] = $data[$loc[$j] - $this->padding] ^ ( + $this->alphaTo[ + $this->modNn( + $this->indexOf[$num1] + $this->indexOf[$num2] + $this->blockSize - $this->indexOf[$den] + ) + ] + ); + } + } + + if (null !== $erasures) { + if (count($erasures) < $count) { + $erasures->setSize($count); + } + + for ($i = 0; $i < $count; $i++) { + $erasures[$i] = $loc[$i]; + } + } + + return $count; + } + + /** + * Computes $x % GF_SIZE, where GF_SIZE is 2**GF_BITS - 1, without a slow divide. + */ + private function modNn(int $x) : int + { + while ($x >= $this->blockSize) { + $x -= $this->blockSize; + $x = ($x >> $this->symbolSize) + ($x & $this->blockSize); + } + + return $x; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Common/Version.php b/vendor/bacon/bacon-qr-code/src/Common/Version.php index 2a52519..68d3d16 100644 --- a/vendor/bacon/bacon-qr-code/src/Common/Version.php +++ b/vendor/bacon/bacon-qr-code/src/Common/Version.php @@ -1,592 +1,592 @@ -|null - */ - private static ?array $versions = null; - - /** - * @param int[] $alignmentPatternCenters - */ - private function __construct( - int $versionNumber, - array $alignmentPatternCenters, - EcBlocks ...$ecBlocks - ) { - $this->versionNumber = $versionNumber; - $this->alignmentPatternCenters = $alignmentPatternCenters; - $this->ecBlocks = $ecBlocks; - - $totalCodewords = 0; - $ecCodewords = $ecBlocks[0]->getEcCodewordsPerBlock(); - - foreach ($ecBlocks[0]->getEcBlocks() as $ecBlock) { - $totalCodewords += $ecBlock->getCount() * ($ecBlock->getDataCodewords() + $ecCodewords); - } - - $this->totalCodewords = $totalCodewords; - } - - /** - * Returns the version number. - */ - public function getVersionNumber() : int - { - return $this->versionNumber; - } - - /** - * Returns the alignment pattern centers. - * - * @return int[] - */ - public function getAlignmentPatternCenters() : array - { - return $this->alignmentPatternCenters; - } - - /** - * Returns the total number of codewords. - */ - public function getTotalCodewords() : int - { - return $this->totalCodewords; - } - - /** - * Calculates the dimension for the current version. - */ - public function getDimensionForVersion() : int - { - return 17 + 4 * $this->versionNumber; - } - - /** - * Returns the number of EC blocks for a specific EC level. - */ - public function getEcBlocksForLevel(ErrorCorrectionLevel $ecLevel) : EcBlocks - { - return $this->ecBlocks[$ecLevel->ordinal()]; - } - - /** - * Gets a provisional version number for a specific dimension. - * - * @throws InvalidArgumentException if dimension is not 1 mod 4 - */ - public static function getProvisionalVersionForDimension(int $dimension) : self - { - if (1 !== $dimension % 4) { - throw new InvalidArgumentException('Dimension is not 1 mod 4'); - } - - return self::getVersionForNumber(intdiv($dimension - 17, 4)); - } - - /** - * Gets a version instance for a specific version number. - * - * @throws InvalidArgumentException if version number is out of range - */ - public static function getVersionForNumber(int $versionNumber) : self - { - if ($versionNumber < 1 || $versionNumber > 40) { - throw new InvalidArgumentException('Version number must be between 1 and 40'); - } - - return self::versions()[$versionNumber - 1]; - } - - /** - * Decodes version information from an integer and returns the version. - */ - public static function decodeVersionInformation(int $versionBits) : ?self - { - $bestDifference = PHP_INT_MAX; - $bestVersion = 0; - - foreach (self::VERSION_DECODE_INFO as $i => $targetVersion) { - if ($targetVersion === $versionBits) { - return self::getVersionForNumber($i + 7); - } - - $bitsDifference = FormatInformation::numBitsDiffering($versionBits, $targetVersion); - - if ($bitsDifference < $bestDifference) { - $bestVersion = $i + 7; - $bestDifference = $bitsDifference; - } - } - - if ($bestDifference <= 3) { - return self::getVersionForNumber($bestVersion); - } - - return null; - } - - /** - * Builds the function pattern for the current version. - */ - public function buildFunctionPattern() : BitMatrix - { - $dimension = $this->getDimensionForVersion(); - $bitMatrix = new BitMatrix($dimension); - - // Top left finder pattern + separator + format - $bitMatrix->setRegion(0, 0, 9, 9); - // Top right finder pattern + separator + format - $bitMatrix->setRegion($dimension - 8, 0, 8, 9); - // Bottom left finder pattern + separator + format - $bitMatrix->setRegion(0, $dimension - 8, 9, 8); - - // Alignment patterns - $max = count($this->alignmentPatternCenters); - - for ($x = 0; $x < $max; ++$x) { - $i = $this->alignmentPatternCenters[$x] - 2; - - for ($y = 0; $y < $max; ++$y) { - if (($x === 0 && ($y === 0 || $y === $max - 1)) || ($x === $max - 1 && $y === 0)) { - // No alignment patterns near the three finder paterns - continue; - } - - $bitMatrix->setRegion($this->alignmentPatternCenters[$y] - 2, $i, 5, 5); - } - } - - // Vertical timing pattern - $bitMatrix->setRegion(6, 9, 1, $dimension - 17); - // Horizontal timing pattern - $bitMatrix->setRegion(9, 6, $dimension - 17, 1); - - if ($this->versionNumber > 6) { - // Version info, top right - $bitMatrix->setRegion($dimension - 11, 0, 3, 6); - // Version info, bottom left - $bitMatrix->setRegion(0, $dimension - 11, 6, 3); - } - - return $bitMatrix; - } - - /** - * Returns a string representation for the version. - */ - public function __toString() : string - { - return (string) $this->versionNumber; - } - - /** - * Build and cache a specific version. - * - * See ISO 18004:2006 6.5.1 Table 9. - * - * @return array - */ - private static function versions() : array - { - if (null !== self::$versions) { - return self::$versions; - } - - return self::$versions = [ - new self( - 1, - [], - new EcBlocks(7, new EcBlock(1, 19)), - new EcBlocks(10, new EcBlock(1, 16)), - new EcBlocks(13, new EcBlock(1, 13)), - new EcBlocks(17, new EcBlock(1, 9)) - ), - new self( - 2, - [6, 18], - new EcBlocks(10, new EcBlock(1, 34)), - new EcBlocks(16, new EcBlock(1, 28)), - new EcBlocks(22, new EcBlock(1, 22)), - new EcBlocks(28, new EcBlock(1, 16)) - ), - new self( - 3, - [6, 22], - new EcBlocks(15, new EcBlock(1, 55)), - new EcBlocks(26, new EcBlock(1, 44)), - new EcBlocks(18, new EcBlock(2, 17)), - new EcBlocks(22, new EcBlock(2, 13)) - ), - new self( - 4, - [6, 26], - new EcBlocks(20, new EcBlock(1, 80)), - new EcBlocks(18, new EcBlock(2, 32)), - new EcBlocks(26, new EcBlock(2, 24)), - new EcBlocks(16, new EcBlock(4, 9)) - ), - new self( - 5, - [6, 30], - new EcBlocks(26, new EcBlock(1, 108)), - new EcBlocks(24, new EcBlock(2, 43)), - new EcBlocks(18, new EcBlock(2, 15), new EcBlock(2, 16)), - new EcBlocks(22, new EcBlock(2, 11), new EcBlock(2, 12)) - ), - new self( - 6, - [6, 34], - new EcBlocks(18, new EcBlock(2, 68)), - new EcBlocks(16, new EcBlock(4, 27)), - new EcBlocks(24, new EcBlock(4, 19)), - new EcBlocks(28, new EcBlock(4, 15)) - ), - new self( - 7, - [6, 22, 38], - new EcBlocks(20, new EcBlock(2, 78)), - new EcBlocks(18, new EcBlock(4, 31)), - new EcBlocks(18, new EcBlock(2, 14), new EcBlock(4, 15)), - new EcBlocks(26, new EcBlock(4, 13), new EcBlock(1, 14)) - ), - new self( - 8, - [6, 24, 42], - new EcBlocks(24, new EcBlock(2, 97)), - new EcBlocks(22, new EcBlock(2, 38), new EcBlock(2, 39)), - new EcBlocks(22, new EcBlock(4, 18), new EcBlock(2, 19)), - new EcBlocks(26, new EcBlock(4, 14), new EcBlock(2, 15)) - ), - new self( - 9, - [6, 26, 46], - new EcBlocks(30, new EcBlock(2, 116)), - new EcBlocks(22, new EcBlock(3, 36), new EcBlock(2, 37)), - new EcBlocks(20, new EcBlock(4, 16), new EcBlock(4, 17)), - new EcBlocks(24, new EcBlock(4, 12), new EcBlock(4, 13)) - ), - new self( - 10, - [6, 28, 50], - new EcBlocks(18, new EcBlock(2, 68), new EcBlock(2, 69)), - new EcBlocks(26, new EcBlock(4, 43), new EcBlock(1, 44)), - new EcBlocks(24, new EcBlock(6, 19), new EcBlock(2, 20)), - new EcBlocks(28, new EcBlock(6, 15), new EcBlock(2, 16)) - ), - new self( - 11, - [6, 30, 54], - new EcBlocks(20, new EcBlock(4, 81)), - new EcBlocks(30, new EcBlock(1, 50), new EcBlock(4, 51)), - new EcBlocks(28, new EcBlock(4, 22), new EcBlock(4, 23)), - new EcBlocks(24, new EcBlock(3, 12), new EcBlock(8, 13)) - ), - new self( - 12, - [6, 32, 58], - new EcBlocks(24, new EcBlock(2, 92), new EcBlock(2, 93)), - new EcBlocks(22, new EcBlock(6, 36), new EcBlock(2, 37)), - new EcBlocks(26, new EcBlock(4, 20), new EcBlock(6, 21)), - new EcBlocks(28, new EcBlock(7, 14), new EcBlock(4, 15)) - ), - new self( - 13, - [6, 34, 62], - new EcBlocks(26, new EcBlock(4, 107)), - new EcBlocks(22, new EcBlock(8, 37), new EcBlock(1, 38)), - new EcBlocks(24, new EcBlock(8, 20), new EcBlock(4, 21)), - new EcBlocks(22, new EcBlock(12, 11), new EcBlock(4, 12)) - ), - new self( - 14, - [6, 26, 46, 66], - new EcBlocks(30, new EcBlock(3, 115), new EcBlock(1, 116)), - new EcBlocks(24, new EcBlock(4, 40), new EcBlock(5, 41)), - new EcBlocks(20, new EcBlock(11, 16), new EcBlock(5, 17)), - new EcBlocks(24, new EcBlock(11, 12), new EcBlock(5, 13)) - ), - new self( - 15, - [6, 26, 48, 70], - new EcBlocks(22, new EcBlock(5, 87), new EcBlock(1, 88)), - new EcBlocks(24, new EcBlock(5, 41), new EcBlock(5, 42)), - new EcBlocks(30, new EcBlock(5, 24), new EcBlock(7, 25)), - new EcBlocks(24, new EcBlock(11, 12), new EcBlock(7, 13)) - ), - new self( - 16, - [6, 26, 50, 74], - new EcBlocks(24, new EcBlock(5, 98), new EcBlock(1, 99)), - new EcBlocks(28, new EcBlock(7, 45), new EcBlock(3, 46)), - new EcBlocks(24, new EcBlock(15, 19), new EcBlock(2, 20)), - new EcBlocks(30, new EcBlock(3, 15), new EcBlock(13, 16)) - ), - new self( - 17, - [6, 30, 54, 78], - new EcBlocks(28, new EcBlock(1, 107), new EcBlock(5, 108)), - new EcBlocks(28, new EcBlock(10, 46), new EcBlock(1, 47)), - new EcBlocks(28, new EcBlock(1, 22), new EcBlock(15, 23)), - new EcBlocks(28, new EcBlock(2, 14), new EcBlock(17, 15)) - ), - new self( - 18, - [6, 30, 56, 82], - new EcBlocks(30, new EcBlock(5, 120), new EcBlock(1, 121)), - new EcBlocks(26, new EcBlock(9, 43), new EcBlock(4, 44)), - new EcBlocks(28, new EcBlock(17, 22), new EcBlock(1, 23)), - new EcBlocks(28, new EcBlock(2, 14), new EcBlock(19, 15)) - ), - new self( - 19, - [6, 30, 58, 86], - new EcBlocks(28, new EcBlock(3, 113), new EcBlock(4, 114)), - new EcBlocks(26, new EcBlock(3, 44), new EcBlock(11, 45)), - new EcBlocks(26, new EcBlock(17, 21), new EcBlock(4, 22)), - new EcBlocks(26, new EcBlock(9, 13), new EcBlock(16, 14)) - ), - new self( - 20, - [6, 34, 62, 90], - new EcBlocks(28, new EcBlock(3, 107), new EcBlock(5, 108)), - new EcBlocks(26, new EcBlock(3, 41), new EcBlock(13, 42)), - new EcBlocks(30, new EcBlock(15, 24), new EcBlock(5, 25)), - new EcBlocks(28, new EcBlock(15, 15), new EcBlock(10, 16)) - ), - new self( - 21, - [6, 28, 50, 72, 94], - new EcBlocks(28, new EcBlock(4, 116), new EcBlock(4, 117)), - new EcBlocks(26, new EcBlock(17, 42)), - new EcBlocks(28, new EcBlock(17, 22), new EcBlock(6, 23)), - new EcBlocks(30, new EcBlock(19, 16), new EcBlock(6, 17)) - ), - new self( - 22, - [6, 26, 50, 74, 98], - new EcBlocks(28, new EcBlock(2, 111), new EcBlock(7, 112)), - new EcBlocks(28, new EcBlock(17, 46)), - new EcBlocks(30, new EcBlock(7, 24), new EcBlock(16, 25)), - new EcBlocks(24, new EcBlock(34, 13)) - ), - new self( - 23, - [6, 30, 54, 78, 102], - new EcBlocks(30, new EcBlock(4, 121), new EcBlock(5, 122)), - new EcBlocks(28, new EcBlock(4, 47), new EcBlock(14, 48)), - new EcBlocks(30, new EcBlock(11, 24), new EcBlock(14, 25)), - new EcBlocks(30, new EcBlock(16, 15), new EcBlock(14, 16)) - ), - new self( - 24, - [6, 28, 54, 80, 106], - new EcBlocks(30, new EcBlock(6, 117), new EcBlock(4, 118)), - new EcBlocks(28, new EcBlock(6, 45), new EcBlock(14, 46)), - new EcBlocks(30, new EcBlock(11, 24), new EcBlock(16, 25)), - new EcBlocks(30, new EcBlock(30, 16), new EcBlock(2, 17)) - ), - new self( - 25, - [6, 32, 58, 84, 110], - new EcBlocks(26, new EcBlock(8, 106), new EcBlock(4, 107)), - new EcBlocks(28, new EcBlock(8, 47), new EcBlock(13, 48)), - new EcBlocks(30, new EcBlock(7, 24), new EcBlock(22, 25)), - new EcBlocks(30, new EcBlock(22, 15), new EcBlock(13, 16)) - ), - new self( - 26, - [6, 30, 58, 86, 114], - new EcBlocks(28, new EcBlock(10, 114), new EcBlock(2, 115)), - new EcBlocks(28, new EcBlock(19, 46), new EcBlock(4, 47)), - new EcBlocks(28, new EcBlock(28, 22), new EcBlock(6, 23)), - new EcBlocks(30, new EcBlock(33, 16), new EcBlock(4, 17)) - ), - new self( - 27, - [6, 34, 62, 90, 118], - new EcBlocks(30, new EcBlock(8, 122), new EcBlock(4, 123)), - new EcBlocks(28, new EcBlock(22, 45), new EcBlock(3, 46)), - new EcBlocks(30, new EcBlock(8, 23), new EcBlock(26, 24)), - new EcBlocks(30, new EcBlock(12, 15), new EcBlock(28, 16)) - ), - new self( - 28, - [6, 26, 50, 74, 98, 122], - new EcBlocks(30, new EcBlock(3, 117), new EcBlock(10, 118)), - new EcBlocks(28, new EcBlock(3, 45), new EcBlock(23, 46)), - new EcBlocks(30, new EcBlock(4, 24), new EcBlock(31, 25)), - new EcBlocks(30, new EcBlock(11, 15), new EcBlock(31, 16)) - ), - new self( - 29, - [6, 30, 54, 78, 102, 126], - new EcBlocks(30, new EcBlock(7, 116), new EcBlock(7, 117)), - new EcBlocks(28, new EcBlock(21, 45), new EcBlock(7, 46)), - new EcBlocks(30, new EcBlock(1, 23), new EcBlock(37, 24)), - new EcBlocks(30, new EcBlock(19, 15), new EcBlock(26, 16)) - ), - new self( - 30, - [6, 26, 52, 78, 104, 130], - new EcBlocks(30, new EcBlock(5, 115), new EcBlock(10, 116)), - new EcBlocks(28, new EcBlock(19, 47), new EcBlock(10, 48)), - new EcBlocks(30, new EcBlock(15, 24), new EcBlock(25, 25)), - new EcBlocks(30, new EcBlock(23, 15), new EcBlock(25, 16)) - ), - new self( - 31, - [6, 30, 56, 82, 108, 134], - new EcBlocks(30, new EcBlock(13, 115), new EcBlock(3, 116)), - new EcBlocks(28, new EcBlock(2, 46), new EcBlock(29, 47)), - new EcBlocks(30, new EcBlock(42, 24), new EcBlock(1, 25)), - new EcBlocks(30, new EcBlock(23, 15), new EcBlock(28, 16)) - ), - new self( - 32, - [6, 34, 60, 86, 112, 138], - new EcBlocks(30, new EcBlock(17, 115)), - new EcBlocks(28, new EcBlock(10, 46), new EcBlock(23, 47)), - new EcBlocks(30, new EcBlock(10, 24), new EcBlock(35, 25)), - new EcBlocks(30, new EcBlock(19, 15), new EcBlock(35, 16)) - ), - new self( - 33, - [6, 30, 58, 86, 114, 142], - new EcBlocks(30, new EcBlock(17, 115), new EcBlock(1, 116)), - new EcBlocks(28, new EcBlock(14, 46), new EcBlock(21, 47)), - new EcBlocks(30, new EcBlock(29, 24), new EcBlock(19, 25)), - new EcBlocks(30, new EcBlock(11, 15), new EcBlock(46, 16)) - ), - new self( - 34, - [6, 34, 62, 90, 118, 146], - new EcBlocks(30, new EcBlock(13, 115), new EcBlock(6, 116)), - new EcBlocks(28, new EcBlock(14, 46), new EcBlock(23, 47)), - new EcBlocks(30, new EcBlock(44, 24), new EcBlock(7, 25)), - new EcBlocks(30, new EcBlock(59, 16), new EcBlock(1, 17)) - ), - new self( - 35, - [6, 30, 54, 78, 102, 126, 150], - new EcBlocks(30, new EcBlock(12, 121), new EcBlock(7, 122)), - new EcBlocks(28, new EcBlock(12, 47), new EcBlock(26, 48)), - new EcBlocks(30, new EcBlock(39, 24), new EcBlock(14, 25)), - new EcBlocks(30, new EcBlock(22, 15), new EcBlock(41, 16)) - ), - new self( - 36, - [6, 24, 50, 76, 102, 128, 154], - new EcBlocks(30, new EcBlock(6, 121), new EcBlock(14, 122)), - new EcBlocks(28, new EcBlock(6, 47), new EcBlock(34, 48)), - new EcBlocks(30, new EcBlock(46, 24), new EcBlock(10, 25)), - new EcBlocks(30, new EcBlock(2, 15), new EcBlock(64, 16)) - ), - new self( - 37, - [6, 28, 54, 80, 106, 132, 158], - new EcBlocks(30, new EcBlock(17, 122), new EcBlock(4, 123)), - new EcBlocks(28, new EcBlock(29, 46), new EcBlock(14, 47)), - new EcBlocks(30, new EcBlock(49, 24), new EcBlock(10, 25)), - new EcBlocks(30, new EcBlock(24, 15), new EcBlock(46, 16)) - ), - new self( - 38, - [6, 32, 58, 84, 110, 136, 162], - new EcBlocks(30, new EcBlock(4, 122), new EcBlock(18, 123)), - new EcBlocks(28, new EcBlock(13, 46), new EcBlock(32, 47)), - new EcBlocks(30, new EcBlock(48, 24), new EcBlock(14, 25)), - new EcBlocks(30, new EcBlock(42, 15), new EcBlock(32, 16)) - ), - new self( - 39, - [6, 26, 54, 82, 110, 138, 166], - new EcBlocks(30, new EcBlock(20, 117), new EcBlock(4, 118)), - new EcBlocks(28, new EcBlock(40, 47), new EcBlock(7, 48)), - new EcBlocks(30, new EcBlock(43, 24), new EcBlock(22, 25)), - new EcBlocks(30, new EcBlock(10, 15), new EcBlock(67, 16)) - ), - new self( - 40, - [6, 30, 58, 86, 114, 142, 170], - new EcBlocks(30, new EcBlock(19, 118), new EcBlock(6, 119)), - new EcBlocks(28, new EcBlock(18, 47), new EcBlock(31, 48)), - new EcBlocks(30, new EcBlock(34, 24), new EcBlock(34, 25)), - new EcBlocks(30, new EcBlock(20, 15), new EcBlock(61, 16)) - ), - ]; - } -} +|null + */ + private static ?array $versions = null; + + /** + * @param int[] $alignmentPatternCenters + */ + private function __construct( + int $versionNumber, + array $alignmentPatternCenters, + EcBlocks ...$ecBlocks + ) { + $this->versionNumber = $versionNumber; + $this->alignmentPatternCenters = $alignmentPatternCenters; + $this->ecBlocks = $ecBlocks; + + $totalCodewords = 0; + $ecCodewords = $ecBlocks[0]->getEcCodewordsPerBlock(); + + foreach ($ecBlocks[0]->getEcBlocks() as $ecBlock) { + $totalCodewords += $ecBlock->getCount() * ($ecBlock->getDataCodewords() + $ecCodewords); + } + + $this->totalCodewords = $totalCodewords; + } + + /** + * Returns the version number. + */ + public function getVersionNumber() : int + { + return $this->versionNumber; + } + + /** + * Returns the alignment pattern centers. + * + * @return int[] + */ + public function getAlignmentPatternCenters() : array + { + return $this->alignmentPatternCenters; + } + + /** + * Returns the total number of codewords. + */ + public function getTotalCodewords() : int + { + return $this->totalCodewords; + } + + /** + * Calculates the dimension for the current version. + */ + public function getDimensionForVersion() : int + { + return 17 + 4 * $this->versionNumber; + } + + /** + * Returns the number of EC blocks for a specific EC level. + */ + public function getEcBlocksForLevel(ErrorCorrectionLevel $ecLevel) : EcBlocks + { + return $this->ecBlocks[$ecLevel->ordinal()]; + } + + /** + * Gets a provisional version number for a specific dimension. + * + * @throws InvalidArgumentException if dimension is not 1 mod 4 + */ + public static function getProvisionalVersionForDimension(int $dimension) : self + { + if (1 !== $dimension % 4) { + throw new InvalidArgumentException('Dimension is not 1 mod 4'); + } + + return self::getVersionForNumber(intdiv($dimension - 17, 4)); + } + + /** + * Gets a version instance for a specific version number. + * + * @throws InvalidArgumentException if version number is out of range + */ + public static function getVersionForNumber(int $versionNumber) : self + { + if ($versionNumber < 1 || $versionNumber > 40) { + throw new InvalidArgumentException('Version number must be between 1 and 40'); + } + + return self::versions()[$versionNumber - 1]; + } + + /** + * Decodes version information from an integer and returns the version. + */ + public static function decodeVersionInformation(int $versionBits) : ?self + { + $bestDifference = PHP_INT_MAX; + $bestVersion = 0; + + foreach (self::VERSION_DECODE_INFO as $i => $targetVersion) { + if ($targetVersion === $versionBits) { + return self::getVersionForNumber($i + 7); + } + + $bitsDifference = FormatInformation::numBitsDiffering($versionBits, $targetVersion); + + if ($bitsDifference < $bestDifference) { + $bestVersion = $i + 7; + $bestDifference = $bitsDifference; + } + } + + if ($bestDifference <= 3) { + return self::getVersionForNumber($bestVersion); + } + + return null; + } + + /** + * Builds the function pattern for the current version. + */ + public function buildFunctionPattern() : BitMatrix + { + $dimension = $this->getDimensionForVersion(); + $bitMatrix = new BitMatrix($dimension); + + // Top left finder pattern + separator + format + $bitMatrix->setRegion(0, 0, 9, 9); + // Top right finder pattern + separator + format + $bitMatrix->setRegion($dimension - 8, 0, 8, 9); + // Bottom left finder pattern + separator + format + $bitMatrix->setRegion(0, $dimension - 8, 9, 8); + + // Alignment patterns + $max = count($this->alignmentPatternCenters); + + for ($x = 0; $x < $max; ++$x) { + $i = $this->alignmentPatternCenters[$x] - 2; + + for ($y = 0; $y < $max; ++$y) { + if (($x === 0 && ($y === 0 || $y === $max - 1)) || ($x === $max - 1 && $y === 0)) { + // No alignment patterns near the three finder paterns + continue; + } + + $bitMatrix->setRegion($this->alignmentPatternCenters[$y] - 2, $i, 5, 5); + } + } + + // Vertical timing pattern + $bitMatrix->setRegion(6, 9, 1, $dimension - 17); + // Horizontal timing pattern + $bitMatrix->setRegion(9, 6, $dimension - 17, 1); + + if ($this->versionNumber > 6) { + // Version info, top right + $bitMatrix->setRegion($dimension - 11, 0, 3, 6); + // Version info, bottom left + $bitMatrix->setRegion(0, $dimension - 11, 6, 3); + } + + return $bitMatrix; + } + + /** + * Returns a string representation for the version. + */ + public function __toString() : string + { + return (string) $this->versionNumber; + } + + /** + * Build and cache a specific version. + * + * See ISO 18004:2006 6.5.1 Table 9. + * + * @return array + */ + private static function versions() : array + { + if (null !== self::$versions) { + return self::$versions; + } + + return self::$versions = [ + new self( + 1, + [], + new EcBlocks(7, new EcBlock(1, 19)), + new EcBlocks(10, new EcBlock(1, 16)), + new EcBlocks(13, new EcBlock(1, 13)), + new EcBlocks(17, new EcBlock(1, 9)) + ), + new self( + 2, + [6, 18], + new EcBlocks(10, new EcBlock(1, 34)), + new EcBlocks(16, new EcBlock(1, 28)), + new EcBlocks(22, new EcBlock(1, 22)), + new EcBlocks(28, new EcBlock(1, 16)) + ), + new self( + 3, + [6, 22], + new EcBlocks(15, new EcBlock(1, 55)), + new EcBlocks(26, new EcBlock(1, 44)), + new EcBlocks(18, new EcBlock(2, 17)), + new EcBlocks(22, new EcBlock(2, 13)) + ), + new self( + 4, + [6, 26], + new EcBlocks(20, new EcBlock(1, 80)), + new EcBlocks(18, new EcBlock(2, 32)), + new EcBlocks(26, new EcBlock(2, 24)), + new EcBlocks(16, new EcBlock(4, 9)) + ), + new self( + 5, + [6, 30], + new EcBlocks(26, new EcBlock(1, 108)), + new EcBlocks(24, new EcBlock(2, 43)), + new EcBlocks(18, new EcBlock(2, 15), new EcBlock(2, 16)), + new EcBlocks(22, new EcBlock(2, 11), new EcBlock(2, 12)) + ), + new self( + 6, + [6, 34], + new EcBlocks(18, new EcBlock(2, 68)), + new EcBlocks(16, new EcBlock(4, 27)), + new EcBlocks(24, new EcBlock(4, 19)), + new EcBlocks(28, new EcBlock(4, 15)) + ), + new self( + 7, + [6, 22, 38], + new EcBlocks(20, new EcBlock(2, 78)), + new EcBlocks(18, new EcBlock(4, 31)), + new EcBlocks(18, new EcBlock(2, 14), new EcBlock(4, 15)), + new EcBlocks(26, new EcBlock(4, 13), new EcBlock(1, 14)) + ), + new self( + 8, + [6, 24, 42], + new EcBlocks(24, new EcBlock(2, 97)), + new EcBlocks(22, new EcBlock(2, 38), new EcBlock(2, 39)), + new EcBlocks(22, new EcBlock(4, 18), new EcBlock(2, 19)), + new EcBlocks(26, new EcBlock(4, 14), new EcBlock(2, 15)) + ), + new self( + 9, + [6, 26, 46], + new EcBlocks(30, new EcBlock(2, 116)), + new EcBlocks(22, new EcBlock(3, 36), new EcBlock(2, 37)), + new EcBlocks(20, new EcBlock(4, 16), new EcBlock(4, 17)), + new EcBlocks(24, new EcBlock(4, 12), new EcBlock(4, 13)) + ), + new self( + 10, + [6, 28, 50], + new EcBlocks(18, new EcBlock(2, 68), new EcBlock(2, 69)), + new EcBlocks(26, new EcBlock(4, 43), new EcBlock(1, 44)), + new EcBlocks(24, new EcBlock(6, 19), new EcBlock(2, 20)), + new EcBlocks(28, new EcBlock(6, 15), new EcBlock(2, 16)) + ), + new self( + 11, + [6, 30, 54], + new EcBlocks(20, new EcBlock(4, 81)), + new EcBlocks(30, new EcBlock(1, 50), new EcBlock(4, 51)), + new EcBlocks(28, new EcBlock(4, 22), new EcBlock(4, 23)), + new EcBlocks(24, new EcBlock(3, 12), new EcBlock(8, 13)) + ), + new self( + 12, + [6, 32, 58], + new EcBlocks(24, new EcBlock(2, 92), new EcBlock(2, 93)), + new EcBlocks(22, new EcBlock(6, 36), new EcBlock(2, 37)), + new EcBlocks(26, new EcBlock(4, 20), new EcBlock(6, 21)), + new EcBlocks(28, new EcBlock(7, 14), new EcBlock(4, 15)) + ), + new self( + 13, + [6, 34, 62], + new EcBlocks(26, new EcBlock(4, 107)), + new EcBlocks(22, new EcBlock(8, 37), new EcBlock(1, 38)), + new EcBlocks(24, new EcBlock(8, 20), new EcBlock(4, 21)), + new EcBlocks(22, new EcBlock(12, 11), new EcBlock(4, 12)) + ), + new self( + 14, + [6, 26, 46, 66], + new EcBlocks(30, new EcBlock(3, 115), new EcBlock(1, 116)), + new EcBlocks(24, new EcBlock(4, 40), new EcBlock(5, 41)), + new EcBlocks(20, new EcBlock(11, 16), new EcBlock(5, 17)), + new EcBlocks(24, new EcBlock(11, 12), new EcBlock(5, 13)) + ), + new self( + 15, + [6, 26, 48, 70], + new EcBlocks(22, new EcBlock(5, 87), new EcBlock(1, 88)), + new EcBlocks(24, new EcBlock(5, 41), new EcBlock(5, 42)), + new EcBlocks(30, new EcBlock(5, 24), new EcBlock(7, 25)), + new EcBlocks(24, new EcBlock(11, 12), new EcBlock(7, 13)) + ), + new self( + 16, + [6, 26, 50, 74], + new EcBlocks(24, new EcBlock(5, 98), new EcBlock(1, 99)), + new EcBlocks(28, new EcBlock(7, 45), new EcBlock(3, 46)), + new EcBlocks(24, new EcBlock(15, 19), new EcBlock(2, 20)), + new EcBlocks(30, new EcBlock(3, 15), new EcBlock(13, 16)) + ), + new self( + 17, + [6, 30, 54, 78], + new EcBlocks(28, new EcBlock(1, 107), new EcBlock(5, 108)), + new EcBlocks(28, new EcBlock(10, 46), new EcBlock(1, 47)), + new EcBlocks(28, new EcBlock(1, 22), new EcBlock(15, 23)), + new EcBlocks(28, new EcBlock(2, 14), new EcBlock(17, 15)) + ), + new self( + 18, + [6, 30, 56, 82], + new EcBlocks(30, new EcBlock(5, 120), new EcBlock(1, 121)), + new EcBlocks(26, new EcBlock(9, 43), new EcBlock(4, 44)), + new EcBlocks(28, new EcBlock(17, 22), new EcBlock(1, 23)), + new EcBlocks(28, new EcBlock(2, 14), new EcBlock(19, 15)) + ), + new self( + 19, + [6, 30, 58, 86], + new EcBlocks(28, new EcBlock(3, 113), new EcBlock(4, 114)), + new EcBlocks(26, new EcBlock(3, 44), new EcBlock(11, 45)), + new EcBlocks(26, new EcBlock(17, 21), new EcBlock(4, 22)), + new EcBlocks(26, new EcBlock(9, 13), new EcBlock(16, 14)) + ), + new self( + 20, + [6, 34, 62, 90], + new EcBlocks(28, new EcBlock(3, 107), new EcBlock(5, 108)), + new EcBlocks(26, new EcBlock(3, 41), new EcBlock(13, 42)), + new EcBlocks(30, new EcBlock(15, 24), new EcBlock(5, 25)), + new EcBlocks(28, new EcBlock(15, 15), new EcBlock(10, 16)) + ), + new self( + 21, + [6, 28, 50, 72, 94], + new EcBlocks(28, new EcBlock(4, 116), new EcBlock(4, 117)), + new EcBlocks(26, new EcBlock(17, 42)), + new EcBlocks(28, new EcBlock(17, 22), new EcBlock(6, 23)), + new EcBlocks(30, new EcBlock(19, 16), new EcBlock(6, 17)) + ), + new self( + 22, + [6, 26, 50, 74, 98], + new EcBlocks(28, new EcBlock(2, 111), new EcBlock(7, 112)), + new EcBlocks(28, new EcBlock(17, 46)), + new EcBlocks(30, new EcBlock(7, 24), new EcBlock(16, 25)), + new EcBlocks(24, new EcBlock(34, 13)) + ), + new self( + 23, + [6, 30, 54, 78, 102], + new EcBlocks(30, new EcBlock(4, 121), new EcBlock(5, 122)), + new EcBlocks(28, new EcBlock(4, 47), new EcBlock(14, 48)), + new EcBlocks(30, new EcBlock(11, 24), new EcBlock(14, 25)), + new EcBlocks(30, new EcBlock(16, 15), new EcBlock(14, 16)) + ), + new self( + 24, + [6, 28, 54, 80, 106], + new EcBlocks(30, new EcBlock(6, 117), new EcBlock(4, 118)), + new EcBlocks(28, new EcBlock(6, 45), new EcBlock(14, 46)), + new EcBlocks(30, new EcBlock(11, 24), new EcBlock(16, 25)), + new EcBlocks(30, new EcBlock(30, 16), new EcBlock(2, 17)) + ), + new self( + 25, + [6, 32, 58, 84, 110], + new EcBlocks(26, new EcBlock(8, 106), new EcBlock(4, 107)), + new EcBlocks(28, new EcBlock(8, 47), new EcBlock(13, 48)), + new EcBlocks(30, new EcBlock(7, 24), new EcBlock(22, 25)), + new EcBlocks(30, new EcBlock(22, 15), new EcBlock(13, 16)) + ), + new self( + 26, + [6, 30, 58, 86, 114], + new EcBlocks(28, new EcBlock(10, 114), new EcBlock(2, 115)), + new EcBlocks(28, new EcBlock(19, 46), new EcBlock(4, 47)), + new EcBlocks(28, new EcBlock(28, 22), new EcBlock(6, 23)), + new EcBlocks(30, new EcBlock(33, 16), new EcBlock(4, 17)) + ), + new self( + 27, + [6, 34, 62, 90, 118], + new EcBlocks(30, new EcBlock(8, 122), new EcBlock(4, 123)), + new EcBlocks(28, new EcBlock(22, 45), new EcBlock(3, 46)), + new EcBlocks(30, new EcBlock(8, 23), new EcBlock(26, 24)), + new EcBlocks(30, new EcBlock(12, 15), new EcBlock(28, 16)) + ), + new self( + 28, + [6, 26, 50, 74, 98, 122], + new EcBlocks(30, new EcBlock(3, 117), new EcBlock(10, 118)), + new EcBlocks(28, new EcBlock(3, 45), new EcBlock(23, 46)), + new EcBlocks(30, new EcBlock(4, 24), new EcBlock(31, 25)), + new EcBlocks(30, new EcBlock(11, 15), new EcBlock(31, 16)) + ), + new self( + 29, + [6, 30, 54, 78, 102, 126], + new EcBlocks(30, new EcBlock(7, 116), new EcBlock(7, 117)), + new EcBlocks(28, new EcBlock(21, 45), new EcBlock(7, 46)), + new EcBlocks(30, new EcBlock(1, 23), new EcBlock(37, 24)), + new EcBlocks(30, new EcBlock(19, 15), new EcBlock(26, 16)) + ), + new self( + 30, + [6, 26, 52, 78, 104, 130], + new EcBlocks(30, new EcBlock(5, 115), new EcBlock(10, 116)), + new EcBlocks(28, new EcBlock(19, 47), new EcBlock(10, 48)), + new EcBlocks(30, new EcBlock(15, 24), new EcBlock(25, 25)), + new EcBlocks(30, new EcBlock(23, 15), new EcBlock(25, 16)) + ), + new self( + 31, + [6, 30, 56, 82, 108, 134], + new EcBlocks(30, new EcBlock(13, 115), new EcBlock(3, 116)), + new EcBlocks(28, new EcBlock(2, 46), new EcBlock(29, 47)), + new EcBlocks(30, new EcBlock(42, 24), new EcBlock(1, 25)), + new EcBlocks(30, new EcBlock(23, 15), new EcBlock(28, 16)) + ), + new self( + 32, + [6, 34, 60, 86, 112, 138], + new EcBlocks(30, new EcBlock(17, 115)), + new EcBlocks(28, new EcBlock(10, 46), new EcBlock(23, 47)), + new EcBlocks(30, new EcBlock(10, 24), new EcBlock(35, 25)), + new EcBlocks(30, new EcBlock(19, 15), new EcBlock(35, 16)) + ), + new self( + 33, + [6, 30, 58, 86, 114, 142], + new EcBlocks(30, new EcBlock(17, 115), new EcBlock(1, 116)), + new EcBlocks(28, new EcBlock(14, 46), new EcBlock(21, 47)), + new EcBlocks(30, new EcBlock(29, 24), new EcBlock(19, 25)), + new EcBlocks(30, new EcBlock(11, 15), new EcBlock(46, 16)) + ), + new self( + 34, + [6, 34, 62, 90, 118, 146], + new EcBlocks(30, new EcBlock(13, 115), new EcBlock(6, 116)), + new EcBlocks(28, new EcBlock(14, 46), new EcBlock(23, 47)), + new EcBlocks(30, new EcBlock(44, 24), new EcBlock(7, 25)), + new EcBlocks(30, new EcBlock(59, 16), new EcBlock(1, 17)) + ), + new self( + 35, + [6, 30, 54, 78, 102, 126, 150], + new EcBlocks(30, new EcBlock(12, 121), new EcBlock(7, 122)), + new EcBlocks(28, new EcBlock(12, 47), new EcBlock(26, 48)), + new EcBlocks(30, new EcBlock(39, 24), new EcBlock(14, 25)), + new EcBlocks(30, new EcBlock(22, 15), new EcBlock(41, 16)) + ), + new self( + 36, + [6, 24, 50, 76, 102, 128, 154], + new EcBlocks(30, new EcBlock(6, 121), new EcBlock(14, 122)), + new EcBlocks(28, new EcBlock(6, 47), new EcBlock(34, 48)), + new EcBlocks(30, new EcBlock(46, 24), new EcBlock(10, 25)), + new EcBlocks(30, new EcBlock(2, 15), new EcBlock(64, 16)) + ), + new self( + 37, + [6, 28, 54, 80, 106, 132, 158], + new EcBlocks(30, new EcBlock(17, 122), new EcBlock(4, 123)), + new EcBlocks(28, new EcBlock(29, 46), new EcBlock(14, 47)), + new EcBlocks(30, new EcBlock(49, 24), new EcBlock(10, 25)), + new EcBlocks(30, new EcBlock(24, 15), new EcBlock(46, 16)) + ), + new self( + 38, + [6, 32, 58, 84, 110, 136, 162], + new EcBlocks(30, new EcBlock(4, 122), new EcBlock(18, 123)), + new EcBlocks(28, new EcBlock(13, 46), new EcBlock(32, 47)), + new EcBlocks(30, new EcBlock(48, 24), new EcBlock(14, 25)), + new EcBlocks(30, new EcBlock(42, 15), new EcBlock(32, 16)) + ), + new self( + 39, + [6, 26, 54, 82, 110, 138, 166], + new EcBlocks(30, new EcBlock(20, 117), new EcBlock(4, 118)), + new EcBlocks(28, new EcBlock(40, 47), new EcBlock(7, 48)), + new EcBlocks(30, new EcBlock(43, 24), new EcBlock(22, 25)), + new EcBlocks(30, new EcBlock(10, 15), new EcBlock(67, 16)) + ), + new self( + 40, + [6, 30, 58, 86, 114, 142, 170], + new EcBlocks(30, new EcBlock(19, 118), new EcBlock(6, 119)), + new EcBlocks(28, new EcBlock(18, 47), new EcBlock(31, 48)), + new EcBlocks(30, new EcBlock(34, 24), new EcBlock(34, 25)), + new EcBlocks(30, new EcBlock(20, 15), new EcBlock(61, 16)) + ), + ]; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Encoder/BlockPair.php b/vendor/bacon/bacon-qr-code/src/Encoder/BlockPair.php index 3b9eb7d..b1dc5c4 100644 --- a/vendor/bacon/bacon-qr-code/src/Encoder/BlockPair.php +++ b/vendor/bacon/bacon-qr-code/src/Encoder/BlockPair.php @@ -1,44 +1,44 @@ - $dataBytes Data bytes in the block. - * @param SplFixedArray $errorCorrectionBytes Error correction bytes in the block. - */ - public function __construct( - private readonly SplFixedArray $dataBytes, - private readonly SplFixedArray $errorCorrectionBytes - ) { - } - - /** - * Gets the data bytes. - * - * @return SplFixedArray - */ - public function getDataBytes() : SplFixedArray - { - return $this->dataBytes; - } - - /** - * Gets the error correction bytes. - * - * @return SplFixedArray - */ - public function getErrorCorrectionBytes() : SplFixedArray - { - return $this->errorCorrectionBytes; - } -} + $dataBytes Data bytes in the block. + * @param SplFixedArray $errorCorrectionBytes Error correction bytes in the block. + */ + public function __construct( + private readonly SplFixedArray $dataBytes, + private readonly SplFixedArray $errorCorrectionBytes + ) { + } + + /** + * Gets the data bytes. + * + * @return SplFixedArray + */ + public function getDataBytes() : SplFixedArray + { + return $this->dataBytes; + } + + /** + * Gets the error correction bytes. + * + * @return SplFixedArray + */ + public function getErrorCorrectionBytes() : SplFixedArray + { + return $this->errorCorrectionBytes; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Encoder/ByteMatrix.php b/vendor/bacon/bacon-qr-code/src/Encoder/ByteMatrix.php index 48830c9..eefcf1c 100644 --- a/vendor/bacon/bacon-qr-code/src/Encoder/ByteMatrix.php +++ b/vendor/bacon/bacon-qr-code/src/Encoder/ByteMatrix.php @@ -1,134 +1,134 @@ -> - */ - private SplFixedArray $bytes; - - public function __construct(private readonly int $width, private readonly int $height) - { - $this->bytes = new SplFixedArray($height); - - for ($y = 0; $y < $height; ++$y) { - $this->bytes[$y] = SplFixedArray::fromArray(array_fill(0, $width, 0)); - } - } - - /** - * Gets the width of the matrix. - */ - public function getWidth() : int - { - return $this->width; - } - - /** - * Gets the height of the matrix. - */ - public function getHeight() : int - { - return $this->height; - } - - /** - * Gets the internal representation of the matrix. - * - * @return SplFixedArray> - */ - public function getArray() : SplFixedArray - { - return $this->bytes; - } - - /** - * @return Traversable - */ - public function getBytes() : Traversable - { - foreach ($this->bytes as $row) { - foreach ($row as $byte) { - yield $byte; - } - } - } - - /** - * Gets the byte for a specific position. - */ - public function get(int $x, int $y) : int - { - return $this->bytes[$y][$x]; - } - - /** - * Sets the byte for a specific position. - */ - public function set(int $x, int $y, int $value) : void - { - $this->bytes[$y][$x] = $value; - } - - /** - * Clears the matrix with a specific value. - */ - public function clear(int $value) : void - { - for ($y = 0; $y < $this->height; ++$y) { - for ($x = 0; $x < $this->width; ++$x) { - $this->bytes[$y][$x] = $value; - } - } - } - - public function __clone() - { - $this->bytes = clone $this->bytes; - - foreach ($this->bytes as $index => $row) { - $this->bytes[$index] = clone $row; - } - } - - /** - * Returns a string representation of the matrix. - */ - public function __toString() : string - { - $result = ''; - - for ($y = 0; $y < $this->height; $y++) { - for ($x = 0; $x < $this->width; $x++) { - switch ($this->bytes[$y][$x]) { - case 0: - $result .= ' 0'; - break; - - case 1: - $result .= ' 1'; - break; - - default: - $result .= ' '; - break; - } - } - - $result .= "\n"; - } - - return $result; - } -} +> + */ + private SplFixedArray $bytes; + + public function __construct(private readonly int $width, private readonly int $height) + { + $this->bytes = new SplFixedArray($height); + + for ($y = 0; $y < $height; ++$y) { + $this->bytes[$y] = SplFixedArray::fromArray(array_fill(0, $width, 0)); + } + } + + /** + * Gets the width of the matrix. + */ + public function getWidth() : int + { + return $this->width; + } + + /** + * Gets the height of the matrix. + */ + public function getHeight() : int + { + return $this->height; + } + + /** + * Gets the internal representation of the matrix. + * + * @return SplFixedArray> + */ + public function getArray() : SplFixedArray + { + return $this->bytes; + } + + /** + * @return Traversable + */ + public function getBytes() : Traversable + { + foreach ($this->bytes as $row) { + foreach ($row as $byte) { + yield $byte; + } + } + } + + /** + * Gets the byte for a specific position. + */ + public function get(int $x, int $y) : int + { + return $this->bytes[$y][$x]; + } + + /** + * Sets the byte for a specific position. + */ + public function set(int $x, int $y, int $value) : void + { + $this->bytes[$y][$x] = $value; + } + + /** + * Clears the matrix with a specific value. + */ + public function clear(int $value) : void + { + for ($y = 0; $y < $this->height; ++$y) { + for ($x = 0; $x < $this->width; ++$x) { + $this->bytes[$y][$x] = $value; + } + } + } + + public function __clone() + { + $this->bytes = clone $this->bytes; + + foreach ($this->bytes as $index => $row) { + $this->bytes[$index] = clone $row; + } + } + + /** + * Returns a string representation of the matrix. + */ + public function __toString() : string + { + $result = ''; + + for ($y = 0; $y < $this->height; $y++) { + for ($x = 0; $x < $this->width; $x++) { + switch ($this->bytes[$y][$x]) { + case 0: + $result .= ' 0'; + break; + + case 1: + $result .= ' 1'; + break; + + default: + $result .= ' '; + break; + } + } + + $result .= "\n"; + } + + return $result; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Encoder/Encoder.php b/vendor/bacon/bacon-qr-code/src/Encoder/Encoder.php index ddc195c..a7e00ff 100644 --- a/vendor/bacon/bacon-qr-code/src/Encoder/Encoder.php +++ b/vendor/bacon/bacon-qr-code/src/Encoder/Encoder.php @@ -1,679 +1,666 @@ - - */ - private static array $codecs = []; - - /** - * Encodes "content" with the error correction level "ecLevel". - */ - public static function encode( - string $content, - ErrorCorrectionLevel $ecLevel, - string $encoding = self::DEFAULT_BYTE_MODE_ENCODING, - ?Version $forcedVersion = null, - // Barcode scanner might not be able to read the encoded message of the QR code with the prefix ECI of UTF-8 - bool $prefixEci = true - ) : QrCode { - // Pick an encoding mode appropriate for the content. Note that this - // will not attempt to use multiple modes / segments even if that were - // more efficient. Would be nice. - $mode = self::chooseMode($content, $encoding); - - // This will store the header information, like mode and length, as well - // as "header" segments like an ECI segment. - $headerBits = new BitArray(); - - // Append ECI segment if applicable - if ($prefixEci && Mode::BYTE() === $mode && self::DEFAULT_BYTE_MODE_ENCODING !== $encoding) { - $eci = CharacterSetEci::getCharacterSetEciByName($encoding); - - if (null !== $eci) { - self::appendEci($eci, $headerBits); - } - } - - // (With ECI in place,) Write the mode marker - self::appendModeInfo($mode, $headerBits); - - // Collect data within the main segment, separately, to count its size - // if needed. Don't add it to main payload yet. - $dataBits = new BitArray(); - self::appendBytes($content, $mode, $dataBits, $encoding); - - // Hard part: need to know version to know how many bits length takes. - // But need to know how many bits it takes to know version. First we - // take a guess at version by assuming version will be the minimum, 1: - $provisionalBitsNeeded = $headerBits->getSize() - + $mode->getCharacterCountBits(Version::getVersionForNumber(1)) - + $dataBits->getSize(); - $provisionalVersion = self::chooseVersion($provisionalBitsNeeded, $ecLevel); - - // Use that guess to calculate the right version. I am still not sure - // this works in 100% of cases. - $bitsNeeded = $headerBits->getSize() - + $mode->getCharacterCountBits($provisionalVersion) - + $dataBits->getSize(); - $version = self::chooseVersion($bitsNeeded, $ecLevel); - - if (null !== $forcedVersion) { - // Forced version check - if ($version->getVersionNumber() <= $forcedVersion->getVersionNumber()) { - // Calculated minimum version is same or equal as forced version - $version = $forcedVersion; - } else { - throw new WriterException( - 'Invalid version! Calculated version: ' - . $version->getVersionNumber() - . ', requested version: ' - . $forcedVersion->getVersionNumber() - ); - } - } - - $headerAndDataBits = new BitArray(); - $headerAndDataBits->appendBitArray($headerBits); - - // Find "length" of main segment and write it. - $numLetters = (Mode::BYTE() === $mode ? $dataBits->getSizeInBytes() : strlen($content)); - self::appendLengthInfo($numLetters, $version, $mode, $headerAndDataBits); - - // Put data together into the overall payload. - $headerAndDataBits->appendBitArray($dataBits); - $ecBlocks = $version->getEcBlocksForLevel($ecLevel); - $numDataBytes = $version->getTotalCodewords() - $ecBlocks->getTotalEcCodewords(); - - // Terminate the bits properly. - self::terminateBits($numDataBytes, $headerAndDataBits); - - // Interleave data bits with error correction code. - $finalBits = self::interleaveWithEcBytes( - $headerAndDataBits, - $version->getTotalCodewords(), - $numDataBytes, - $ecBlocks->getNumBlocks() - ); - - // Choose the mask pattern. - $dimension = $version->getDimensionForVersion(); - $matrix = new ByteMatrix($dimension, $dimension); - $maskPattern = self::chooseMaskPattern($finalBits, $ecLevel, $version, $matrix); - - // Build the matrix. - MatrixUtil::buildMatrix($finalBits, $ecLevel, $version, $maskPattern, $matrix); - - return new QrCode($mode, $ecLevel, $version, $maskPattern, $matrix); - } - - /** - * Gets the alphanumeric code for a byte. - */ - private static function getAlphanumericCode(int $code) : int - { - if (isset(self::ALPHANUMERIC_TABLE[$code])) { - return self::ALPHANUMERIC_TABLE[$code]; - } - - return -1; - } - - /** - * Chooses the best mode for a given content. - */ - private static function chooseMode(string $content, ?string $encoding = null) : Mode - { - if (null !== $encoding && 0 === strcasecmp($encoding, 'SHIFT-JIS')) { - return self::isOnlyDoubleByteKanji($content) ? Mode::KANJI() : Mode::BYTE(); - } - - $hasNumeric = false; - $hasAlphanumeric = false; - $contentLength = strlen($content); - - for ($i = 0; $i < $contentLength; ++$i) { - $char = $content[$i]; - - if (ctype_digit($char)) { - $hasNumeric = true; - } elseif (-1 !== self::getAlphanumericCode(ord($char))) { - $hasAlphanumeric = true; - } else { - return Mode::BYTE(); - } - } - - if ($hasAlphanumeric) { - return Mode::ALPHANUMERIC(); - } elseif ($hasNumeric) { - return Mode::NUMERIC(); - } - - return Mode::BYTE(); - } - - /** - * Calculates the mask penalty for a matrix. - */ - private static function calculateMaskPenalty(ByteMatrix $matrix) : int - { - return ( - MaskUtil::applyMaskPenaltyRule1($matrix) - + MaskUtil::applyMaskPenaltyRule2($matrix) - + MaskUtil::applyMaskPenaltyRule3($matrix) - + MaskUtil::applyMaskPenaltyRule4($matrix) - ); - } - - /** - * Checks if content only consists of double-byte kanji characters. - */ - private static function isOnlyDoubleByteKanji(string $content) : bool - { - $bytes = @iconv('utf-8', 'SHIFT-JIS', $content); - - if (false === $bytes) { - return false; - } - - $length = strlen($bytes); - - if (0 !== $length % 2) { - return false; - } - - for ($i = 0; $i < $length; $i += 2) { - $byte = ord($bytes[$i]) & 0xff; - - if (($byte < 0x81 || $byte > 0x9f) && $byte < 0xe0 || $byte > 0xeb) { - return false; - } - } - - return true; - } - - /** - * Chooses the best mask pattern for a matrix. - */ - private static function chooseMaskPattern( - BitArray $bits, - ErrorCorrectionLevel $ecLevel, - Version $version, - ByteMatrix $matrix - ) : int { - $minPenalty = PHP_INT_MAX; - $bestMaskPattern = -1; - - for ($maskPattern = 0; $maskPattern < QrCode::NUM_MASK_PATTERNS; ++$maskPattern) { - MatrixUtil::buildMatrix($bits, $ecLevel, $version, $maskPattern, $matrix); - $penalty = self::calculateMaskPenalty($matrix); - - if ($penalty < $minPenalty) { - $minPenalty = $penalty; - $bestMaskPattern = $maskPattern; - } - } - - return $bestMaskPattern; - } - - /** - * Chooses the best version for the input. - * - * @throws WriterException if data is too big - */ - private static function chooseVersion(int $numInputBits, ErrorCorrectionLevel $ecLevel) : Version - { - for ($versionNum = 1; $versionNum <= 40; ++$versionNum) { - $version = Version::getVersionForNumber($versionNum); - $numBytes = $version->getTotalCodewords(); - - $ecBlocks = $version->getEcBlocksForLevel($ecLevel); - $numEcBytes = $ecBlocks->getTotalEcCodewords(); - - $numDataBytes = $numBytes - $numEcBytes; - $totalInputBytes = intdiv($numInputBits + 8, 8); - - if ($numDataBytes >= $totalInputBytes) { - return $version; - } - } - - throw new WriterException('Data too big'); - } - - /** - * Terminates the bits in a bit array. - * - * @throws WriterException if data bits cannot fit in the QR code - * @throws WriterException if bits size does not equal the capacity - */ - private static function terminateBits(int $numDataBytes, BitArray $bits) : void - { - $capacity = $numDataBytes << 3; - - if ($bits->getSize() > $capacity) { - throw new WriterException('Data bits cannot fit in the QR code'); - } - - for ($i = 0; $i < 4 && $bits->getSize() < $capacity; ++$i) { - $bits->appendBit(false); - } - - $numBitsInLastByte = $bits->getSize() & 0x7; - - if ($numBitsInLastByte > 0) { - for ($i = $numBitsInLastByte; $i < 8; ++$i) { - $bits->appendBit(false); - } - } - - $numPaddingBytes = $numDataBytes - $bits->getSizeInBytes(); - - for ($i = 0; $i < $numPaddingBytes; ++$i) { - $bits->appendBits(0 === ($i & 0x1) ? 0xec : 0x11, 8); - } - - if ($bits->getSize() !== $capacity) { - throw new WriterException('Bits size does not equal capacity'); - } - } - - /** - * Gets number of data- and EC bytes for a block ID. - * - * @return int[] - * @throws WriterException if block ID is too large - * @throws WriterException if EC bytes mismatch - * @throws WriterException if RS blocks mismatch - * @throws WriterException if total bytes mismatch - */ - private static function getNumDataBytesAndNumEcBytesForBlockId( - int $numTotalBytes, - int $numDataBytes, - int $numRsBlocks, - int $blockId - ) : array { - if ($blockId >= $numRsBlocks) { - throw new WriterException('Block ID too large'); - } - - $numRsBlocksInGroup2 = $numTotalBytes % $numRsBlocks; - $numRsBlocksInGroup1 = $numRsBlocks - $numRsBlocksInGroup2; - $numTotalBytesInGroup1 = intdiv($numTotalBytes, $numRsBlocks); - $numTotalBytesInGroup2 = $numTotalBytesInGroup1 + 1; - $numDataBytesInGroup1 = intdiv($numDataBytes, $numRsBlocks); - $numDataBytesInGroup2 = $numDataBytesInGroup1 + 1; - $numEcBytesInGroup1 = $numTotalBytesInGroup1 - $numDataBytesInGroup1; - $numEcBytesInGroup2 = $numTotalBytesInGroup2 - $numDataBytesInGroup2; - - if ($numEcBytesInGroup1 !== $numEcBytesInGroup2) { - throw new WriterException('EC bytes mismatch'); - } - - if ($numRsBlocks !== $numRsBlocksInGroup1 + $numRsBlocksInGroup2) { - throw new WriterException('RS blocks mismatch'); - } - - if ($numTotalBytes !== - (($numDataBytesInGroup1 + $numEcBytesInGroup1) * $numRsBlocksInGroup1) - + (($numDataBytesInGroup2 + $numEcBytesInGroup2) * $numRsBlocksInGroup2) - ) { - throw new WriterException('Total bytes mismatch'); - } - - if ($blockId < $numRsBlocksInGroup1) { - return [$numDataBytesInGroup1, $numEcBytesInGroup1]; - } else { - return [$numDataBytesInGroup2, $numEcBytesInGroup2]; - } - } - - /** - * Interleaves data with EC bytes. - * - * @throws WriterException if number of bits and data bytes does not match - * @throws WriterException if data bytes does not match offset - * @throws WriterException if an interleaving error occurs - */ - private static function interleaveWithEcBytes( - BitArray $bits, - int $numTotalBytes, - int $numDataBytes, - int $numRsBlocks - ) : BitArray { - if ($bits->getSizeInBytes() !== $numDataBytes) { - throw new WriterException('Number of bits and data bytes does not match'); - } - - $dataBytesOffset = 0; - $maxNumDataBytes = 0; - $maxNumEcBytes = 0; - - $blocks = new SplFixedArray($numRsBlocks); - - for ($i = 0; $i < $numRsBlocks; ++$i) { - list($numDataBytesInBlock, $numEcBytesInBlock) = self::getNumDataBytesAndNumEcBytesForBlockId( - $numTotalBytes, - $numDataBytes, - $numRsBlocks, - $i - ); - - $size = $numDataBytesInBlock; - $dataBytes = $bits->toBytes(8 * $dataBytesOffset, $size); - $ecBytes = self::generateEcBytes($dataBytes, $numEcBytesInBlock); - $blocks[$i] = new BlockPair($dataBytes, $ecBytes); - - $maxNumDataBytes = max($maxNumDataBytes, $size); - $maxNumEcBytes = max($maxNumEcBytes, count($ecBytes)); - $dataBytesOffset += $numDataBytesInBlock; - } - - if ($numDataBytes !== $dataBytesOffset) { - throw new WriterException('Data bytes does not match offset'); - } - - $result = new BitArray(); - - for ($i = 0; $i < $maxNumDataBytes; ++$i) { - foreach ($blocks as $block) { - $dataBytes = $block->getDataBytes(); - - if ($i < count($dataBytes)) { - $result->appendBits($dataBytes[$i], 8); - } - } - } - - for ($i = 0; $i < $maxNumEcBytes; ++$i) { - foreach ($blocks as $block) { - $ecBytes = $block->getErrorCorrectionBytes(); - - if ($i < count($ecBytes)) { - $result->appendBits($ecBytes[$i], 8); - } - } - } - - if ($numTotalBytes !== $result->getSizeInBytes()) { - throw new WriterException( - 'Interleaving error: ' . $numTotalBytes . ' and ' . $result->getSizeInBytes() . ' differ' - ); - } - - return $result; - } - - /** - * Generates EC bytes for given data. - * - * @param SplFixedArray $dataBytes - * @return SplFixedArray - */ - private static function generateEcBytes(SplFixedArray $dataBytes, int $numEcBytesInBlock) : SplFixedArray - { - $numDataBytes = count($dataBytes); - $toEncode = new SplFixedArray($numDataBytes + $numEcBytesInBlock); - - for ($i = 0; $i < $numDataBytes; $i++) { - $toEncode[$i] = $dataBytes[$i] & 0xff; - } - - $ecBytes = new SplFixedArray($numEcBytesInBlock); - $codec = self::getCodec($numDataBytes, $numEcBytesInBlock); - $codec->encode($toEncode, $ecBytes); - - return $ecBytes; - } - - /** - * Gets an RS codec and caches it. - */ - private static function getCodec(int $numDataBytes, int $numEcBytesInBlock) : ReedSolomonCodec - { - $cacheId = $numDataBytes . '-' . $numEcBytesInBlock; - - if (isset(self::$codecs[$cacheId])) { - return self::$codecs[$cacheId]; - } - - return self::$codecs[$cacheId] = new ReedSolomonCodec( - 8, - 0x11d, - 0, - 1, - $numEcBytesInBlock, - 255 - $numDataBytes - $numEcBytesInBlock - ); - } - - /** - * Appends mode information to a bit array. - */ - private static function appendModeInfo(Mode $mode, BitArray $bits) : void - { - $bits->appendBits($mode->getBits(), 4); - } - - /** - * Appends length information to a bit array. - * - * @throws WriterException if num letters is bigger than expected - */ - private static function appendLengthInfo(int $numLetters, Version $version, Mode $mode, BitArray $bits) : void - { - $numBits = $mode->getCharacterCountBits($version); - - if ($numLetters >= (1 << $numBits)) { - throw new WriterException($numLetters . ' is bigger than ' . ((1 << $numBits) - 1)); - } - - $bits->appendBits($numLetters, $numBits); - } - - /** - * Appends bytes to a bit array in a specific mode. - * - * @throws WriterException if an invalid mode was supplied - */ - private static function appendBytes(string $content, Mode $mode, BitArray $bits, string $encoding) : void - { - switch ($mode) { - case Mode::NUMERIC(): - self::appendNumericBytes($content, $bits); - break; - - case Mode::ALPHANUMERIC(): - self::appendAlphanumericBytes($content, $bits); - break; - - case Mode::BYTE(): - self::append8BitBytes($content, $bits, $encoding); - break; - - case Mode::KANJI(): - self::appendKanjiBytes($content, $bits); - break; - - default: - throw new WriterException('Invalid mode: ' . $mode); - } - } - - /** - * Appends numeric bytes to a bit array. - */ - private static function appendNumericBytes(string $content, BitArray $bits) : void - { - $length = strlen($content); - $i = 0; - - while ($i < $length) { - $num1 = (int) $content[$i]; - - if ($i + 2 < $length) { - // Encode three numeric letters in ten bits. - $num2 = (int) $content[$i + 1]; - $num3 = (int) $content[$i + 2]; - $bits->appendBits($num1 * 100 + $num2 * 10 + $num3, 10); - $i += 3; - } elseif ($i + 1 < $length) { - // Encode two numeric letters in seven bits. - $num2 = (int) $content[$i + 1]; - $bits->appendBits($num1 * 10 + $num2, 7); - $i += 2; - } else { - // Encode one numeric letter in four bits. - $bits->appendBits($num1, 4); - ++$i; - } - } - } - - /** - * Appends alpha-numeric bytes to a bit array. - * - * @throws WriterException if an invalid alphanumeric code was found - */ - private static function appendAlphanumericBytes(string $content, BitArray $bits) : void - { - $length = strlen($content); - $i = 0; - - while ($i < $length) { - $code1 = self::getAlphanumericCode(ord($content[$i])); - - if (-1 === $code1) { - throw new WriterException('Invalid alphanumeric code'); - } - - if ($i + 1 < $length) { - $code2 = self::getAlphanumericCode(ord($content[$i + 1])); - - if (-1 === $code2) { - throw new WriterException('Invalid alphanumeric code'); - } - - // Encode two alphanumeric letters in 11 bits. - $bits->appendBits($code1 * 45 + $code2, 11); - $i += 2; - } else { - // Encode one alphanumeric letter in six bits. - $bits->appendBits($code1, 6); - ++$i; - } - } - } - - /** - * Appends regular 8-bit bytes to a bit array. - * - * @throws WriterException if content cannot be encoded to target encoding - */ - private static function append8BitBytes(string $content, BitArray $bits, string $encoding) : void - { - $bytes = @iconv('utf-8', $encoding, $content); - - if (false === $bytes) { - throw new WriterException('Could not encode content to ' . $encoding); - } - - $length = strlen($bytes); - - for ($i = 0; $i < $length; $i++) { - $bits->appendBits(ord($bytes[$i]), 8); - } - } - - /** - * Appends KANJI bytes to a bit array. - * - * @throws WriterException if content does not seem to be encoded in SHIFT-JIS - * @throws WriterException if an invalid byte sequence occurs - */ - private static function appendKanjiBytes(string $content, BitArray $bits) : void - { - $bytes = @iconv('utf-8', 'SHIFT-JIS', $content); - - if (false === $bytes) { - throw new WriterException('Content could not be converted to SHIFT-JIS'); - } - - if (strlen($bytes) % 2 > 0) { - // We just do a simple length check here. The for loop will check - // individual characters. - throw new WriterException('Content does not seem to be encoded in SHIFT-JIS'); - } - - $length = strlen($bytes); - - for ($i = 0; $i < $length; $i += 2) { - $byte1 = ord($bytes[$i]) & 0xff; - $byte2 = ord($bytes[$i + 1]) & 0xff; - $code = ($byte1 << 8) | $byte2; - - if ($code >= 0x8140 && $code <= 0x9ffc) { - $subtracted = $code - 0x8140; - } elseif ($code >= 0xe040 && $code <= 0xebbf) { - $subtracted = $code - 0xc140; - } else { - throw new WriterException('Invalid byte sequence'); - } - - $encoded = (($subtracted >> 8) * 0xc0) + ($subtracted & 0xff); - - $bits->appendBits($encoded, 13); - } - } - - /** - * Appends ECI information to a bit array. - */ - private static function appendEci(CharacterSetEci $eci, BitArray $bits) : void - { - $mode = Mode::ECI(); - $bits->appendBits($mode->getBits(), 4); - $bits->appendBits($eci->getValue(), 8); - } -} + + */ + private static array $codecs = []; + + /** + * Encodes "content" with the error correction level "ecLevel". + */ + public static function encode( + string $content, + ErrorCorrectionLevel $ecLevel, + string $encoding = self::DEFAULT_BYTE_MODE_ENCODING, + ?Version $forcedVersion = null, + // Barcode scanner might not be able to read the encoded message of the QR code with the prefix ECI of UTF-8 + bool $prefixEci = true + ) : QrCode { + // Pick an encoding mode appropriate for the content. Note that this + // will not attempt to use multiple modes / segments even if that were + // more efficient. Would be nice. + $mode = self::chooseMode($content, $encoding); + + // This will store the header information, like mode and length, as well + // as "header" segments like an ECI segment. + $headerBits = new BitArray(); + + // Append ECI segment if applicable + if ($prefixEci && Mode::BYTE() === $mode && self::DEFAULT_BYTE_MODE_ENCODING !== $encoding) { + $eci = CharacterSetEci::getCharacterSetEciByName($encoding); + + if (null !== $eci) { + self::appendEci($eci, $headerBits); + } + } + + // (With ECI in place,) Write the mode marker + self::appendModeInfo($mode, $headerBits); + + // Collect data within the main segment, separately, to count its size + // if needed. Don't add it to main payload yet. + $dataBits = new BitArray(); + self::appendBytes($content, $mode, $dataBits, $encoding); + + // Hard part: need to know version to know how many bits length takes. + // But need to know how many bits it takes to know version. First we + // take a guess at version by assuming version will be the minimum, 1: + $provisionalBitsNeeded = $headerBits->getSize() + + $mode->getCharacterCountBits(Version::getVersionForNumber(1)) + + $dataBits->getSize(); + $provisionalVersion = self::chooseVersion($provisionalBitsNeeded, $ecLevel); + + // Use that guess to calculate the right version. I am still not sure + // this works in 100% of cases. + $bitsNeeded = $headerBits->getSize() + + $mode->getCharacterCountBits($provisionalVersion) + + $dataBits->getSize(); + $version = self::chooseVersion($bitsNeeded, $ecLevel); + + if (null !== $forcedVersion) { + // Forced version check + if ($version->getVersionNumber() <= $forcedVersion->getVersionNumber()) { + // Calculated minimum version is same or equal as forced version + $version = $forcedVersion; + } else { + throw new WriterException( + 'Invalid version! Calculated version: ' + . $version->getVersionNumber() + . ', requested version: ' + . $forcedVersion->getVersionNumber() + ); + } + } + + $headerAndDataBits = new BitArray(); + $headerAndDataBits->appendBitArray($headerBits); + + // Find "length" of main segment and write it. + $numLetters = match ($mode) { + Mode::BYTE() => $dataBits->getSizeInBytes(), + Mode::NUMERIC(), Mode::ALPHANUMERIC() => strlen($content), + Mode::KANJI() => iconv_strlen($content, 'utf-8'), + }; + self::appendLengthInfo($numLetters, $version, $mode, $headerAndDataBits); + + // Put data together into the overall payload. + $headerAndDataBits->appendBitArray($dataBits); + $ecBlocks = $version->getEcBlocksForLevel($ecLevel); + $numDataBytes = $version->getTotalCodewords() - $ecBlocks->getTotalEcCodewords(); + + // Terminate the bits properly. + self::terminateBits($numDataBytes, $headerAndDataBits); + + // Interleave data bits with error correction code. + $finalBits = self::interleaveWithEcBytes( + $headerAndDataBits, + $version->getTotalCodewords(), + $numDataBytes, + $ecBlocks->getNumBlocks() + ); + + // Choose the mask pattern. + $dimension = $version->getDimensionForVersion(); + $matrix = new ByteMatrix($dimension, $dimension); + $maskPattern = self::chooseMaskPattern($finalBits, $ecLevel, $version, $matrix); + + // Build the matrix. + MatrixUtil::buildMatrix($finalBits, $ecLevel, $version, $maskPattern, $matrix); + + return new QrCode($mode, $ecLevel, $version, $maskPattern, $matrix); + } + + /** + * Gets the alphanumeric code for a byte. + */ + private static function getAlphanumericCode(int $byte) : int + { + return self::ALPHANUMERIC_TABLE[$byte] ?? -1; + } + + /** + * Chooses the best mode for a given content. + */ + private static function chooseMode(string $content, ?string $encoding = null) : Mode + { + if ('' === $content) { + return Mode::BYTE(); + } + + if (null !== $encoding && 0 === strcasecmp($encoding, 'SHIFT-JIS')) { + return self::isOnlyDoubleByteKanji($content) ? Mode::KANJI() : Mode::BYTE(); + } + + if (ctype_digit($content)) { + return Mode::NUMERIC(); + } + + if (self::isOnlyAlphanumeric($content)) { + return Mode::ALPHANUMERIC(); + } + + return Mode::BYTE(); + } + + /** + * Calculates the mask penalty for a matrix. + */ + private static function calculateMaskPenalty(ByteMatrix $matrix) : int + { + return ( + MaskUtil::applyMaskPenaltyRule1($matrix) + + MaskUtil::applyMaskPenaltyRule2($matrix) + + MaskUtil::applyMaskPenaltyRule3($matrix) + + MaskUtil::applyMaskPenaltyRule4($matrix) + ); + } + + /** + * Checks if content only consists of double-byte kanji characters (or is empty). + */ + private static function isOnlyDoubleByteKanji(string $content) : bool + { + $bytes = @iconv('utf-8', 'SHIFT-JIS', $content); + + if (false === $bytes) { + return false; + } + + $length = strlen($bytes); + + if (0 !== $length % 2) { + return false; + } + + for ($i = 0; $i < $length; $i += 2) { + $byte = ord($bytes[$i]); + + if (($byte < 0x81 || $byte > 0x9f) && $byte < 0xe0 || $byte > 0xeb) { + return false; + } + } + + return true; + } + + /** + * Checks if content only consists of alphanumeric characters (or is empty). + */ + private static function isOnlyAlphanumeric(string $content) : bool + { + return strlen($content) === strspn($content, self::ALPHANUMERIC_CHARS); + } + + /** + * Chooses the best mask pattern for a matrix. + */ + private static function chooseMaskPattern( + BitArray $bits, + ErrorCorrectionLevel $ecLevel, + Version $version, + ByteMatrix $matrix + ) : int { + $minPenalty = PHP_INT_MAX; + $bestMaskPattern = -1; + + for ($maskPattern = 0; $maskPattern < QrCode::NUM_MASK_PATTERNS; ++$maskPattern) { + MatrixUtil::buildMatrix($bits, $ecLevel, $version, $maskPattern, $matrix); + $penalty = self::calculateMaskPenalty($matrix); + + if ($penalty < $minPenalty) { + $minPenalty = $penalty; + $bestMaskPattern = $maskPattern; + } + } + + return $bestMaskPattern; + } + + /** + * Chooses the best version for the input. + * + * @throws WriterException if data is too big + */ + private static function chooseVersion(int $numInputBits, ErrorCorrectionLevel $ecLevel) : Version + { + for ($versionNum = 1; $versionNum <= 40; ++$versionNum) { + $version = Version::getVersionForNumber($versionNum); + $numBytes = $version->getTotalCodewords(); + + $ecBlocks = $version->getEcBlocksForLevel($ecLevel); + $numEcBytes = $ecBlocks->getTotalEcCodewords(); + + $numDataBytes = $numBytes - $numEcBytes; + $totalInputBytes = intdiv($numInputBits + 8, 8); + + if ($numDataBytes >= $totalInputBytes) { + return $version; + } + } + + throw new WriterException('Data too big'); + } + + /** + * Terminates the bits in a bit array. + * + * @throws WriterException if data bits cannot fit in the QR code + * @throws WriterException if bits size does not equal the capacity + */ + private static function terminateBits(int $numDataBytes, BitArray $bits) : void + { + $capacity = $numDataBytes << 3; + + if ($bits->getSize() > $capacity) { + throw new WriterException('Data bits cannot fit in the QR code'); + } + + for ($i = 0; $i < 4 && $bits->getSize() < $capacity; ++$i) { + $bits->appendBit(false); + } + + $numBitsInLastByte = $bits->getSize() & 0x7; + + if ($numBitsInLastByte > 0) { + for ($i = $numBitsInLastByte; $i < 8; ++$i) { + $bits->appendBit(false); + } + } + + $numPaddingBytes = $numDataBytes - $bits->getSizeInBytes(); + + for ($i = 0; $i < $numPaddingBytes; ++$i) { + $bits->appendBits(0 === ($i & 0x1) ? 0xec : 0x11, 8); + } + + if ($bits->getSize() !== $capacity) { + throw new WriterException('Bits size does not equal capacity'); + } + } + + /** + * Gets number of data- and EC bytes for a block ID. + * + * @return int[] + * @throws WriterException if block ID is too large + * @throws WriterException if EC bytes mismatch + * @throws WriterException if RS blocks mismatch + * @throws WriterException if total bytes mismatch + */ + private static function getNumDataBytesAndNumEcBytesForBlockId( + int $numTotalBytes, + int $numDataBytes, + int $numRsBlocks, + int $blockId + ) : array { + if ($blockId >= $numRsBlocks) { + throw new WriterException('Block ID too large'); + } + + $numRsBlocksInGroup2 = $numTotalBytes % $numRsBlocks; + $numRsBlocksInGroup1 = $numRsBlocks - $numRsBlocksInGroup2; + $numTotalBytesInGroup1 = intdiv($numTotalBytes, $numRsBlocks); + $numTotalBytesInGroup2 = $numTotalBytesInGroup1 + 1; + $numDataBytesInGroup1 = intdiv($numDataBytes, $numRsBlocks); + $numDataBytesInGroup2 = $numDataBytesInGroup1 + 1; + $numEcBytesInGroup1 = $numTotalBytesInGroup1 - $numDataBytesInGroup1; + $numEcBytesInGroup2 = $numTotalBytesInGroup2 - $numDataBytesInGroup2; + + if ($numEcBytesInGroup1 !== $numEcBytesInGroup2) { + throw new WriterException('EC bytes mismatch'); + } + + if ($numRsBlocks !== $numRsBlocksInGroup1 + $numRsBlocksInGroup2) { + throw new WriterException('RS blocks mismatch'); + } + + if ($numTotalBytes !== + (($numDataBytesInGroup1 + $numEcBytesInGroup1) * $numRsBlocksInGroup1) + + (($numDataBytesInGroup2 + $numEcBytesInGroup2) * $numRsBlocksInGroup2) + ) { + throw new WriterException('Total bytes mismatch'); + } + + if ($blockId < $numRsBlocksInGroup1) { + return [$numDataBytesInGroup1, $numEcBytesInGroup1]; + } else { + return [$numDataBytesInGroup2, $numEcBytesInGroup2]; + } + } + + /** + * Interleaves data with EC bytes. + * + * @throws WriterException if number of bits and data bytes does not match + * @throws WriterException if data bytes does not match offset + * @throws WriterException if an interleaving error occurs + */ + private static function interleaveWithEcBytes( + BitArray $bits, + int $numTotalBytes, + int $numDataBytes, + int $numRsBlocks + ) : BitArray { + if ($bits->getSizeInBytes() !== $numDataBytes) { + throw new WriterException('Number of bits and data bytes does not match'); + } + + $dataBytesOffset = 0; + $maxNumDataBytes = 0; + $maxNumEcBytes = 0; + + $blocks = new SplFixedArray($numRsBlocks); + + for ($i = 0; $i < $numRsBlocks; ++$i) { + list($numDataBytesInBlock, $numEcBytesInBlock) = self::getNumDataBytesAndNumEcBytesForBlockId( + $numTotalBytes, + $numDataBytes, + $numRsBlocks, + $i + ); + + $size = $numDataBytesInBlock; + $dataBytes = $bits->toBytes(8 * $dataBytesOffset, $size); + $ecBytes = self::generateEcBytes($dataBytes, $numEcBytesInBlock); + $blocks[$i] = new BlockPair($dataBytes, $ecBytes); + + $maxNumDataBytes = max($maxNumDataBytes, $size); + $maxNumEcBytes = max($maxNumEcBytes, count($ecBytes)); + $dataBytesOffset += $numDataBytesInBlock; + } + + if ($numDataBytes !== $dataBytesOffset) { + throw new WriterException('Data bytes does not match offset'); + } + + $result = new BitArray(); + + for ($i = 0; $i < $maxNumDataBytes; ++$i) { + foreach ($blocks as $block) { + $dataBytes = $block->getDataBytes(); + + if ($i < count($dataBytes)) { + $result->appendBits($dataBytes[$i], 8); + } + } + } + + for ($i = 0; $i < $maxNumEcBytes; ++$i) { + foreach ($blocks as $block) { + $ecBytes = $block->getErrorCorrectionBytes(); + + if ($i < count($ecBytes)) { + $result->appendBits($ecBytes[$i], 8); + } + } + } + + if ($numTotalBytes !== $result->getSizeInBytes()) { + throw new WriterException( + 'Interleaving error: ' . $numTotalBytes . ' and ' . $result->getSizeInBytes() . ' differ' + ); + } + + return $result; + } + + /** + * Generates EC bytes for given data. + * + * @param SplFixedArray $dataBytes + * @return SplFixedArray + */ + private static function generateEcBytes(SplFixedArray $dataBytes, int $numEcBytesInBlock) : SplFixedArray + { + $numDataBytes = count($dataBytes); + $toEncode = new SplFixedArray($numDataBytes + $numEcBytesInBlock); + + for ($i = 0; $i < $numDataBytes; $i++) { + $toEncode[$i] = $dataBytes[$i]; + } + + $ecBytes = new SplFixedArray($numEcBytesInBlock); + $codec = self::getCodec($numDataBytes, $numEcBytesInBlock); + $codec->encode($toEncode, $ecBytes); + + return $ecBytes; + } + + /** + * Gets an RS codec and caches it. + */ + private static function getCodec(int $numDataBytes, int $numEcBytesInBlock) : ReedSolomonCodec + { + $cacheId = $numDataBytes . '-' . $numEcBytesInBlock; + + if (isset(self::$codecs[$cacheId])) { + return self::$codecs[$cacheId]; + } + + return self::$codecs[$cacheId] = new ReedSolomonCodec( + 8, + 0x11d, + 0, + 1, + $numEcBytesInBlock, + 255 - $numDataBytes - $numEcBytesInBlock + ); + } + + /** + * Appends mode information to a bit array. + */ + private static function appendModeInfo(Mode $mode, BitArray $bits) : void + { + $bits->appendBits($mode->getBits(), 4); + } + + /** + * Appends length information to a bit array. + * + * @throws WriterException if num letters is bigger than expected + */ + private static function appendLengthInfo(int $numLetters, Version $version, Mode $mode, BitArray $bits) : void + { + $numBits = $mode->getCharacterCountBits($version); + + if ($numLetters >= (1 << $numBits)) { + throw new WriterException($numLetters . ' is bigger than ' . ((1 << $numBits) - 1)); + } + + $bits->appendBits($numLetters, $numBits); + } + + /** + * Appends bytes to a bit array in a specific mode. + */ + private static function appendBytes(string $content, Mode $mode, BitArray $bits, string $encoding) : void + { + match ($mode) { + Mode::NUMERIC() => self::appendNumericBytes($content, $bits), + Mode::ALPHANUMERIC() => self::appendAlphanumericBytes($content, $bits), + Mode::BYTE() => self::append8BitBytes($content, $bits, $encoding), + Mode::KANJI() => self::appendKanjiBytes($content, $bits), + }; + } + + /** + * Appends numeric bytes to a bit array. + */ + private static function appendNumericBytes(string $content, BitArray $bits) : void + { + $length = strlen($content); + $i = 0; + + while ($i < $length) { + $num1 = (int) $content[$i]; + + if ($i + 2 < $length) { + // Encode three numeric letters in ten bits. + $num2 = (int) $content[$i + 1]; + $num3 = (int) $content[$i + 2]; + $bits->appendBits($num1 * 100 + $num2 * 10 + $num3, 10); + $i += 3; + } elseif ($i + 1 < $length) { + // Encode two numeric letters in seven bits. + $num2 = (int) $content[$i + 1]; + $bits->appendBits($num1 * 10 + $num2, 7); + $i += 2; + } else { + // Encode one numeric letter in four bits. + $bits->appendBits($num1, 4); + ++$i; + } + } + } + + /** + * Appends alpha-numeric bytes to a bit array. + * + * @throws WriterException if an invalid alphanumeric code was found + */ + private static function appendAlphanumericBytes(string $content, BitArray $bits) : void + { + $length = strlen($content); + $i = 0; + + while ($i < $length) { + $code1 = self::getAlphanumericCode(ord($content[$i])); + + if (-1 === $code1) { + throw new WriterException('Invalid alphanumeric code'); + } + + if ($i + 1 < $length) { + $code2 = self::getAlphanumericCode(ord($content[$i + 1])); + + if (-1 === $code2) { + throw new WriterException('Invalid alphanumeric code'); + } + + // Encode two alphanumeric letters in 11 bits. + $bits->appendBits($code1 * 45 + $code2, 11); + $i += 2; + } else { + // Encode one alphanumeric letter in six bits. + $bits->appendBits($code1, 6); + ++$i; + } + } + } + + /** + * Appends regular 8-bit bytes to a bit array. + * + * @throws WriterException if content cannot be encoded to target encoding + */ + private static function append8BitBytes(string $content, BitArray $bits, string $encoding) : void + { + $bytes = @iconv('utf-8', $encoding, $content); + + if (false === $bytes) { + throw new WriterException('Could not encode content to ' . $encoding); + } + + $length = strlen($bytes); + + for ($i = 0; $i < $length; $i++) { + $bits->appendBits(ord($bytes[$i]), 8); + } + } + + /** + * Appends KANJI bytes to a bit array. + * + * @throws WriterException if content does not seem to be encoded in SHIFT-JIS + * @throws WriterException if an invalid byte sequence occurs + */ + private static function appendKanjiBytes(string $content, BitArray $bits) : void + { + $bytes = @iconv('utf-8', 'SHIFT-JIS', $content); + + if (false === $bytes) { + throw new WriterException('Content could not be converted to SHIFT-JIS'); + } + + if (strlen($bytes) % 2 > 0) { + // We just do a simple length check here. The for loop will check + // individual characters. + throw new WriterException('Content does not seem to be encoded in SHIFT-JIS'); + } + + $length = strlen($bytes); + + for ($i = 0; $i < $length; $i += 2) { + $byte1 = ord($bytes[$i]); + $byte2 = ord($bytes[$i + 1]); + $code = ($byte1 << 8) | $byte2; + + if ($code >= 0x8140 && $code <= 0x9ffc) { + $subtracted = $code - 0x8140; + } elseif ($code >= 0xe040 && $code <= 0xebbf) { + $subtracted = $code - 0xc140; + } else { + throw new WriterException('Invalid byte sequence'); + } + + $encoded = (($subtracted >> 8) * 0xc0) + ($subtracted & 0xff); + + $bits->appendBits($encoded, 13); + } + } + + /** + * Appends ECI information to a bit array. + */ + private static function appendEci(CharacterSetEci $eci, BitArray $bits) : void + { + $mode = Mode::ECI(); + $bits->appendBits($mode->getBits(), 4); + $bits->appendBits($eci->getValue(), 8); + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Encoder/MaskUtil.php b/vendor/bacon/bacon-qr-code/src/Encoder/MaskUtil.php index 497dec8..cc85a40 100644 --- a/vendor/bacon/bacon-qr-code/src/Encoder/MaskUtil.php +++ b/vendor/bacon/bacon-qr-code/src/Encoder/MaskUtil.php @@ -1,271 +1,235 @@ -getArray(); - $width = $matrix->getWidth(); - $height = $matrix->getHeight(); - - for ($y = 0; $y < $height - 1; ++$y) { - for ($x = 0; $x < $width - 1; ++$x) { - $value = $array[$y][$x]; - - if ($value === $array[$y][$x + 1] - && $value === $array[$y + 1][$x] - && $value === $array[$y + 1][$x + 1] - ) { - ++$penalty; - } - } - } - - return self::N2 * $penalty; - } - - /** - * Applies mask penalty rule 3 and returns the penalty. - * - * Finds consecutive cells of 00001011101 or 10111010000, and gives penalty - * to them. If we find patterns like 000010111010000, we give penalties - * twice (i.e. 40 * 2). - */ - public static function applyMaskPenaltyRule3(ByteMatrix $matrix) : int - { - $penalty = 0; - $array = $matrix->getArray(); - $width = $matrix->getWidth(); - $height = $matrix->getHeight(); - - for ($y = 0; $y < $height; ++$y) { - for ($x = 0; $x < $width; ++$x) { - if ($x + 6 < $width - && 1 === $array[$y][$x] - && 0 === $array[$y][$x + 1] - && 1 === $array[$y][$x + 2] - && 1 === $array[$y][$x + 3] - && 1 === $array[$y][$x + 4] - && 0 === $array[$y][$x + 5] - && 1 === $array[$y][$x + 6] - && ( - ( - $x + 10 < $width - && 0 === $array[$y][$x + 7] - && 0 === $array[$y][$x + 8] - && 0 === $array[$y][$x + 9] - && 0 === $array[$y][$x + 10] - ) - || ( - $x - 4 >= 0 - && 0 === $array[$y][$x - 1] - && 0 === $array[$y][$x - 2] - && 0 === $array[$y][$x - 3] - && 0 === $array[$y][$x - 4] - ) - ) - ) { - $penalty += self::N3; - } - - if ($y + 6 < $height - && 1 === $array[$y][$x] - && 0 === $array[$y + 1][$x] - && 1 === $array[$y + 2][$x] - && 1 === $array[$y + 3][$x] - && 1 === $array[$y + 4][$x] - && 0 === $array[$y + 5][$x] - && 1 === $array[$y + 6][$x] - && ( - ( - $y + 10 < $height - && 0 === $array[$y + 7][$x] - && 0 === $array[$y + 8][$x] - && 0 === $array[$y + 9][$x] - && 0 === $array[$y + 10][$x] - ) - || ( - $y - 4 >= 0 - && 0 === $array[$y - 1][$x] - && 0 === $array[$y - 2][$x] - && 0 === $array[$y - 3][$x] - && 0 === $array[$y - 4][$x] - ) - ) - ) { - $penalty += self::N3; - } - } - } - - return $penalty; - } - - /** - * Applies mask penalty rule 4 and returns the penalty. - * - * Calculates the ratio of dark cells and gives penalty if the ratio is far - * from 50%. It gives 10 penalty for 5% distance. - */ - public static function applyMaskPenaltyRule4(ByteMatrix $matrix) : int - { - $numDarkCells = 0; - - $array = $matrix->getArray(); - $width = $matrix->getWidth(); - $height = $matrix->getHeight(); - - for ($y = 0; $y < $height; ++$y) { - $arrayY = $array[$y]; - - for ($x = 0; $x < $width; ++$x) { - if (1 === $arrayY[$x]) { - ++$numDarkCells; - } - } - } - - $numTotalCells = $height * $width; - $darkRatio = $numDarkCells / $numTotalCells; - $fixedPercentVariances = (int) (abs($darkRatio - 0.5) * 20); - - return $fixedPercentVariances * self::N4; - } - - /** - * Returns the mask bit for "getMaskPattern" at "x" and "y". - * - * See 8.8 of JISX0510:2004 for mask pattern conditions. - * - * @throws InvalidArgumentException if an invalid mask pattern was supplied - */ - public static function getDataMaskBit(int $maskPattern, int $x, int $y) : bool - { - switch ($maskPattern) { - case 0: - $intermediate = ($y + $x) & 0x1; - break; - - case 1: - $intermediate = $y & 0x1; - break; - - case 2: - $intermediate = $x % 3; - break; - - case 3: - $intermediate = ($y + $x) % 3; - break; - - case 4: - $intermediate = (BitUtils::unsignedRightShift($y, 1) + (int) ($x / 3)) & 0x1; - break; - - case 5: - $temp = $y * $x; - $intermediate = ($temp & 0x1) + ($temp % 3); - break; - - case 6: - $temp = $y * $x; - $intermediate = (($temp & 0x1) + ($temp % 3)) & 0x1; - break; - - case 7: - $temp = $y * $x; - $intermediate = (($temp % 3) + (($y + $x) & 0x1)) & 0x1; - break; - - default: - throw new InvalidArgumentException('Invalid mask pattern: ' . $maskPattern); - } - - return 0 == $intermediate; - } - - /** - * Helper function for applyMaskPenaltyRule1. - * - * We need this for doing this calculation in both vertical and horizontal - * orders respectively. - */ - private static function applyMaskPenaltyRule1Internal(ByteMatrix $matrix, bool $isHorizontal) : int - { - $penalty = 0; - $iLimit = $isHorizontal ? $matrix->getHeight() : $matrix->getWidth(); - $jLimit = $isHorizontal ? $matrix->getWidth() : $matrix->getHeight(); - $array = $matrix->getArray(); - - for ($i = 0; $i < $iLimit; ++$i) { - $numSameBitCells = 0; - $prevBit = -1; - - for ($j = 0; $j < $jLimit; $j++) { - $bit = $isHorizontal ? $array[$i][$j] : $array[$j][$i]; - - if ($bit === $prevBit) { - ++$numSameBitCells; - } else { - if ($numSameBitCells >= 5) { - $penalty += self::N1 + ($numSameBitCells - 5); - } - - $numSameBitCells = 1; - $prevBit = $bit; - } - } - - if ($numSameBitCells >= 5) { - $penalty += self::N1 + ($numSameBitCells - 5); - } - } - - return $penalty; - } -} +getArray(); + $width = $matrix->getWidth(); + $height = $matrix->getHeight(); + + for ($y = 0; $y < $height - 1; ++$y) { + for ($x = 0; $x < $width - 1; ++$x) { + $value = $array[$y][$x]; + + if ($value === $array[$y][$x + 1] + && $value === $array[$y + 1][$x] + && $value === $array[$y + 1][$x + 1] + ) { + ++$penalty; + } + } + } + + return self::N2 * $penalty; + } + + /** + * Applies mask penalty rule 3 and returns the penalty. + * + * Finds consecutive cells of 00001011101 or 10111010000, and gives penalty + * to them. If we find patterns like 000010111010000, we give penalties + * twice (i.e. 40 * 2). + */ + public static function applyMaskPenaltyRule3(ByteMatrix $matrix) : int + { + $penalty = 0; + $array = $matrix->getArray(); + $width = $matrix->getWidth(); + $height = $matrix->getHeight(); + + for ($y = 0; $y < $height; ++$y) { + for ($x = 0; $x < $width; ++$x) { + if ($x + 6 < $width + && 1 === $array[$y][$x] + && 0 === $array[$y][$x + 1] + && 1 === $array[$y][$x + 2] + && 1 === $array[$y][$x + 3] + && 1 === $array[$y][$x + 4] + && 0 === $array[$y][$x + 5] + && 1 === $array[$y][$x + 6] + && ( + ( + $x + 10 < $width + && 0 === $array[$y][$x + 7] + && 0 === $array[$y][$x + 8] + && 0 === $array[$y][$x + 9] + && 0 === $array[$y][$x + 10] + ) + || ( + $x - 4 >= 0 + && 0 === $array[$y][$x - 1] + && 0 === $array[$y][$x - 2] + && 0 === $array[$y][$x - 3] + && 0 === $array[$y][$x - 4] + ) + ) + ) { + $penalty += self::N3; + } + + if ($y + 6 < $height + && 1 === $array[$y][$x] + && 0 === $array[$y + 1][$x] + && 1 === $array[$y + 2][$x] + && 1 === $array[$y + 3][$x] + && 1 === $array[$y + 4][$x] + && 0 === $array[$y + 5][$x] + && 1 === $array[$y + 6][$x] + && ( + ( + $y + 10 < $height + && 0 === $array[$y + 7][$x] + && 0 === $array[$y + 8][$x] + && 0 === $array[$y + 9][$x] + && 0 === $array[$y + 10][$x] + ) + || ( + $y - 4 >= 0 + && 0 === $array[$y - 1][$x] + && 0 === $array[$y - 2][$x] + && 0 === $array[$y - 3][$x] + && 0 === $array[$y - 4][$x] + ) + ) + ) { + $penalty += self::N3; + } + } + } + + return $penalty; + } + + /** + * Applies mask penalty rule 4 and returns the penalty. + * + * Calculates the ratio of dark cells and gives penalty if the ratio is far + * from 50%. It gives 10 penalty for 5% distance. + */ + public static function applyMaskPenaltyRule4(ByteMatrix $matrix) : int + { + $numDarkCells = 0; + + $array = $matrix->getArray(); + $width = $matrix->getWidth(); + $height = $matrix->getHeight(); + + for ($y = 0; $y < $height; ++$y) { + $arrayY = $array[$y]; + + for ($x = 0; $x < $width; ++$x) { + if (1 === $arrayY[$x]) { + ++$numDarkCells; + } + } + } + + $numTotalCells = $height * $width; + $darkRatio = $numDarkCells / $numTotalCells; + $fixedPercentVariances = (int) floor(abs($darkRatio - 0.5) * 20); + + return $fixedPercentVariances * self::N4; + } + + /** + * Returns the mask bit for "getMaskPattern" at "x" and "y". + * + * See 8.8 of JISX0510:2004 for mask pattern conditions. + */ + public static function getDataMaskBit(int $maskPattern, int $x, int $y) : bool + { + return 0 === match ($maskPattern) { + 0 => ($x + $y) % 2, + 1 => $y % 2, + 2 => $x % 3, + 3 => ($x + $y) % 3, + 4 => (intdiv($y, 2) + intdiv($x, 3)) % 2, + 5 => (($x * $y) % 2) + (($x * $y) % 3), + 6 => ((($x * $y) % 2) + (($x * $y) % 3)) % 2, + 7 => ((($x + $y) % 2) + (($x * $y) % 3)) % 2, + }; + } + + /** + * Helper function for applyMaskPenaltyRule1. + * + * We need this for doing this calculation in both vertical and horizontal + * orders respectively. + */ + private static function applyMaskPenaltyRule1Internal(ByteMatrix $matrix, bool $isHorizontal) : int + { + $penalty = 0; + $iLimit = $isHorizontal ? $matrix->getHeight() : $matrix->getWidth(); + $jLimit = $isHorizontal ? $matrix->getWidth() : $matrix->getHeight(); + $array = $matrix->getArray(); + + for ($i = 0; $i < $iLimit; ++$i) { + $numSameBitCells = 0; + $prevBit = -1; + + for ($j = 0; $j < $jLimit; $j++) { + $bit = $isHorizontal ? $array[$i][$j] : $array[$j][$i]; + + if ($bit === $prevBit) { + ++$numSameBitCells; + } else { + if ($numSameBitCells >= 5) { + $penalty += self::N1 + ($numSameBitCells - 5); + } + + $numSameBitCells = 1; + $prevBit = $bit; + } + } + + if ($numSameBitCells >= 5) { + $penalty += self::N1 + ($numSameBitCells - 5); + } + } + + return $penalty; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Encoder/MatrixUtil.php b/vendor/bacon/bacon-qr-code/src/Encoder/MatrixUtil.php index 4b233e3..0967e29 100644 --- a/vendor/bacon/bacon-qr-code/src/Encoder/MatrixUtil.php +++ b/vendor/bacon/bacon-qr-code/src/Encoder/MatrixUtil.php @@ -1,513 +1,513 @@ -clear(-1); - } - - /** - * Builds a complete matrix. - */ - public static function buildMatrix( - BitArray $dataBits, - ErrorCorrectionLevel $level, - Version $version, - int $maskPattern, - ByteMatrix $matrix - ) : void { - self::clearMatrix($matrix); - self::embedBasicPatterns($version, $matrix); - self::embedTypeInfo($level, $maskPattern, $matrix); - self::maybeEmbedVersionInfo($version, $matrix); - self::embedDataBits($dataBits, $maskPattern, $matrix); - } - - /** - * Removes the position detection patterns from a matrix. - * - * This can be useful if you need to render those patterns separately. - */ - public static function removePositionDetectionPatterns(ByteMatrix $matrix) : void - { - $pdpWidth = count(self::POSITION_DETECTION_PATTERN[0]); - - self::removePositionDetectionPattern(0, 0, $matrix); - self::removePositionDetectionPattern($matrix->getWidth() - $pdpWidth, 0, $matrix); - self::removePositionDetectionPattern(0, $matrix->getWidth() - $pdpWidth, $matrix); - } - - /** - * Embeds type information into a matrix. - */ - private static function embedTypeInfo(ErrorCorrectionLevel $level, int $maskPattern, ByteMatrix $matrix) : void - { - $typeInfoBits = new BitArray(); - self::makeTypeInfoBits($level, $maskPattern, $typeInfoBits); - - $typeInfoBitsSize = $typeInfoBits->getSize(); - - for ($i = 0; $i < $typeInfoBitsSize; ++$i) { - $bit = $typeInfoBits->get($typeInfoBitsSize - 1 - $i); - - $x1 = self::TYPE_INFO_COORDINATES[$i][0]; - $y1 = self::TYPE_INFO_COORDINATES[$i][1]; - - $matrix->set($x1, $y1, (int) $bit); - - if ($i < 8) { - $x2 = $matrix->getWidth() - $i - 1; - $y2 = 8; - } else { - $x2 = 8; - $y2 = $matrix->getHeight() - 7 + ($i - 8); - } - - $matrix->set($x2, $y2, (int) $bit); - } - } - - /** - * Generates type information bits and appends them to a bit array. - * - * @throws RuntimeException if bit array resulted in invalid size - */ - private static function makeTypeInfoBits(ErrorCorrectionLevel $level, int $maskPattern, BitArray $bits) : void - { - $typeInfo = ($level->getBits() << 3) | $maskPattern; - $bits->appendBits($typeInfo, 5); - - $bchCode = self::calculateBchCode($typeInfo, self::TYPE_INFO_POLY); - $bits->appendBits($bchCode, 10); - - $maskBits = new BitArray(); - $maskBits->appendBits(self::TYPE_INFO_MASK_PATTERN, 15); - $bits->xorBits($maskBits); - - if (15 !== $bits->getSize()) { - throw new RuntimeException('Bit array resulted in invalid size: ' . $bits->getSize()); - } - } - - /** - * Embeds version information if required. - */ - private static function maybeEmbedVersionInfo(Version $version, ByteMatrix $matrix) : void - { - if ($version->getVersionNumber() < 7) { - return; - } - - $versionInfoBits = new BitArray(); - self::makeVersionInfoBits($version, $versionInfoBits); - - $bitIndex = 6 * 3 - 1; - - for ($i = 0; $i < 6; ++$i) { - for ($j = 0; $j < 3; ++$j) { - $bit = $versionInfoBits->get($bitIndex); - --$bitIndex; - - $matrix->set($i, $matrix->getHeight() - 11 + $j, (int) $bit); - $matrix->set($matrix->getHeight() - 11 + $j, $i, (int) $bit); - } - } - } - - /** - * Generates version information bits and appends them to a bit array. - * - * @throws RuntimeException if bit array resulted in invalid size - */ - private static function makeVersionInfoBits(Version $version, BitArray $bits) : void - { - $bits->appendBits($version->getVersionNumber(), 6); - - $bchCode = self::calculateBchCode($version->getVersionNumber(), self::VERSION_INFO_POLY); - $bits->appendBits($bchCode, 12); - - if (18 !== $bits->getSize()) { - throw new RuntimeException('Bit array resulted in invalid size: ' . $bits->getSize()); - } - } - - /** - * Calculates the BCH code for a value and a polynomial. - */ - private static function calculateBchCode(int $value, int $poly) : int - { - $msbSetInPoly = self::findMsbSet($poly); - $value <<= $msbSetInPoly - 1; - - while (self::findMsbSet($value) >= $msbSetInPoly) { - $value ^= $poly << (self::findMsbSet($value) - $msbSetInPoly); - } - - return $value; - } - - /** - * Finds and MSB set. - */ - private static function findMsbSet(int $value) : int - { - $numDigits = 0; - - while (0 !== $value) { - $value >>= 1; - ++$numDigits; - } - - return $numDigits; - } - - /** - * Embeds basic patterns into a matrix. - */ - private static function embedBasicPatterns(Version $version, ByteMatrix $matrix) : void - { - self::embedPositionDetectionPatternsAndSeparators($matrix); - self::embedDarkDotAtLeftBottomCorner($matrix); - self::maybeEmbedPositionAdjustmentPatterns($version, $matrix); - self::embedTimingPatterns($matrix); - } - - /** - * Embeds position detection patterns and separators into a byte matrix. - */ - private static function embedPositionDetectionPatternsAndSeparators(ByteMatrix $matrix) : void - { - $pdpWidth = count(self::POSITION_DETECTION_PATTERN[0]); - - self::embedPositionDetectionPattern(0, 0, $matrix); - self::embedPositionDetectionPattern($matrix->getWidth() - $pdpWidth, 0, $matrix); - self::embedPositionDetectionPattern(0, $matrix->getWidth() - $pdpWidth, $matrix); - - $hspWidth = 8; - - self::embedHorizontalSeparationPattern(0, $hspWidth - 1, $matrix); - self::embedHorizontalSeparationPattern($matrix->getWidth() - $hspWidth, $hspWidth - 1, $matrix); - self::embedHorizontalSeparationPattern(0, $matrix->getWidth() - $hspWidth, $matrix); - - $vspSize = 7; - - self::embedVerticalSeparationPattern($vspSize, 0, $matrix); - self::embedVerticalSeparationPattern($matrix->getHeight() - $vspSize - 1, 0, $matrix); - self::embedVerticalSeparationPattern($vspSize, $matrix->getHeight() - $vspSize, $matrix); - } - - /** - * Embeds a single position detection pattern into a byte matrix. - */ - private static function embedPositionDetectionPattern(int $xStart, int $yStart, ByteMatrix $matrix) : void - { - for ($y = 0; $y < 7; ++$y) { - for ($x = 0; $x < 7; ++$x) { - $matrix->set($xStart + $x, $yStart + $y, self::POSITION_DETECTION_PATTERN[$y][$x]); - } - } - } - - private static function removePositionDetectionPattern(int $xStart, int $yStart, ByteMatrix $matrix) : void - { - for ($y = 0; $y < 7; ++$y) { - for ($x = 0; $x < 7; ++$x) { - $matrix->set($xStart + $x, $yStart + $y, 0); - } - } - } - - /** - * Embeds a single horizontal separation pattern. - * - * @throws RuntimeException if a byte was already set - */ - private static function embedHorizontalSeparationPattern(int $xStart, int $yStart, ByteMatrix $matrix) : void - { - for ($x = 0; $x < 8; $x++) { - if (-1 !== $matrix->get($xStart + $x, $yStart)) { - throw new RuntimeException('Byte already set'); - } - - $matrix->set($xStart + $x, $yStart, 0); - } - } - - /** - * Embeds a single vertical separation pattern. - * - * @throws RuntimeException if a byte was already set - */ - private static function embedVerticalSeparationPattern(int $xStart, int $yStart, ByteMatrix $matrix) : void - { - for ($y = 0; $y < 7; $y++) { - if (-1 !== $matrix->get($xStart, $yStart + $y)) { - throw new RuntimeException('Byte already set'); - } - - $matrix->set($xStart, $yStart + $y, 0); - } - } - - /** - * Embeds a dot at the left bottom corner. - * - * @throws RuntimeException if a byte was already set to 0 - */ - private static function embedDarkDotAtLeftBottomCorner(ByteMatrix $matrix) : void - { - if (0 === $matrix->get(8, $matrix->getHeight() - 8)) { - throw new RuntimeException('Byte already set to 0'); - } - - $matrix->set(8, $matrix->getHeight() - 8, 1); - } - - /** - * Embeds position adjustment patterns if required. - */ - private static function maybeEmbedPositionAdjustmentPatterns(Version $version, ByteMatrix $matrix) : void - { - if ($version->getVersionNumber() < 2) { - return; - } - - $index = $version->getVersionNumber() - 1; - - $coordinates = self::POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[$index]; - $numCoordinates = count($coordinates); - - for ($i = 0; $i < $numCoordinates; ++$i) { - for ($j = 0; $j < $numCoordinates; ++$j) { - $y = $coordinates[$i]; - $x = $coordinates[$j]; - - if (null === $x || null === $y) { - continue; - } - - if (-1 === $matrix->get($x, $y)) { - self::embedPositionAdjustmentPattern($x - 2, $y - 2, $matrix); - } - } - } - } - - /** - * Embeds a single position adjustment pattern. - */ - private static function embedPositionAdjustmentPattern(int $xStart, int $yStart, ByteMatrix $matrix) : void - { - for ($y = 0; $y < 5; $y++) { - for ($x = 0; $x < 5; $x++) { - $matrix->set($xStart + $x, $yStart + $y, self::POSITION_ADJUSTMENT_PATTERN[$y][$x]); - } - } - } - - /** - * Embeds timing patterns into a matrix. - */ - private static function embedTimingPatterns(ByteMatrix $matrix) : void - { - $matrixWidth = $matrix->getWidth(); - - for ($i = 8; $i < $matrixWidth - 8; ++$i) { - $bit = ($i + 1) % 2; - - if (-1 === $matrix->get($i, 6)) { - $matrix->set($i, 6, $bit); - } - - if (-1 === $matrix->get(6, $i)) { - $matrix->set(6, $i, $bit); - } - } - } - - /** - * Embeds "dataBits" using "getMaskPattern". - * - * For debugging purposes, it skips masking process if "getMaskPattern" is -1. See 8.7 of JISX0510:2004 (p.38) for - * how to embed data bits. - * - * @throws WriterException if not all bits could be consumed - */ - private static function embedDataBits(BitArray $dataBits, int $maskPattern, ByteMatrix $matrix) : void - { - $bitIndex = 0; - $direction = -1; - - // Start from the right bottom cell. - $x = $matrix->getWidth() - 1; - $y = $matrix->getHeight() - 1; - - while ($x > 0) { - // Skip vertical timing pattern. - if (6 === $x) { - --$x; - } - - while ($y >= 0 && $y < $matrix->getHeight()) { - for ($i = 0; $i < 2; $i++) { - $xx = $x - $i; - - // Skip the cell if it's not empty. - if (-1 !== $matrix->get($xx, $y)) { - continue; - } - - if ($bitIndex < $dataBits->getSize()) { - $bit = $dataBits->get($bitIndex); - ++$bitIndex; - } else { - // Padding bit. If there is no bit left, we'll fill the - // left cells with 0, as described in 8.4.9 of - // JISX0510:2004 (p. 24). - $bit = false; - } - - // Skip masking if maskPattern is -1. - if (-1 !== $maskPattern && MaskUtil::getDataMaskBit($maskPattern, $xx, $y)) { - $bit = ! $bit; - } - - $matrix->set($xx, $y, (int) $bit); - } - - $y += $direction; - } - - $direction = -$direction; - $y += $direction; - $x -= 2; - } - - // All bits should be consumed - if ($dataBits->getSize() !== $bitIndex) { - throw new WriterException('Not all bits consumed (' . $bitIndex . ' out of ' . $dataBits->getSize() .')'); - } - } -} +clear(-1); + } + + /** + * Builds a complete matrix. + */ + public static function buildMatrix( + BitArray $dataBits, + ErrorCorrectionLevel $level, + Version $version, + int $maskPattern, + ByteMatrix $matrix + ) : void { + self::clearMatrix($matrix); + self::embedBasicPatterns($version, $matrix); + self::embedTypeInfo($level, $maskPattern, $matrix); + self::maybeEmbedVersionInfo($version, $matrix); + self::embedDataBits($dataBits, $maskPattern, $matrix); + } + + /** + * Removes the position detection patterns from a matrix. + * + * This can be useful if you need to render those patterns separately. + */ + public static function removePositionDetectionPatterns(ByteMatrix $matrix) : void + { + $pdpWidth = count(self::POSITION_DETECTION_PATTERN[0]); + + self::removePositionDetectionPattern(0, 0, $matrix); + self::removePositionDetectionPattern($matrix->getWidth() - $pdpWidth, 0, $matrix); + self::removePositionDetectionPattern(0, $matrix->getWidth() - $pdpWidth, $matrix); + } + + /** + * Embeds type information into a matrix. + */ + private static function embedTypeInfo(ErrorCorrectionLevel $level, int $maskPattern, ByteMatrix $matrix) : void + { + $typeInfoBits = new BitArray(); + self::makeTypeInfoBits($level, $maskPattern, $typeInfoBits); + + $typeInfoBitsSize = $typeInfoBits->getSize(); + + for ($i = 0; $i < $typeInfoBitsSize; ++$i) { + $bit = $typeInfoBits->get($typeInfoBitsSize - 1 - $i); + + $x1 = self::TYPE_INFO_COORDINATES[$i][0]; + $y1 = self::TYPE_INFO_COORDINATES[$i][1]; + + $matrix->set($x1, $y1, (int) $bit); + + if ($i < 8) { + $x2 = $matrix->getWidth() - $i - 1; + $y2 = 8; + } else { + $x2 = 8; + $y2 = $matrix->getHeight() - 7 + ($i - 8); + } + + $matrix->set($x2, $y2, (int) $bit); + } + } + + /** + * Generates type information bits and appends them to a bit array. + * + * @throws RuntimeException if bit array resulted in invalid size + */ + private static function makeTypeInfoBits(ErrorCorrectionLevel $level, int $maskPattern, BitArray $bits) : void + { + $typeInfo = ($level->getBits() << 3) | $maskPattern; + $bits->appendBits($typeInfo, 5); + + $bchCode = self::calculateBchCode($typeInfo, self::TYPE_INFO_POLY); + $bits->appendBits($bchCode, 10); + + $maskBits = new BitArray(); + $maskBits->appendBits(self::TYPE_INFO_MASK_PATTERN, 15); + $bits->xorBits($maskBits); + + if (15 !== $bits->getSize()) { + throw new RuntimeException('Bit array resulted in invalid size: ' . $bits->getSize()); + } + } + + /** + * Embeds version information if required. + */ + private static function maybeEmbedVersionInfo(Version $version, ByteMatrix $matrix) : void + { + if ($version->getVersionNumber() < 7) { + return; + } + + $versionInfoBits = new BitArray(); + self::makeVersionInfoBits($version, $versionInfoBits); + + $bitIndex = 6 * 3 - 1; + + for ($i = 0; $i < 6; ++$i) { + for ($j = 0; $j < 3; ++$j) { + $bit = $versionInfoBits->get($bitIndex); + --$bitIndex; + + $matrix->set($i, $matrix->getHeight() - 11 + $j, (int) $bit); + $matrix->set($matrix->getHeight() - 11 + $j, $i, (int) $bit); + } + } + } + + /** + * Generates version information bits and appends them to a bit array. + * + * @throws RuntimeException if bit array resulted in invalid size + */ + private static function makeVersionInfoBits(Version $version, BitArray $bits) : void + { + $bits->appendBits($version->getVersionNumber(), 6); + + $bchCode = self::calculateBchCode($version->getVersionNumber(), self::VERSION_INFO_POLY); + $bits->appendBits($bchCode, 12); + + if (18 !== $bits->getSize()) { + throw new RuntimeException('Bit array resulted in invalid size: ' . $bits->getSize()); + } + } + + /** + * Calculates the BCH code for a value and a polynomial. + */ + private static function calculateBchCode(int $value, int $poly) : int + { + $msbSetInPoly = self::findMsbSet($poly); + $value <<= $msbSetInPoly - 1; + + while (self::findMsbSet($value) >= $msbSetInPoly) { + $value ^= $poly << (self::findMsbSet($value) - $msbSetInPoly); + } + + return $value; + } + + /** + * Finds and MSB set. + */ + private static function findMsbSet(int $value) : int + { + $numDigits = 0; + + while (0 !== $value) { + $value >>= 1; + ++$numDigits; + } + + return $numDigits; + } + + /** + * Embeds basic patterns into a matrix. + */ + private static function embedBasicPatterns(Version $version, ByteMatrix $matrix) : void + { + self::embedPositionDetectionPatternsAndSeparators($matrix); + self::embedDarkDotAtLeftBottomCorner($matrix); + self::maybeEmbedPositionAdjustmentPatterns($version, $matrix); + self::embedTimingPatterns($matrix); + } + + /** + * Embeds position detection patterns and separators into a byte matrix. + */ + private static function embedPositionDetectionPatternsAndSeparators(ByteMatrix $matrix) : void + { + $pdpWidth = count(self::POSITION_DETECTION_PATTERN[0]); + + self::embedPositionDetectionPattern(0, 0, $matrix); + self::embedPositionDetectionPattern($matrix->getWidth() - $pdpWidth, 0, $matrix); + self::embedPositionDetectionPattern(0, $matrix->getWidth() - $pdpWidth, $matrix); + + $hspWidth = 8; + + self::embedHorizontalSeparationPattern(0, $hspWidth - 1, $matrix); + self::embedHorizontalSeparationPattern($matrix->getWidth() - $hspWidth, $hspWidth - 1, $matrix); + self::embedHorizontalSeparationPattern(0, $matrix->getWidth() - $hspWidth, $matrix); + + $vspSize = 7; + + self::embedVerticalSeparationPattern($vspSize, 0, $matrix); + self::embedVerticalSeparationPattern($matrix->getHeight() - $vspSize - 1, 0, $matrix); + self::embedVerticalSeparationPattern($vspSize, $matrix->getHeight() - $vspSize, $matrix); + } + + /** + * Embeds a single position detection pattern into a byte matrix. + */ + private static function embedPositionDetectionPattern(int $xStart, int $yStart, ByteMatrix $matrix) : void + { + for ($y = 0; $y < 7; ++$y) { + for ($x = 0; $x < 7; ++$x) { + $matrix->set($xStart + $x, $yStart + $y, self::POSITION_DETECTION_PATTERN[$y][$x]); + } + } + } + + private static function removePositionDetectionPattern(int $xStart, int $yStart, ByteMatrix $matrix) : void + { + for ($y = 0; $y < 7; ++$y) { + for ($x = 0; $x < 7; ++$x) { + $matrix->set($xStart + $x, $yStart + $y, 0); + } + } + } + + /** + * Embeds a single horizontal separation pattern. + * + * @throws RuntimeException if a byte was already set + */ + private static function embedHorizontalSeparationPattern(int $xStart, int $yStart, ByteMatrix $matrix) : void + { + for ($x = 0; $x < 8; $x++) { + if (-1 !== $matrix->get($xStart + $x, $yStart)) { + throw new RuntimeException('Byte already set'); + } + + $matrix->set($xStart + $x, $yStart, 0); + } + } + + /** + * Embeds a single vertical separation pattern. + * + * @throws RuntimeException if a byte was already set + */ + private static function embedVerticalSeparationPattern(int $xStart, int $yStart, ByteMatrix $matrix) : void + { + for ($y = 0; $y < 7; $y++) { + if (-1 !== $matrix->get($xStart, $yStart + $y)) { + throw new RuntimeException('Byte already set'); + } + + $matrix->set($xStart, $yStart + $y, 0); + } + } + + /** + * Embeds a dot at the left bottom corner. + * + * @throws RuntimeException if a byte was already set to 0 + */ + private static function embedDarkDotAtLeftBottomCorner(ByteMatrix $matrix) : void + { + if (0 === $matrix->get(8, $matrix->getHeight() - 8)) { + throw new RuntimeException('Byte already set to 0'); + } + + $matrix->set(8, $matrix->getHeight() - 8, 1); + } + + /** + * Embeds position adjustment patterns if required. + */ + private static function maybeEmbedPositionAdjustmentPatterns(Version $version, ByteMatrix $matrix) : void + { + if ($version->getVersionNumber() < 2) { + return; + } + + $index = $version->getVersionNumber() - 1; + + $coordinates = self::POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[$index]; + $numCoordinates = count($coordinates); + + for ($i = 0; $i < $numCoordinates; ++$i) { + for ($j = 0; $j < $numCoordinates; ++$j) { + $y = $coordinates[$i]; + $x = $coordinates[$j]; + + if (null === $x || null === $y) { + continue; + } + + if (-1 === $matrix->get($x, $y)) { + self::embedPositionAdjustmentPattern($x - 2, $y - 2, $matrix); + } + } + } + } + + /** + * Embeds a single position adjustment pattern. + */ + private static function embedPositionAdjustmentPattern(int $xStart, int $yStart, ByteMatrix $matrix) : void + { + for ($y = 0; $y < 5; $y++) { + for ($x = 0; $x < 5; $x++) { + $matrix->set($xStart + $x, $yStart + $y, self::POSITION_ADJUSTMENT_PATTERN[$y][$x]); + } + } + } + + /** + * Embeds timing patterns into a matrix. + */ + private static function embedTimingPatterns(ByteMatrix $matrix) : void + { + $matrixWidth = $matrix->getWidth(); + + for ($i = 8; $i < $matrixWidth - 8; ++$i) { + $bit = ($i + 1) % 2; + + if (-1 === $matrix->get($i, 6)) { + $matrix->set($i, 6, $bit); + } + + if (-1 === $matrix->get(6, $i)) { + $matrix->set(6, $i, $bit); + } + } + } + + /** + * Embeds "dataBits" using "getMaskPattern". + * + * For debugging purposes, it skips masking process if "getMaskPattern" is -1. See 8.7 of JISX0510:2004 (p.38) for + * how to embed data bits. + * + * @throws WriterException if not all bits could be consumed + */ + private static function embedDataBits(BitArray $dataBits, int $maskPattern, ByteMatrix $matrix) : void + { + $bitIndex = 0; + $direction = -1; + + // Start from the right bottom cell. + $x = $matrix->getWidth() - 1; + $y = $matrix->getHeight() - 1; + + while ($x > 0) { + // Skip vertical timing pattern. + if (6 === $x) { + --$x; + } + + while ($y >= 0 && $y < $matrix->getHeight()) { + for ($i = 0; $i < 2; $i++) { + $xx = $x - $i; + + // Skip the cell if it's not empty. + if (-1 !== $matrix->get($xx, $y)) { + continue; + } + + if ($bitIndex < $dataBits->getSize()) { + $bit = $dataBits->get($bitIndex); + ++$bitIndex; + } else { + // Padding bit. If there is no bit left, we'll fill the + // left cells with 0, as described in 8.4.9 of + // JISX0510:2004 (p. 24). + $bit = false; + } + + // Skip masking if maskPattern is -1. + if (-1 !== $maskPattern && MaskUtil::getDataMaskBit($maskPattern, $xx, $y)) { + $bit = ! $bit; + } + + $matrix->set($xx, $y, (int) $bit); + } + + $y += $direction; + } + + $direction = -$direction; + $y += $direction; + $x -= 2; + } + + // All bits should be consumed + if ($dataBits->getSize() !== $bitIndex) { + throw new WriterException('Not all bits consumed (' . $bitIndex . ' out of ' . $dataBits->getSize() .')'); + } + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Encoder/QrCode.php b/vendor/bacon/bacon-qr-code/src/Encoder/QrCode.php index 11eff70..c3398f4 100644 --- a/vendor/bacon/bacon-qr-code/src/Encoder/QrCode.php +++ b/vendor/bacon/bacon-qr-code/src/Encoder/QrCode.php @@ -1,108 +1,108 @@ -maskPattern = $maskPattern; - $this->matrix = $matrix; - } - - /** - * Gets the mode. - */ - public function getMode() : Mode - { - return $this->mode; - } - - /** - * Gets the EC level. - */ - public function getErrorCorrectionLevel() : ErrorCorrectionLevel - { - return $this->errorCorrectionLevel; - } - - /** - * Gets the version. - */ - public function getVersion() : Version - { - return $this->version; - } - - /** - * Gets the mask pattern. - */ - public function getMaskPattern() : int - { - return $this->maskPattern; - } - - public function getMatrix(): ByteMatrix - { - return $this->matrix; - } - - /** - * Validates whether a mask pattern is valid. - */ - public static function isValidMaskPattern(int $maskPattern) : bool - { - return $maskPattern > 0 && $maskPattern < self::NUM_MASK_PATTERNS; - } - - /** - * Returns a string representation of the QR code. - */ - public function __toString() : string - { - $result = "<<\n" - . ' mode: ' . $this->mode . "\n" - . ' ecLevel: ' . $this->errorCorrectionLevel . "\n" - . ' version: ' . $this->version . "\n" - . ' maskPattern: ' . $this->maskPattern . "\n"; - - if ($this->matrix === null) { - $result .= " matrix: null\n"; - } else { - $result .= " matrix:\n"; - $result .= $this->matrix; - } - - $result .= ">>\n"; - - return $result; - } -} +maskPattern = $maskPattern; + $this->matrix = $matrix; + } + + /** + * Gets the mode. + */ + public function getMode() : Mode + { + return $this->mode; + } + + /** + * Gets the EC level. + */ + public function getErrorCorrectionLevel() : ErrorCorrectionLevel + { + return $this->errorCorrectionLevel; + } + + /** + * Gets the version. + */ + public function getVersion() : Version + { + return $this->version; + } + + /** + * Gets the mask pattern. + */ + public function getMaskPattern() : int + { + return $this->maskPattern; + } + + public function getMatrix(): ByteMatrix + { + return $this->matrix; + } + + /** + * Validates whether a mask pattern is valid. + */ + public static function isValidMaskPattern(int $maskPattern) : bool + { + return $maskPattern > 0 && $maskPattern < self::NUM_MASK_PATTERNS; + } + + /** + * Returns a string representation of the QR code. + */ + public function __toString() : string + { + $result = "<<\n" + . ' mode: ' . $this->mode . "\n" + . ' ecLevel: ' . $this->errorCorrectionLevel . "\n" + . ' version: ' . $this->version . "\n" + . ' maskPattern: ' . $this->maskPattern . "\n"; + + if ($this->matrix === null) { + $result .= " matrix: null\n"; + } else { + $result .= " matrix:\n"; + $result .= $this->matrix; + } + + $result .= ">>\n"; + + return $result; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Exception/ExceptionInterface.php b/vendor/bacon/bacon-qr-code/src/Exception/ExceptionInterface.php index c402c54..6f70c20 100644 --- a/vendor/bacon/bacon-qr-code/src/Exception/ExceptionInterface.php +++ b/vendor/bacon/bacon-qr-code/src/Exception/ExceptionInterface.php @@ -1,10 +1,10 @@ - 100) { - throw new Exception\InvalidArgumentException('Alpha must be between 0 and 100'); - } - } - - public function getAlpha() : int - { - return $this->alpha; - } - - public function getBaseColor() : ColorInterface - { - return $this->baseColor; - } - - public function toRgb() : Rgb - { - return $this->baseColor->toRgb(); - } - - public function toCmyk() : Cmyk - { - return $this->baseColor->toCmyk(); - } - - public function toGray() : Gray - { - return $this->baseColor->toGray(); - } -} + 100) { + throw new Exception\InvalidArgumentException('Alpha must be between 0 and 100'); + } + } + + public function getAlpha() : int + { + return $this->alpha; + } + + public function getBaseColor() : ColorInterface + { + return $this->baseColor; + } + + public function toRgb() : Rgb + { + return $this->baseColor->toRgb(); + } + + public function toCmyk() : Cmyk + { + return $this->baseColor->toCmyk(); + } + + public function toGray() : Gray + { + return $this->baseColor->toGray(); + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Color/Cmyk.php b/vendor/bacon/bacon-qr-code/src/Renderer/Color/Cmyk.php index a802ebd..eaf34f4 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Color/Cmyk.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Color/Cmyk.php @@ -1,82 +1,82 @@ - 100) { - throw new Exception\InvalidArgumentException('Cyan must be between 0 and 100'); - } - - if ($magenta < 0 || $magenta > 100) { - throw new Exception\InvalidArgumentException('Magenta must be between 0 and 100'); - } - - if ($yellow < 0 || $yellow > 100) { - throw new Exception\InvalidArgumentException('Yellow must be between 0 and 100'); - } - - if ($black < 0 || $black > 100) { - throw new Exception\InvalidArgumentException('Black must be between 0 and 100'); - } - } - - public function getCyan() : int - { - return $this->cyan; - } - - public function getMagenta() : int - { - return $this->magenta; - } - - public function getYellow() : int - { - return $this->yellow; - } - - public function getBlack() : int - { - return $this->black; - } - - public function toRgb() : Rgb - { - $k = $this->black / 100; - $c = (-$k * $this->cyan + $k * 100 + $this->cyan) / 100; - $m = (-$k * $this->magenta + $k * 100 + $this->magenta) / 100; - $y = (-$k * $this->yellow + $k * 100 + $this->yellow) / 100; - - return new Rgb( - (int) (-$c * 255 + 255), - (int) (-$m * 255 + 255), - (int) (-$y * 255 + 255) - ); - } - - public function toCmyk() : Cmyk - { - return $this; - } - - public function toGray() : Gray - { - return $this->toRgb()->toGray(); - } -} + 100) { + throw new Exception\InvalidArgumentException('Cyan must be between 0 and 100'); + } + + if ($magenta < 0 || $magenta > 100) { + throw new Exception\InvalidArgumentException('Magenta must be between 0 and 100'); + } + + if ($yellow < 0 || $yellow > 100) { + throw new Exception\InvalidArgumentException('Yellow must be between 0 and 100'); + } + + if ($black < 0 || $black > 100) { + throw new Exception\InvalidArgumentException('Black must be between 0 and 100'); + } + } + + public function getCyan() : int + { + return $this->cyan; + } + + public function getMagenta() : int + { + return $this->magenta; + } + + public function getYellow() : int + { + return $this->yellow; + } + + public function getBlack() : int + { + return $this->black; + } + + public function toRgb() : Rgb + { + $c = $this->cyan / 100; + $m = $this->magenta / 100; + $y = $this->yellow / 100; + $k = $this->black / 100; + + return new Rgb( + (int) round(255 * (1 - $c) * (1 - $k)), + (int) round(255 * (1 - $m) * (1 - $k)), + (int) round(255 * (1 - $y) * (1 - $k)) + ); + } + + public function toCmyk() : Cmyk + { + return $this; + } + + public function toGray() : Gray + { + return $this->toRgb()->toGray(); + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Color/ColorInterface.php b/vendor/bacon/bacon-qr-code/src/Renderer/Color/ColorInterface.php index 3452adc..b50d1ca 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Color/ColorInterface.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Color/ColorInterface.php @@ -1,22 +1,22 @@ - 100) { - throw new Exception\InvalidArgumentException('Gray must be between 0 and 100'); - } - } - - public function getGray() : int - { - return $this->gray; - } - - public function toRgb() : Rgb - { - return new Rgb((int) ($this->gray * 2.55), (int) ($this->gray * 2.55), (int) ($this->gray * 2.55)); - } - - public function toCmyk() : Cmyk - { - return new Cmyk(0, 0, 0, 100 - $this->gray); - } - - public function toGray() : Gray - { - return $this; - } -} + 100) { + throw new Exception\InvalidArgumentException('Gray must be between 0 and 100'); + } + } + + public function getGray() : int + { + return $this->gray; + } + + public function toRgb() : Rgb + { + // use 255/100 instead of 2.55 to avoid floating-point precision loss (100 * 2.55 = 254.999...) + $value = (int) round($this->gray * 255 / 100); + + return new Rgb($value, $value, $value); + } + + public function toCmyk() : Cmyk + { + return new Cmyk(0, 0, 0, 100 - $this->gray); + } + + public function toGray() : Gray + { + return $this; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Color/Rgb.php b/vendor/bacon/bacon-qr-code/src/Renderer/Color/Rgb.php index 70c1f4b..051c5be 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Color/Rgb.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Color/Rgb.php @@ -1,73 +1,75 @@ - 255) { - throw new Exception\InvalidArgumentException('Red must be between 0 and 255'); - } - - if ($green < 0 || $green > 255) { - throw new Exception\InvalidArgumentException('Green must be between 0 and 255'); - } - - if ($blue < 0 || $blue > 255) { - throw new Exception\InvalidArgumentException('Blue must be between 0 and 255'); - } - } - - public function getRed() : int - { - return $this->red; - } - - public function getGreen() : int - { - return $this->green; - } - - public function getBlue() : int - { - return $this->blue; - } - - public function toRgb() : Rgb - { - return $this; - } - - public function toCmyk() : Cmyk - { - $c = 1 - ($this->red / 255); - $m = 1 - ($this->green / 255); - $y = 1 - ($this->blue / 255); - $k = min($c, $m, $y); - - if ($k === 0) { - return new Cmyk(0, 0, 0, 0); - } - - return new Cmyk( - (int) (100 * ($c - $k) / (1 - $k)), - (int) (100 * ($m - $k) / (1 - $k)), - (int) (100 * ($y - $k) / (1 - $k)), - (int) (100 * $k) - ); - } - - public function toGray() : Gray - { - return new Gray((int) (($this->red * 0.21 + $this->green * 0.71 + $this->blue * 0.07) / 2.55)); - } -} + 255) { + throw new Exception\InvalidArgumentException('Red must be between 0 and 255'); + } + + if ($green < 0 || $green > 255) { + throw new Exception\InvalidArgumentException('Green must be between 0 and 255'); + } + + if ($blue < 0 || $blue > 255) { + throw new Exception\InvalidArgumentException('Blue must be between 0 and 255'); + } + } + + public function getRed() : int + { + return $this->red; + } + + public function getGreen() : int + { + return $this->green; + } + + public function getBlue() : int + { + return $this->blue; + } + + public function toRgb() : Rgb + { + return $this; + } + + public function toCmyk() : Cmyk + { + // avoid division by zero with input rgb(0,0,0), by handling it as a specific case + if (0 === $this->red && 0 === $this->green && 0 === $this->blue) { + return new Cmyk(0, 0, 0, 100); + } + + $c = 1 - ($this->red / 255); + $m = 1 - ($this->green / 255); + $y = 1 - ($this->blue / 255); + $k = min($c, $m, $y); + + return new Cmyk( + (int) round(100 * ($c - $k) / (1 - $k)), + (int) round(100 * ($m - $k) / (1 - $k)), + (int) round(100 * ($y - $k) / (1 - $k)), + (int) round(100 * $k) + ); + } + + public function toGray() : Gray + { + // use integer-based calculation to avoid floating-point precision loss + return new Gray((int) round(($this->red * 2126 + $this->green * 7152 + $this->blue * 722) / 25500)); + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Eye/CompositeEye.php b/vendor/bacon/bacon-qr-code/src/Renderer/Eye/CompositeEye.php index 8a2ed5f..379e5c7 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Eye/CompositeEye.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Eye/CompositeEye.php @@ -1,26 +1,26 @@ -externalEye->getExternalPath(); - } - - public function getInternalPath() : Path - { - return $this->internalEye->getInternalPath(); - } -} +externalEye->getExternalPath(); + } + + public function getInternalPath() : Path + { + return $this->internalEye->getInternalPath(); + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Eye/EyeInterface.php b/vendor/bacon/bacon-qr-code/src/Renderer/Eye/EyeInterface.php index 3b3fbde..ab68f3c 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Eye/EyeInterface.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Eye/EyeInterface.php @@ -1,26 +1,26 @@ -set($x, 0, 1); - $matrix->set($x, 6, 1); - } - - for ($y = 1; $y < 6; ++$y) { - $matrix->set(0, $y, 1); - $matrix->set(6, $y, 1); - } - - return $this->module->createPath($matrix)->translate(-3.5, -3.5); - } - - public function getInternalPath() : Path - { - $matrix = new ByteMatrix(3, 3); - - for ($x = 0; $x < 3; ++$x) { - for ($y = 0; $y < 3; ++$y) { - $matrix->set($x, $y, 1); - } - } - - return $this->module->createPath($matrix)->translate(-1.5, -1.5); - } -} +set($x, 0, 1); + $matrix->set($x, 6, 1); + } + + for ($y = 1; $y < 6; ++$y) { + $matrix->set(0, $y, 1); + $matrix->set(6, $y, 1); + } + + return $this->module->createPath($matrix)->translate(-3.5, -3.5); + } + + public function getInternalPath() : Path + { + $matrix = new ByteMatrix(3, 3); + + for ($x = 0; $x < 3; ++$x) { + for ($y = 0; $y < 3; ++$y) { + $matrix->set($x, $y, 1); + } + } + + return $this->module->createPath($matrix)->translate(-1.5, -1.5); + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Eye/PointyEye.php b/vendor/bacon/bacon-qr-code/src/Renderer/Eye/PointyEye.php index f516998..39c7d23 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Eye/PointyEye.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Eye/PointyEye.php @@ -1,56 +1,56 @@ -move(-3.5, 3.5) - ->line(-3.5, 0) - ->ellipticArc(3.5, 3.5, 0, false, true, 0, -3.5) - ->line(3.5, -3.5) - ->line(3.5, 3.5) - ->close() - ->move(2.5, 0) - ->ellipticArc(2.5, 2.5, 0, false, true, 0, 2.5) - ->ellipticArc(2.5, 2.5, 0, false, true, -2.5, 0) - ->ellipticArc(2.5, 2.5, 0, false, true, 0, -2.5) - ->ellipticArc(2.5, 2.5, 0, false, true, 2.5, 0) - ->close() - ; - } - - public function getInternalPath() : Path - { - return (new Path()) - ->move(1.5, 0) - ->ellipticArc(1.5, 1.5, 0., false, true, 0., 1.5) - ->ellipticArc(1.5, 1.5, 0., false, true, -1.5, 0.) - ->ellipticArc(1.5, 1.5, 0., false, true, 0., -1.5) - ->ellipticArc(1.5, 1.5, 0., false, true, 1.5, 0.) - ->close() - ; - } -} +move(-3.5, 3.5) + ->line(-3.5, 0) + ->ellipticArc(3.5, 3.5, 0, false, true, 0, -3.5) + ->line(3.5, -3.5) + ->line(3.5, 3.5) + ->close() + ->move(2.5, 0) + ->ellipticArc(2.5, 2.5, 0, false, true, 0, 2.5) + ->ellipticArc(2.5, 2.5, 0, false, true, -2.5, 0) + ->ellipticArc(2.5, 2.5, 0, false, true, 0, -2.5) + ->ellipticArc(2.5, 2.5, 0, false, true, 2.5, 0) + ->close() + ; + } + + public function getInternalPath() : Path + { + return (new Path()) + ->move(1.5, 0) + ->ellipticArc(1.5, 1.5, 0., false, true, 0., 1.5) + ->ellipticArc(1.5, 1.5, 0., false, true, -1.5, 0.) + ->ellipticArc(1.5, 1.5, 0., false, true, 0., -1.5) + ->ellipticArc(1.5, 1.5, 0., false, true, 1.5, 0.) + ->close() + ; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Eye/SimpleCircleEye.php b/vendor/bacon/bacon-qr-code/src/Renderer/Eye/SimpleCircleEye.php index 8eedf93..735d326 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Eye/SimpleCircleEye.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Eye/SimpleCircleEye.php @@ -1,51 +1,51 @@ -move(-3.5, -3.5) - ->line(3.5, -3.5) - ->line(3.5, 3.5) - ->line(-3.5, 3.5) - ->close() - ->move(-2.5, -2.5) - ->line(-2.5, 2.5) - ->line(2.5, 2.5) - ->line(2.5, -2.5) - ->close() - ; - } - - public function getInternalPath() : Path - { - return (new Path()) - ->move(1.5, 0) - ->ellipticArc(1.5, 1.5, 0., false, true, 0., 1.5) - ->ellipticArc(1.5, 1.5, 0., false, true, -1.5, 0.) - ->ellipticArc(1.5, 1.5, 0., false, true, 0., -1.5) - ->ellipticArc(1.5, 1.5, 0., false, true, 1.5, 0.) - ->close() - ; - } -} +move(-3.5, -3.5) + ->line(3.5, -3.5) + ->line(3.5, 3.5) + ->line(-3.5, 3.5) + ->close() + ->move(-2.5, -2.5) + ->line(-2.5, 2.5) + ->line(2.5, 2.5) + ->line(2.5, -2.5) + ->close() + ; + } + + public function getInternalPath() : Path + { + return (new Path()) + ->move(1.5, 0) + ->ellipticArc(1.5, 1.5, 0., false, true, 0., 1.5) + ->ellipticArc(1.5, 1.5, 0., false, true, -1.5, 0.) + ->ellipticArc(1.5, 1.5, 0., false, true, 0., -1.5) + ->ellipticArc(1.5, 1.5, 0., false, true, 1.5, 0.) + ->close() + ; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Eye/SquareEye.php b/vendor/bacon/bacon-qr-code/src/Renderer/Eye/SquareEye.php index 754c089..09bedfe 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Eye/SquareEye.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Eye/SquareEye.php @@ -1,50 +1,50 @@ -move(-3.5, -3.5) - ->line(3.5, -3.5) - ->line(3.5, 3.5) - ->line(-3.5, 3.5) - ->close() - ->move(-2.5, -2.5) - ->line(-2.5, 2.5) - ->line(2.5, 2.5) - ->line(2.5, -2.5) - ->close() - ; - } - - public function getInternalPath() : Path - { - return (new Path()) - ->move(-1.5, -1.5) - ->line(1.5, -1.5) - ->line(1.5, 1.5) - ->line(-1.5, 1.5) - ->close() - ; - } -} +move(-3.5, -3.5) + ->line(3.5, -3.5) + ->line(3.5, 3.5) + ->line(-3.5, 3.5) + ->close() + ->move(-2.5, -2.5) + ->line(-2.5, 2.5) + ->line(2.5, 2.5) + ->line(2.5, -2.5) + ->close() + ; + } + + public function getInternalPath() : Path + { + return (new Path()) + ->move(-1.5, -1.5) + ->line(1.5, -1.5) + ->line(1.5, 1.5) + ->line(-1.5, 1.5) + ->close() + ; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/GDLibRenderer.php b/vendor/bacon/bacon-qr-code/src/Renderer/GDLibRenderer.php index dac4ca3..7e6efc0 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/GDLibRenderer.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/GDLibRenderer.php @@ -1,238 +1,237 @@ - - */ - private array $colors; - - public function __construct( - private int $size, - private int $margin = 4, - private string $imageFormat = 'png', - private int $compressionQuality = 9, - private ?Fill $fill = null - ) { - if (! extension_loaded('gd') || ! function_exists('gd_info')) { - throw new RuntimeException('You need to install the GD extension to use this back end'); - } - - if ($this->fill === null) { - $this->fill = Fill::default(); - } - if ($this->fill->hasGradientFill()) { - throw new InvalidArgumentException('GDLibRenderer does not support gradients'); - } - } - - /** - * @throws InvalidArgumentException if matrix width doesn't match height - */ - public function render(QrCode $qrCode): string - { - $matrix = $qrCode->getMatrix(); - $matrixSize = $matrix->getWidth(); - - if ($matrixSize !== $matrix->getHeight()) { - throw new InvalidArgumentException('Matrix must have the same width and height'); - } - - MatrixUtil::removePositionDetectionPatterns($matrix); - $this->newImage(); - $this->draw($matrix); - - return $this->renderImage(); - } - - private function newImage(): void - { - $img = imagecreatetruecolor($this->size, $this->size); - if ($img === false) { - throw new RuntimeException('Failed to create image of that size'); - } - - $this->image = $img; - imagealphablending($this->image, false); - imagesavealpha($this->image, true); - - - $bg = $this->getColor($this->fill->getBackgroundColor()); - imagefilledrectangle($this->image, 0, 0, $this->size, $this->size, $bg); - imagealphablending($this->image, true); - } - - private function draw(ByteMatrix $matrix): void - { - $matrixSize = $matrix->getWidth(); - - $pointsOnSide = $matrix->getWidth() + $this->margin * 2; - $pointInPx = $this->size / $pointsOnSide; - - $this->drawEye(0, 0, $pointInPx, $this->fill->getTopLeftEyeFill()); - $this->drawEye($matrixSize - 7, 0, $pointInPx, $this->fill->getTopRightEyeFill()); - $this->drawEye(0, $matrixSize - 7, $pointInPx, $this->fill->getBottomLeftEyeFill()); - - $rows = $matrix->getArray()->toArray(); - $color = $this->getColor($this->fill->getForegroundColor()); - for ($y = 0; $y < $matrixSize; $y += 1) { - for ($x = 0; $x < $matrixSize; $x += 1) { - if (! $rows[$y][$x]) { - continue; - } - - $points = $this->normalizePoints([ - ($this->margin + $x) * $pointInPx, ($this->margin + $y) * $pointInPx, - ($this->margin + $x + 1) * $pointInPx, ($this->margin + $y) * $pointInPx, - ($this->margin + $x + 1) * $pointInPx, ($this->margin + $y + 1) * $pointInPx, - ($this->margin + $x) * $pointInPx, ($this->margin + $y + 1) * $pointInPx, - ]); - imagefilledpolygon($this->image, $points, $color); - } - } - } - - private function drawEye(int $xOffset, int $yOffset, float $pointInPx, EyeFill $eyeFill): void - { - $internalColor = $this->getColor($eyeFill->inheritsInternalColor() - ? $this->fill->getForegroundColor() - : $eyeFill->getInternalColor()); - - $externalColor = $this->getColor($eyeFill->inheritsExternalColor() - ? $this->fill->getForegroundColor() - : $eyeFill->getExternalColor()); - - for ($y = 0; $y < 7; $y += 1) { - for ($x = 0; $x < 7; $x += 1) { - if ((($y === 1 || $y === 5) && $x > 0 && $x < 6) || (($x === 1 || $x === 5) && $y > 0 && $y < 6)) { - continue; - } - - $points = $this->normalizePoints([ - ($this->margin + $x + $xOffset) * $pointInPx, ($this->margin + $y + $yOffset) * $pointInPx, - ($this->margin + $x + $xOffset + 1) * $pointInPx, ($this->margin + $y + $yOffset) * $pointInPx, - ($this->margin + $x + $xOffset + 1) * $pointInPx, ($this->margin + $y + $yOffset + 1) * $pointInPx, - ($this->margin + $x + $xOffset) * $pointInPx, ($this->margin + $y + $yOffset + 1) * $pointInPx, - ]); - - if ($y > 1 && $y < 5 && $x > 1 && $x < 5) { - imagefilledpolygon($this->image, $points, $internalColor); - } else { - imagefilledpolygon($this->image, $points, $externalColor); - } - } - } - } - - /** - * Normalize points will trim right and bottom line by 1 pixel. - * Otherwise pixels of neighbors are overlapping which leads to issue with transparency and small QR codes. - */ - private function normalizePoints(array $points): array - { - $maxX = $maxY = 0; - for ($i = 0; $i < count($points); $i += 2) { - // Do manual round as GD just removes decimal part - $points[$i] = $newX = round($points[$i]); - $points[$i + 1] = $newY = round($points[$i + 1]); - - $maxX = max($maxX, $newX); - $maxY = max($maxY, $newY); - } - - // Do trimming only if there are 4 points (8 coordinates), assumes this is square. - - for ($i = 0; $i < count($points); $i += 2) { - $points[$i] = min($points[$i], $maxX - 1); - $points[$i + 1] = min($points[$i + 1], $maxY - 1); - } - - return $points; - } - - private function renderImage(): string - { - ob_start(); - $quality = $this->compressionQuality; - switch ($this->imageFormat) { - case 'png': - if ($quality > 9 || $quality < 0) { - $quality = 9; - } - imagepng($this->image, null, $quality); - break; - - case 'gif': - imagegif($this->image, null); - break; - - case 'jpeg': - case 'jpg': - if ($quality > 100 || $quality < 0) { - $quality = 85; - } - imagejpeg($this->image, null, $quality); - break; - default: - ob_end_clean(); - throw new InvalidArgumentException( - 'Supported image formats are jpeg, png and gif, got: ' . $this->imageFormat - ); - } - - imagedestroy($this->image); - $this->colors = []; - $this->image = null; - - return ob_get_clean(); - } - - private function getColor(ColorInterface $color): int - { - $alpha = 100; - - if ($color instanceof Alpha) { - $alpha = $color->getAlpha(); - $color = $color->getBaseColor(); - } - - $rgb = $color->toRgb(); - - $colorKey = sprintf('%02X%02X%02X%02X', $rgb->getRed(), $rgb->getGreen(), $rgb->getBlue(), $alpha); - - if (! isset($this->colors[$colorKey])) { - $colorId = imagecolorallocatealpha( - $this->image, - $rgb->getRed(), - $rgb->getGreen(), - $rgb->getBlue(), - (int)((100 - $alpha) / 100 * 127) // Alpha for GD is in range 0 (opaque) - 127 (transparent) - ); - - if ($colorId === false) { - throw new RuntimeException('Failed to create color: #' . $colorKey); - } - - $this->colors[$colorKey] = $colorId; - } - - return $this->colors[$colorKey]; - } -} + + */ + private array $colors; + + public function __construct( + private int $size, + private int $margin = 4, + private string $imageFormat = 'png', + private int $compressionQuality = 9, + private ?Fill $fill = null + ) { + if (! extension_loaded('gd') || ! function_exists('gd_info')) { + throw new RuntimeException('You need to install the GD extension to use this back end'); + } + + if ($this->fill === null) { + $this->fill = Fill::default(); + } + if ($this->fill->hasGradientFill()) { + throw new InvalidArgumentException('GDLibRenderer does not support gradients'); + } + } + + /** + * @throws InvalidArgumentException if matrix width doesn't match height + */ + public function render(QrCode $qrCode): string + { + $matrix = $qrCode->getMatrix(); + $matrixSize = $matrix->getWidth(); + + if ($matrixSize !== $matrix->getHeight()) { + throw new InvalidArgumentException('Matrix must have the same width and height'); + } + + MatrixUtil::removePositionDetectionPatterns($matrix); + $this->newImage(); + $this->draw($matrix); + + return $this->renderImage(); + } + + private function newImage(): void + { + $img = imagecreatetruecolor($this->size, $this->size); + if ($img === false) { + throw new RuntimeException('Failed to create image of that size'); + } + + $this->image = $img; + imagealphablending($this->image, false); + imagesavealpha($this->image, true); + + + $bg = $this->getColor($this->fill->getBackgroundColor()); + imagefilledrectangle($this->image, 0, 0, $this->size, $this->size, $bg); + imagealphablending($this->image, true); + } + + private function draw(ByteMatrix $matrix): void + { + $matrixSize = $matrix->getWidth(); + + $pointsOnSide = $matrix->getWidth() + $this->margin * 2; + $pointInPx = $this->size / $pointsOnSide; + + $this->drawEye(0, 0, $pointInPx, $this->fill->getTopLeftEyeFill()); + $this->drawEye($matrixSize - 7, 0, $pointInPx, $this->fill->getTopRightEyeFill()); + $this->drawEye(0, $matrixSize - 7, $pointInPx, $this->fill->getBottomLeftEyeFill()); + + $rows = $matrix->getArray()->toArray(); + $color = $this->getColor($this->fill->getForegroundColor()); + for ($y = 0; $y < $matrixSize; $y += 1) { + for ($x = 0; $x < $matrixSize; $x += 1) { + if (! $rows[$y][$x]) { + continue; + } + + $points = $this->normalizePoints([ + ($this->margin + $x) * $pointInPx, ($this->margin + $y) * $pointInPx, + ($this->margin + $x + 1) * $pointInPx, ($this->margin + $y) * $pointInPx, + ($this->margin + $x + 1) * $pointInPx, ($this->margin + $y + 1) * $pointInPx, + ($this->margin + $x) * $pointInPx, ($this->margin + $y + 1) * $pointInPx, + ]); + imagefilledpolygon($this->image, $points, $color); + } + } + } + + private function drawEye(int $xOffset, int $yOffset, float $pointInPx, EyeFill $eyeFill): void + { + $internalColor = $this->getColor($eyeFill->inheritsInternalColor() + ? $this->fill->getForegroundColor() + : $eyeFill->getInternalColor()); + + $externalColor = $this->getColor($eyeFill->inheritsExternalColor() + ? $this->fill->getForegroundColor() + : $eyeFill->getExternalColor()); + + for ($y = 0; $y < 7; $y += 1) { + for ($x = 0; $x < 7; $x += 1) { + if ((($y === 1 || $y === 5) && $x > 0 && $x < 6) || (($x === 1 || $x === 5) && $y > 0 && $y < 6)) { + continue; + } + + $points = $this->normalizePoints([ + ($this->margin + $x + $xOffset) * $pointInPx, ($this->margin + $y + $yOffset) * $pointInPx, + ($this->margin + $x + $xOffset + 1) * $pointInPx, ($this->margin + $y + $yOffset) * $pointInPx, + ($this->margin + $x + $xOffset + 1) * $pointInPx, ($this->margin + $y + $yOffset + 1) * $pointInPx, + ($this->margin + $x + $xOffset) * $pointInPx, ($this->margin + $y + $yOffset + 1) * $pointInPx, + ]); + + if ($y > 1 && $y < 5 && $x > 1 && $x < 5) { + imagefilledpolygon($this->image, $points, $internalColor); + } else { + imagefilledpolygon($this->image, $points, $externalColor); + } + } + } + } + + /** + * Normalize points will trim right and bottom line by 1 pixel. + * Otherwise pixels of neighbors are overlapping which leads to issue with transparency and small QR codes. + */ + private function normalizePoints(array $points): array + { + $maxX = $maxY = 0; + for ($i = 0; $i < count($points); $i += 2) { + // Do manual round as GD just removes decimal part + $points[$i] = $newX = round($points[$i]); + $points[$i + 1] = $newY = round($points[$i + 1]); + + $maxX = max($maxX, $newX); + $maxY = max($maxY, $newY); + } + + // Do trimming only if there are 4 points (8 coordinates), assumes this is square. + + for ($i = 0; $i < count($points); $i += 2) { + $points[$i] = min($points[$i], $maxX - 1); + $points[$i + 1] = min($points[$i + 1], $maxY - 1); + } + + return $points; + } + + private function renderImage(): string + { + ob_start(); + $quality = $this->compressionQuality; + switch ($this->imageFormat) { + case 'png': + if ($quality > 9 || $quality < 0) { + $quality = 9; + } + imagepng($this->image, null, $quality); + break; + + case 'gif': + imagegif($this->image, null); + break; + + case 'jpeg': + case 'jpg': + if ($quality > 100 || $quality < 0) { + $quality = 85; + } + imagejpeg($this->image, null, $quality); + break; + default: + ob_end_clean(); + throw new InvalidArgumentException( + 'Supported image formats are jpeg, png and gif, got: ' . $this->imageFormat + ); + } + + $this->colors = []; + $this->image = null; + + return ob_get_clean(); + } + + private function getColor(ColorInterface $color): int + { + $alpha = 100; + + if ($color instanceof Alpha) { + $alpha = $color->getAlpha(); + $color = $color->getBaseColor(); + } + + $rgb = $color->toRgb(); + + $colorKey = sprintf('%02X%02X%02X%02X', $rgb->getRed(), $rgb->getGreen(), $rgb->getBlue(), $alpha); + + if (! isset($this->colors[$colorKey])) { + $colorId = imagecolorallocatealpha( + $this->image, + $rgb->getRed(), + $rgb->getGreen(), + $rgb->getBlue(), + (int)((100 - $alpha) / 100 * 127) // Alpha for GD is in range 0 (opaque) - 127 (transparent) + ); + + if ($colorId === false) { + throw new RuntimeException('Failed to create color: #' . $colorKey); + } + + $this->colors[$colorKey] = $colorId; + } + + return $this->colors[$colorKey]; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Image/EpsImageBackEnd.php b/vendor/bacon/bacon-qr-code/src/Renderer/Image/EpsImageBackEnd.php index 2f413b2..4269456 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Image/EpsImageBackEnd.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Image/EpsImageBackEnd.php @@ -1,373 +1,373 @@ -eps = "%!PS-Adobe-3.0 EPSF-3.0\n" - . "%%Creator: BaconQrCode\n" - . sprintf("%%%%BoundingBox: 0 0 %d %d \n", $size, $size) - . "%%BeginProlog\n" - . "save\n" - . "50 dict begin\n" - . "/q { gsave } bind def\n" - . "/Q { grestore } bind def\n" - . "/s { scale } bind def\n" - . "/t { translate } bind def\n" - . "/r { rotate } bind def\n" - . "/n { newpath } bind def\n" - . "/m { moveto } bind def\n" - . "/l { lineto } bind def\n" - . "/c { curveto } bind def\n" - . "/z { closepath } bind def\n" - . "/f { eofill } bind def\n" - . "/rgb { setrgbcolor } bind def\n" - . "/cmyk { setcmykcolor } bind def\n" - . "/gray { setgray } bind def\n" - . "%%EndProlog\n" - . "1 -1 s\n" - . sprintf("0 -%d t\n", $size); - - if ($backgroundColor instanceof Alpha && 0 === $backgroundColor->getAlpha()) { - return; - } - - $this->eps .= wordwrap( - '0 0 m' - . sprintf(' %s 0 l', (string) $size) - . sprintf(' %s %s l', (string) $size, (string) $size) - . sprintf(' 0 %s l', (string) $size) - . ' z' - . ' ' .$this->getColorSetString($backgroundColor) . " f\n", - 75, - "\n " - ); - } - - public function scale(float $size) : void - { - if (null === $this->eps) { - throw new RuntimeException('No image has been started'); - } - - $this->eps .= sprintf("%1\$s %1\$s s\n", round($size, self::PRECISION)); - } - - public function translate(float $x, float $y) : void - { - if (null === $this->eps) { - throw new RuntimeException('No image has been started'); - } - - $this->eps .= sprintf("%s %s t\n", round($x, self::PRECISION), round($y, self::PRECISION)); - } - - public function rotate(int $degrees) : void - { - if (null === $this->eps) { - throw new RuntimeException('No image has been started'); - } - - $this->eps .= sprintf("%d r\n", $degrees); - } - - public function push() : void - { - if (null === $this->eps) { - throw new RuntimeException('No image has been started'); - } - - $this->eps .= "q\n"; - } - - public function pop() : void - { - if (null === $this->eps) { - throw new RuntimeException('No image has been started'); - } - - $this->eps .= "Q\n"; - } - - public function drawPathWithColor(Path $path, ColorInterface $color) : void - { - if (null === $this->eps) { - throw new RuntimeException('No image has been started'); - } - - $fromX = 0; - $fromY = 0; - $this->eps .= wordwrap( - 'n ' - . $this->drawPathOperations($path, $fromX, $fromY) - . ' ' . $this->getColorSetString($color) . " f\n", - 75, - "\n " - ); - } - - public function drawPathWithGradient( - Path $path, - Gradient $gradient, - float $x, - float $y, - float $width, - float $height - ) : void { - if (null === $this->eps) { - throw new RuntimeException('No image has been started'); - } - - $fromX = 0; - $fromY = 0; - $this->eps .= wordwrap( - 'q n ' . $this->drawPathOperations($path, $fromX, $fromY) . "\n", - 75, - "\n " - ); - - $this->createGradientFill($gradient, $x, $y, $width, $height); - } - - public function done() : string - { - if (null === $this->eps) { - throw new RuntimeException('No image has been started'); - } - - $this->eps .= "%%TRAILER\nend restore\n%%EOF"; - $blob = $this->eps; - $this->eps = null; - - return $blob; - } - - private function drawPathOperations(Iterable $ops, &$fromX, &$fromY) : string - { - $pathData = []; - - foreach ($ops as $op) { - switch (true) { - case $op instanceof Move: - $fromX = $toX = round($op->getX(), self::PRECISION); - $fromY = $toY = round($op->getY(), self::PRECISION); - $pathData[] = sprintf('%s %s m', $toX, $toY); - break; - - case $op instanceof Line: - $fromX = $toX = round($op->getX(), self::PRECISION); - $fromY = $toY = round($op->getY(), self::PRECISION); - $pathData[] = sprintf('%s %s l', $toX, $toY); - break; - - case $op instanceof EllipticArc: - $pathData[] = $this->drawPathOperations($op->toCurves($fromX, $fromY), $fromX, $fromY); - break; - - case $op instanceof Curve: - $x1 = round($op->getX1(), self::PRECISION); - $y1 = round($op->getY1(), self::PRECISION); - $x2 = round($op->getX2(), self::PRECISION); - $y2 = round($op->getY2(), self::PRECISION); - $fromX = $x3 = round($op->getX3(), self::PRECISION); - $fromY = $y3 = round($op->getY3(), self::PRECISION); - $pathData[] = sprintf('%s %s %s %s %s %s c', $x1, $y1, $x2, $y2, $x3, $y3); - break; - - case $op instanceof Close: - $pathData[] = 'z'; - break; - - default: - throw new RuntimeException('Unexpected draw operation: ' . get_class($op)); - } - } - - return implode(' ', $pathData); - } - - private function createGradientFill(Gradient $gradient, float $x, float $y, float $width, float $height) : void - { - $startColor = $gradient->getStartColor(); - $endColor = $gradient->getEndColor(); - - if ($startColor instanceof Alpha) { - $startColor = $startColor->getBaseColor(); - } - - $startColorType = get_class($startColor); - - if (! in_array($startColorType, [Rgb::class, Cmyk::class, Gray::class])) { - $startColorType = Cmyk::class; - $startColor = $startColor->toCmyk(); - } - - if (get_class($endColor) !== $startColorType) { - switch ($startColorType) { - case Cmyk::class: - $endColor = $endColor->toCmyk(); - break; - - case Rgb::class: - $endColor = $endColor->toRgb(); - break; - - case Gray::class: - $endColor = $endColor->toGray(); - break; - } - } - - $this->eps .= "eoclip\n<<\n"; - - if ($gradient->getType() === GradientType::RADIAL()) { - $this->eps .= " /ShadingType 3\n"; - } else { - $this->eps .= " /ShadingType 2\n"; - } - - $this->eps .= " /Extend [ true true ]\n" - . " /AntiAlias true\n"; - - switch ($startColorType) { - case Cmyk::class: - $this->eps .= " /ColorSpace /DeviceCMYK\n"; - break; - - case Rgb::class: - $this->eps .= " /ColorSpace /DeviceRGB\n"; - break; - - case Gray::class: - $this->eps .= " /ColorSpace /DeviceGray\n"; - break; - } - - switch ($gradient->getType()) { - case GradientType::HORIZONTAL(): - $this->eps .= sprintf( - " /Coords [ %s %s %s %s ]\n", - round($x, self::PRECISION), - round($y, self::PRECISION), - round($x + $width, self::PRECISION), - round($y, self::PRECISION) - ); - break; - - case GradientType::VERTICAL(): - $this->eps .= sprintf( - " /Coords [ %s %s %s %s ]\n", - round($x, self::PRECISION), - round($y, self::PRECISION), - round($x, self::PRECISION), - round($y + $height, self::PRECISION) - ); - break; - - case GradientType::DIAGONAL(): - $this->eps .= sprintf( - " /Coords [ %s %s %s %s ]\n", - round($x, self::PRECISION), - round($y, self::PRECISION), - round($x + $width, self::PRECISION), - round($y + $height, self::PRECISION) - ); - break; - - case GradientType::INVERSE_DIAGONAL(): - $this->eps .= sprintf( - " /Coords [ %s %s %s %s ]\n", - round($x, self::PRECISION), - round($y + $height, self::PRECISION), - round($x + $width, self::PRECISION), - round($y, self::PRECISION) - ); - break; - - case GradientType::RADIAL(): - $centerX = ($x + $width) / 2; - $centerY = ($y + $height) / 2; - - $this->eps .= sprintf( - " /Coords [ %s %s 0 %s %s %s ]\n", - round($centerX, self::PRECISION), - round($centerY, self::PRECISION), - round($centerX, self::PRECISION), - round($centerY, self::PRECISION), - round(max($width, $height) / 2, self::PRECISION) - ); - break; - } - - $this->eps .= " /Function\n" - . " <<\n" - . " /FunctionType 2\n" - . " /Domain [ 0 1 ]\n" - . sprintf(" /C0 [ %s ]\n", $this->getColorString($startColor)) - . sprintf(" /C1 [ %s ]\n", $this->getColorString($endColor)) - . " /N 1\n" - . " >>\n>>\nshfill\nQ\n"; - } - - private function getColorSetString(ColorInterface $color) : string - { - if ($color instanceof Rgb) { - return $this->getColorString($color) . ' rgb'; - } - - if ($color instanceof Cmyk) { - return $this->getColorString($color) . ' cmyk'; - } - - if ($color instanceof Gray) { - return $this->getColorString($color) . ' gray'; - } - - return $this->getColorSetString($color->toCmyk()); - } - - private function getColorString(ColorInterface $color) : string - { - if ($color instanceof Rgb) { - return sprintf('%s %s %s', $color->getRed() / 255, $color->getGreen() / 255, $color->getBlue() / 255); - } - - if ($color instanceof Cmyk) { - return sprintf( - '%s %s %s %s', - $color->getCyan() / 100, - $color->getMagenta() / 100, - $color->getYellow() / 100, - $color->getBlack() / 100 - ); - } - - if ($color instanceof Gray) { - return sprintf('%s', $color->getGray() / 100); - } - - return $this->getColorString($color->toCmyk()); - } -} +eps = "%!PS-Adobe-3.0 EPSF-3.0\n" + . "%%Creator: BaconQrCode\n" + . sprintf("%%%%BoundingBox: 0 0 %d %d \n", $size, $size) + . "%%BeginProlog\n" + . "save\n" + . "50 dict begin\n" + . "/q { gsave } bind def\n" + . "/Q { grestore } bind def\n" + . "/s { scale } bind def\n" + . "/t { translate } bind def\n" + . "/r { rotate } bind def\n" + . "/n { newpath } bind def\n" + . "/m { moveto } bind def\n" + . "/l { lineto } bind def\n" + . "/c { curveto } bind def\n" + . "/z { closepath } bind def\n" + . "/f { eofill } bind def\n" + . "/rgb { setrgbcolor } bind def\n" + . "/cmyk { setcmykcolor } bind def\n" + . "/gray { setgray } bind def\n" + . "%%EndProlog\n" + . "1 -1 s\n" + . sprintf("0 -%d t\n", $size); + + if ($backgroundColor instanceof Alpha && 0 === $backgroundColor->getAlpha()) { + return; + } + + $this->eps .= wordwrap( + '0 0 m' + . sprintf(' %s 0 l', (string) $size) + . sprintf(' %s %s l', (string) $size, (string) $size) + . sprintf(' 0 %s l', (string) $size) + . ' z' + . ' ' .$this->getColorSetString($backgroundColor) . " f\n", + 75, + "\n " + ); + } + + public function scale(float $size) : void + { + if (null === $this->eps) { + throw new RuntimeException('No image has been started'); + } + + $this->eps .= sprintf("%1\$s %1\$s s\n", round($size, self::PRECISION)); + } + + public function translate(float $x, float $y) : void + { + if (null === $this->eps) { + throw new RuntimeException('No image has been started'); + } + + $this->eps .= sprintf("%s %s t\n", round($x, self::PRECISION), round($y, self::PRECISION)); + } + + public function rotate(int $degrees) : void + { + if (null === $this->eps) { + throw new RuntimeException('No image has been started'); + } + + $this->eps .= sprintf("%d r\n", $degrees); + } + + public function push() : void + { + if (null === $this->eps) { + throw new RuntimeException('No image has been started'); + } + + $this->eps .= "q\n"; + } + + public function pop() : void + { + if (null === $this->eps) { + throw new RuntimeException('No image has been started'); + } + + $this->eps .= "Q\n"; + } + + public function drawPathWithColor(Path $path, ColorInterface $color) : void + { + if (null === $this->eps) { + throw new RuntimeException('No image has been started'); + } + + $fromX = 0; + $fromY = 0; + $this->eps .= wordwrap( + 'n ' + . $this->drawPathOperations($path, $fromX, $fromY) + . ' ' . $this->getColorSetString($color) . " f\n", + 75, + "\n " + ); + } + + public function drawPathWithGradient( + Path $path, + Gradient $gradient, + float $x, + float $y, + float $width, + float $height + ) : void { + if (null === $this->eps) { + throw new RuntimeException('No image has been started'); + } + + $fromX = 0; + $fromY = 0; + $this->eps .= wordwrap( + 'q n ' . $this->drawPathOperations($path, $fromX, $fromY) . "\n", + 75, + "\n " + ); + + $this->createGradientFill($gradient, $x, $y, $width, $height); + } + + public function done() : string + { + if (null === $this->eps) { + throw new RuntimeException('No image has been started'); + } + + $this->eps .= "%%TRAILER\nend restore\n%%EOF"; + $blob = $this->eps; + $this->eps = null; + + return $blob; + } + + private function drawPathOperations(Iterable $ops, &$fromX, &$fromY) : string + { + $pathData = []; + + foreach ($ops as $op) { + switch (true) { + case $op instanceof Move: + $fromX = $toX = round($op->getX(), self::PRECISION); + $fromY = $toY = round($op->getY(), self::PRECISION); + $pathData[] = sprintf('%s %s m', $toX, $toY); + break; + + case $op instanceof Line: + $fromX = $toX = round($op->getX(), self::PRECISION); + $fromY = $toY = round($op->getY(), self::PRECISION); + $pathData[] = sprintf('%s %s l', $toX, $toY); + break; + + case $op instanceof EllipticArc: + $pathData[] = $this->drawPathOperations($op->toCurves($fromX, $fromY), $fromX, $fromY); + break; + + case $op instanceof Curve: + $x1 = round($op->getX1(), self::PRECISION); + $y1 = round($op->getY1(), self::PRECISION); + $x2 = round($op->getX2(), self::PRECISION); + $y2 = round($op->getY2(), self::PRECISION); + $fromX = $x3 = round($op->getX3(), self::PRECISION); + $fromY = $y3 = round($op->getY3(), self::PRECISION); + $pathData[] = sprintf('%s %s %s %s %s %s c', $x1, $y1, $x2, $y2, $x3, $y3); + break; + + case $op instanceof Close: + $pathData[] = 'z'; + break; + + default: + throw new RuntimeException('Unexpected draw operation: ' . get_class($op)); + } + } + + return implode(' ', $pathData); + } + + private function createGradientFill(Gradient $gradient, float $x, float $y, float $width, float $height) : void + { + $startColor = $gradient->getStartColor(); + $endColor = $gradient->getEndColor(); + + if ($startColor instanceof Alpha) { + $startColor = $startColor->getBaseColor(); + } + + $startColorType = get_class($startColor); + + if (! in_array($startColorType, [Rgb::class, Cmyk::class, Gray::class])) { + $startColorType = Cmyk::class; + $startColor = $startColor->toCmyk(); + } + + if (get_class($endColor) !== $startColorType) { + switch ($startColorType) { + case Cmyk::class: + $endColor = $endColor->toCmyk(); + break; + + case Rgb::class: + $endColor = $endColor->toRgb(); + break; + + case Gray::class: + $endColor = $endColor->toGray(); + break; + } + } + + $this->eps .= "eoclip\n<<\n"; + + if ($gradient->getType() === GradientType::RADIAL()) { + $this->eps .= " /ShadingType 3\n"; + } else { + $this->eps .= " /ShadingType 2\n"; + } + + $this->eps .= " /Extend [ true true ]\n" + . " /AntiAlias true\n"; + + switch ($startColorType) { + case Cmyk::class: + $this->eps .= " /ColorSpace /DeviceCMYK\n"; + break; + + case Rgb::class: + $this->eps .= " /ColorSpace /DeviceRGB\n"; + break; + + case Gray::class: + $this->eps .= " /ColorSpace /DeviceGray\n"; + break; + } + + switch ($gradient->getType()) { + case GradientType::HORIZONTAL(): + $this->eps .= sprintf( + " /Coords [ %s %s %s %s ]\n", + round($x, self::PRECISION), + round($y, self::PRECISION), + round($x + $width, self::PRECISION), + round($y, self::PRECISION) + ); + break; + + case GradientType::VERTICAL(): + $this->eps .= sprintf( + " /Coords [ %s %s %s %s ]\n", + round($x, self::PRECISION), + round($y, self::PRECISION), + round($x, self::PRECISION), + round($y + $height, self::PRECISION) + ); + break; + + case GradientType::DIAGONAL(): + $this->eps .= sprintf( + " /Coords [ %s %s %s %s ]\n", + round($x, self::PRECISION), + round($y, self::PRECISION), + round($x + $width, self::PRECISION), + round($y + $height, self::PRECISION) + ); + break; + + case GradientType::INVERSE_DIAGONAL(): + $this->eps .= sprintf( + " /Coords [ %s %s %s %s ]\n", + round($x, self::PRECISION), + round($y + $height, self::PRECISION), + round($x + $width, self::PRECISION), + round($y, self::PRECISION) + ); + break; + + case GradientType::RADIAL(): + $centerX = ($x + $width) / 2; + $centerY = ($y + $height) / 2; + + $this->eps .= sprintf( + " /Coords [ %s %s 0 %s %s %s ]\n", + round($centerX, self::PRECISION), + round($centerY, self::PRECISION), + round($centerX, self::PRECISION), + round($centerY, self::PRECISION), + round(max($width, $height) / 2, self::PRECISION) + ); + break; + } + + $this->eps .= " /Function\n" + . " <<\n" + . " /FunctionType 2\n" + . " /Domain [ 0 1 ]\n" + . sprintf(" /C0 [ %s ]\n", $this->getColorString($startColor)) + . sprintf(" /C1 [ %s ]\n", $this->getColorString($endColor)) + . " /N 1\n" + . " >>\n>>\nshfill\nQ\n"; + } + + private function getColorSetString(ColorInterface $color) : string + { + if ($color instanceof Rgb) { + return $this->getColorString($color) . ' rgb'; + } + + if ($color instanceof Cmyk) { + return $this->getColorString($color) . ' cmyk'; + } + + if ($color instanceof Gray) { + return $this->getColorString($color) . ' gray'; + } + + return $this->getColorSetString($color->toCmyk()); + } + + private function getColorString(ColorInterface $color) : string + { + if ($color instanceof Rgb) { + return sprintf('%s %s %s', $color->getRed() / 255, $color->getGreen() / 255, $color->getBlue() / 255); + } + + if ($color instanceof Cmyk) { + return sprintf( + '%s %s %s %s', + $color->getCyan() / 100, + $color->getMagenta() / 100, + $color->getYellow() / 100, + $color->getBlack() / 100 + ); + } + + if ($color instanceof Gray) { + return sprintf('%s', $color->getGray() / 100); + } + + return $this->getColorString($color->toCmyk()); + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Image/ImageBackEndInterface.php b/vendor/bacon/bacon-qr-code/src/Renderer/Image/ImageBackEndInterface.php index ec9d7a9..0935819 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Image/ImageBackEndInterface.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Image/ImageBackEndInterface.php @@ -1,87 +1,87 @@ -imageFormat = $imageFormat; - $this->compressionQuality = $compressionQuality; - } - - public function new(int $size, ColorInterface $backgroundColor) : void - { - $this->image = new Imagick(); - $this->image->newImage($size, $size, $this->getColorPixel($backgroundColor)); - $this->image->setImageFormat($this->imageFormat); - $this->image->setCompressionQuality($this->compressionQuality); - $this->draw = new ImagickDraw(); - $this->gradientCount = 0; - $this->matrices = [new TransformationMatrix()]; - $this->matrixIndex = 0; - } - - public function scale(float $size) : void - { - if (null === $this->draw) { - throw new RuntimeException('No image has been started'); - } - - $this->draw->scale($size, $size); - $this->matrices[$this->matrixIndex] = $this->matrices[$this->matrixIndex] - ->multiply(TransformationMatrix::scale($size)); - } - - public function translate(float $x, float $y) : void - { - if (null === $this->draw) { - throw new RuntimeException('No image has been started'); - } - - $this->draw->translate($x, $y); - $this->matrices[$this->matrixIndex] = $this->matrices[$this->matrixIndex] - ->multiply(TransformationMatrix::translate($x, $y)); - } - - public function rotate(int $degrees) : void - { - if (null === $this->draw) { - throw new RuntimeException('No image has been started'); - } - - $this->draw->rotate($degrees); - $this->matrices[$this->matrixIndex] = $this->matrices[$this->matrixIndex] - ->multiply(TransformationMatrix::rotate($degrees)); - } - - public function push() : void - { - if (null === $this->draw) { - throw new RuntimeException('No image has been started'); - } - - $this->draw->push(); - $this->matrices[++$this->matrixIndex] = $this->matrices[$this->matrixIndex - 1]; - } - - public function pop() : void - { - if (null === $this->draw) { - throw new RuntimeException('No image has been started'); - } - - $this->draw->pop(); - unset($this->matrices[$this->matrixIndex--]); - } - - public function drawPathWithColor(Path $path, ColorInterface $color) : void - { - if (null === $this->draw) { - throw new RuntimeException('No image has been started'); - } - - $this->draw->setFillColor($this->getColorPixel($color)); - $this->drawPath($path); - } - - public function drawPathWithGradient( - Path $path, - Gradient $gradient, - float $x, - float $y, - float $width, - float $height - ) : void { - if (null === $this->draw) { - throw new RuntimeException('No image has been started'); - } - - $this->draw->setFillPatternURL('#' . $this->createGradientFill($gradient, $x, $y, $width, $height)); - $this->drawPath($path); - } - - public function done() : string - { - if (null === $this->draw) { - throw new RuntimeException('No image has been started'); - } - - $this->image->drawImage($this->draw); - $blob = $this->image->getImageBlob(); - $this->draw->clear(); - $this->image->clear(); - $this->draw = null; - $this->image = null; - $this->gradientCount = null; - - return $blob; - } - - private function drawPath(Path $path) : void - { - $this->draw->pathStart(); - - foreach ($path as $op) { - switch (true) { - case $op instanceof Move: - $this->draw->pathMoveToAbsolute($op->getX(), $op->getY()); - break; - - case $op instanceof Line: - $this->draw->pathLineToAbsolute($op->getX(), $op->getY()); - break; - - case $op instanceof EllipticArc: - $this->draw->pathEllipticArcAbsolute( - $op->getXRadius(), - $op->getYRadius(), - $op->getXAxisAngle(), - $op->isLargeArc(), - $op->isSweep(), - $op->getX(), - $op->getY() - ); - break; - - case $op instanceof Curve: - $this->draw->pathCurveToAbsolute( - $op->getX1(), - $op->getY1(), - $op->getX2(), - $op->getY2(), - $op->getX3(), - $op->getY3() - ); - break; - - case $op instanceof Close: - $this->draw->pathClose(); - break; - - default: - throw new RuntimeException('Unexpected draw operation: ' . get_class($op)); - } - } - - $this->draw->pathFinish(); - } - - private function createGradientFill(Gradient $gradient, float $x, float $y, float $width, float $height) : string - { - list($width, $height) = $this->matrices[$this->matrixIndex]->apply($width, $height); - - $startColor = $this->getColorPixel($gradient->getStartColor())->getColorAsString(); - $endColor = $this->getColorPixel($gradient->getEndColor())->getColorAsString(); - $gradientImage = new Imagick(); - - switch ($gradient->getType()) { - case GradientType::HORIZONTAL(): - $gradientImage->newPseudoImage((int) $height, (int) $width, sprintf( - 'gradient:%s-%s', - $startColor, - $endColor - )); - $gradientImage->rotateImage('transparent', -90); - break; - - case GradientType::VERTICAL(): - $gradientImage->newPseudoImage((int) $width, (int) $height, sprintf( - 'gradient:%s-%s', - $startColor, - $endColor - )); - break; - - case GradientType::DIAGONAL(): - case GradientType::INVERSE_DIAGONAL(): - $gradientImage->newPseudoImage((int) ($width * sqrt(2)), (int) ($height * sqrt(2)), sprintf( - 'gradient:%s-%s', - $startColor, - $endColor - )); - - if (GradientType::DIAGONAL() === $gradient->getType()) { - $gradientImage->rotateImage('transparent', -45); - } else { - $gradientImage->rotateImage('transparent', -135); - } - - $rotatedWidth = $gradientImage->getImageWidth(); - $rotatedHeight = $gradientImage->getImageHeight(); - - $gradientImage->setImagePage($rotatedWidth, $rotatedHeight, 0, 0); - $gradientImage->cropImage( - intdiv($rotatedWidth, 2) - 2, - intdiv($rotatedHeight, 2) - 2, - intdiv($rotatedWidth, 4) + 1, - intdiv($rotatedWidth, 4) + 1 - ); - break; - - case GradientType::RADIAL(): - $gradientImage->newPseudoImage((int) $width, (int) $height, sprintf( - 'radial-gradient:%s-%s', - $startColor, - $endColor - )); - break; - } - - $id = sprintf('g%d', ++$this->gradientCount); - $this->draw->pushPattern($id, 0, 0, $width, $height); - $this->draw->composite(Imagick::COMPOSITE_COPY, 0, 0, $width, $height, $gradientImage); - $this->draw->popPattern(); - return $id; - } - - private function getColorPixel(ColorInterface $color) : ImagickPixel - { - $alpha = 100; - - if ($color instanceof Alpha) { - $alpha = $color->getAlpha(); - $color = $color->getBaseColor(); - } - - if ($color instanceof Rgb) { - return new ImagickPixel(sprintf( - 'rgba(%d, %d, %d, %F)', - $color->getRed(), - $color->getGreen(), - $color->getBlue(), - $alpha / 100 - )); - } - - if ($color instanceof Cmyk) { - return new ImagickPixel(sprintf( - 'cmyka(%d, %d, %d, %d, %F)', - $color->getCyan(), - $color->getMagenta(), - $color->getYellow(), - $color->getBlack(), - $alpha / 100 - )); - } - - if ($color instanceof Gray) { - return new ImagickPixel(sprintf( - 'graya(%d%%, %F)', - $color->getGray(), - $alpha / 100 - )); - } - - return $this->getColorPixel(new Alpha($alpha, $color->toRgb())); - } -} +imageFormat = $imageFormat; + $this->compressionQuality = $compressionQuality; + $this->antialias = $antialias; + } + + public function new(int $size, ColorInterface $backgroundColor) : void + { + $this->image = new Imagick(); + $this->image->newImage($size, $size, $this->getColorPixel($backgroundColor)); + $this->image->setImageFormat($this->imageFormat); + $this->image->setCompressionQuality($this->compressionQuality); + $this->draw = new ImagickDraw(); + + if (! $this->antialias) { + $this->image->setAntiAlias(false); + $this->draw->setStrokeAntialias(false); + } + + $this->gradientCount = 0; + $this->matrices = [new TransformationMatrix()]; + $this->matrixIndex = 0; + } + + public function scale(float $size) : void + { + if (null === $this->draw) { + throw new RuntimeException('No image has been started'); + } + + $this->draw->scale($size, $size); + $this->matrices[$this->matrixIndex] = $this->matrices[$this->matrixIndex] + ->multiply(TransformationMatrix::scale($size)); + } + + public function translate(float $x, float $y) : void + { + if (null === $this->draw) { + throw new RuntimeException('No image has been started'); + } + + $this->draw->translate($x, $y); + $this->matrices[$this->matrixIndex] = $this->matrices[$this->matrixIndex] + ->multiply(TransformationMatrix::translate($x, $y)); + } + + public function rotate(int $degrees) : void + { + if (null === $this->draw) { + throw new RuntimeException('No image has been started'); + } + + $this->draw->rotate($degrees); + $this->matrices[$this->matrixIndex] = $this->matrices[$this->matrixIndex] + ->multiply(TransformationMatrix::rotate($degrees)); + } + + public function push() : void + { + if (null === $this->draw) { + throw new RuntimeException('No image has been started'); + } + + $this->draw->push(); + $this->matrices[++$this->matrixIndex] = $this->matrices[$this->matrixIndex - 1]; + } + + public function pop() : void + { + if (null === $this->draw) { + throw new RuntimeException('No image has been started'); + } + + $this->draw->pop(); + unset($this->matrices[$this->matrixIndex--]); + } + + public function drawPathWithColor(Path $path, ColorInterface $color) : void + { + if (null === $this->draw) { + throw new RuntimeException('No image has been started'); + } + + $this->draw->setFillColor($this->getColorPixel($color)); + $this->drawPath($path); + } + + public function drawPathWithGradient( + Path $path, + Gradient $gradient, + float $x, + float $y, + float $width, + float $height + ) : void { + if (null === $this->draw) { + throw new RuntimeException('No image has been started'); + } + + $this->draw->setFillPatternURL('#' . $this->createGradientFill($gradient, $x, $y, $width, $height)); + $this->drawPath($path); + } + + public function done() : string + { + if (null === $this->draw) { + throw new RuntimeException('No image has been started'); + } + + $this->image->drawImage($this->draw); + $blob = $this->image->getImageBlob(); + $this->draw->clear(); + $this->image->clear(); + $this->draw = null; + $this->image = null; + $this->gradientCount = null; + + return $blob; + } + + private function drawPath(Path $path) : void + { + $this->draw->pathStart(); + + foreach ($path as $op) { + switch (true) { + case $op instanceof Move: + $this->draw->pathMoveToAbsolute($op->getX(), $op->getY()); + break; + + case $op instanceof Line: + $this->draw->pathLineToAbsolute($op->getX(), $op->getY()); + break; + + case $op instanceof EllipticArc: + $this->draw->pathEllipticArcAbsolute( + $op->getXRadius(), + $op->getYRadius(), + $op->getXAxisAngle(), + $op->isLargeArc(), + $op->isSweep(), + $op->getX(), + $op->getY() + ); + break; + + case $op instanceof Curve: + $this->draw->pathCurveToAbsolute( + $op->getX1(), + $op->getY1(), + $op->getX2(), + $op->getY2(), + $op->getX3(), + $op->getY3() + ); + break; + + case $op instanceof Close: + $this->draw->pathClose(); + break; + + default: + throw new RuntimeException('Unexpected draw operation: ' . get_class($op)); + } + } + + $this->draw->pathFinish(); + } + + private function createGradientFill(Gradient $gradient, float $x, float $y, float $width, float $height) : string + { + list($width, $height) = $this->matrices[$this->matrixIndex]->apply($width, $height); + + $startColor = $this->getColorPixel($gradient->getStartColor())->getColorAsString(); + $endColor = $this->getColorPixel($gradient->getEndColor())->getColorAsString(); + $gradientImage = new Imagick(); + + switch ($gradient->getType()) { + case GradientType::HORIZONTAL(): + $gradientImage->newPseudoImage((int) $height, (int) $width, sprintf( + 'gradient:%s-%s', + $startColor, + $endColor + )); + $gradientImage->rotateImage('transparent', -90); + break; + + case GradientType::VERTICAL(): + $gradientImage->newPseudoImage((int) $width, (int) $height, sprintf( + 'gradient:%s-%s', + $startColor, + $endColor + )); + break; + + case GradientType::DIAGONAL(): + case GradientType::INVERSE_DIAGONAL(): + $gradientImage->newPseudoImage((int) ($width * sqrt(2)), (int) ($height * sqrt(2)), sprintf( + 'gradient:%s-%s', + $startColor, + $endColor + )); + + if (GradientType::DIAGONAL() === $gradient->getType()) { + $gradientImage->rotateImage('transparent', -45); + } else { + $gradientImage->rotateImage('transparent', -135); + } + + $rotatedWidth = $gradientImage->getImageWidth(); + $rotatedHeight = $gradientImage->getImageHeight(); + + $gradientImage->setImagePage($rotatedWidth, $rotatedHeight, 0, 0); + $gradientImage->cropImage( + intdiv($rotatedWidth, 2) - 2, + intdiv($rotatedHeight, 2) - 2, + intdiv($rotatedWidth, 4) + 1, + intdiv($rotatedWidth, 4) + 1 + ); + break; + + case GradientType::RADIAL(): + $gradientImage->newPseudoImage((int) $width, (int) $height, sprintf( + 'radial-gradient:%s-%s', + $startColor, + $endColor + )); + break; + } + + $id = sprintf('g%d', ++$this->gradientCount); + $this->draw->pushPattern($id, 0, 0, $width, $height); + $this->draw->composite(Imagick::COMPOSITE_COPY, 0, 0, $width, $height, $gradientImage); + $this->draw->popPattern(); + return $id; + } + + private function getColorPixel(ColorInterface $color) : ImagickPixel + { + $alpha = 100; + + if ($color instanceof Alpha) { + $alpha = $color->getAlpha(); + $color = $color->getBaseColor(); + } + + if ($color instanceof Rgb) { + return new ImagickPixel(sprintf( + 'rgba(%d, %d, %d, %F)', + $color->getRed(), + $color->getGreen(), + $color->getBlue(), + $alpha / 100 + )); + } + + if ($color instanceof Cmyk) { + return new ImagickPixel(sprintf( + 'cmyka(%d, %d, %d, %d, %F)', + $color->getCyan(), + $color->getMagenta(), + $color->getYellow(), + $color->getBlack(), + $alpha / 100 + )); + } + + if ($color instanceof Gray) { + return new ImagickPixel(sprintf( + 'graya(%d%%, %F)', + $color->getGray(), + $alpha / 100 + )); + } + + return $this->getColorPixel(new Alpha($alpha, $color->toRgb())); + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Image/SvgImageBackEnd.php b/vendor/bacon/bacon-qr-code/src/Renderer/Image/SvgImageBackEnd.php index 3a49918..5b6709a 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Image/SvgImageBackEnd.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Image/SvgImageBackEnd.php @@ -1,363 +1,363 @@ -xmlWriter = new XMLWriter(); - $this->xmlWriter->openMemory(); - - $this->xmlWriter->startDocument('1.0', 'UTF-8'); - $this->xmlWriter->startElement('svg'); - $this->xmlWriter->writeAttribute('xmlns', 'http://www.w3.org/2000/svg'); - $this->xmlWriter->writeAttribute('version', '1.1'); - $this->xmlWriter->writeAttribute('width', (string) $size); - $this->xmlWriter->writeAttribute('height', (string) $size); - $this->xmlWriter->writeAttribute('viewBox', '0 0 '. $size . ' ' . $size); - - $this->gradientCount = 0; - $this->currentStack = 0; - $this->stack[0] = 0; - - $alpha = 1; - - if ($backgroundColor instanceof Alpha) { - $alpha = $backgroundColor->getAlpha() / 100; - } - - if (0 === $alpha) { - return; - } - - $this->xmlWriter->startElement('rect'); - $this->xmlWriter->writeAttribute('x', '0'); - $this->xmlWriter->writeAttribute('y', '0'); - $this->xmlWriter->writeAttribute('width', (string) $size); - $this->xmlWriter->writeAttribute('height', (string) $size); - $this->xmlWriter->writeAttribute('fill', $this->getColorString($backgroundColor)); - - if ($alpha < 1) { - $this->xmlWriter->writeAttribute('fill-opacity', (string) $alpha); - } - - $this->xmlWriter->endElement(); - } - - public function scale(float $size) : void - { - if (null === $this->xmlWriter) { - throw new RuntimeException('No image has been started'); - } - - $this->xmlWriter->startElement('g'); - $this->xmlWriter->writeAttribute( - 'transform', - sprintf(self::SCALE_FORMAT, round($size, self::PRECISION)) - ); - ++$this->stack[$this->currentStack]; - } - - public function translate(float $x, float $y) : void - { - if (null === $this->xmlWriter) { - throw new RuntimeException('No image has been started'); - } - - $this->xmlWriter->startElement('g'); - $this->xmlWriter->writeAttribute( - 'transform', - sprintf(self::TRANSLATE_FORMAT, round($x, self::PRECISION), round($y, self::PRECISION)) - ); - ++$this->stack[$this->currentStack]; - } - - public function rotate(int $degrees) : void - { - if (null === $this->xmlWriter) { - throw new RuntimeException('No image has been started'); - } - - $this->xmlWriter->startElement('g'); - $this->xmlWriter->writeAttribute('transform', sprintf('rotate(%d)', $degrees)); - ++$this->stack[$this->currentStack]; - } - - public function push() : void - { - if (null === $this->xmlWriter) { - throw new RuntimeException('No image has been started'); - } - - $this->xmlWriter->startElement('g'); - $this->stack[] = 1; - ++$this->currentStack; - } - - public function pop() : void - { - if (null === $this->xmlWriter) { - throw new RuntimeException('No image has been started'); - } - - for ($i = 0; $i < $this->stack[$this->currentStack]; ++$i) { - $this->xmlWriter->endElement(); - } - - array_pop($this->stack); - --$this->currentStack; - } - - public function drawPathWithColor(Path $path, ColorInterface $color) : void - { - if (null === $this->xmlWriter) { - throw new RuntimeException('No image has been started'); - } - - $alpha = 1; - - if ($color instanceof Alpha) { - $alpha = $color->getAlpha() / 100; - } - - $this->startPathElement($path); - $this->xmlWriter->writeAttribute('fill', $this->getColorString($color)); - - if ($alpha < 1) { - $this->xmlWriter->writeAttribute('fill-opacity', (string) $alpha); - } - - $this->xmlWriter->endElement(); - } - - public function drawPathWithGradient( - Path $path, - Gradient $gradient, - float $x, - float $y, - float $width, - float $height - ) : void { - if (null === $this->xmlWriter) { - throw new RuntimeException('No image has been started'); - } - - $gradientId = $this->createGradientFill($gradient, $x, $y, $width, $height); - $this->startPathElement($path); - $this->xmlWriter->writeAttribute('fill', 'url(#' . $gradientId . ')'); - $this->xmlWriter->endElement(); - } - - public function done() : string - { - if (null === $this->xmlWriter) { - throw new RuntimeException('No image has been started'); - } - - foreach ($this->stack as $openElements) { - for ($i = $openElements; $i > 0; --$i) { - $this->xmlWriter->endElement(); - } - } - - $this->xmlWriter->endDocument(); - $blob = $this->xmlWriter->outputMemory(true); - $this->xmlWriter = null; - $this->stack = null; - $this->currentStack = null; - $this->gradientCount = null; - - return $blob; - } - - private function startPathElement(Path $path) : void - { - $pathData = []; - - foreach ($path as $op) { - switch (true) { - case $op instanceof Move: - $pathData[] = sprintf( - 'M%s %s', - round($op->getX(), self::PRECISION), - round($op->getY(), self::PRECISION) - ); - break; - - case $op instanceof Line: - $pathData[] = sprintf( - 'L%s %s', - round($op->getX(), self::PRECISION), - round($op->getY(), self::PRECISION) - ); - break; - - case $op instanceof EllipticArc: - $pathData[] = sprintf( - 'A%s %s %s %u %u %s %s', - round($op->getXRadius(), self::PRECISION), - round($op->getYRadius(), self::PRECISION), - round($op->getXAxisAngle(), self::PRECISION), - $op->isLargeArc(), - $op->isSweep(), - round($op->getX(), self::PRECISION), - round($op->getY(), self::PRECISION) - ); - break; - - case $op instanceof Curve: - $pathData[] = sprintf( - 'C%s %s %s %s %s %s', - round($op->getX1(), self::PRECISION), - round($op->getY1(), self::PRECISION), - round($op->getX2(), self::PRECISION), - round($op->getY2(), self::PRECISION), - round($op->getX3(), self::PRECISION), - round($op->getY3(), self::PRECISION) - ); - break; - - case $op instanceof Close: - $pathData[] = 'Z'; - break; - - default: - throw new RuntimeException('Unexpected draw operation: ' . get_class($op)); - } - } - - $this->xmlWriter->startElement('path'); - $this->xmlWriter->writeAttribute('fill-rule', 'evenodd'); - $this->xmlWriter->writeAttribute('d', implode('', $pathData)); - } - - private function createGradientFill(Gradient $gradient, float $x, float $y, float $width, float $height) : string - { - $this->xmlWriter->startElement('defs'); - - $startColor = $gradient->getStartColor(); - $endColor = $gradient->getEndColor(); - - if ($gradient->getType() === GradientType::RADIAL()) { - $this->xmlWriter->startElement('radialGradient'); - } else { - $this->xmlWriter->startElement('linearGradient'); - } - - $this->xmlWriter->writeAttribute('gradientUnits', 'userSpaceOnUse'); - - switch ($gradient->getType()) { - case GradientType::HORIZONTAL(): - $this->xmlWriter->writeAttribute('x1', (string) round($x, self::PRECISION)); - $this->xmlWriter->writeAttribute('y1', (string) round($y, self::PRECISION)); - $this->xmlWriter->writeAttribute('x2', (string) round($x + $width, self::PRECISION)); - $this->xmlWriter->writeAttribute('y2', (string) round($y, self::PRECISION)); - break; - - case GradientType::VERTICAL(): - $this->xmlWriter->writeAttribute('x1', (string) round($x, self::PRECISION)); - $this->xmlWriter->writeAttribute('y1', (string) round($y, self::PRECISION)); - $this->xmlWriter->writeAttribute('x2', (string) round($x, self::PRECISION)); - $this->xmlWriter->writeAttribute('y2', (string) round($y + $height, self::PRECISION)); - break; - - case GradientType::DIAGONAL(): - $this->xmlWriter->writeAttribute('x1', (string) round($x, self::PRECISION)); - $this->xmlWriter->writeAttribute('y1', (string) round($y, self::PRECISION)); - $this->xmlWriter->writeAttribute('x2', (string) round($x + $width, self::PRECISION)); - $this->xmlWriter->writeAttribute('y2', (string) round($y + $height, self::PRECISION)); - break; - - case GradientType::INVERSE_DIAGONAL(): - $this->xmlWriter->writeAttribute('x1', (string) round($x, self::PRECISION)); - $this->xmlWriter->writeAttribute('y1', (string) round($y + $height, self::PRECISION)); - $this->xmlWriter->writeAttribute('x2', (string) round($x + $width, self::PRECISION)); - $this->xmlWriter->writeAttribute('y2', (string) round($y, self::PRECISION)); - break; - - case GradientType::RADIAL(): - $this->xmlWriter->writeAttribute('cx', (string) round(($x + $width) / 2, self::PRECISION)); - $this->xmlWriter->writeAttribute('cy', (string) round(($y + $height) / 2, self::PRECISION)); - $this->xmlWriter->writeAttribute('r', (string) round(max($width, $height) / 2, self::PRECISION)); - break; - } - - $toBeHashed = $this->getColorString($startColor) . $this->getColorString($endColor) . $gradient->getType(); - if ($startColor instanceof Alpha) { - $toBeHashed .= (string) $startColor->getAlpha(); - } - $id = sprintf('g%d-%s', ++$this->gradientCount, hash('xxh64', $toBeHashed)); - $this->xmlWriter->writeAttribute('id', $id); - - $this->xmlWriter->startElement('stop'); - $this->xmlWriter->writeAttribute('offset', '0%'); - $this->xmlWriter->writeAttribute('stop-color', $this->getColorString($startColor)); - - if ($startColor instanceof Alpha) { - $this->xmlWriter->writeAttribute('stop-opacity', (string) $startColor->getAlpha()); - } - - $this->xmlWriter->endElement(); - - $this->xmlWriter->startElement('stop'); - $this->xmlWriter->writeAttribute('offset', '100%'); - $this->xmlWriter->writeAttribute('stop-color', $this->getColorString($endColor)); - - if ($endColor instanceof Alpha) { - $this->xmlWriter->writeAttribute('stop-opacity', (string) $endColor->getAlpha()); - } - - $this->xmlWriter->endElement(); - - $this->xmlWriter->endElement(); - $this->xmlWriter->endElement(); - - return $id; - } - - private function getColorString(ColorInterface $color) : string - { - $color = $color->toRgb(); - - return sprintf( - '#%02x%02x%02x', - $color->getRed(), - $color->getGreen(), - $color->getBlue() - ); - } -} +xmlWriter = new XMLWriter(); + $this->xmlWriter->openMemory(); + + $this->xmlWriter->startDocument('1.0', 'UTF-8'); + $this->xmlWriter->startElement('svg'); + $this->xmlWriter->writeAttribute('xmlns', 'http://www.w3.org/2000/svg'); + $this->xmlWriter->writeAttribute('version', '1.1'); + $this->xmlWriter->writeAttribute('width', (string) $size); + $this->xmlWriter->writeAttribute('height', (string) $size); + $this->xmlWriter->writeAttribute('viewBox', '0 0 '. $size . ' ' . $size); + + $this->gradientCount = 0; + $this->currentStack = 0; + $this->stack[0] = 0; + + $alpha = 1; + + if ($backgroundColor instanceof Alpha) { + $alpha = $backgroundColor->getAlpha() / 100; + } + + if (0 === $alpha) { + return; + } + + $this->xmlWriter->startElement('rect'); + $this->xmlWriter->writeAttribute('x', '0'); + $this->xmlWriter->writeAttribute('y', '0'); + $this->xmlWriter->writeAttribute('width', (string) $size); + $this->xmlWriter->writeAttribute('height', (string) $size); + $this->xmlWriter->writeAttribute('fill', $this->getColorString($backgroundColor)); + + if ($alpha < 1) { + $this->xmlWriter->writeAttribute('fill-opacity', (string) $alpha); + } + + $this->xmlWriter->endElement(); + } + + public function scale(float $size) : void + { + if (null === $this->xmlWriter) { + throw new RuntimeException('No image has been started'); + } + + $this->xmlWriter->startElement('g'); + $this->xmlWriter->writeAttribute( + 'transform', + sprintf('scale(%s)', round($size, self::PRECISION)) + ); + ++$this->stack[$this->currentStack]; + } + + public function translate(float $x, float $y) : void + { + if (null === $this->xmlWriter) { + throw new RuntimeException('No image has been started'); + } + + $this->xmlWriter->startElement('g'); + $this->xmlWriter->writeAttribute( + 'transform', + sprintf('translate(%s,%s)', round($x, self::PRECISION), round($y, self::PRECISION)) + ); + ++$this->stack[$this->currentStack]; + } + + public function rotate(int $degrees) : void + { + if (null === $this->xmlWriter) { + throw new RuntimeException('No image has been started'); + } + + $this->xmlWriter->startElement('g'); + $this->xmlWriter->writeAttribute('transform', sprintf('rotate(%d)', $degrees)); + ++$this->stack[$this->currentStack]; + } + + public function push() : void + { + if (null === $this->xmlWriter) { + throw new RuntimeException('No image has been started'); + } + + $this->xmlWriter->startElement('g'); + $this->stack[] = 1; + ++$this->currentStack; + } + + public function pop() : void + { + if (null === $this->xmlWriter) { + throw new RuntimeException('No image has been started'); + } + + for ($i = 0; $i < $this->stack[$this->currentStack]; ++$i) { + $this->xmlWriter->endElement(); + } + + array_pop($this->stack); + --$this->currentStack; + } + + public function drawPathWithColor(Path $path, ColorInterface $color) : void + { + if (null === $this->xmlWriter) { + throw new RuntimeException('No image has been started'); + } + + $alpha = 1; + + if ($color instanceof Alpha) { + $alpha = $color->getAlpha() / 100; + } + + $this->startPathElement($path); + $this->xmlWriter->writeAttribute('fill', $this->getColorString($color)); + + if ($alpha < 1) { + $this->xmlWriter->writeAttribute('fill-opacity', (string) $alpha); + } + + $this->xmlWriter->endElement(); + } + + public function drawPathWithGradient( + Path $path, + Gradient $gradient, + float $x, + float $y, + float $width, + float $height + ) : void { + if (null === $this->xmlWriter) { + throw new RuntimeException('No image has been started'); + } + + $gradientId = $this->createGradientFill($gradient, $x, $y, $width, $height); + $this->startPathElement($path); + $this->xmlWriter->writeAttribute('fill', 'url(#' . $gradientId . ')'); + $this->xmlWriter->endElement(); + } + + public function done() : string + { + if (null === $this->xmlWriter) { + throw new RuntimeException('No image has been started'); + } + + foreach ($this->stack as $openElements) { + for ($i = $openElements; $i > 0; --$i) { + $this->xmlWriter->endElement(); + } + } + + $this->xmlWriter->endDocument(); + $blob = $this->xmlWriter->outputMemory(true); + $this->xmlWriter = null; + $this->stack = null; + $this->currentStack = null; + $this->gradientCount = null; + + return $blob; + } + + private function startPathElement(Path $path) : void + { + $pathData = []; + + foreach ($path as $op) { + switch (true) { + case $op instanceof Move: + $pathData[] = sprintf( + 'M%s %s', + round($op->getX(), self::PRECISION), + round($op->getY(), self::PRECISION) + ); + break; + + case $op instanceof Line: + $pathData[] = sprintf( + 'L%s %s', + round($op->getX(), self::PRECISION), + round($op->getY(), self::PRECISION) + ); + break; + + case $op instanceof EllipticArc: + $pathData[] = sprintf( + 'A%s %s %s %u %u %s %s', + round($op->getXRadius(), self::PRECISION), + round($op->getYRadius(), self::PRECISION), + round($op->getXAxisAngle(), self::PRECISION), + $op->isLargeArc(), + $op->isSweep(), + round($op->getX(), self::PRECISION), + round($op->getY(), self::PRECISION) + ); + break; + + case $op instanceof Curve: + $pathData[] = sprintf( + 'C%s %s %s %s %s %s', + round($op->getX1(), self::PRECISION), + round($op->getY1(), self::PRECISION), + round($op->getX2(), self::PRECISION), + round($op->getY2(), self::PRECISION), + round($op->getX3(), self::PRECISION), + round($op->getY3(), self::PRECISION) + ); + break; + + case $op instanceof Close: + $pathData[] = 'Z'; + break; + + default: + throw new RuntimeException('Unexpected draw operation: ' . get_class($op)); + } + } + + $this->xmlWriter->startElement('path'); + $this->xmlWriter->writeAttribute('fill-rule', 'evenodd'); + $this->xmlWriter->writeAttribute('d', implode('', $pathData)); + } + + private function createGradientFill(Gradient $gradient, float $x, float $y, float $width, float $height) : string + { + $this->xmlWriter->startElement('defs'); + + $startColor = $gradient->getStartColor(); + $endColor = $gradient->getEndColor(); + + if ($gradient->getType() === GradientType::RADIAL()) { + $this->xmlWriter->startElement('radialGradient'); + } else { + $this->xmlWriter->startElement('linearGradient'); + } + + $this->xmlWriter->writeAttribute('gradientUnits', 'userSpaceOnUse'); + + switch ($gradient->getType()) { + case GradientType::HORIZONTAL(): + $this->xmlWriter->writeAttribute('x1', (string) round($x, self::PRECISION)); + $this->xmlWriter->writeAttribute('y1', (string) round($y, self::PRECISION)); + $this->xmlWriter->writeAttribute('x2', (string) round($x + $width, self::PRECISION)); + $this->xmlWriter->writeAttribute('y2', (string) round($y, self::PRECISION)); + break; + + case GradientType::VERTICAL(): + $this->xmlWriter->writeAttribute('x1', (string) round($x, self::PRECISION)); + $this->xmlWriter->writeAttribute('y1', (string) round($y, self::PRECISION)); + $this->xmlWriter->writeAttribute('x2', (string) round($x, self::PRECISION)); + $this->xmlWriter->writeAttribute('y2', (string) round($y + $height, self::PRECISION)); + break; + + case GradientType::DIAGONAL(): + $this->xmlWriter->writeAttribute('x1', (string) round($x, self::PRECISION)); + $this->xmlWriter->writeAttribute('y1', (string) round($y, self::PRECISION)); + $this->xmlWriter->writeAttribute('x2', (string) round($x + $width, self::PRECISION)); + $this->xmlWriter->writeAttribute('y2', (string) round($y + $height, self::PRECISION)); + break; + + case GradientType::INVERSE_DIAGONAL(): + $this->xmlWriter->writeAttribute('x1', (string) round($x, self::PRECISION)); + $this->xmlWriter->writeAttribute('y1', (string) round($y + $height, self::PRECISION)); + $this->xmlWriter->writeAttribute('x2', (string) round($x + $width, self::PRECISION)); + $this->xmlWriter->writeAttribute('y2', (string) round($y, self::PRECISION)); + break; + + case GradientType::RADIAL(): + $this->xmlWriter->writeAttribute('cx', (string) round(($x + $width) / 2, self::PRECISION)); + $this->xmlWriter->writeAttribute('cy', (string) round(($y + $height) / 2, self::PRECISION)); + $this->xmlWriter->writeAttribute('r', (string) round(max($width, $height) / 2, self::PRECISION)); + break; + } + + $toBeHashed = $this->getColorString($startColor) . $this->getColorString($endColor) . $gradient->getType(); + if ($startColor instanceof Alpha) { + $toBeHashed .= (string) $startColor->getAlpha(); + } + $id = sprintf('g%d-%s', ++$this->gradientCount, hash('xxh3', $toBeHashed)); + $this->xmlWriter->writeAttribute('id', $id); + + $this->xmlWriter->startElement('stop'); + $this->xmlWriter->writeAttribute('offset', '0%'); + $this->xmlWriter->writeAttribute('stop-color', $this->getColorString($startColor)); + + if ($startColor instanceof Alpha) { + $this->xmlWriter->writeAttribute('stop-opacity', (string) $startColor->getAlpha()); + } + + $this->xmlWriter->endElement(); + + $this->xmlWriter->startElement('stop'); + $this->xmlWriter->writeAttribute('offset', '100%'); + $this->xmlWriter->writeAttribute('stop-color', $this->getColorString($endColor)); + + if ($endColor instanceof Alpha) { + $this->xmlWriter->writeAttribute('stop-opacity', (string) $endColor->getAlpha()); + } + + $this->xmlWriter->endElement(); + + $this->xmlWriter->endElement(); + $this->xmlWriter->endElement(); + + return $id; + } + + private function getColorString(ColorInterface $color) : string + { + $color = $color->toRgb(); + + return sprintf( + '#%02x%02x%02x', + $color->getRed(), + $color->getGreen(), + $color->getBlue() + ); + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Image/TransformationMatrix.php b/vendor/bacon/bacon-qr-code/src/Renderer/Image/TransformationMatrix.php index cee353f..9b435a0 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Image/TransformationMatrix.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Image/TransformationMatrix.php @@ -1,68 +1,68 @@ -values = [1, 0, 0, 1, 0, 0]; - } - - public function multiply(self $other) : self - { - $matrix = new self(); - $matrix->values[0] = $this->values[0] * $other->values[0] + $this->values[2] * $other->values[1]; - $matrix->values[1] = $this->values[1] * $other->values[0] + $this->values[3] * $other->values[1]; - $matrix->values[2] = $this->values[0] * $other->values[2] + $this->values[2] * $other->values[3]; - $matrix->values[3] = $this->values[1] * $other->values[2] + $this->values[3] * $other->values[3]; - $matrix->values[4] = $this->values[0] * $other->values[4] + $this->values[2] * $other->values[5] - + $this->values[4]; - $matrix->values[5] = $this->values[1] * $other->values[4] + $this->values[3] * $other->values[5] - + $this->values[5]; - - return $matrix; - } - - public static function scale(float $size) : self - { - $matrix = new self(); - $matrix->values = [$size, 0, 0, $size, 0, 0]; - return $matrix; - } - - public static function translate(float $x, float $y) : self - { - $matrix = new self(); - $matrix->values = [1, 0, 0, 1, $x, $y]; - return $matrix; - } - - public static function rotate(int $degrees) : self - { - $matrix = new self(); - $rad = deg2rad($degrees); - $matrix->values = [cos($rad), sin($rad), -sin($rad), cos($rad), 0, 0]; - return $matrix; - } - - - /** - * Applies this matrix onto a point and returns the resulting viewport point. - * - * @return float[] - */ - public function apply(float $x, float $y) : array - { - return [ - $x * $this->values[0] + $y * $this->values[2] + $this->values[4], - $x * $this->values[1] + $y * $this->values[3] + $this->values[5], - ]; - } -} +values = [1, 0, 0, 1, 0, 0]; + } + + public function multiply(self $other) : self + { + $matrix = new self(); + $matrix->values[0] = $this->values[0] * $other->values[0] + $this->values[2] * $other->values[1]; + $matrix->values[1] = $this->values[1] * $other->values[0] + $this->values[3] * $other->values[1]; + $matrix->values[2] = $this->values[0] * $other->values[2] + $this->values[2] * $other->values[3]; + $matrix->values[3] = $this->values[1] * $other->values[2] + $this->values[3] * $other->values[3]; + $matrix->values[4] = $this->values[0] * $other->values[4] + $this->values[2] * $other->values[5] + + $this->values[4]; + $matrix->values[5] = $this->values[1] * $other->values[4] + $this->values[3] * $other->values[5] + + $this->values[5]; + + return $matrix; + } + + public static function scale(float $size) : self + { + $matrix = new self(); + $matrix->values = [$size, 0, 0, $size, 0, 0]; + return $matrix; + } + + public static function translate(float $x, float $y) : self + { + $matrix = new self(); + $matrix->values = [1, 0, 0, 1, $x, $y]; + return $matrix; + } + + public static function rotate(int $degrees) : self + { + $matrix = new self(); + $rad = deg2rad($degrees); + $matrix->values = [cos($rad), sin($rad), -sin($rad), cos($rad), 0, 0]; + return $matrix; + } + + + /** + * Applies this matrix onto a point and returns the resulting viewport point. + * + * @return float[] + */ + public function apply(float $x, float $y) : array + { + return [ + $x * $this->values[0] + $y * $this->values[2] + $this->values[4], + $x * $this->values[1] + $y * $this->values[3] + $this->values[5], + ]; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/ImageRenderer.php b/vendor/bacon/bacon-qr-code/src/Renderer/ImageRenderer.php index 4192218..0d33303 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/ImageRenderer.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/ImageRenderer.php @@ -1,150 +1,150 @@ -rendererStyle->getSize(); - $margin = $this->rendererStyle->getMargin(); - $matrix = $qrCode->getMatrix(); - $matrixSize = $matrix->getWidth(); - - if ($matrixSize !== $matrix->getHeight()) { - throw new InvalidArgumentException('Matrix must have the same width and height'); - } - - $totalSize = $matrixSize + ($margin * 2); - $moduleSize = $size / $totalSize; - $fill = $this->rendererStyle->getFill(); - - $this->imageBackEnd->new($size, $fill->getBackgroundColor()); - $this->imageBackEnd->scale((float) $moduleSize); - $this->imageBackEnd->translate((float) $margin, (float) $margin); - - $module = $this->rendererStyle->getModule(); - $moduleMatrix = clone $matrix; - MatrixUtil::removePositionDetectionPatterns($moduleMatrix); - $modulePath = $this->drawEyes($matrixSize, $module->createPath($moduleMatrix)); - - if ($fill->hasGradientFill()) { - $this->imageBackEnd->drawPathWithGradient( - $modulePath, - $fill->getForegroundGradient(), - 0, - 0, - $matrixSize, - $matrixSize - ); - } else { - $this->imageBackEnd->drawPathWithColor($modulePath, $fill->getForegroundColor()); - } - - return $this->imageBackEnd->done(); - } - - private function drawEyes(int $matrixSize, Path $modulePath) : Path - { - $fill = $this->rendererStyle->getFill(); - - $eye = $this->rendererStyle->getEye(); - $externalPath = $eye->getExternalPath(); - $internalPath = $eye->getInternalPath(); - - $modulePath = $this->drawEye( - $externalPath, - $internalPath, - $fill->getTopLeftEyeFill(), - 3.5, - 3.5, - 0, - $modulePath - ); - $modulePath = $this->drawEye( - $externalPath, - $internalPath, - $fill->getTopRightEyeFill(), - $matrixSize - 3.5, - 3.5, - 90, - $modulePath - ); - $modulePath = $this->drawEye( - $externalPath, - $internalPath, - $fill->getBottomLeftEyeFill(), - 3.5, - $matrixSize - 3.5, - -90, - $modulePath - ); - - return $modulePath; - } - - private function drawEye( - Path $externalPath, - Path $internalPath, - EyeFill $fill, - float $xTranslation, - float $yTranslation, - int $rotation, - Path $modulePath - ) : Path { - if ($fill->inheritsBothColors()) { - return $modulePath - ->append( - $externalPath->rotate($rotation)->translate($xTranslation, $yTranslation) - ) - ->append( - $internalPath->rotate($rotation)->translate($xTranslation, $yTranslation) - ); - } - - $this->imageBackEnd->push(); - $this->imageBackEnd->translate($xTranslation, $yTranslation); - - if (0 !== $rotation) { - $this->imageBackEnd->rotate($rotation); - } - - if ($fill->inheritsExternalColor()) { - $modulePath = $modulePath->append( - $externalPath->rotate($rotation)->translate($xTranslation, $yTranslation) - ); - } else { - $this->imageBackEnd->drawPathWithColor($externalPath, $fill->getExternalColor()); - } - - if ($fill->inheritsInternalColor()) { - $modulePath = $modulePath->append( - $internalPath->rotate($rotation)->translate($xTranslation, $yTranslation) - ); - } else { - $this->imageBackEnd->drawPathWithColor($internalPath, $fill->getInternalColor()); - } - - $this->imageBackEnd->pop(); - - return $modulePath; - } -} +rendererStyle->getSize(); + $margin = $this->rendererStyle->getMargin(); + $matrix = $qrCode->getMatrix(); + $matrixSize = $matrix->getWidth(); + + if ($matrixSize !== $matrix->getHeight()) { + throw new InvalidArgumentException('Matrix must have the same width and height'); + } + + $totalSize = $matrixSize + ($margin * 2); + $moduleSize = $size / $totalSize; + $fill = $this->rendererStyle->getFill(); + + $this->imageBackEnd->new($size, $fill->getBackgroundColor()); + $this->imageBackEnd->scale((float) $moduleSize); + $this->imageBackEnd->translate((float) $margin, (float) $margin); + + $module = $this->rendererStyle->getModule(); + $moduleMatrix = clone $matrix; + MatrixUtil::removePositionDetectionPatterns($moduleMatrix); + $modulePath = $this->drawEyes($matrixSize, $module->createPath($moduleMatrix)); + + if ($fill->hasGradientFill()) { + $this->imageBackEnd->drawPathWithGradient( + $modulePath, + $fill->getForegroundGradient(), + 0, + 0, + $matrixSize, + $matrixSize + ); + } else { + $this->imageBackEnd->drawPathWithColor($modulePath, $fill->getForegroundColor()); + } + + return $this->imageBackEnd->done(); + } + + private function drawEyes(int $matrixSize, Path $modulePath) : Path + { + $fill = $this->rendererStyle->getFill(); + + $eye = $this->rendererStyle->getEye(); + $externalPath = $eye->getExternalPath(); + $internalPath = $eye->getInternalPath(); + + $modulePath = $this->drawEye( + $externalPath, + $internalPath, + $fill->getTopLeftEyeFill(), + 3.5, + 3.5, + 0, + $modulePath + ); + $modulePath = $this->drawEye( + $externalPath, + $internalPath, + $fill->getTopRightEyeFill(), + $matrixSize - 3.5, + 3.5, + 90, + $modulePath + ); + $modulePath = $this->drawEye( + $externalPath, + $internalPath, + $fill->getBottomLeftEyeFill(), + 3.5, + $matrixSize - 3.5, + -90, + $modulePath + ); + + return $modulePath; + } + + private function drawEye( + Path $externalPath, + Path $internalPath, + EyeFill $fill, + float $xTranslation, + float $yTranslation, + int $rotation, + Path $modulePath + ) : Path { + if ($fill->inheritsBothColors()) { + return $modulePath + ->append( + $externalPath->rotate($rotation)->translate($xTranslation, $yTranslation) + ) + ->append( + $internalPath->rotate($rotation)->translate($xTranslation, $yTranslation) + ); + } + + $this->imageBackEnd->push(); + $this->imageBackEnd->translate($xTranslation, $yTranslation); + + if (0 !== $rotation) { + $this->imageBackEnd->rotate($rotation); + } + + if ($fill->inheritsExternalColor()) { + $modulePath = $modulePath->append( + $externalPath->rotate($rotation)->translate($xTranslation, $yTranslation) + ); + } else { + $this->imageBackEnd->drawPathWithColor($externalPath, $fill->getExternalColor()); + } + + if ($fill->inheritsInternalColor()) { + $modulePath = $modulePath->append( + $internalPath->rotate($rotation)->translate($xTranslation, $yTranslation) + ); + } else { + $this->imageBackEnd->drawPathWithColor($internalPath, $fill->getInternalColor()); + } + + $this->imageBackEnd->pop(); + + return $modulePath; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Module/DotsModule.php b/vendor/bacon/bacon-qr-code/src/Renderer/Module/DotsModule.php index c94f9f7..c5d5c6f 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Module/DotsModule.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Module/DotsModule.php @@ -1,56 +1,56 @@ - 1) { - throw new InvalidArgumentException('Size must between 0 (exclusive) and 1 (inclusive)'); - } - } - - public function createPath(ByteMatrix $matrix) : Path - { - $width = $matrix->getWidth(); - $height = $matrix->getHeight(); - $path = new Path(); - $halfSize = $this->size / 2; - $margin = (1 - $this->size) / 2; - - for ($y = 0; $y < $height; ++$y) { - for ($x = 0; $x < $width; ++$x) { - if (! $matrix->get($x, $y)) { - continue; - } - - $pathX = $x + $margin; - $pathY = $y + $margin; - - $path = $path - ->move($pathX + $this->size, $pathY + $halfSize) - ->ellipticArc($halfSize, $halfSize, 0, false, true, $pathX + $halfSize, $pathY + $this->size) - ->ellipticArc($halfSize, $halfSize, 0, false, true, $pathX, $pathY + $halfSize) - ->ellipticArc($halfSize, $halfSize, 0, false, true, $pathX + $halfSize, $pathY) - ->ellipticArc($halfSize, $halfSize, 0, false, true, $pathX + $this->size, $pathY + $halfSize) - ->close() - ; - } - } - - return $path; - } -} + 1) { + throw new InvalidArgumentException('Size must between 0 (exclusive) and 1 (inclusive)'); + } + } + + public function createPath(ByteMatrix $matrix) : Path + { + $width = $matrix->getWidth(); + $height = $matrix->getHeight(); + $path = new Path(); + $halfSize = $this->size / 2; + $margin = (1 - $this->size) / 2; + + for ($y = 0; $y < $height; ++$y) { + for ($x = 0; $x < $width; ++$x) { + if (! $matrix->get($x, $y)) { + continue; + } + + $pathX = $x + $margin; + $pathY = $y + $margin; + + $path = $path + ->move($pathX + $this->size, $pathY + $halfSize) + ->ellipticArc($halfSize, $halfSize, 0, false, true, $pathX + $halfSize, $pathY + $this->size) + ->ellipticArc($halfSize, $halfSize, 0, false, true, $pathX, $pathY + $halfSize) + ->ellipticArc($halfSize, $halfSize, 0, false, true, $pathX + $halfSize, $pathY) + ->ellipticArc($halfSize, $halfSize, 0, false, true, $pathX + $this->size, $pathY + $halfSize) + ->close() + ; + } + } + + return $path; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Module/EdgeIterator/Edge.php b/vendor/bacon/bacon-qr-code/src/Renderer/Module/EdgeIterator/Edge.php index 250b146..141d66c 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Module/EdgeIterator/Edge.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Module/EdgeIterator/Edge.php @@ -1,82 +1,82 @@ - - */ - private array $points = []; - - /** - * @var array|null - */ - private ?array $simplifiedPoints = null; - - private int $minX = PHP_INT_MAX; - - private int $minY = PHP_INT_MAX; - - private int $maxX = -1; - - private int $maxY = -1; - - public function __construct(private readonly bool $positive) - { - } - - public function addPoint(int $x, int $y) : void - { - $this->points[] = [$x, $y]; - $this->minX = min($this->minX, $x); - $this->minY = min($this->minY, $y); - $this->maxX = max($this->maxX, $x); - $this->maxY = max($this->maxY, $y); - } - - public function isPositive() : bool - { - return $this->positive; - } - - /** - * @return array - */ - public function getPoints() : array - { - return $this->points; - } - - public function getMaxX() : int - { - return $this->maxX; - } - - public function getSimplifiedPoints() : array - { - if (null !== $this->simplifiedPoints) { - return $this->simplifiedPoints; - } - - $points = []; - $length = count($this->points); - - for ($i = 0; $i < $length; ++$i) { - $previousPoint = $this->points[(0 === $i ? $length : $i) - 1]; - $nextPoint = $this->points[($length - 1 === $i ? -1 : $i) + 1]; - $currentPoint = $this->points[$i]; - - if (($previousPoint[0] === $currentPoint[0] && $currentPoint[0] === $nextPoint[0]) - || ($previousPoint[1] === $currentPoint[1] && $currentPoint[1] === $nextPoint[1]) - ) { - continue; - } - - $points[] = $currentPoint; - } - - return $this->simplifiedPoints = $points; - } -} + + */ + private array $points = []; + + /** + * @var array|null + */ + private ?array $simplifiedPoints = null; + + private int $minX = PHP_INT_MAX; + + private int $minY = PHP_INT_MAX; + + private int $maxX = -1; + + private int $maxY = -1; + + public function __construct(private readonly bool $positive) + { + } + + public function addPoint(int $x, int $y) : void + { + $this->points[] = [$x, $y]; + $this->minX = min($this->minX, $x); + $this->minY = min($this->minY, $y); + $this->maxX = max($this->maxX, $x); + $this->maxY = max($this->maxY, $y); + } + + public function isPositive() : bool + { + return $this->positive; + } + + /** + * @return array + */ + public function getPoints() : array + { + return $this->points; + } + + public function getMaxX() : int + { + return $this->maxX; + } + + public function getSimplifiedPoints() : array + { + if (null !== $this->simplifiedPoints) { + return $this->simplifiedPoints; + } + + $points = []; + $length = count($this->points); + + for ($i = 0; $i < $length; ++$i) { + $previousPoint = $this->points[(0 === $i ? $length : $i) - 1]; + $nextPoint = $this->points[($length - 1 === $i ? -1 : $i) + 1]; + $currentPoint = $this->points[$i]; + + if (($previousPoint[0] === $currentPoint[0] && $currentPoint[0] === $nextPoint[0]) + || ($previousPoint[1] === $currentPoint[1] && $currentPoint[1] === $nextPoint[1]) + ) { + continue; + } + + $points[] = $currentPoint; + } + + return $this->simplifiedPoints = $points; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Module/EdgeIterator/EdgeIterator.php b/vendor/bacon/bacon-qr-code/src/Renderer/Module/EdgeIterator/EdgeIterator.php index 0dff753..01f692c 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Module/EdgeIterator/EdgeIterator.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Module/EdgeIterator/EdgeIterator.php @@ -1,160 +1,160 @@ -bytes = iterator_to_array($matrix->getBytes()); - $this->size = count($this->bytes); - $this->width = $matrix->getWidth(); - $this->height = $matrix->getHeight(); - } - - /** - * @return Traversable - */ - public function getIterator() : Traversable - { - $originalBytes = $this->bytes; - $point = $this->findNext(0, 0); - - while (null !== $point) { - $edge = $this->findEdge($point[0], $point[1]); - $this->xorEdge($edge); - - yield $edge; - - $point = $this->findNext($point[0], $point[1]); - } - - $this->bytes = $originalBytes; - } - - /** - * @return int[]|null - */ - private function findNext(int $x, int $y) : ?array - { - $i = $this->width * $y + $x; - - while ($i < $this->size && 1 !== $this->bytes[$i]) { - ++$i; - } - - if ($i < $this->size) { - return $this->pointOf($i); - } - - return null; - } - - private function findEdge(int $x, int $y) : Edge - { - $edge = new Edge($this->isSet($x, $y)); - $startX = $x; - $startY = $y; - $dirX = 0; - $dirY = 1; - - while (true) { - $edge->addPoint($x, $y); - $x += $dirX; - $y += $dirY; - - if ($x === $startX && $y === $startY) { - break; - } - - $left = $this->isSet($x + ($dirX + $dirY - 1 ) / 2, $y + ($dirY - $dirX - 1) / 2); - $right = $this->isSet($x + ($dirX - $dirY - 1) / 2, $y + ($dirY + $dirX - 1) / 2); - - if ($right && ! $left) { - $tmp = $dirX; - $dirX = -$dirY; - $dirY = $tmp; - } elseif ($right) { - $tmp = $dirX; - $dirX = -$dirY; - $dirY = $tmp; - } elseif (! $left) { - $tmp = $dirX; - $dirX = $dirY; - $dirY = -$tmp; - } - } - - return $edge; - } - - private function xorEdge(Edge $path) : void - { - $points = $path->getPoints(); - $y1 = $points[0][1]; - $length = count($points); - $maxX = $path->getMaxX(); - - for ($i = 1; $i < $length; ++$i) { - $y = $points[$i][1]; - - if ($y === $y1) { - continue; - } - - $x = $points[$i][0]; - $minY = min($y1, $y); - - for ($j = $x; $j < $maxX; ++$j) { - $this->flip($j, $minY); - } - - $y1 = $y; - } - } - - private function isSet(int $x, int $y) : bool - { - return ( - $x >= 0 - && $x < $this->width - && $y >= 0 - && $y < $this->height - ) && 1 === $this->bytes[$this->width * $y + $x]; - } - - /** - * @return int[] - */ - private function pointOf(int $i) : array - { - $y = intdiv($i, $this->width); - return [$i - $y * $this->width, $y]; - } - - private function flip(int $x, int $y) : void - { - $this->bytes[$this->width * $y + $x] = ( - $this->isSet($x, $y) ? 0 : 1 - ); - } -} +bytes = iterator_to_array($matrix->getBytes()); + $this->size = count($this->bytes); + $this->width = $matrix->getWidth(); + $this->height = $matrix->getHeight(); + } + + /** + * @return Traversable + */ + public function getIterator() : Traversable + { + $originalBytes = $this->bytes; + $point = $this->findNext(0, 0); + + while (null !== $point) { + $edge = $this->findEdge($point[0], $point[1]); + $this->xorEdge($edge); + + yield $edge; + + $point = $this->findNext($point[0], $point[1]); + } + + $this->bytes = $originalBytes; + } + + /** + * @return int[]|null + */ + private function findNext(int $x, int $y) : ?array + { + $i = $this->width * $y + $x; + + while ($i < $this->size && 1 !== $this->bytes[$i]) { + ++$i; + } + + if ($i < $this->size) { + return $this->pointOf($i); + } + + return null; + } + + private function findEdge(int $x, int $y) : Edge + { + $edge = new Edge($this->isSet($x, $y)); + $startX = $x; + $startY = $y; + $dirX = 0; + $dirY = 1; + + while (true) { + $edge->addPoint($x, $y); + $x += $dirX; + $y += $dirY; + + if ($x === $startX && $y === $startY) { + break; + } + + $left = $this->isSet($x + ($dirX + $dirY - 1 ) / 2, $y + ($dirY - $dirX - 1) / 2); + $right = $this->isSet($x + ($dirX - $dirY - 1) / 2, $y + ($dirY + $dirX - 1) / 2); + + if ($right && ! $left) { + $tmp = $dirX; + $dirX = -$dirY; + $dirY = $tmp; + } elseif ($right) { + $tmp = $dirX; + $dirX = -$dirY; + $dirY = $tmp; + } elseif (! $left) { + $tmp = $dirX; + $dirX = $dirY; + $dirY = -$tmp; + } + } + + return $edge; + } + + private function xorEdge(Edge $path) : void + { + $points = $path->getPoints(); + $y1 = $points[0][1]; + $length = count($points); + $maxX = $path->getMaxX(); + + for ($i = 1; $i < $length; ++$i) { + $y = $points[$i][1]; + + if ($y === $y1) { + continue; + } + + $x = $points[$i][0]; + $minY = min($y1, $y); + + for ($j = $x; $j < $maxX; ++$j) { + $this->flip($j, $minY); + } + + $y1 = $y; + } + } + + private function isSet(int $x, int $y) : bool + { + return ( + $x >= 0 + && $x < $this->width + && $y >= 0 + && $y < $this->height + ) && 1 === $this->bytes[$this->width * $y + $x]; + } + + /** + * @return int[] + */ + private function pointOf(int $i) : array + { + $y = intdiv($i, $this->width); + return [$i - $y * $this->width, $y]; + } + + private function flip(int $x, int $y) : void + { + $this->bytes[$this->width * $y + $x] = ( + $this->isSet($x, $y) ? 0 : 1 + ); + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Module/ModuleInterface.php b/vendor/bacon/bacon-qr-code/src/Renderer/Module/ModuleInterface.php index 4698e2a..0ccb0e0 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Module/ModuleInterface.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Module/ModuleInterface.php @@ -1,18 +1,18 @@ - 1) { - throw new InvalidArgumentException('Intensity must between 0 (exclusive) and 1 (inclusive)'); - } - - $this->intensity = $intensity / 2; - } - - public function createPath(ByteMatrix $matrix) : Path - { - $path = new Path(); - - foreach (new EdgeIterator($matrix) as $edge) { - $points = $edge->getSimplifiedPoints(); - $length = count($points); - - $currentPoint = $points[0]; - $nextPoint = $points[1]; - $horizontal = ($currentPoint[1] === $nextPoint[1]); - - if ($horizontal) { - $right = $nextPoint[0] > $currentPoint[0]; - $path = $path->move( - $currentPoint[0] + ($right ? $this->intensity : -$this->intensity), - $currentPoint[1] - ); - } else { - $up = $nextPoint[0] < $currentPoint[0]; - $path = $path->move( - $currentPoint[0], - $currentPoint[1] + ($up ? -$this->intensity : $this->intensity) - ); - } - - for ($i = 1; $i <= $length; ++$i) { - if ($i === $length) { - $previousPoint = $points[$length - 1]; - $currentPoint = $points[0]; - $nextPoint = $points[1]; - } else { - $previousPoint = $points[(0 === $i ? $length : $i) - 1]; - $currentPoint = $points[$i]; - $nextPoint = $points[($length - 1 === $i ? -1 : $i) + 1]; - } - - $horizontal = ($previousPoint[1] === $currentPoint[1]); - - if ($horizontal) { - $right = $previousPoint[0] < $currentPoint[0]; - $up = $nextPoint[1] < $currentPoint[1]; - $sweep = ($up xor $right); - - if ($this->intensity < 0.5 - || ($right && $previousPoint[0] !== $currentPoint[0] - 1) - || (! $right && $previousPoint[0] - 1 !== $currentPoint[0]) - ) { - $path = $path->line( - $currentPoint[0] + ($right ? -$this->intensity : $this->intensity), - $currentPoint[1] - ); - } - - $path = $path->ellipticArc( - $this->intensity, - $this->intensity, - 0, - false, - $sweep, - $currentPoint[0], - $currentPoint[1] + ($up ? -$this->intensity : $this->intensity) - ); - } else { - $up = $previousPoint[1] > $currentPoint[1]; - $right = $nextPoint[0] > $currentPoint[0]; - $sweep = ! ($up xor $right); - - if ($this->intensity < 0.5 - || ($up && $previousPoint[1] !== $currentPoint[1] + 1) - || (! $up && $previousPoint[0] + 1 !== $currentPoint[0]) - ) { - $path = $path->line( - $currentPoint[0], - $currentPoint[1] + ($up ? $this->intensity : -$this->intensity) - ); - } - - $path = $path->ellipticArc( - $this->intensity, - $this->intensity, - 0, - false, - $sweep, - $currentPoint[0] + ($right ? $this->intensity : -$this->intensity), - $currentPoint[1] - ); - } - } - - $path = $path->close(); - } - - return $path; - } -} + 1) { + throw new InvalidArgumentException('Intensity must between 0 (exclusive) and 1 (inclusive)'); + } + + $this->intensity = $intensity / 2; + } + + public function createPath(ByteMatrix $matrix) : Path + { + $path = new Path(); + + foreach (new EdgeIterator($matrix) as $edge) { + $points = $edge->getSimplifiedPoints(); + $length = count($points); + + $currentPoint = $points[0]; + $nextPoint = $points[1]; + $horizontal = ($currentPoint[1] === $nextPoint[1]); + + if ($horizontal) { + $right = $nextPoint[0] > $currentPoint[0]; + $path = $path->move( + $currentPoint[0] + ($right ? $this->intensity : -$this->intensity), + $currentPoint[1] + ); + } else { + $up = $nextPoint[0] < $currentPoint[0]; + $path = $path->move( + $currentPoint[0], + $currentPoint[1] + ($up ? -$this->intensity : $this->intensity) + ); + } + + for ($i = 1; $i <= $length; ++$i) { + if ($i === $length) { + $previousPoint = $points[$length - 1]; + $currentPoint = $points[0]; + $nextPoint = $points[1]; + } else { + $previousPoint = $points[(0 === $i ? $length : $i) - 1]; + $currentPoint = $points[$i]; + $nextPoint = $points[($length - 1 === $i ? -1 : $i) + 1]; + } + + $horizontal = ($previousPoint[1] === $currentPoint[1]); + + if ($horizontal) { + $right = $previousPoint[0] < $currentPoint[0]; + $up = $nextPoint[1] < $currentPoint[1]; + $sweep = ($up xor $right); + + if ($this->intensity < 0.5 + || ($right && $previousPoint[0] !== $currentPoint[0] - 1) + || (! $right && $previousPoint[0] - 1 !== $currentPoint[0]) + ) { + $path = $path->line( + $currentPoint[0] + ($right ? -$this->intensity : $this->intensity), + $currentPoint[1] + ); + } + + $path = $path->ellipticArc( + $this->intensity, + $this->intensity, + 0, + false, + $sweep, + $currentPoint[0], + $currentPoint[1] + ($up ? -$this->intensity : $this->intensity) + ); + } else { + $up = $previousPoint[1] > $currentPoint[1]; + $right = $nextPoint[0] > $currentPoint[0]; + $sweep = ! ($up xor $right); + + if ($this->intensity < 0.5 + || ($up && $previousPoint[1] !== $currentPoint[1] + 1) + || (! $up && $previousPoint[0] + 1 !== $currentPoint[0]) + ) { + $path = $path->line( + $currentPoint[0], + $currentPoint[1] + ($up ? $this->intensity : -$this->intensity) + ); + } + + $path = $path->ellipticArc( + $this->intensity, + $this->intensity, + 0, + false, + $sweep, + $currentPoint[0] + ($right ? $this->intensity : -$this->intensity), + $currentPoint[1] + ); + } + } + + $path = $path->close(); + } + + return $path; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Module/SquareModule.php b/vendor/bacon/bacon-qr-code/src/Renderer/Module/SquareModule.php index dd12b1a..8cf1d0b 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Module/SquareModule.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Module/SquareModule.php @@ -1,44 +1,44 @@ -getSimplifiedPoints(); - $length = count($points); - $path = $path->move($points[0][0], $points[0][1]); - - for ($i = 1; $i < $length; ++$i) { - $path = $path->line($points[$i][0], $points[$i][1]); - } - - $path = $path->close(); - } - - return $path; - } -} +getSimplifiedPoints(); + $length = count($points); + $path = $path->move($points[0][0], $points[0][1]); + + for ($i = 1; $i < $length; ++$i) { + $path = $path->line($points[$i][0], $points[$i][1]); + } + + $path = $path->close(); + } + + return $path; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Path/Close.php b/vendor/bacon/bacon-qr-code/src/Renderer/Path/Close.php index b9c2562..bddf2d0 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Path/Close.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Path/Close.php @@ -1,34 +1,34 @@ -x1; - } - - public function getY1() : float - { - return $this->y1; - } - - public function getX2() : float - { - return $this->x2; - } - - public function getY2() : float - { - return $this->y2; - } - - public function getX3() : float - { - return $this->x3; - } - - public function getY3() : float - { - return $this->y3; - } - - /** - * @return self - */ - public function translate(float $x, float $y) : OperationInterface - { - return new self( - $this->x1 + $x, - $this->y1 + $y, - $this->x2 + $x, - $this->y2 + $y, - $this->x3 + $x, - $this->y3 + $y - ); - } - - /** - * @return self - */ - public function rotate(int $degrees) : OperationInterface - { - $radians = deg2rad($degrees); - $sin = sin($radians); - $cos = cos($radians); - $x1r = $this->x1 * $cos - $this->y1 * $sin; - $y1r = $this->x1 * $sin + $this->y1 * $cos; - $x2r = $this->x2 * $cos - $this->y2 * $sin; - $y2r = $this->x2 * $sin + $this->y2 * $cos; - $x3r = $this->x3 * $cos - $this->y3 * $sin; - $y3r = $this->x3 * $sin + $this->y3 * $cos; - return new self( - $x1r, - $y1r, - $x2r, - $y2r, - $x3r, - $y3r - ); - } -} +x1; + } + + public function getY1() : float + { + return $this->y1; + } + + public function getX2() : float + { + return $this->x2; + } + + public function getY2() : float + { + return $this->y2; + } + + public function getX3() : float + { + return $this->x3; + } + + public function getY3() : float + { + return $this->y3; + } + + /** + * @return self + */ + public function translate(float $x, float $y) : OperationInterface + { + return new self( + $this->x1 + $x, + $this->y1 + $y, + $this->x2 + $x, + $this->y2 + $y, + $this->x3 + $x, + $this->y3 + $y + ); + } + + /** + * @return self + */ + public function rotate(int $degrees) : OperationInterface + { + $radians = deg2rad($degrees); + $sin = sin($radians); + $cos = cos($radians); + $x1r = $this->x1 * $cos - $this->y1 * $sin; + $y1r = $this->x1 * $sin + $this->y1 * $cos; + $x2r = $this->x2 * $cos - $this->y2 * $sin; + $y2r = $this->x2 * $sin + $this->y2 * $cos; + $x3r = $this->x3 * $cos - $this->y3 * $sin; + $y3r = $this->x3 * $sin + $this->y3 * $cos; + return new self( + $x1r, + $y1r, + $x2r, + $y2r, + $x3r, + $y3r + ); + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Path/EllipticArc.php b/vendor/bacon/bacon-qr-code/src/Renderer/Path/EllipticArc.php index 0bce583..800a032 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Path/EllipticArc.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Path/EllipticArc.php @@ -1,264 +1,266 @@ -xRadius = abs($xRadius); - $this->yRadius = abs($yRadius); - $this->xAxisAngle = $xAxisAngle % 360; - } - - public function getXRadius() : float - { - return $this->xRadius; - } - - public function getYRadius() : float - { - return $this->yRadius; - } - - public function getXAxisAngle() : float - { - return $this->xAxisAngle; - } - - public function isLargeArc() : bool - { - return $this->largeArc; - } - - public function isSweep() : bool - { - return $this->sweep; - } - - public function getX() : float - { - return $this->x; - } - - public function getY() : float - { - return $this->y; - } - - /** - * @return self - */ - public function translate(float $x, float $y) : OperationInterface - { - return new self( - $this->xRadius, - $this->yRadius, - $this->xAxisAngle, - $this->largeArc, - $this->sweep, - $this->x + $x, - $this->y + $y - ); - } - - /** - * @return self - */ - public function rotate(int $degrees) : OperationInterface - { - $radians = deg2rad($degrees); - $sin = sin($radians); - $cos = cos($radians); - $xr = $this->x * $cos - $this->y * $sin; - $yr = $this->x * $sin + $this->y * $cos; - return new self( - $this->xRadius, - $this->yRadius, - $this->xAxisAngle, - $this->largeArc, - $this->sweep, - $xr, - $yr - ); - } - - /** - * Converts the elliptic arc to multiple curves. - * - * Since not all image back ends support elliptic arcs, this method allows to convert the arc into multiple curves - * resembling the same result. - * - * @see https://mortoray.com/2017/02/16/rendering-an-svg-elliptical-arc-as-bezier-curves/ - * @return array - */ - public function toCurves(float $fromX, float $fromY) : array - { - if (sqrt(($fromX - $this->x) ** 2 + ($fromY - $this->y) ** 2) < self::ZERO_TOLERANCE) { - return []; - } - - if ($this->xRadius < self::ZERO_TOLERANCE || $this->yRadius < self::ZERO_TOLERANCE) { - return [new Line($this->x, $this->y)]; - } - - return $this->createCurves($fromX, $fromY); - } - - /** - * @return Curve[] - */ - private function createCurves(float $fromX, float $fromY) : array - { - $xAngle = deg2rad($this->xAxisAngle); - list($centerX, $centerY, $radiusX, $radiusY, $startAngle, $deltaAngle) = - $this->calculateCenterPointParameters($fromX, $fromY, $xAngle); - - $s = $startAngle; - $e = $s + $deltaAngle; - $sign = ($e < $s) ? -1 : 1; - $remain = abs($e - $s); - $p1 = self::point($centerX, $centerY, $radiusX, $radiusY, $xAngle, $s); - $curves = []; - - while ($remain > self::ZERO_TOLERANCE) { - $step = min($remain, pi() / 2); - $signStep = $step * $sign; - $p2 = self::point($centerX, $centerY, $radiusX, $radiusY, $xAngle, $s + $signStep); - - $alphaT = tan($signStep / 2); - $alpha = sin($signStep) * (sqrt(4 + 3 * $alphaT ** 2) - 1) / 3; - $d1 = self::derivative($radiusX, $radiusY, $xAngle, $s); - $d2 = self::derivative($radiusX, $radiusY, $xAngle, $s + $signStep); - - $curves[] = new Curve( - $p1[0] + $alpha * $d1[0], - $p1[1] + $alpha * $d1[1], - $p2[0] - $alpha * $d2[0], - $p2[1] - $alpha * $d2[1], - $p2[0], - $p2[1] - ); - - $s += $signStep; - $remain -= $step; - $p1 = $p2; - } - - return $curves; - } - - /** - * @return float[] - */ - private function calculateCenterPointParameters(float $fromX, float $fromY, float $xAngle): array - { - $rX = $this->xRadius; - $rY = $this->yRadius; - - // F.6.5.1 - $dx2 = ($fromX - $this->x) / 2; - $dy2 = ($fromY - $this->y) / 2; - $x1p = cos($xAngle) * $dx2 + sin($xAngle) * $dy2; - $y1p = -sin($xAngle) * $dx2 + cos($xAngle) * $dy2; - - // F.6.5.2 - $rxs = $rX ** 2; - $rys = $rY ** 2; - $x1ps = $x1p ** 2; - $y1ps = $y1p ** 2; - $cr = $x1ps / $rxs + $y1ps / $rys; - - if ($cr > 1) { - $s = sqrt($cr); - $rX *= $s; - $rY *= $s; - $rxs = $rX ** 2; - $rys = $rY ** 2; - } - - $dq = ($rxs * $y1ps + $rys * $x1ps); - $pq = ($rxs * $rys - $dq) / $dq; - $q = sqrt(max(0, $pq)); - - if ($this->largeArc === $this->sweep) { - $q = -$q; - } - - $cxp = $q * $rX * $y1p / $rY; - $cyp = -$q * $rY * $x1p / $rX; - - // F.6.5.3 - $cx = cos($xAngle) * $cxp - sin($xAngle) * $cyp + ($fromX + $this->x) / 2; - $cy = sin($xAngle) * $cxp + cos($xAngle) * $cyp + ($fromY + $this->y) / 2; - - // F.6.5.5 - $theta = self::angle(1, 0, ($x1p - $cxp) / $rX, ($y1p - $cyp) / $rY); - - // F.6.5.6 - $delta = self::angle(($x1p - $cxp) / $rX, ($y1p - $cyp) / $rY, (-$x1p - $cxp) / $rX, (-$y1p - $cyp) / $rY); - $delta = fmod($delta, pi() * 2); - - if (! $this->sweep) { - $delta -= 2 * pi(); - } - - return [$cx, $cy, $rX, $rY, $theta, $delta]; - } - - private static function angle(float $ux, float $uy, float $vx, float $vy) : float - { - // F.6.5.4 - $dot = $ux * $vx + $uy * $vy; - $length = sqrt($ux ** 2 + $uy ** 2) * sqrt($vx ** 2 + $vy ** 2); - $angle = acos(min(1, max(-1, $dot / $length))); - - if (($ux * $vy - $uy * $vx) < 0) { - return -$angle; - } - - return $angle; - } - - /** - * @return float[] - */ - private static function point( - float $centerX, - float $centerY, - float $radiusX, - float $radiusY, - float $xAngle, - float $angle - ) : array { - return [ - $centerX + $radiusX * cos($xAngle) * cos($angle) - $radiusY * sin($xAngle) * sin($angle), - $centerY + $radiusX * sin($xAngle) * cos($angle) + $radiusY * cos($xAngle) * sin($angle), - ]; - } - - /** - * @return float[] - */ - private static function derivative(float $radiusX, float $radiusY, float $xAngle, float $angle) : array - { - return [ - -$radiusX * cos($xAngle) * sin($angle) - $radiusY * sin($xAngle) * cos($angle), - -$radiusX * sin($xAngle) * sin($angle) + $radiusY * cos($xAngle) * cos($angle), - ]; - } -} +xRadius = abs($xRadius); + $this->yRadius = abs($yRadius); + $this->xAxisAngle = $xAxisAngle % 360; + } + + public function getXRadius() : float + { + return $this->xRadius; + } + + public function getYRadius() : float + { + return $this->yRadius; + } + + public function getXAxisAngle() : float + { + return $this->xAxisAngle; + } + + public function isLargeArc() : bool + { + return $this->largeArc; + } + + public function isSweep() : bool + { + return $this->sweep; + } + + public function getX() : float + { + return $this->x; + } + + public function getY() : float + { + return $this->y; + } + + /** + * @return self + */ + public function translate(float $x, float $y) : OperationInterface + { + return new self( + $this->xRadius, + $this->yRadius, + $this->xAxisAngle, + $this->largeArc, + $this->sweep, + $this->x + $x, + $this->y + $y + ); + } + + /** + * @return self + */ + public function rotate(int $degrees) : OperationInterface + { + $radians = deg2rad($degrees); + $sin = sin($radians); + $cos = cos($radians); + $xr = $this->x * $cos - $this->y * $sin; + $yr = $this->x * $sin + $this->y * $cos; + return new self( + $this->xRadius, + $this->yRadius, + $this->xAxisAngle, + $this->largeArc, + $this->sweep, + $xr, + $yr + ); + } + + /** + * Converts the elliptic arc to multiple curves. + * + * Since not all image back ends support elliptic arcs, this method allows to convert the arc into multiple curves + * resembling the same result. + * + * @see https://mortoray.com/2017/02/16/rendering-an-svg-elliptical-arc-as-bezier-curves/ + * @return array + */ + public function toCurves(float $fromX, float $fromY) : array + { + if (sqrt(($fromX - $this->x) ** 2 + ($fromY - $this->y) ** 2) < self::ZERO_TOLERANCE) { + return []; + } + + if ($this->xRadius < self::ZERO_TOLERANCE || $this->yRadius < self::ZERO_TOLERANCE) { + return [new Line($this->x, $this->y)]; + } + + return $this->createCurves($fromX, $fromY); + } + + /** + * @return Curve[] + */ + private function createCurves(float $fromX, float $fromY) : array + { + $xAngle = deg2rad($this->xAxisAngle); + list($centerX, $centerY, $radiusX, $radiusY, $startAngle, $deltaAngle) = + $this->calculateCenterPointParameters($fromX, $fromY, $xAngle); + + $s = $startAngle; + $e = $s + $deltaAngle; + $sign = ($e < $s) ? -1 : 1; + $remain = abs($e - $s); + $p1 = self::point($centerX, $centerY, $radiusX, $radiusY, $xAngle, $s); + $curves = []; + + while ($remain > self::ZERO_TOLERANCE) { + $step = min($remain, pi() / 2); + $signStep = $step * $sign; + $p2 = self::point($centerX, $centerY, $radiusX, $radiusY, $xAngle, $s + $signStep); + + $alphaT = tan($signStep / 2); + $alpha = sin($signStep) * (sqrt(4 + 3 * $alphaT ** 2) - 1) / 3; + $d1 = self::derivative($radiusX, $radiusY, $xAngle, $s); + $d2 = self::derivative($radiusX, $radiusY, $xAngle, $s + $signStep); + + $curves[] = new Curve( + $p1[0] + $alpha * $d1[0], + $p1[1] + $alpha * $d1[1], + $p2[0] - $alpha * $d2[0], + $p2[1] - $alpha * $d2[1], + $p2[0], + $p2[1] + ); + + $s += $signStep; + $remain -= $step; + $p1 = $p2; + } + + return $curves; + } + + /** + * @return float[] + */ + private function calculateCenterPointParameters(float $fromX, float $fromY, float $xAngle): array + { + $rX = $this->xRadius; + $rY = $this->yRadius; + + // F.6.5.1 + $dx2 = ($fromX - $this->x) / 2; + $dy2 = ($fromY - $this->y) / 2; + $x1p = cos($xAngle) * $dx2 + sin($xAngle) * $dy2; + $y1p = -sin($xAngle) * $dx2 + cos($xAngle) * $dy2; + + // F.6.5.2 + $rxs = $rX ** 2; + $rys = $rY ** 2; + $x1ps = $x1p ** 2; + $y1ps = $y1p ** 2; + $cr = $x1ps / $rxs + $y1ps / $rys; + + if ($cr > 1) { + $s = sqrt($cr); + $rX *= $s; + $rY *= $s; + $rxs = $rX ** 2; + $rys = $rY ** 2; + } + + $dq = ($rxs * $y1ps + $rys * $x1ps); + $pq = ($rxs * $rys - $dq) / $dq; + $q = sqrt(max(0, $pq)); + + if ($this->largeArc === $this->sweep) { + $q = -$q; + } + + $cxp = $q * $rX * $y1p / $rY; + $cyp = -$q * $rY * $x1p / $rX; + + // F.6.5.3 + $cx = cos($xAngle) * $cxp - sin($xAngle) * $cyp + ($fromX + $this->x) / 2; + $cy = sin($xAngle) * $cxp + cos($xAngle) * $cyp + ($fromY + $this->y) / 2; + + // F.6.5.5 + $theta = self::angle(1, 0, ($x1p - $cxp) / $rX, ($y1p - $cyp) / $rY); + + // F.6.5.6 + $delta = self::angle(($x1p - $cxp) / $rX, ($y1p - $cyp) / $rY, (-$x1p - $cxp) / $rX, (-$y1p - $cyp) / $rY); + $delta = fmod($delta, pi() * 2); + + if (! $this->sweep && $delta > 0) { + $delta -= 2 * pi(); + } elseif ($this->sweep && $delta < 0) { + $delta += 2 * pi(); + } + + return [$cx, $cy, $rX, $rY, $theta, $delta]; + } + + private static function angle(float $ux, float $uy, float $vx, float $vy) : float + { + // F.6.5.4 + $dot = $ux * $vx + $uy * $vy; + $length = sqrt($ux ** 2 + $uy ** 2) * sqrt($vx ** 2 + $vy ** 2); + $angle = acos(min(1, max(-1, $dot / $length))); + + if (($ux * $vy - $uy * $vx) < 0) { + return -$angle; + } + + return $angle; + } + + /** + * @return float[] + */ + private static function point( + float $centerX, + float $centerY, + float $radiusX, + float $radiusY, + float $xAngle, + float $angle + ) : array { + return [ + $centerX + $radiusX * cos($xAngle) * cos($angle) - $radiusY * sin($xAngle) * sin($angle), + $centerY + $radiusX * sin($xAngle) * cos($angle) + $radiusY * cos($xAngle) * sin($angle), + ]; + } + + /** + * @return float[] + */ + private static function derivative(float $radiusX, float $radiusY, float $xAngle, float $angle) : array + { + return [ + -$radiusX * cos($xAngle) * sin($angle) - $radiusY * sin($xAngle) * cos($angle), + -$radiusX * sin($xAngle) * sin($angle) + $radiusY * cos($xAngle) * cos($angle), + ]; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Path/Line.php b/vendor/bacon/bacon-qr-code/src/Renderer/Path/Line.php index c994aa8..dec46fd 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Path/Line.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Path/Line.php @@ -1,42 +1,42 @@ -x; - } - - public function getY() : float - { - return $this->y; - } - - /** - * @return self - */ - public function translate(float $x, float $y) : OperationInterface - { - return new self($this->x + $x, $this->y + $y); - } - - /** - * @return self - */ - public function rotate(int $degrees) : OperationInterface - { - $radians = deg2rad($degrees); - $sin = sin($radians); - $cos = cos($radians); - $xr = $this->x * $cos - $this->y * $sin; - $yr = $this->x * $sin + $this->y * $cos; - return new self($xr, $yr); - } -} +x; + } + + public function getY() : float + { + return $this->y; + } + + /** + * @return self + */ + public function translate(float $x, float $y) : OperationInterface + { + return new self($this->x + $x, $this->y + $y); + } + + /** + * @return self + */ + public function rotate(int $degrees) : OperationInterface + { + $radians = deg2rad($degrees); + $sin = sin($radians); + $cos = cos($radians); + $xr = $this->x * $cos - $this->y * $sin; + $yr = $this->x * $sin + $this->y * $cos; + return new self($xr, $yr); + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Path/Move.php b/vendor/bacon/bacon-qr-code/src/Renderer/Path/Move.php index b6cbc5d..c3c9a56 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Path/Move.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Path/Move.php @@ -1,42 +1,42 @@ -x; - } - - public function getY() : float - { - return $this->y; - } - - /** - * @return self - */ - public function translate(float $x, float $y) : OperationInterface - { - return new self($this->x + $x, $this->y + $y); - } - - /** - * @return self - */ - public function rotate(int $degrees) : OperationInterface - { - $radians = deg2rad($degrees); - $sin = sin($radians); - $cos = cos($radians); - $xr = $this->x * $cos - $this->y * $sin; - $yr = $this->x * $sin + $this->y * $cos; - return new self($xr, $yr); - } -} +x; + } + + public function getY() : float + { + return $this->y; + } + + /** + * @return self + */ + public function translate(float $x, float $y) : OperationInterface + { + return new self($this->x + $x, $this->y + $y); + } + + /** + * @return self + */ + public function rotate(int $degrees) : OperationInterface + { + $radians = deg2rad($degrees); + $sin = sin($radians); + $cos = cos($radians); + $xr = $this->x * $cos - $this->y * $sin; + $yr = $this->x * $sin + $this->y * $cos; + return new self($xr, $yr); + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/Path/OperationInterface.php b/vendor/bacon/bacon-qr-code/src/Renderer/Path/OperationInterface.php index 926f64d..9271555 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/Path/OperationInterface.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/Path/OperationInterface.php @@ -1,17 +1,17 @@ -operations[] = new Move($x, $y); - return $path; - } - - /** - * Draws a line from the current position to another position. - */ - public function line(float $x, float $y) : self - { - $path = clone $this; - $path->operations[] = new Line($x, $y); - return $path; - } - - /** - * Draws an elliptic arc from the current position to another position. - */ - public function ellipticArc( - float $xRadius, - float $yRadius, - float $xAxisRotation, - bool $largeArc, - bool $sweep, - float $x, - float $y - ) : self { - $path = clone $this; - $path->operations[] = new EllipticArc($xRadius, $yRadius, $xAxisRotation, $largeArc, $sweep, $x, $y); - return $path; - } - - /** - * Draws a curve from the current position to another position. - */ - public function curve(float $x1, float $y1, float $x2, float $y2, float $x3, float $y3) : self - { - $path = clone $this; - $path->operations[] = new Curve($x1, $y1, $x2, $y2, $x3, $y3); - return $path; - } - - /** - * Closes a sub-path. - */ - public function close() : self - { - $path = clone $this; - $path->operations[] = Close::instance(); - return $path; - } - - /** - * Appends another path to this one. - */ - public function append(self $other) : self - { - $path = clone $this; - $path->operations = array_merge($this->operations, $other->operations); - return $path; - } - - public function translate(float $x, float $y) : self - { - $path = new self(); - - foreach ($this->operations as $operation) { - $path->operations[] = $operation->translate($x, $y); - } - - return $path; - } - - public function rotate(int $degrees) : self - { - $path = new self(); - - foreach ($this->operations as $operation) { - $path->operations[] = $operation->rotate($degrees); - } - - return $path; - } - - /** - * @return Traversable - */ - public function getIterator() : Traversable - { - foreach ($this->operations as $operation) { - yield $operation; - } - } -} +operations[] = new Move($x, $y); + return $path; + } + + /** + * Draws a line from the current position to another position. + */ + public function line(float $x, float $y) : self + { + $path = clone $this; + $path->operations[] = new Line($x, $y); + return $path; + } + + /** + * Draws an elliptic arc from the current position to another position. + */ + public function ellipticArc( + float $xRadius, + float $yRadius, + float $xAxisRotation, + bool $largeArc, + bool $sweep, + float $x, + float $y + ) : self { + $path = clone $this; + $path->operations[] = new EllipticArc($xRadius, $yRadius, $xAxisRotation, $largeArc, $sweep, $x, $y); + return $path; + } + + /** + * Draws a curve from the current position to another position. + */ + public function curve(float $x1, float $y1, float $x2, float $y2, float $x3, float $y3) : self + { + $path = clone $this; + $path->operations[] = new Curve($x1, $y1, $x2, $y2, $x3, $y3); + return $path; + } + + /** + * Closes a sub-path. + */ + public function close() : self + { + $path = clone $this; + $path->operations[] = Close::instance(); + return $path; + } + + /** + * Appends another path to this one. + */ + public function append(self $other) : self + { + $path = clone $this; + $path->operations = array_merge($this->operations, $other->operations); + return $path; + } + + public function translate(float $x, float $y) : self + { + $path = new self(); + + foreach ($this->operations as $operation) { + $path->operations[] = $operation->translate($x, $y); + } + + return $path; + } + + public function rotate(int $degrees) : self + { + $path = new self(); + + foreach ($this->operations as $operation) { + $path->operations[] = $operation->rotate($degrees); + } + + return $path; + } + + /** + * @return Traversable + */ + public function getIterator() : Traversable + { + foreach ($this->operations as $operation) { + yield $operation; + } + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/PlainTextRenderer.php b/vendor/bacon/bacon-qr-code/src/Renderer/PlainTextRenderer.php index b253b84..219bbf3 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/PlainTextRenderer.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/PlainTextRenderer.php @@ -1,80 +1,80 @@ -getMatrix(); - $matrixSize = $matrix->getWidth(); - - if ($matrixSize !== $matrix->getHeight()) { - throw new InvalidArgumentException('Matrix must have the same width and height'); - } - - $rows = $matrix->getArray()->toArray(); - - if (0 !== $matrixSize % 2) { - $rows[] = array_fill(0, $matrixSize, 0); - } - - $horizontalMargin = str_repeat(self::EMPTY_BLOCK, $this->margin); - $result = str_repeat("\n", (int) ceil($this->margin / 2)); - - for ($i = 0; $i < $matrixSize; $i += 2) { - $result .= $horizontalMargin; - - $upperRow = $rows[$i]; - $lowerRow = $rows[$i + 1]; - - for ($j = 0; $j < $matrixSize; ++$j) { - $upperBit = $upperRow[$j]; - $lowerBit = $lowerRow[$j]; - - if ($upperBit) { - $result .= $lowerBit ? self::FULL_BLOCK : self::UPPER_HALF_BLOCK; - } else { - $result .= $lowerBit ? self::LOWER_HALF_BLOCK : self::EMPTY_BLOCK; - } - } - - $result .= $horizontalMargin . "\n"; - } - - $result .= str_repeat("\n", (int) ceil($this->margin / 2)); - - return $result; - } -} +getMatrix(); + $matrixSize = $matrix->getWidth(); + + if ($matrixSize !== $matrix->getHeight()) { + throw new InvalidArgumentException('Matrix must have the same width and height'); + } + + $rows = $matrix->getArray()->toArray(); + + if (0 !== $matrixSize % 2) { + $rows[] = array_fill(0, $matrixSize, 0); + } + + $horizontalMargin = str_repeat(self::EMPTY_BLOCK, $this->margin); + $result = str_repeat("\n", (int) ceil($this->margin / 2)); + + for ($i = 0; $i < $matrixSize; $i += 2) { + $result .= $horizontalMargin; + + $upperRow = $rows[$i]; + $lowerRow = $rows[$i + 1]; + + for ($j = 0; $j < $matrixSize; ++$j) { + $upperBit = $upperRow[$j]; + $lowerBit = $lowerRow[$j]; + + if ($upperBit) { + $result .= $lowerBit ? self::FULL_BLOCK : self::UPPER_HALF_BLOCK; + } else { + $result .= $lowerBit ? self::LOWER_HALF_BLOCK : self::EMPTY_BLOCK; + } + } + + $result .= $horizontalMargin . "\n"; + } + + $result .= str_repeat("\n", (int) ceil($this->margin / 2)); + + return $result; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/RendererInterface.php b/vendor/bacon/bacon-qr-code/src/Renderer/RendererInterface.php index 03e99f0..b0aae39 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/RendererInterface.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/RendererInterface.php @@ -1,11 +1,11 @@ -externalColor && null === $this->internalColor; - } - - public function inheritsExternalColor() : bool - { - return null === $this->externalColor; - } - - public function inheritsInternalColor() : bool - { - return null === $this->internalColor; - } - - public function getExternalColor() : ColorInterface - { - if (null === $this->externalColor) { - throw new RuntimeException('External eye color inherits foreground color'); - } - - return $this->externalColor; - } - - public function getInternalColor() : ColorInterface - { - if (null === $this->internalColor) { - throw new RuntimeException('Internal eye color inherits foreground color'); - } - - return $this->internalColor; - } -} +externalColor && null === $this->internalColor; + } + + public function inheritsExternalColor() : bool + { + return null === $this->externalColor; + } + + public function inheritsInternalColor() : bool + { + return null === $this->internalColor; + } + + public function getExternalColor() : ColorInterface + { + if (null === $this->externalColor) { + throw new RuntimeException('External eye color inherits foreground color'); + } + + return $this->externalColor; + } + + public function getInternalColor() : ColorInterface + { + if (null === $this->internalColor) { + throw new RuntimeException('Internal eye color inherits foreground color'); + } + + return $this->internalColor; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/RendererStyle/Fill.php b/vendor/bacon/bacon-qr-code/src/Renderer/RendererStyle/Fill.php index f94df82..19de25d 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/RendererStyle/Fill.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/RendererStyle/Fill.php @@ -1,129 +1,129 @@ -foregroundGradient; - } - - public function getBackgroundColor() : ColorInterface - { - return $this->backgroundColor; - } - - public function getForegroundColor() : ColorInterface - { - if (null === $this->foregroundColor) { - throw new RuntimeException('Fill uses a gradient, thus no foreground color is available'); - } - - return $this->foregroundColor; - } - - public function getForegroundGradient() : Gradient - { - if (null === $this->foregroundGradient) { - throw new RuntimeException('Fill uses a single color, thus no foreground gradient is available'); - } - - return $this->foregroundGradient; - } - - public function getTopLeftEyeFill() : EyeFill - { - return $this->topLeftEyeFill; - } - - public function getTopRightEyeFill() : EyeFill - { - return $this->topRightEyeFill; - } - - public function getBottomLeftEyeFill() : EyeFill - { - return $this->bottomLeftEyeFill; - } -} +foregroundGradient; + } + + public function getBackgroundColor() : ColorInterface + { + return $this->backgroundColor; + } + + public function getForegroundColor() : ColorInterface + { + if (null === $this->foregroundColor) { + throw new RuntimeException('Fill uses a gradient, thus no foreground color is available'); + } + + return $this->foregroundColor; + } + + public function getForegroundGradient() : Gradient + { + if (null === $this->foregroundGradient) { + throw new RuntimeException('Fill uses a single color, thus no foreground gradient is available'); + } + + return $this->foregroundGradient; + } + + public function getTopLeftEyeFill() : EyeFill + { + return $this->topLeftEyeFill; + } + + public function getTopRightEyeFill() : EyeFill + { + return $this->topRightEyeFill; + } + + public function getBottomLeftEyeFill() : EyeFill + { + return $this->bottomLeftEyeFill; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/RendererStyle/Gradient.php b/vendor/bacon/bacon-qr-code/src/Renderer/RendererStyle/Gradient.php index cdada86..eea4031 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/RendererStyle/Gradient.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/RendererStyle/Gradient.php @@ -1,31 +1,31 @@ -startColor; - } - - public function getEndColor() : ColorInterface - { - return $this->endColor; - } - - public function getType() : GradientType - { - return $this->type; - } -} +startColor; + } + + public function getEndColor() : ColorInterface + { + return $this->endColor; + } + + public function getType() : GradientType + { + return $this->type; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Renderer/RendererStyle/GradientType.php b/vendor/bacon/bacon-qr-code/src/Renderer/RendererStyle/GradientType.php index 16cfe13..c1ca754 100644 --- a/vendor/bacon/bacon-qr-code/src/Renderer/RendererStyle/GradientType.php +++ b/vendor/bacon/bacon-qr-code/src/Renderer/RendererStyle/GradientType.php @@ -1,22 +1,22 @@ -module = $module ?: SquareModule::instance(); - $this->eye = $eye ?: new ModuleEye($this->module); - $this->fill = $fill ?: Fill::default(); - } - - public function withSize(int $size) : self - { - $style = clone $this; - $style->size = $size; - return $style; - } - - public function withMargin(int $margin) : self - { - $style = clone $this; - $style->margin = $margin; - return $style; - } - - public function getSize() : int - { - return $this->size; - } - - public function getMargin() : int - { - return $this->margin; - } - - public function getModule() : ModuleInterface - { - return $this->module; - } - - public function getEye() : EyeInterface - { - return $this->eye; - } - - public function getFill() : Fill - { - return $this->fill; - } -} +module = $module ?: SquareModule::instance(); + $this->eye = $eye ?: new ModuleEye($this->module); + $this->fill = $fill ?: Fill::default(); + } + + public function withSize(int $size) : self + { + $style = clone $this; + $style->size = $size; + return $style; + } + + public function withMargin(int $margin) : self + { + $style = clone $this; + $style->margin = $margin; + return $style; + } + + public function getSize() : int + { + return $this->size; + } + + public function getMargin() : int + { + return $this->margin; + } + + public function getModule() : ModuleInterface + { + return $this->module; + } + + public function getEye() : EyeInterface + { + return $this->eye; + } + + public function getFill() : Fill + { + return $this->fill; + } +} diff --git a/vendor/bacon/bacon-qr-code/src/Writer.php b/vendor/bacon/bacon-qr-code/src/Writer.php index b2b3250..d7f7ebb 100644 --- a/vendor/bacon/bacon-qr-code/src/Writer.php +++ b/vendor/bacon/bacon-qr-code/src/Writer.php @@ -1,63 +1,63 @@ -renderer->render(Encoder::encode($content, $ecLevel, $encoding, $forcedVersion)); - } - - /** - * Writes QR code to a file. - * - * @see Writer::writeString() - */ - public function writeFile( - string $content, - string $filename, - string $encoding = Encoder::DEFAULT_BYTE_MODE_ENCODING, - ?ErrorCorrectionLevel $ecLevel = null, - ?Version $forcedVersion = null - ) : void { - file_put_contents($filename, $this->writeString($content, $encoding, $ecLevel, $forcedVersion)); - } -} +renderer->render(Encoder::encode($content, $ecLevel, $encoding, $forcedVersion)); + } + + /** + * Writes QR code to a file. + * + * @see Writer::writeString() + */ + public function writeFile( + string $content, + string $filename, + string $encoding = Encoder::DEFAULT_BYTE_MODE_ENCODING, + ?ErrorCorrectionLevel $ecLevel = null, + ?Version $forcedVersion = null + ) : void { + file_put_contents($filename, $this->writeString($content, $encoding, $ecLevel, $forcedVersion)); + } +} diff --git a/vendor/composer/ClassLoader.php b/vendor/composer/ClassLoader.php index dbd55bb..7824d8f 100644 --- a/vendor/composer/ClassLoader.php +++ b/vendor/composer/ClassLoader.php @@ -1,579 +1,579 @@ - - * Jordi Boggiano - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Composer\Autoload; - -/** - * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. - * - * $loader = new \Composer\Autoload\ClassLoader(); - * - * // register classes with namespaces - * $loader->add('Symfony\Component', __DIR__.'/component'); - * $loader->add('Symfony', __DIR__.'/framework'); - * - * // activate the autoloader - * $loader->register(); - * - * // to enable searching the include path (eg. for PEAR packages) - * $loader->setUseIncludePath(true); - * - * In this example, if you try to use a class in the Symfony\Component - * namespace or one of its children (Symfony\Component\Console for instance), - * the autoloader will first look for the class under the component/ - * directory, and it will then fallback to the framework/ directory if not - * found before giving up. - * - * This class is loosely based on the Symfony UniversalClassLoader. - * - * @author Fabien Potencier - * @author Jordi Boggiano - * @see https://www.php-fig.org/psr/psr-0/ - * @see https://www.php-fig.org/psr/psr-4/ - */ -class ClassLoader -{ - /** @var \Closure(string):void */ - private static $includeFile; - - /** @var string|null */ - private $vendorDir; - - // PSR-4 - /** - * @var array> - */ - private $prefixLengthsPsr4 = array(); - /** - * @var array> - */ - private $prefixDirsPsr4 = array(); - /** - * @var list - */ - private $fallbackDirsPsr4 = array(); - - // PSR-0 - /** - * List of PSR-0 prefixes - * - * Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2'))) - * - * @var array>> - */ - private $prefixesPsr0 = array(); - /** - * @var list - */ - private $fallbackDirsPsr0 = array(); - - /** @var bool */ - private $useIncludePath = false; - - /** - * @var array - */ - private $classMap = array(); - - /** @var bool */ - private $classMapAuthoritative = false; - - /** - * @var array - */ - private $missingClasses = array(); - - /** @var string|null */ - private $apcuPrefix; - - /** - * @var array - */ - private static $registeredLoaders = array(); - - /** - * @param string|null $vendorDir - */ - public function __construct($vendorDir = null) - { - $this->vendorDir = $vendorDir; - self::initializeIncludeClosure(); - } - - /** - * @return array> - */ - public function getPrefixes() - { - if (!empty($this->prefixesPsr0)) { - return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); - } - - return array(); - } - - /** - * @return array> - */ - public function getPrefixesPsr4() - { - return $this->prefixDirsPsr4; - } - - /** - * @return list - */ - public function getFallbackDirs() - { - return $this->fallbackDirsPsr0; - } - - /** - * @return list - */ - public function getFallbackDirsPsr4() - { - return $this->fallbackDirsPsr4; - } - - /** - * @return array Array of classname => path - */ - public function getClassMap() - { - return $this->classMap; - } - - /** - * @param array $classMap Class to filename map - * - * @return void - */ - public function addClassMap(array $classMap) - { - if ($this->classMap) { - $this->classMap = array_merge($this->classMap, $classMap); - } else { - $this->classMap = $classMap; - } - } - - /** - * Registers a set of PSR-0 directories for a given prefix, either - * appending or prepending to the ones previously set for this prefix. - * - * @param string $prefix The prefix - * @param list|string $paths The PSR-0 root directories - * @param bool $prepend Whether to prepend the directories - * - * @return void - */ - public function add($prefix, $paths, $prepend = false) - { - $paths = (array) $paths; - if (!$prefix) { - if ($prepend) { - $this->fallbackDirsPsr0 = array_merge( - $paths, - $this->fallbackDirsPsr0 - ); - } else { - $this->fallbackDirsPsr0 = array_merge( - $this->fallbackDirsPsr0, - $paths - ); - } - - return; - } - - $first = $prefix[0]; - if (!isset($this->prefixesPsr0[$first][$prefix])) { - $this->prefixesPsr0[$first][$prefix] = $paths; - - return; - } - if ($prepend) { - $this->prefixesPsr0[$first][$prefix] = array_merge( - $paths, - $this->prefixesPsr0[$first][$prefix] - ); - } else { - $this->prefixesPsr0[$first][$prefix] = array_merge( - $this->prefixesPsr0[$first][$prefix], - $paths - ); - } - } - - /** - * Registers a set of PSR-4 directories for a given namespace, either - * appending or prepending to the ones previously set for this namespace. - * - * @param string $prefix The prefix/namespace, with trailing '\\' - * @param list|string $paths The PSR-4 base directories - * @param bool $prepend Whether to prepend the directories - * - * @throws \InvalidArgumentException - * - * @return void - */ - public function addPsr4($prefix, $paths, $prepend = false) - { - $paths = (array) $paths; - if (!$prefix) { - // Register directories for the root namespace. - if ($prepend) { - $this->fallbackDirsPsr4 = array_merge( - $paths, - $this->fallbackDirsPsr4 - ); - } else { - $this->fallbackDirsPsr4 = array_merge( - $this->fallbackDirsPsr4, - $paths - ); - } - } elseif (!isset($this->prefixDirsPsr4[$prefix])) { - // Register directories for a new namespace. - $length = strlen($prefix); - if ('\\' !== $prefix[$length - 1]) { - throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); - } - $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; - $this->prefixDirsPsr4[$prefix] = $paths; - } elseif ($prepend) { - // Prepend directories for an already registered namespace. - $this->prefixDirsPsr4[$prefix] = array_merge( - $paths, - $this->prefixDirsPsr4[$prefix] - ); - } else { - // Append directories for an already registered namespace. - $this->prefixDirsPsr4[$prefix] = array_merge( - $this->prefixDirsPsr4[$prefix], - $paths - ); - } - } - - /** - * Registers a set of PSR-0 directories for a given prefix, - * replacing any others previously set for this prefix. - * - * @param string $prefix The prefix - * @param list|string $paths The PSR-0 base directories - * - * @return void - */ - public function set($prefix, $paths) - { - if (!$prefix) { - $this->fallbackDirsPsr0 = (array) $paths; - } else { - $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; - } - } - - /** - * Registers a set of PSR-4 directories for a given namespace, - * replacing any others previously set for this namespace. - * - * @param string $prefix The prefix/namespace, with trailing '\\' - * @param list|string $paths The PSR-4 base directories - * - * @throws \InvalidArgumentException - * - * @return void - */ - public function setPsr4($prefix, $paths) - { - if (!$prefix) { - $this->fallbackDirsPsr4 = (array) $paths; - } else { - $length = strlen($prefix); - if ('\\' !== $prefix[$length - 1]) { - throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); - } - $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; - $this->prefixDirsPsr4[$prefix] = (array) $paths; - } - } - - /** - * Turns on searching the include path for class files. - * - * @param bool $useIncludePath - * - * @return void - */ - public function setUseIncludePath($useIncludePath) - { - $this->useIncludePath = $useIncludePath; - } - - /** - * Can be used to check if the autoloader uses the include path to check - * for classes. - * - * @return bool - */ - public function getUseIncludePath() - { - return $this->useIncludePath; - } - - /** - * Turns off searching the prefix and fallback directories for classes - * that have not been registered with the class map. - * - * @param bool $classMapAuthoritative - * - * @return void - */ - public function setClassMapAuthoritative($classMapAuthoritative) - { - $this->classMapAuthoritative = $classMapAuthoritative; - } - - /** - * Should class lookup fail if not found in the current class map? - * - * @return bool - */ - public function isClassMapAuthoritative() - { - return $this->classMapAuthoritative; - } - - /** - * APCu prefix to use to cache found/not-found classes, if the extension is enabled. - * - * @param string|null $apcuPrefix - * - * @return void - */ - public function setApcuPrefix($apcuPrefix) - { - $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; - } - - /** - * The APCu prefix in use, or null if APCu caching is not enabled. - * - * @return string|null - */ - public function getApcuPrefix() - { - return $this->apcuPrefix; - } - - /** - * Registers this instance as an autoloader. - * - * @param bool $prepend Whether to prepend the autoloader or not - * - * @return void - */ - public function register($prepend = false) - { - spl_autoload_register(array($this, 'loadClass'), true, $prepend); - - if (null === $this->vendorDir) { - return; - } - - if ($prepend) { - self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; - } else { - unset(self::$registeredLoaders[$this->vendorDir]); - self::$registeredLoaders[$this->vendorDir] = $this; - } - } - - /** - * Unregisters this instance as an autoloader. - * - * @return void - */ - public function unregister() - { - spl_autoload_unregister(array($this, 'loadClass')); - - if (null !== $this->vendorDir) { - unset(self::$registeredLoaders[$this->vendorDir]); - } - } - - /** - * Loads the given class or interface. - * - * @param string $class The name of the class - * @return true|null True if loaded, null otherwise - */ - public function loadClass($class) - { - if ($file = $this->findFile($class)) { - $includeFile = self::$includeFile; - $includeFile($file); - - return true; - } - - return null; - } - - /** - * Finds the path to the file where the class is defined. - * - * @param string $class The name of the class - * - * @return string|false The path if found, false otherwise - */ - public function findFile($class) - { - // class map lookup - if (isset($this->classMap[$class])) { - return $this->classMap[$class]; - } - if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { - return false; - } - if (null !== $this->apcuPrefix) { - $file = apcu_fetch($this->apcuPrefix.$class, $hit); - if ($hit) { - return $file; - } - } - - $file = $this->findFileWithExtension($class, '.php'); - - // Search for Hack files if we are running on HHVM - if (false === $file && defined('HHVM_VERSION')) { - $file = $this->findFileWithExtension($class, '.hh'); - } - - if (null !== $this->apcuPrefix) { - apcu_add($this->apcuPrefix.$class, $file); - } - - if (false === $file) { - // Remember that this class does not exist. - $this->missingClasses[$class] = true; - } - - return $file; - } - - /** - * Returns the currently registered loaders keyed by their corresponding vendor directories. - * - * @return array - */ - public static function getRegisteredLoaders() - { - return self::$registeredLoaders; - } - - /** - * @param string $class - * @param string $ext - * @return string|false - */ - private function findFileWithExtension($class, $ext) - { - // PSR-4 lookup - $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; - - $first = $class[0]; - if (isset($this->prefixLengthsPsr4[$first])) { - $subPath = $class; - while (false !== $lastPos = strrpos($subPath, '\\')) { - $subPath = substr($subPath, 0, $lastPos); - $search = $subPath . '\\'; - if (isset($this->prefixDirsPsr4[$search])) { - $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); - foreach ($this->prefixDirsPsr4[$search] as $dir) { - if (file_exists($file = $dir . $pathEnd)) { - return $file; - } - } - } - } - } - - // PSR-4 fallback dirs - foreach ($this->fallbackDirsPsr4 as $dir) { - if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { - return $file; - } - } - - // PSR-0 lookup - if (false !== $pos = strrpos($class, '\\')) { - // namespaced class name - $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) - . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); - } else { - // PEAR-like class name - $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; - } - - if (isset($this->prefixesPsr0[$first])) { - foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { - if (0 === strpos($class, $prefix)) { - foreach ($dirs as $dir) { - if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { - return $file; - } - } - } - } - } - - // PSR-0 fallback dirs - foreach ($this->fallbackDirsPsr0 as $dir) { - if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { - return $file; - } - } - - // PSR-0 include paths. - if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { - return $file; - } - - return false; - } - - /** - * @return void - */ - private static function initializeIncludeClosure() - { - if (self::$includeFile !== null) { - return; - } - - /** - * Scope isolated include. - * - * Prevents access to $this/self from included files. - * - * @param string $file - * @return void - */ - self::$includeFile = \Closure::bind(static function($file) { - include $file; - }, null, null); - } -} + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @see https://www.php-fig.org/psr/psr-0/ + * @see https://www.php-fig.org/psr/psr-4/ + */ +class ClassLoader +{ + /** @var \Closure(string):void */ + private static $includeFile; + + /** @var string|null */ + private $vendorDir; + + // PSR-4 + /** + * @var array> + */ + private $prefixLengthsPsr4 = array(); + /** + * @var array> + */ + private $prefixDirsPsr4 = array(); + /** + * @var list + */ + private $fallbackDirsPsr4 = array(); + + // PSR-0 + /** + * List of PSR-0 prefixes + * + * Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2'))) + * + * @var array>> + */ + private $prefixesPsr0 = array(); + /** + * @var list + */ + private $fallbackDirsPsr0 = array(); + + /** @var bool */ + private $useIncludePath = false; + + /** + * @var array + */ + private $classMap = array(); + + /** @var bool */ + private $classMapAuthoritative = false; + + /** + * @var array + */ + private $missingClasses = array(); + + /** @var string|null */ + private $apcuPrefix; + + /** + * @var array + */ + private static $registeredLoaders = array(); + + /** + * @param string|null $vendorDir + */ + public function __construct($vendorDir = null) + { + $this->vendorDir = $vendorDir; + self::initializeIncludeClosure(); + } + + /** + * @return array> + */ + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); + } + + return array(); + } + + /** + * @return array> + */ + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + /** + * @return list + */ + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + /** + * @return list + */ + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + /** + * @return array Array of classname => path + */ + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param array $classMap Class to filename map + * + * @return void + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param list|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + * + * @return void + */ + public function add($prefix, $paths, $prepend = false) + { + $paths = (array) $paths; + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param list|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + $paths = (array) $paths; + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param list|string $paths The PSR-0 base directories + * + * @return void + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param list|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function setPsr4($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + * + * @return void + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Turns off searching the prefix and fallback directories for classes + * that have not been registered with the class map. + * + * @param bool $classMapAuthoritative + * + * @return void + */ + public function setClassMapAuthoritative($classMapAuthoritative) + { + $this->classMapAuthoritative = $classMapAuthoritative; + } + + /** + * Should class lookup fail if not found in the current class map? + * + * @return bool + */ + public function isClassMapAuthoritative() + { + return $this->classMapAuthoritative; + } + + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + * + * @return void + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; + } + + /** + * The APCu prefix in use, or null if APCu caching is not enabled. + * + * @return string|null + */ + public function getApcuPrefix() + { + return $this->apcuPrefix; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + * + * @return void + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + + if (null === $this->vendorDir) { + return; + } + + if ($prepend) { + self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; + } else { + unset(self::$registeredLoaders[$this->vendorDir]); + self::$registeredLoaders[$this->vendorDir] = $this; + } + } + + /** + * Unregisters this instance as an autoloader. + * + * @return void + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + + if (null !== $this->vendorDir) { + unset(self::$registeredLoaders[$this->vendorDir]); + } + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return true|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + $includeFile = self::$includeFile; + $includeFile($file); + + return true; + } + + return null; + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { + return false; + } + if (null !== $this->apcuPrefix) { + $file = apcu_fetch($this->apcuPrefix.$class, $hit); + if ($hit) { + return $file; + } + } + + $file = $this->findFileWithExtension($class, '.php'); + + // Search for Hack files if we are running on HHVM + if (false === $file && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { + // Remember that this class does not exist. + $this->missingClasses[$class] = true; + } + + return $file; + } + + /** + * Returns the currently registered loaders keyed by their corresponding vendor directories. + * + * @return array + */ + public static function getRegisteredLoaders() + { + return self::$registeredLoaders; + } + + /** + * @param string $class + * @param string $ext + * @return string|false + */ + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + $subPath = $class; + while (false !== $lastPos = strrpos($subPath, '\\')) { + $subPath = substr($subPath, 0, $lastPos); + $search = $subPath . '\\'; + if (isset($this->prefixDirsPsr4[$search])) { + $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); + foreach ($this->prefixDirsPsr4[$search] as $dir) { + if (file_exists($file = $dir . $pathEnd)) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + + return false; + } + + /** + * @return void + */ + private static function initializeIncludeClosure() + { + if (self::$includeFile !== null) { + return; + } + + /** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + * + * @param string $file + * @return void + */ + self::$includeFile = \Closure::bind(static function($file) { + include $file; + }, null, null); + } +} diff --git a/vendor/composer/InstalledVersions.php b/vendor/composer/InstalledVersions.php index c158fb4..2052022 100644 --- a/vendor/composer/InstalledVersions.php +++ b/vendor/composer/InstalledVersions.php @@ -1,359 +1,396 @@ - - * Jordi Boggiano - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Composer; - -use Composer\Autoload\ClassLoader; -use Composer\Semver\VersionParser; - -/** - * This class is copied in every Composer installed project and available to all - * - * See also https://getcomposer.org/doc/07-runtime.md#installed-versions - * - * To require its presence, you can require `composer-runtime-api ^2.0` - * - * @final - */ -class InstalledVersions -{ - /** - * @var mixed[]|null - * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array}|array{}|null - */ - private static $installed; - - /** - * @var bool|null - */ - private static $canGetVendors; - - /** - * @var array[] - * @psalm-var array}> - */ - private static $installedByVendor = array(); - - /** - * Returns a list of all package names which are present, either by being installed, replaced or provided - * - * @return string[] - * @psalm-return list - */ - public static function getInstalledPackages() - { - $packages = array(); - foreach (self::getInstalled() as $installed) { - $packages[] = array_keys($installed['versions']); - } - - if (1 === \count($packages)) { - return $packages[0]; - } - - return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); - } - - /** - * Returns a list of all package names with a specific type e.g. 'library' - * - * @param string $type - * @return string[] - * @psalm-return list - */ - public static function getInstalledPackagesByType($type) - { - $packagesByType = array(); - - foreach (self::getInstalled() as $installed) { - foreach ($installed['versions'] as $name => $package) { - if (isset($package['type']) && $package['type'] === $type) { - $packagesByType[] = $name; - } - } - } - - return $packagesByType; - } - - /** - * Checks whether the given package is installed - * - * This also returns true if the package name is provided or replaced by another package - * - * @param string $packageName - * @param bool $includeDevRequirements - * @return bool - */ - public static function isInstalled($packageName, $includeDevRequirements = true) - { - foreach (self::getInstalled() as $installed) { - if (isset($installed['versions'][$packageName])) { - return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false; - } - } - - return false; - } - - /** - * Checks whether the given package satisfies a version constraint - * - * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: - * - * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') - * - * @param VersionParser $parser Install composer/semver to have access to this class and functionality - * @param string $packageName - * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package - * @return bool - */ - public static function satisfies(VersionParser $parser, $packageName, $constraint) - { - $constraint = $parser->parseConstraints((string) $constraint); - $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); - - return $provided->matches($constraint); - } - - /** - * Returns a version constraint representing all the range(s) which are installed for a given package - * - * It is easier to use this via isInstalled() with the $constraint argument if you need to check - * whether a given version of a package is installed, and not just whether it exists - * - * @param string $packageName - * @return string Version constraint usable with composer/semver - */ - public static function getVersionRanges($packageName) - { - foreach (self::getInstalled() as $installed) { - if (!isset($installed['versions'][$packageName])) { - continue; - } - - $ranges = array(); - if (isset($installed['versions'][$packageName]['pretty_version'])) { - $ranges[] = $installed['versions'][$packageName]['pretty_version']; - } - if (array_key_exists('aliases', $installed['versions'][$packageName])) { - $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); - } - if (array_key_exists('replaced', $installed['versions'][$packageName])) { - $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); - } - if (array_key_exists('provided', $installed['versions'][$packageName])) { - $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); - } - - return implode(' || ', $ranges); - } - - throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); - } - - /** - * @param string $packageName - * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present - */ - public static function getVersion($packageName) - { - foreach (self::getInstalled() as $installed) { - if (!isset($installed['versions'][$packageName])) { - continue; - } - - if (!isset($installed['versions'][$packageName]['version'])) { - return null; - } - - return $installed['versions'][$packageName]['version']; - } - - throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); - } - - /** - * @param string $packageName - * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present - */ - public static function getPrettyVersion($packageName) - { - foreach (self::getInstalled() as $installed) { - if (!isset($installed['versions'][$packageName])) { - continue; - } - - if (!isset($installed['versions'][$packageName]['pretty_version'])) { - return null; - } - - return $installed['versions'][$packageName]['pretty_version']; - } - - throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); - } - - /** - * @param string $packageName - * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference - */ - public static function getReference($packageName) - { - foreach (self::getInstalled() as $installed) { - if (!isset($installed['versions'][$packageName])) { - continue; - } - - if (!isset($installed['versions'][$packageName]['reference'])) { - return null; - } - - return $installed['versions'][$packageName]['reference']; - } - - throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); - } - - /** - * @param string $packageName - * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. - */ - public static function getInstallPath($packageName) - { - foreach (self::getInstalled() as $installed) { - if (!isset($installed['versions'][$packageName])) { - continue; - } - - return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; - } - - throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); - } - - /** - * @return array - * @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} - */ - public static function getRootPackage() - { - $installed = self::getInstalled(); - - return $installed[0]['root']; - } - - /** - * Returns the raw installed.php data for custom implementations - * - * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. - * @return array[] - * @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} - */ - public static function getRawData() - { - @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); - - if (null === self::$installed) { - // only require the installed.php file if this file is loaded from its dumped location, - // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 - if (substr(__DIR__, -8, 1) !== 'C') { - self::$installed = include __DIR__ . '/installed.php'; - } else { - self::$installed = array(); - } - } - - return self::$installed; - } - - /** - * Returns the raw data of all installed.php which are currently loaded for custom implementations - * - * @return array[] - * @psalm-return list}> - */ - public static function getAllRawData() - { - return self::getInstalled(); - } - - /** - * Lets you reload the static array from another file - * - * This is only useful for complex integrations in which a project needs to use - * this class but then also needs to execute another project's autoloader in process, - * and wants to ensure both projects have access to their version of installed.php. - * - * A typical case would be PHPUnit, where it would need to make sure it reads all - * the data it needs from this class, then call reload() with - * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure - * the project in which it runs can then also use this class safely, without - * interference between PHPUnit's dependencies and the project's dependencies. - * - * @param array[] $data A vendor/composer/installed.php data set - * @return void - * - * @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $data - */ - public static function reload($data) - { - self::$installed = $data; - self::$installedByVendor = array(); - } - - /** - * @return array[] - * @psalm-return list}> - */ - private static function getInstalled() - { - if (null === self::$canGetVendors) { - self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); - } - - $installed = array(); - - if (self::$canGetVendors) { - foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { - if (isset(self::$installedByVendor[$vendorDir])) { - $installed[] = self::$installedByVendor[$vendorDir]; - } elseif (is_file($vendorDir.'/composer/installed.php')) { - /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ - $required = require $vendorDir.'/composer/installed.php'; - $installed[] = self::$installedByVendor[$vendorDir] = $required; - if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { - self::$installed = $installed[count($installed) - 1]; - } - } - } - } - - if (null === self::$installed) { - // only require the installed.php file if this file is loaded from its dumped location, - // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 - if (substr(__DIR__, -8, 1) !== 'C') { - /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ - $required = require __DIR__ . '/installed.php'; - self::$installed = $required; - } else { - self::$installed = array(); - } - } - - if (self::$installed !== array()) { - $installed[] = self::$installed; - } - - return $installed; - } -} + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer; + +use Composer\Autoload\ClassLoader; +use Composer\Semver\VersionParser; + +/** + * This class is copied in every Composer installed project and available to all + * + * See also https://getcomposer.org/doc/07-runtime.md#installed-versions + * + * To require its presence, you can require `composer-runtime-api ^2.0` + * + * @final + */ +class InstalledVersions +{ + /** + * @var string|null if set (by reflection by Composer), this should be set to the path where this class is being copied to + * @internal + */ + private static $selfDir = null; + + /** + * @var mixed[]|null + * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array}|array{}|null + */ + private static $installed; + + /** + * @var bool + */ + private static $installedIsLocalDir; + + /** + * @var bool|null + */ + private static $canGetVendors; + + /** + * @var array[] + * @psalm-var array}> + */ + private static $installedByVendor = array(); + + /** + * Returns a list of all package names which are present, either by being installed, replaced or provided + * + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackages() + { + $packages = array(); + foreach (self::getInstalled() as $installed) { + $packages[] = array_keys($installed['versions']); + } + + if (1 === \count($packages)) { + return $packages[0]; + } + + return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); + } + + /** + * Returns a list of all package names with a specific type e.g. 'library' + * + * @param string $type + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackagesByType($type) + { + $packagesByType = array(); + + foreach (self::getInstalled() as $installed) { + foreach ($installed['versions'] as $name => $package) { + if (isset($package['type']) && $package['type'] === $type) { + $packagesByType[] = $name; + } + } + } + + return $packagesByType; + } + + /** + * Checks whether the given package is installed + * + * This also returns true if the package name is provided or replaced by another package + * + * @param string $packageName + * @param bool $includeDevRequirements + * @return bool + */ + public static function isInstalled($packageName, $includeDevRequirements = true) + { + foreach (self::getInstalled() as $installed) { + if (isset($installed['versions'][$packageName])) { + return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false; + } + } + + return false; + } + + /** + * Checks whether the given package satisfies a version constraint + * + * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: + * + * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') + * + * @param VersionParser $parser Install composer/semver to have access to this class and functionality + * @param string $packageName + * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package + * @return bool + */ + public static function satisfies(VersionParser $parser, $packageName, $constraint) + { + $constraint = $parser->parseConstraints((string) $constraint); + $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); + + return $provided->matches($constraint); + } + + /** + * Returns a version constraint representing all the range(s) which are installed for a given package + * + * It is easier to use this via isInstalled() with the $constraint argument if you need to check + * whether a given version of a package is installed, and not just whether it exists + * + * @param string $packageName + * @return string Version constraint usable with composer/semver + */ + public static function getVersionRanges($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + $ranges = array(); + if (isset($installed['versions'][$packageName]['pretty_version'])) { + $ranges[] = $installed['versions'][$packageName]['pretty_version']; + } + if (array_key_exists('aliases', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); + } + if (array_key_exists('replaced', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); + } + if (array_key_exists('provided', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); + } + + return implode(' || ', $ranges); + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['version'])) { + return null; + } + + return $installed['versions'][$packageName]['version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getPrettyVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['pretty_version'])) { + return null; + } + + return $installed['versions'][$packageName]['pretty_version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference + */ + public static function getReference($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['reference'])) { + return null; + } + + return $installed['versions'][$packageName]['reference']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. + */ + public static function getInstallPath($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @return array + * @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} + */ + public static function getRootPackage() + { + $installed = self::getInstalled(); + + return $installed[0]['root']; + } + + /** + * Returns the raw installed.php data for custom implementations + * + * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. + * @return array[] + * @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} + */ + public static function getRawData() + { + @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = include __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + + return self::$installed; + } + + /** + * Returns the raw data of all installed.php which are currently loaded for custom implementations + * + * @return array[] + * @psalm-return list}> + */ + public static function getAllRawData() + { + return self::getInstalled(); + } + + /** + * Lets you reload the static array from another file + * + * This is only useful for complex integrations in which a project needs to use + * this class but then also needs to execute another project's autoloader in process, + * and wants to ensure both projects have access to their version of installed.php. + * + * A typical case would be PHPUnit, where it would need to make sure it reads all + * the data it needs from this class, then call reload() with + * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure + * the project in which it runs can then also use this class safely, without + * interference between PHPUnit's dependencies and the project's dependencies. + * + * @param array[] $data A vendor/composer/installed.php data set + * @return void + * + * @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $data + */ + public static function reload($data) + { + self::$installed = $data; + self::$installedByVendor = array(); + + // when using reload, we disable the duplicate protection to ensure that self::$installed data is + // always returned, but we cannot know whether it comes from the installed.php in __DIR__ or not, + // so we have to assume it does not, and that may result in duplicate data being returned when listing + // all installed packages for example + self::$installedIsLocalDir = false; + } + + /** + * @return string + */ + private static function getSelfDir() + { + if (self::$selfDir === null) { + self::$selfDir = strtr(__DIR__, '\\', '/'); + } + + return self::$selfDir; + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + $copiedLocalDir = false; + + if (self::$canGetVendors) { + $selfDir = self::getSelfDir(); + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + $vendorDir = strtr($vendorDir, '\\', '/'); + if (isset(self::$installedByVendor[$vendorDir])) { + $installed[] = self::$installedByVendor[$vendorDir]; + } elseif (is_file($vendorDir.'/composer/installed.php')) { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require $vendorDir.'/composer/installed.php'; + self::$installedByVendor[$vendorDir] = $required; + $installed[] = $required; + if (self::$installed === null && $vendorDir.'/composer' === $selfDir) { + self::$installed = $required; + self::$installedIsLocalDir = true; + } + } + if (self::$installedIsLocalDir && $vendorDir.'/composer' === $selfDir) { + $copiedLocalDir = true; + } + } + } + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = require __DIR__ . '/installed.php'; + self::$installed = $required; + } else { + self::$installed = array(); + } + } + + if (self::$installed !== array() && !$copiedLocalDir) { + $installed[] = self::$installed; + } + + return $installed; + } +} diff --git a/vendor/composer/LICENSE b/vendor/composer/LICENSE index 41f0d18..f27399a 100644 --- a/vendor/composer/LICENSE +++ b/vendor/composer/LICENSE @@ -1,19 +1,21 @@ -Copyright (c) Nils Adermann, Jordi Boggiano - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is furnished -to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. + +Copyright (c) Nils Adermann, Jordi Boggiano + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/vendor/composer/autoload_classmap.php b/vendor/composer/autoload_classmap.php index a3ed879..ebd8ac5 100644 --- a/vendor/composer/autoload_classmap.php +++ b/vendor/composer/autoload_classmap.php @@ -1,10 +1,82 @@ - $vendorDir . '/composer/InstalledVersions.php', -); + $vendorDir . '/bacon/bacon-qr-code/src/Common/BitArray.php', + 'BaconQrCode\\Common\\BitMatrix' => $vendorDir . '/bacon/bacon-qr-code/src/Common/BitMatrix.php', + 'BaconQrCode\\Common\\BitUtils' => $vendorDir . '/bacon/bacon-qr-code/src/Common/BitUtils.php', + 'BaconQrCode\\Common\\CharacterSetEci' => $vendorDir . '/bacon/bacon-qr-code/src/Common/CharacterSetEci.php', + 'BaconQrCode\\Common\\EcBlock' => $vendorDir . '/bacon/bacon-qr-code/src/Common/EcBlock.php', + 'BaconQrCode\\Common\\EcBlocks' => $vendorDir . '/bacon/bacon-qr-code/src/Common/EcBlocks.php', + 'BaconQrCode\\Common\\ErrorCorrectionLevel' => $vendorDir . '/bacon/bacon-qr-code/src/Common/ErrorCorrectionLevel.php', + 'BaconQrCode\\Common\\FormatInformation' => $vendorDir . '/bacon/bacon-qr-code/src/Common/FormatInformation.php', + 'BaconQrCode\\Common\\Mode' => $vendorDir . '/bacon/bacon-qr-code/src/Common/Mode.php', + 'BaconQrCode\\Common\\ReedSolomonCodec' => $vendorDir . '/bacon/bacon-qr-code/src/Common/ReedSolomonCodec.php', + 'BaconQrCode\\Common\\Version' => $vendorDir . '/bacon/bacon-qr-code/src/Common/Version.php', + 'BaconQrCode\\Encoder\\BlockPair' => $vendorDir . '/bacon/bacon-qr-code/src/Encoder/BlockPair.php', + 'BaconQrCode\\Encoder\\ByteMatrix' => $vendorDir . '/bacon/bacon-qr-code/src/Encoder/ByteMatrix.php', + 'BaconQrCode\\Encoder\\Encoder' => $vendorDir . '/bacon/bacon-qr-code/src/Encoder/Encoder.php', + 'BaconQrCode\\Encoder\\MaskUtil' => $vendorDir . '/bacon/bacon-qr-code/src/Encoder/MaskUtil.php', + 'BaconQrCode\\Encoder\\MatrixUtil' => $vendorDir . '/bacon/bacon-qr-code/src/Encoder/MatrixUtil.php', + 'BaconQrCode\\Encoder\\QrCode' => $vendorDir . '/bacon/bacon-qr-code/src/Encoder/QrCode.php', + 'BaconQrCode\\Exception\\ExceptionInterface' => $vendorDir . '/bacon/bacon-qr-code/src/Exception/ExceptionInterface.php', + 'BaconQrCode\\Exception\\InvalidArgumentException' => $vendorDir . '/bacon/bacon-qr-code/src/Exception/InvalidArgumentException.php', + 'BaconQrCode\\Exception\\OutOfBoundsException' => $vendorDir . '/bacon/bacon-qr-code/src/Exception/OutOfBoundsException.php', + 'BaconQrCode\\Exception\\RuntimeException' => $vendorDir . '/bacon/bacon-qr-code/src/Exception/RuntimeException.php', + 'BaconQrCode\\Exception\\UnexpectedValueException' => $vendorDir . '/bacon/bacon-qr-code/src/Exception/UnexpectedValueException.php', + 'BaconQrCode\\Exception\\WriterException' => $vendorDir . '/bacon/bacon-qr-code/src/Exception/WriterException.php', + 'BaconQrCode\\Renderer\\Color\\Alpha' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Color/Alpha.php', + 'BaconQrCode\\Renderer\\Color\\Cmyk' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Color/Cmyk.php', + 'BaconQrCode\\Renderer\\Color\\ColorInterface' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Color/ColorInterface.php', + 'BaconQrCode\\Renderer\\Color\\Gray' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Color/Gray.php', + 'BaconQrCode\\Renderer\\Color\\Rgb' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Color/Rgb.php', + 'BaconQrCode\\Renderer\\Eye\\CompositeEye' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Eye/CompositeEye.php', + 'BaconQrCode\\Renderer\\Eye\\EyeInterface' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Eye/EyeInterface.php', + 'BaconQrCode\\Renderer\\Eye\\ModuleEye' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Eye/ModuleEye.php', + 'BaconQrCode\\Renderer\\Eye\\PointyEye' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Eye/PointyEye.php', + 'BaconQrCode\\Renderer\\Eye\\SimpleCircleEye' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Eye/SimpleCircleEye.php', + 'BaconQrCode\\Renderer\\Eye\\SquareEye' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Eye/SquareEye.php', + 'BaconQrCode\\Renderer\\GDLibRenderer' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/GDLibRenderer.php', + 'BaconQrCode\\Renderer\\ImageRenderer' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/ImageRenderer.php', + 'BaconQrCode\\Renderer\\Image\\EpsImageBackEnd' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Image/EpsImageBackEnd.php', + 'BaconQrCode\\Renderer\\Image\\ImageBackEndInterface' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Image/ImageBackEndInterface.php', + 'BaconQrCode\\Renderer\\Image\\ImagickImageBackEnd' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Image/ImagickImageBackEnd.php', + 'BaconQrCode\\Renderer\\Image\\SvgImageBackEnd' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Image/SvgImageBackEnd.php', + 'BaconQrCode\\Renderer\\Image\\TransformationMatrix' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Image/TransformationMatrix.php', + 'BaconQrCode\\Renderer\\Module\\DotsModule' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Module/DotsModule.php', + 'BaconQrCode\\Renderer\\Module\\EdgeIterator\\Edge' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Module/EdgeIterator/Edge.php', + 'BaconQrCode\\Renderer\\Module\\EdgeIterator\\EdgeIterator' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Module/EdgeIterator/EdgeIterator.php', + 'BaconQrCode\\Renderer\\Module\\ModuleInterface' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Module/ModuleInterface.php', + 'BaconQrCode\\Renderer\\Module\\RoundnessModule' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Module/RoundnessModule.php', + 'BaconQrCode\\Renderer\\Module\\SquareModule' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Module/SquareModule.php', + 'BaconQrCode\\Renderer\\Path\\Close' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Path/Close.php', + 'BaconQrCode\\Renderer\\Path\\Curve' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Path/Curve.php', + 'BaconQrCode\\Renderer\\Path\\EllipticArc' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Path/EllipticArc.php', + 'BaconQrCode\\Renderer\\Path\\Line' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Path/Line.php', + 'BaconQrCode\\Renderer\\Path\\Move' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Path/Move.php', + 'BaconQrCode\\Renderer\\Path\\OperationInterface' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Path/OperationInterface.php', + 'BaconQrCode\\Renderer\\Path\\Path' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/Path/Path.php', + 'BaconQrCode\\Renderer\\PlainTextRenderer' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/PlainTextRenderer.php', + 'BaconQrCode\\Renderer\\RendererInterface' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/RendererInterface.php', + 'BaconQrCode\\Renderer\\RendererStyle\\EyeFill' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/RendererStyle/EyeFill.php', + 'BaconQrCode\\Renderer\\RendererStyle\\Fill' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/RendererStyle/Fill.php', + 'BaconQrCode\\Renderer\\RendererStyle\\Gradient' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/RendererStyle/Gradient.php', + 'BaconQrCode\\Renderer\\RendererStyle\\GradientType' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/RendererStyle/GradientType.php', + 'BaconQrCode\\Renderer\\RendererStyle\\RendererStyle' => $vendorDir . '/bacon/bacon-qr-code/src/Renderer/RendererStyle/RendererStyle.php', + 'BaconQrCode\\Writer' => $vendorDir . '/bacon/bacon-qr-code/src/Writer.php', + 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', + 'DASPRiD\\Enum\\AbstractEnum' => $vendorDir . '/dasprid/enum/src/AbstractEnum.php', + 'DASPRiD\\Enum\\EnumMap' => $vendorDir . '/dasprid/enum/src/EnumMap.php', + 'DASPRiD\\Enum\\Exception\\CloneNotSupportedException' => $vendorDir . '/dasprid/enum/src/Exception/CloneNotSupportedException.php', + 'DASPRiD\\Enum\\Exception\\ExceptionInterface' => $vendorDir . '/dasprid/enum/src/Exception/ExceptionInterface.php', + 'DASPRiD\\Enum\\Exception\\ExpectationException' => $vendorDir . '/dasprid/enum/src/Exception/ExpectationException.php', + 'DASPRiD\\Enum\\Exception\\IllegalArgumentException' => $vendorDir . '/dasprid/enum/src/Exception/IllegalArgumentException.php', + 'DASPRiD\\Enum\\Exception\\MismatchException' => $vendorDir . '/dasprid/enum/src/Exception/MismatchException.php', + 'DASPRiD\\Enum\\Exception\\SerializeNotSupportedException' => $vendorDir . '/dasprid/enum/src/Exception/SerializeNotSupportedException.php', + 'DASPRiD\\Enum\\Exception\\UnserializeNotSupportedException' => $vendorDir . '/dasprid/enum/src/Exception/UnserializeNotSupportedException.php', + 'DASPRiD\\Enum\\NullValue' => $vendorDir . '/dasprid/enum/src/NullValue.php', +); diff --git a/vendor/composer/autoload_namespaces.php b/vendor/composer/autoload_namespaces.php index ff5488f..15a2ff3 100644 --- a/vendor/composer/autoload_namespaces.php +++ b/vendor/composer/autoload_namespaces.php @@ -1,9 +1,9 @@ - array($vendorDir . '/dasprid/enum/src'), - 'BaconQrCode\\' => array($vendorDir . '/bacon/bacon-qr-code/src'), -); + array($vendorDir . '/dasprid/enum/src'), + 'BaconQrCode\\' => array($vendorDir . '/bacon/bacon-qr-code/src'), +); diff --git a/vendor/composer/autoload_real.php b/vendor/composer/autoload_real.php index 192ff1e..8955884 100644 --- a/vendor/composer/autoload_real.php +++ b/vendor/composer/autoload_real.php @@ -1,38 +1,38 @@ -register(true); - - return $loader; - } -} +register(true); + + return $loader; + } +} diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php index a237851..6c31766 100644 --- a/vendor/composer/autoload_static.php +++ b/vendor/composer/autoload_static.php @@ -1,44 +1,116 @@ - - array ( - 'DASPRiD\\Enum\\' => 13, - ), - 'B' => - array ( - 'BaconQrCode\\' => 12, - ), - ); - - public static $prefixDirsPsr4 = array ( - 'DASPRiD\\Enum\\' => - array ( - 0 => __DIR__ . '/..' . '/dasprid/enum/src', - ), - 'BaconQrCode\\' => - array ( - 0 => __DIR__ . '/..' . '/bacon/bacon-qr-code/src', - ), - ); - - public static $classMap = array ( - 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', - ); - - public static function getInitializer(ClassLoader $loader) - { - return \Closure::bind(function () use ($loader) { - $loader->prefixLengthsPsr4 = ComposerStaticInit3c8f2c10a8655d88b9115205b533c7e2::$prefixLengthsPsr4; - $loader->prefixDirsPsr4 = ComposerStaticInit3c8f2c10a8655d88b9115205b533c7e2::$prefixDirsPsr4; - $loader->classMap = ComposerStaticInit3c8f2c10a8655d88b9115205b533c7e2::$classMap; - - }, null, ClassLoader::class); - } -} + + array ( + 'DASPRiD\\Enum\\' => 13, + ), + 'B' => + array ( + 'BaconQrCode\\' => 12, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'DASPRiD\\Enum\\' => + array ( + 0 => __DIR__ . '/..' . '/dasprid/enum/src', + ), + 'BaconQrCode\\' => + array ( + 0 => __DIR__ . '/..' . '/bacon/bacon-qr-code/src', + ), + ); + + public static $classMap = array ( + 'BaconQrCode\\Common\\BitArray' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Common/BitArray.php', + 'BaconQrCode\\Common\\BitMatrix' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Common/BitMatrix.php', + 'BaconQrCode\\Common\\BitUtils' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Common/BitUtils.php', + 'BaconQrCode\\Common\\CharacterSetEci' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Common/CharacterSetEci.php', + 'BaconQrCode\\Common\\EcBlock' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Common/EcBlock.php', + 'BaconQrCode\\Common\\EcBlocks' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Common/EcBlocks.php', + 'BaconQrCode\\Common\\ErrorCorrectionLevel' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Common/ErrorCorrectionLevel.php', + 'BaconQrCode\\Common\\FormatInformation' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Common/FormatInformation.php', + 'BaconQrCode\\Common\\Mode' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Common/Mode.php', + 'BaconQrCode\\Common\\ReedSolomonCodec' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Common/ReedSolomonCodec.php', + 'BaconQrCode\\Common\\Version' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Common/Version.php', + 'BaconQrCode\\Encoder\\BlockPair' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Encoder/BlockPair.php', + 'BaconQrCode\\Encoder\\ByteMatrix' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Encoder/ByteMatrix.php', + 'BaconQrCode\\Encoder\\Encoder' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Encoder/Encoder.php', + 'BaconQrCode\\Encoder\\MaskUtil' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Encoder/MaskUtil.php', + 'BaconQrCode\\Encoder\\MatrixUtil' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Encoder/MatrixUtil.php', + 'BaconQrCode\\Encoder\\QrCode' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Encoder/QrCode.php', + 'BaconQrCode\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Exception/ExceptionInterface.php', + 'BaconQrCode\\Exception\\InvalidArgumentException' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Exception/InvalidArgumentException.php', + 'BaconQrCode\\Exception\\OutOfBoundsException' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Exception/OutOfBoundsException.php', + 'BaconQrCode\\Exception\\RuntimeException' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Exception/RuntimeException.php', + 'BaconQrCode\\Exception\\UnexpectedValueException' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Exception/UnexpectedValueException.php', + 'BaconQrCode\\Exception\\WriterException' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Exception/WriterException.php', + 'BaconQrCode\\Renderer\\Color\\Alpha' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Color/Alpha.php', + 'BaconQrCode\\Renderer\\Color\\Cmyk' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Color/Cmyk.php', + 'BaconQrCode\\Renderer\\Color\\ColorInterface' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Color/ColorInterface.php', + 'BaconQrCode\\Renderer\\Color\\Gray' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Color/Gray.php', + 'BaconQrCode\\Renderer\\Color\\Rgb' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Color/Rgb.php', + 'BaconQrCode\\Renderer\\Eye\\CompositeEye' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Eye/CompositeEye.php', + 'BaconQrCode\\Renderer\\Eye\\EyeInterface' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Eye/EyeInterface.php', + 'BaconQrCode\\Renderer\\Eye\\ModuleEye' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Eye/ModuleEye.php', + 'BaconQrCode\\Renderer\\Eye\\PointyEye' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Eye/PointyEye.php', + 'BaconQrCode\\Renderer\\Eye\\SimpleCircleEye' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Eye/SimpleCircleEye.php', + 'BaconQrCode\\Renderer\\Eye\\SquareEye' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Eye/SquareEye.php', + 'BaconQrCode\\Renderer\\GDLibRenderer' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/GDLibRenderer.php', + 'BaconQrCode\\Renderer\\ImageRenderer' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/ImageRenderer.php', + 'BaconQrCode\\Renderer\\Image\\EpsImageBackEnd' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Image/EpsImageBackEnd.php', + 'BaconQrCode\\Renderer\\Image\\ImageBackEndInterface' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Image/ImageBackEndInterface.php', + 'BaconQrCode\\Renderer\\Image\\ImagickImageBackEnd' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Image/ImagickImageBackEnd.php', + 'BaconQrCode\\Renderer\\Image\\SvgImageBackEnd' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Image/SvgImageBackEnd.php', + 'BaconQrCode\\Renderer\\Image\\TransformationMatrix' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Image/TransformationMatrix.php', + 'BaconQrCode\\Renderer\\Module\\DotsModule' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Module/DotsModule.php', + 'BaconQrCode\\Renderer\\Module\\EdgeIterator\\Edge' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Module/EdgeIterator/Edge.php', + 'BaconQrCode\\Renderer\\Module\\EdgeIterator\\EdgeIterator' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Module/EdgeIterator/EdgeIterator.php', + 'BaconQrCode\\Renderer\\Module\\ModuleInterface' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Module/ModuleInterface.php', + 'BaconQrCode\\Renderer\\Module\\RoundnessModule' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Module/RoundnessModule.php', + 'BaconQrCode\\Renderer\\Module\\SquareModule' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Module/SquareModule.php', + 'BaconQrCode\\Renderer\\Path\\Close' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Path/Close.php', + 'BaconQrCode\\Renderer\\Path\\Curve' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Path/Curve.php', + 'BaconQrCode\\Renderer\\Path\\EllipticArc' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Path/EllipticArc.php', + 'BaconQrCode\\Renderer\\Path\\Line' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Path/Line.php', + 'BaconQrCode\\Renderer\\Path\\Move' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Path/Move.php', + 'BaconQrCode\\Renderer\\Path\\OperationInterface' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Path/OperationInterface.php', + 'BaconQrCode\\Renderer\\Path\\Path' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/Path/Path.php', + 'BaconQrCode\\Renderer\\PlainTextRenderer' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/PlainTextRenderer.php', + 'BaconQrCode\\Renderer\\RendererInterface' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/RendererInterface.php', + 'BaconQrCode\\Renderer\\RendererStyle\\EyeFill' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/RendererStyle/EyeFill.php', + 'BaconQrCode\\Renderer\\RendererStyle\\Fill' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/RendererStyle/Fill.php', + 'BaconQrCode\\Renderer\\RendererStyle\\Gradient' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/RendererStyle/Gradient.php', + 'BaconQrCode\\Renderer\\RendererStyle\\GradientType' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/RendererStyle/GradientType.php', + 'BaconQrCode\\Renderer\\RendererStyle\\RendererStyle' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Renderer/RendererStyle/RendererStyle.php', + 'BaconQrCode\\Writer' => __DIR__ . '/..' . '/bacon/bacon-qr-code/src/Writer.php', + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + 'DASPRiD\\Enum\\AbstractEnum' => __DIR__ . '/..' . '/dasprid/enum/src/AbstractEnum.php', + 'DASPRiD\\Enum\\EnumMap' => __DIR__ . '/..' . '/dasprid/enum/src/EnumMap.php', + 'DASPRiD\\Enum\\Exception\\CloneNotSupportedException' => __DIR__ . '/..' . '/dasprid/enum/src/Exception/CloneNotSupportedException.php', + 'DASPRiD\\Enum\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/dasprid/enum/src/Exception/ExceptionInterface.php', + 'DASPRiD\\Enum\\Exception\\ExpectationException' => __DIR__ . '/..' . '/dasprid/enum/src/Exception/ExpectationException.php', + 'DASPRiD\\Enum\\Exception\\IllegalArgumentException' => __DIR__ . '/..' . '/dasprid/enum/src/Exception/IllegalArgumentException.php', + 'DASPRiD\\Enum\\Exception\\MismatchException' => __DIR__ . '/..' . '/dasprid/enum/src/Exception/MismatchException.php', + 'DASPRiD\\Enum\\Exception\\SerializeNotSupportedException' => __DIR__ . '/..' . '/dasprid/enum/src/Exception/SerializeNotSupportedException.php', + 'DASPRiD\\Enum\\Exception\\UnserializeNotSupportedException' => __DIR__ . '/..' . '/dasprid/enum/src/Exception/UnserializeNotSupportedException.php', + 'DASPRiD\\Enum\\NullValue' => __DIR__ . '/..' . '/dasprid/enum/src/NullValue.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInit3c8f2c10a8655d88b9115205b533c7e2::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInit3c8f2c10a8655d88b9115205b533c7e2::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInit3c8f2c10a8655d88b9115205b533c7e2::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json index 66b9f6c..96bab95 100644 --- a/vendor/composer/installed.json +++ b/vendor/composer/installed.json @@ -1,116 +1,117 @@ -{ - "packages": [ - { - "name": "bacon/bacon-qr-code", - "version": "v3.0.1", - "version_normalized": "3.0.1.0", - "source": { - "type": "git", - "url": "https://github.com/Bacon/BaconQrCode.git", - "reference": "f9cc1f52b5a463062251d666761178dbdb6b544f" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/Bacon/BaconQrCode/zipball/f9cc1f52b5a463062251d666761178dbdb6b544f", - "reference": "f9cc1f52b5a463062251d666761178dbdb6b544f", - "shasum": "" - }, - "require": { - "dasprid/enum": "^1.0.3", - "ext-iconv": "*", - "php": "^8.1" - }, - "require-dev": { - "phly/keep-a-changelog": "^2.12", - "phpunit/phpunit": "^10.5.11 || 11.0.4", - "spatie/phpunit-snapshot-assertions": "^5.1.5", - "squizlabs/php_codesniffer": "^3.9" - }, - "suggest": { - "ext-imagick": "to generate QR code images" - }, - "time": "2024-10-01T13:55:55+00:00", - "type": "library", - "installation-source": "dist", - "autoload": { - "psr-4": { - "BaconQrCode\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "BSD-2-Clause" - ], - "authors": [ - { - "name": "Ben Scholzen 'DASPRiD'", - "email": "mail@dasprids.de", - "homepage": "https://dasprids.de/", - "role": "Developer" - } - ], - "description": "BaconQrCode is a QR code generator for PHP.", - "homepage": "https://github.com/Bacon/BaconQrCode", - "support": { - "issues": "https://github.com/Bacon/BaconQrCode/issues", - "source": "https://github.com/Bacon/BaconQrCode/tree/v3.0.1" - }, - "install-path": "../bacon/bacon-qr-code" - }, - { - "name": "dasprid/enum", - "version": "1.0.7", - "version_normalized": "1.0.7.0", - "source": { - "type": "git", - "url": "https://github.com/DASPRiD/Enum.git", - "reference": "b5874fa9ed0043116c72162ec7f4fb50e02e7cce" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/DASPRiD/Enum/zipball/b5874fa9ed0043116c72162ec7f4fb50e02e7cce", - "reference": "b5874fa9ed0043116c72162ec7f4fb50e02e7cce", - "shasum": "" - }, - "require": { - "php": ">=7.1 <9.0" - }, - "require-dev": { - "phpunit/phpunit": "^7 || ^8 || ^9 || ^10 || ^11", - "squizlabs/php_codesniffer": "*" - }, - "time": "2025-09-16T12:23:56+00:00", - "type": "library", - "installation-source": "dist", - "autoload": { - "psr-4": { - "DASPRiD\\Enum\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "BSD-2-Clause" - ], - "authors": [ - { - "name": "Ben Scholzen 'DASPRiD'", - "email": "mail@dasprids.de", - "homepage": "https://dasprids.de/", - "role": "Developer" - } - ], - "description": "PHP 7.1 enum implementation", - "keywords": [ - "enum", - "map" - ], - "support": { - "issues": "https://github.com/DASPRiD/Enum/issues", - "source": "https://github.com/DASPRiD/Enum/tree/1.0.7" - }, - "install-path": "../dasprid/enum" - } - ], - "dev": true, - "dev-package-names": [] -} +{ + "packages": [ + { + "name": "bacon/bacon-qr-code", + "version": "v3.1.1", + "version_normalized": "3.1.1.0", + "source": { + "type": "git", + "url": "https://github.com/Bacon/BaconQrCode.git", + "reference": "4da2233e72eeecd9be3b62e0dc2cc9ed8e2e31c2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/Bacon/BaconQrCode/zipball/4da2233e72eeecd9be3b62e0dc2cc9ed8e2e31c2", + "reference": "4da2233e72eeecd9be3b62e0dc2cc9ed8e2e31c2", + "shasum": "" + }, + "require": { + "dasprid/enum": "^1.0.3", + "ext-iconv": "*", + "php": "^8.1" + }, + "require-dev": { + "phly/keep-a-changelog": "^2.12", + "phpunit/phpunit": "^10.5.11 || ^11.0.4", + "spatie/phpunit-snapshot-assertions": "^5.1.5", + "spatie/pixelmatch-php": "^1.2.0", + "squizlabs/php_codesniffer": "^3.9" + }, + "suggest": { + "ext-imagick": "to generate QR code images" + }, + "time": "2026-04-05T21:06:35+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "BaconQrCode\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-2-Clause" + ], + "authors": [ + { + "name": "Ben Scholzen 'DASPRiD'", + "email": "mail@dasprids.de", + "homepage": "https://dasprids.de/", + "role": "Developer" + } + ], + "description": "BaconQrCode is a QR code generator for PHP.", + "homepage": "https://github.com/Bacon/BaconQrCode", + "support": { + "issues": "https://github.com/Bacon/BaconQrCode/issues", + "source": "https://github.com/Bacon/BaconQrCode/tree/v3.1.1" + }, + "install-path": "../bacon/bacon-qr-code" + }, + { + "name": "dasprid/enum", + "version": "1.0.7", + "version_normalized": "1.0.7.0", + "source": { + "type": "git", + "url": "https://github.com/DASPRiD/Enum.git", + "reference": "b5874fa9ed0043116c72162ec7f4fb50e02e7cce" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/DASPRiD/Enum/zipball/b5874fa9ed0043116c72162ec7f4fb50e02e7cce", + "reference": "b5874fa9ed0043116c72162ec7f4fb50e02e7cce", + "shasum": "" + }, + "require": { + "php": ">=7.1 <9.0" + }, + "require-dev": { + "phpunit/phpunit": "^7 || ^8 || ^9 || ^10 || ^11", + "squizlabs/php_codesniffer": "*" + }, + "time": "2025-09-16T12:23:56+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "DASPRiD\\Enum\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-2-Clause" + ], + "authors": [ + { + "name": "Ben Scholzen 'DASPRiD'", + "email": "mail@dasprids.de", + "homepage": "https://dasprids.de/", + "role": "Developer" + } + ], + "description": "PHP 7.1 enum implementation", + "keywords": [ + "enum", + "map" + ], + "support": { + "issues": "https://github.com/DASPRiD/Enum/issues", + "source": "https://github.com/DASPRiD/Enum/tree/1.0.7" + }, + "install-path": "../dasprid/enum" + } + ], + "dev": false, + "dev-package-names": [] +} diff --git a/vendor/composer/installed.php b/vendor/composer/installed.php index b425195..e12552c 100644 --- a/vendor/composer/installed.php +++ b/vendor/composer/installed.php @@ -1,41 +1,41 @@ - array( - 'name' => '__root__', - 'pretty_version' => 'dev-main', - 'version' => 'dev-main', - 'reference' => '9546254abadf71309663af35e000f972f035fc00', - 'type' => 'library', - 'install_path' => __DIR__ . '/../../', - 'aliases' => array(), - 'dev' => true, - ), - 'versions' => array( - '__root__' => array( - 'pretty_version' => 'dev-main', - 'version' => 'dev-main', - 'reference' => '9546254abadf71309663af35e000f972f035fc00', - 'type' => 'library', - 'install_path' => __DIR__ . '/../../', - 'aliases' => array(), - 'dev_requirement' => false, - ), - 'bacon/bacon-qr-code' => array( - 'pretty_version' => 'v3.0.1', - 'version' => '3.0.1.0', - 'reference' => 'f9cc1f52b5a463062251d666761178dbdb6b544f', - 'type' => 'library', - 'install_path' => __DIR__ . '/../bacon/bacon-qr-code', - 'aliases' => array(), - 'dev_requirement' => false, - ), - 'dasprid/enum' => array( - 'pretty_version' => '1.0.7', - 'version' => '1.0.7.0', - 'reference' => 'b5874fa9ed0043116c72162ec7f4fb50e02e7cce', - 'type' => 'library', - 'install_path' => __DIR__ . '/../dasprid/enum', - 'aliases' => array(), - 'dev_requirement' => false, - ), - ), -); + array( + 'name' => 'robotstxt/robotstxt-2fa', + 'pretty_version' => '1.0.0+no-version-set', + 'version' => '1.0.0.0', + 'reference' => null, + 'type' => 'wordpress-plugin', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev' => false, + ), + 'versions' => array( + 'bacon/bacon-qr-code' => array( + 'pretty_version' => 'v3.1.1', + 'version' => '3.1.1.0', + 'reference' => '4da2233e72eeecd9be3b62e0dc2cc9ed8e2e31c2', + 'type' => 'library', + 'install_path' => __DIR__ . '/../bacon/bacon-qr-code', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'dasprid/enum' => array( + 'pretty_version' => '1.0.7', + 'version' => '1.0.7.0', + 'reference' => 'b5874fa9ed0043116c72162ec7f4fb50e02e7cce', + 'type' => 'library', + 'install_path' => __DIR__ . '/../dasprid/enum', + 'aliases' => array(), + 'dev_requirement' => false, + ), + 'robotstxt/robotstxt-2fa' => array( + 'pretty_version' => '1.0.0+no-version-set', + 'version' => '1.0.0.0', + 'reference' => null, + 'type' => 'wordpress-plugin', + 'install_path' => __DIR__ . '/../../', + 'aliases' => array(), + 'dev_requirement' => false, + ), + ), +); diff --git a/vendor/composer/platform_check.php b/vendor/composer/platform_check.php index 5ffde28..14bf88d 100644 --- a/vendor/composer/platform_check.php +++ b/vendor/composer/platform_check.php @@ -1,26 +1,25 @@ -= 80100)) { - $issues[] = 'Your Composer dependencies require a PHP version ">= 8.1.0". You are running ' . PHP_VERSION . '.'; -} - -if ($issues) { - if (!headers_sent()) { - header('HTTP/1.1 500 Internal Server Error'); - } - if (!ini_get('display_errors')) { - if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { - fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); - } elseif (!headers_sent()) { - echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; - } - } - trigger_error( - 'Composer detected issues in your platform: ' . implode(' ', $issues), - E_USER_ERROR - ); -} += 80200)) { + $issues[] = 'Your Composer dependencies require a PHP version ">= 8.2.0". You are running ' . PHP_VERSION . '.'; +} + +if ($issues) { + if (!headers_sent()) { + header('HTTP/1.1 500 Internal Server Error'); + } + if (!ini_get('display_errors')) { + if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { + fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); + } elseif (!headers_sent()) { + echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; + } + } + throw new \RuntimeException( + 'Composer detected issues in your platform: ' . implode(' ', $issues) + ); +}