diff --git a/service/php/.gitattributes b/service/php/.gitattributes
new file mode 100644
index 0000000000000000000000000000000000000000..ff6aa5a192b7e4e5937045cd44bb01526ca2874a
--- /dev/null
+++ b/service/php/.gitattributes
@@ -0,0 +1,2 @@
+test/ export-ignore
+tests/ export-ignore
diff --git a/service/php/.gitignore b/service/php/.gitignore
index 9cad9f986dc6ce52b7292898422ec2415fd9f4b4..1797a7053ddb82fb70ea8eaf112bcb889f383a04 100644
--- a/service/php/.gitignore
+++ b/service/php/.gitignore
@@ -13,4 +13,4 @@ test/html
test/nginx.htaccess
test/.htaccess
test/runtime
-
+docs/*
\ No newline at end of file
diff --git a/service/php/CHANGELOG.md b/service/php/CHANGELOG.md
new file mode 100644
index 0000000000000000000000000000000000000000..d55201f3b2f18d69508eaa487d12fc1e75b4a45b
--- /dev/null
+++ b/service/php/CHANGELOG.md
@@ -0,0 +1,42 @@
+# aj-captcha迭代文档
+
+## v2.0.0 2025-12-18
+### 新增特性
+* **原生绘图模式 (Drawing Mode)**: 新增 `DrawingTemplateProvider`,支持实时生成滑块,彻底解决边缘锯齿问题。
+* **多形状支持**: 滑块形状现在支持 `jigsaw` (拼图), `red_heart` (红桃), `spade` (黑桃), `diamond` (方片), `club` (草花) 等多种样式。
+* **点击验证码增强**: 新增 `distract_num` 配置,支持生成干扰字;新增智能碰撞检测算法,防止文字重叠。
+* **策略模式架构**: 引入 `TemplateProviderInterface` 和 `ShapeDrawerInterface`,解耦模板生成逻辑,便于扩展。
+* **兼容性**: 完美兼容 PHP 8.0+ 及即将到来的 PHP 8.5 (废弃 `imagedestroy` 处理)。
+
+### 变更优化
+* **依赖移除**: 彻底移除 `intervention/image` 依赖,完全基于原生 GD 库实现,体积更小,性能更高。
+* **配置结构**: `config.php` 新增 `block_puzzle.mode` 和 `block_puzzle.shape_type` 配置项。
+* **底层优化**: 重构 `ImageUtils`,统一封装 GD 操作,屏蔽 PHP 版本差异。
+* **视觉优化**: 滑块自带内阴影和半透明质感,背景凹槽采用动态变暗逻辑,视觉效果更自然。
+
+
+## v1.1.2 2021-12-15
+* server 增加`verificationByEncryptCode` 方法,兼容前端二次验证`captchaVerification`值
+
+## v1.1.1 2021-12-13
+* 去除多余代码、注释
+
+## v1.1.0 2021-12-9
+* 重构工厂类与领域层
+* 永久缓存图片像素值,增加响应性能
+
+## v1.0.7 2021-11-24
+* 增强缓存冗错
+* 自定义缓存配置
+
+## v1.0.3 2021-10-11
+* 新增二次验证
+
+
+## v1.0.0 2021-7-16
+* 初步实现滑动验证码与文字点选验证码
+
+
+
+
+
diff --git a/service/php/LICENSE b/service/php/LICENSE
index 94a9ed024d3859793618152ea559a168bbcbb5e2..818433ecc0e094a4db1023c68b33f24344643ad8 100644
--- a/service/php/LICENSE
+++ b/service/php/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/service/php/README.md b/service/php/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..098b28468bfc40a06dec525a6e774fe1a41ac443
--- /dev/null
+++ b/service/php/README.md
@@ -0,0 +1,317 @@
+# AJ-Captcha for PHP
+
+
+
+
+
+这个类库使用 PHP 实现了行为验证码(滑动拼图、点选文字)。
+v2.0 版本基于 **Strategy Pattern(策略模式)** 彻底重构了底层架构,移除了第三方图像库依赖,引入了原生 GD 绘图与抗锯齿技术,带来了更极致的体验与更高的性能。
+
+Java实现: https://gitee.com/belief-team/captcha
+
+PHP实现: https://gitee.com/fastknife/aj-captcha
+
+文档地址:https://ajcaptcha.beliefteam.cn/captcha-doc/captchaDoc/html.html
+##### 预览效果
+
+ 
+
+## ✨ 核心特性 (v2.0)
+
+* **轻量零依赖**:彻底移除 `intervention/image`,完全基于 PHP 原生 GD 库,体积更小,兼容性更强(PHP 7.1 ~ 8.5+)。
+* **极致抗锯齿 (Anti-Aliasing)**:
+ * 全新的 `Drawing` 模式,抛弃了传统的图片模板抠图方案。
+ * 采用 **6 倍超采样 (Super Sampling) + 高斯模糊 (Gaussian Blur)** 技术实时绘制滑块。
+ * 生成的滑块边缘平滑细腻,自带内阴影与半透明质感,完美融合背景。
+* **多形状支持**:内置多种滑块形状,支持一键切换:
+ * 🧩 拼图 (`jigsaw`)
+ * ❤️ 红桃 (`red_heart`)
+ * ♠️ 黑桃 (`spade`)
+ * ♦️ 方片 (`diamond`)
+ * ♣️ 草花 (`club`)
+* **安全增强**:
+ * **干扰图**:滑动验证码支持随机生成干扰滑块(位置、形状随机),增加机器识别难度。
+ * **干扰字**:点击验证码支持生成随机干扰文字。
+ * **智能布局**:采用 **随机坐标 + 碰撞检测算法**,确保文字不重叠、不越界。
+* **双模式兼容**:保留了旧版“图片模板”模式 (`resource`),老用户可无缝切换。
+
+## 📸 效果预览
+
+### 滑动验证码 (Drawing 模式)
+*(无需任何图片素材,纯代码实时绘制)*
+
+> 效果图占位:建议运行 testImage.php 查看实际效果
+
+### 点击验证码
+支持文字点选,自带干扰文字与随机布局。
+
+## 🛠 安装
+
+### 要求
+* PHP >= 7.1
+* ext-gd
+* ext-openssl
+
+### Composer 安装
+```bash
+composer require fastknife/ajcaptcha
+```
+
+## 🚀 快速开始
+
+### 1. 原生 PHP 使用
+```php
+get();
+
+// --- 一次验证 (前端滑动/点选后调用) ---
+$token = $_REQUEST['token'];
+$pointJson = $_REQUEST['pointJson'];
+try {
+ // 验证成功会返回加密的 captchaVerification
+ $captchaVerification = $service->check($token, $pointJson);
+
+ // 将 captchaVerification 返回给前端
+ // echo json_encode(['success' => true, 'repData' => ['captchaVerification' => $captchaVerification]]);
+} catch (\Exception $e) {
+ // 验证失败
+}
+
+// --- 二次验证 (业务接口登录/注册时调用) ---
+// 前端将上一步获取的 captchaVerification 传给业务接口
+$captchaVerification = $_REQUEST['captchaVerification'];
+try {
+ $service->verificationByEncryptCode($captchaVerification);
+ // 验证通过,执行业务逻辑 (登录/注册...)
+} catch (\Exception $e) {
+ // 二次验证失败,拦截业务请求
+}
+```
+
+### 2. 框架集成
+本库无任何全局变量与单例依赖,完美支持 ThinkPHP, Laravel, Hyperf, Swoole 等现代框架。只需在控制器中实例化 Service 即可。
+
+## ⚙️ 详细配置说明
+
+在 `src/config.php` 中进行配置:
+
+```php
+return [
+ // --------------------------------------------------------------------
+ // 基础配置
+ // --------------------------------------------------------------------
+
+ // 自定义字体包路径,不填使用默认值 (resources/fonts/WenQuanZhengHei.ttf)
+ 'font_file' => '',
+
+ // 水印配置
+ 'watermark' => [
+ 'fontsize' => 12,
+ 'color' => '#ffffff',
+ 'text' => '我的水印'
+ ],
+
+ // --------------------------------------------------------------------
+ // 滑动验证码配置 (Block Puzzle)
+ // --------------------------------------------------------------------
+ 'block_puzzle' => [
+ // 模式: 'drawing' (推荐, 原生绘图), 'resource' (旧版图片模板)
+ 'mode' => 'drawing',
+
+ // 形状类型 (仅在 drawing 模式下生效)
+ // 可选: 'jigsaw' (拼图), 'red_heart' (红桃), 'spade' (黑桃), 'diamond' (方片), 'club' (草花)
+ 'shape_type' => 'jigsaw',
+
+ // 开启干扰图 (在 drawing 模式下生成干扰凹槽,在 resource 模式下生成干扰拼图)
+ 'is_interfere' => true,
+
+ // 容错偏移量 (px)
+ 'offset' => 10,
+
+ // 背景图路径
+ // 支持 string (目录路径) 或 array (文件路径列表)
+ // 'backgrounds' => '/path/to/images/',
+ 'backgrounds' => [],
+
+ // 模板图路径 (仅在 resource 模式下生效)
+ 'templates' => [],
+
+ // 是否开启像素缓存 (仅在 resource 模式下生效,提升性能)
+ 'is_cache_pixel' => true,
+ ],
+
+ // --------------------------------------------------------------------
+ // 点击验证码配置 (Click Word)
+ // --------------------------------------------------------------------
+ 'click_word' => [
+ // 干扰字数量 (混淆视觉,增加破解难度)
+ 'distract_num' => 2,
+
+ // 目标字数量 (需要点击的文字数量)
+ 'word_num' => 4,
+
+ // 背景图路径
+ 'backgrounds' => [],
+ ],
+
+ // --------------------------------------------------------------------
+ // 缓存配置
+ // --------------------------------------------------------------------
+ // 默认使用内置文件缓存 (\Fastknife\Utils\CacheUtils)
+ 'cache' => [
+ 'constructor' => \Fastknife\Utils\CacheUtils::class,
+ 'method' => [
+ // 如果您的缓存驱动符合 PSR-16 规范 (如 Laravel, TP6, Hyperf),则无需配置此项
+ // 如果是不兼容的旧框架 (如 TP5),需在此处做方法映射
+ 'get' => 'get', // 获取缓存方法名
+ 'set' => 'set', // 设置缓存方法名
+ 'delete' => 'delete',// 删除缓存方法名 (TP5 为 'rm')
+ 'has' => 'has' // 检查存在方法名
+ ],
+ 'options' => [
+ 'expire' => 300, // 300秒有效期
+ 'prefix' => '',
+ 'path' => '', // 缓存目录 (仅内置缓存有效)
+ ]
+ ]
+];
+```
+
+### 框架缓存集成详解
+
+默认使用的 `\Fastknife\Utils\CacheUtils` 是一个基于 ThinkPHP 文件缓存改写的轻量级缓存驱动。它会在项目工作目录下自动创建 `runtime/cache` 目录来存储缓存文件。
+
+* **轻量场景**:如果文件缓存符合您的目录权限要求,且项目单机运行,您完全可以继续使用内置缓存,无需配置。
+* **高性能/分布式**:如果您追求更高的性能(如 Redis)或运行在分布式环境中,强烈建议替换为框架自带的缓存驱动或外部缓存引擎。
+
+#### 1. 方法映射 (适配非 PSR-16 框架)
+本库默认期望缓存驱动遵循 PSR-16 规范。如果您的框架缓存方法名不同(例如 ThinkPHP 5.0 使用 `rm` 而不是 `delete`),您需要通过 `method` 配置项进行映射:
+
+```php
+// ThinkPHP 5.0 示例
+'cache' => [
+ 'constructor' => [think\Cache::class, 'store'],
+ 'method' => [
+ 'get' => 'get',
+ 'set' => 'set',
+ 'delete' => 'rm', // TP5 删除缓存的方法是 rm
+ 'has' => 'has'
+ ],
+ // ...
+]
+```
+
+#### 2. 常用框架配置示例
+
+**Laravel / Lumen**:
+```php
+'cache' => [
+ 'constructor' => [Illuminate\Support\Facades\Cache::class, 'store'],
+ // Laravel 符合 PSR-16,无需配置 method
+]
+```
+
+**ThinkPHP 6**:
+```php
+'cache' => [
+ 'constructor' => [think\Facade\Cache::class, 'instance'],
+ // TP6 符合 PSR-16,无需配置 method
+]
+```
+
+**Hyperf**:
+```php
+'cache' => [
+ 'constructor' => function () {
+ return \Hyperf\Utils\ApplicationContext::getContainer()->get(\Psr\SimpleCache\CacheInterface::class);
+ },
+]
+```
+
+## 💻 前端集成注意事项
+
+前端请求时,请确保 `Content-Type` 设置为 `application/x-www-form-urlencoded`。
+
+**Axios 示例**:
+```javascript
+import axios from 'axios';
+import qs from 'qs';
+
+axios.defaults.baseURL = 'https://your-api.com/captcha-api';
+
+const service = axios.create({
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
+ },
+})
+
+service.interceptors.request.use(config => {
+ if (config.data) {
+ config.data = qs.stringify(config.data)
+ }
+ return config
+})
+```
+
+## 🏗 架构设计
+
+v2.0 引入了**策略模式 (Strategy Pattern)**,将滑块的生成逻辑解耦。
+
+### 核心目录结构
+
+```
+src/
+├── Domain/
+│ ├── Template/ # 策略层
+│ │ ├── TemplateProviderInterface.php # 策略接口
+│ │ ├── DrawingTemplateProvider.php # 策略A: 原生绘图 (抗锯齿核心)
+│ │ ├── ResourceTemplateProvider.php # 策略B: 图片资源 (兼容旧版)
+│ │ │
+│ │ └── Shape/ # 形状绘制子策略
+│ │ ├── ShapeDrawerInterface.php
+│ │ ├── ShapeFactory.php # 工厂模式
+│ │ ├── JigsawShapeDrawer.php # 拼图形状
+│ │ ├── RedHeartShapeDrawer.php # 红桃形状
+│ │ ├── SpadeShapeDrawer.php # 黑桃形状
+│ │ ├── DiamondShapeDrawer.php # 方片形状
+│ │ └── ClubShapeDrawer.php # 草花形状
+│ │
+│ └── Logic/ # 业务逻辑层
+│ ├── BlockImage.php # 滑动验证码合成逻辑 (Alpha混合, 挖槽)
+│ └── ...
+│
+├── Utils/
+│ └── ImageUtils.php # 基础设施层: GD 库底层封装 (屏蔽 PHP 版本差异)
+└── ...
+```
+
+### 绘图原理 (Drawing Mode)
+
+1. **大画布绘制**:系统首先创建一个 6 倍于目标尺寸的透明画布。
+2. **矢量路径**:使用 `imagefilledpolygon` 等函数在画布上绘制高精度的矢量形状(拼图、心形等)。
+3. **光影渲染**:在形状内部绘制半透明的内阴影、外发光,模拟立体感。
+4. **高斯模糊**:应用轻微的高斯模糊 (`IMG_FILTER_GAUSSIAN_BLUR`) 柔化边缘。
+5. **下采样**:使用 `imagecopyresampled` 将大图缩放回原尺寸,生成高质量的 Alpha Mask。
+6. **混合渲染**:利用 Alpha Blending 将 Mask 与背景图混合,实现完美的抠图效果。
+
+## 📝 变更日志
+
+查看 [CHANGELOG.md](./CHANGELOG.md)
+
+## 🤝 贡献
+
+欢迎提交 Issue 和 Pull Request!如果你想添加新的滑块形状,只需实现 `ShapeDrawerInterface` 并在 `ShapeFactory` 中注册即可。
+
+## 📄 License
+
+MIT
diff --git a/service/php/changelog.md b/service/php/changelog.md
deleted file mode 100644
index b705626c8a78e37e8bb4304b483c9aec48a14dac..0000000000000000000000000000000000000000
--- a/service/php/changelog.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# aj-captcha迭代文档
-## v1.1.2 2021-12-15
-* server 增加`verificationByEncryptCode` 方法,兼容前端二次验证`captchaVerification`值
-
-## v1.1.1 2021-12-13
-* 去除多余代码、注释
-
-## v1.1.0 2021-12-9
-* 重构工厂类与领域层
-* 永久缓存图片像素值,增加响应性能
-
-## v1.0.7 2021-11-24
-* 增强缓存冗错
-* 自定义缓存配置
-
-## v1.0.3 2021-10-11
-* 新增二次验证
-
-
-## v1.0.0 2021-7-16
-* 初步实现滑动验证码与文字点选验证码
-
-
-
-
-
diff --git a/service/php/composer.json b/service/php/composer.json
index 5b66e8a058d80b777bb81c542597b4b179f3df20..0158df6d064cfef624b2adbb9bf8306d99581f7e 100644
--- a/service/php/composer.json
+++ b/service/php/composer.json
@@ -12,7 +12,6 @@
"php": ">=7.1",
"ext-gd": "*",
"ext-openssl": "*",
- "intervention/image": "^2.5",
"ext-iconv": "*",
"ext-json": "*"
},
@@ -22,5 +21,11 @@
"psr-4": {
"Fastknife\\": "src"
}
+ },
+ "archive": {
+ "exclude": [
+ "test/",
+ "tests/"
+ ]
}
}
diff --git a/service/php/demo.md b/service/php/demo.md
index eaf56132e1172b61d6d46f9d9759187ff398ff8f..3294c9fa69e8390a5ca00ec88494d6e69f4dfa3a 100644
--- a/service/php/demo.md
+++ b/service/php/demo.md
@@ -8,8 +8,10 @@
return [
'font_file' => '', //自定义字体包路径, 不填使用默认值
//文字验证码
- 'click_world' => [
- 'backgrounds' => []
+ 'click_word' => [
+ 'backgrounds' => [],
+ 'word_num' => 3,
+ 'distract_num' => 2
],
//滑动验证码
'block_puzzle' => [
@@ -27,9 +29,9 @@ return [
'text' => '我的水印'
],
'cache' => [
- 'constructor' => \Fastknife\Utils\CacheUtils::class,//若您使用了框架,不推荐使用该配置
+ 'constructor' => \Fastknife\Utils\CacheUtils::class,//若您使用了框架,并且想使用类似于redis这样的缓存驱动,则应换成框架的中的缓存驱动
'method' => [
- //遵守PSR-16规范不需要设置此项目(tp6, laravel,hyperf)。如tp5就不支持(delete => rm),
+ // 遵守PSR-16规范不需要设置此项(tp6, laravel,hyperf)。如tp5就不支持(tp5缓存方法是rm,所以要配置为"delete" => "rm"),
'get' => 'get', //获取
'set' => 'set', //设置
'delete' => 'delete',//删除
@@ -236,4 +238,4 @@ service.interceptors.request.use(
```
本包后续更新 ThinkPHP、Hyperf 等框架的demo,请持续关注
-https://gitee.com/fastknife/aj-captcha
\ No newline at end of file
+https://gitee.com/fastknife/aj-captcha
diff --git a/service/php/readme.md b/service/php/readme.md
deleted file mode 100644
index bd122260834865c2d17125776e820800431097b9..0000000000000000000000000000000000000000
--- a/service/php/readme.md
+++ /dev/null
@@ -1,72 +0,0 @@
-AJ-Captcha · php
-----
-
-#### 介绍
-
-这个类库使用 PHP实现了行为验证码。基于gd扩展生成滑动验证码和文字验证码。允许 phper定制验证码规则,并且不再使用 curl来请求第三方验证。
-
-官方地址: https://gitee.com/anji-plus/captcha
-
-PHP实现: https://gitee.com/fastknife/aj-captcha
-
-##### 官方预览效果
-
- 
-
-#### 注意事项
-* 你需要打开 gd、 openssl扩展
-* PHP版本至少需要7.1
-* 此软件包自带缓存,如有需要请自行更换
-* anji-plus/captcha前端默认请求头是 application/json 需替换为 application/x-www-form-urlencode
-
-#### 如何使用
-test 目录下示例了三种使用方式,phper可以参考使用。[查看demo](./demo.md)
-> 本软件包需要配合composer一起使用
-1. 非框架使用的场景,直接使用git下载这个软件包。然后执行composer命令`composer install`安装本软件包依赖,接着手动引入对应的 service层文件即可(同test目录里的原生引用方式)。
-
-2. 基于框架使用的场景,输入安装命令`composer require fastknife/ajcaptcha`(稳定版) 或者`composer require fastknife/ajcaptcha dev-master`(最新版) ,建议使用composer阿里源(`https://mirrors.aliyun.com/composer`)
- * 支持各种前沿框架(ThinkPHP, YII, Laravel, Hyperf,IMI,Swoft,EasySwoole)
- * 本软件包内,未使用单例、注册树(容器)模式,不含任何全局变量,基于swoole开发的同学不用担心内存泄露。
-
-3. 以thinkphp框架后端和vue框架前端为例,在本地开发环境运行起示例项目说明:
-3.1 开启命令行窗口,进入 captcha\service\php\test\thinkphp 目录,执行 `composer install` 命令安装依赖,执行 `php think run` 命令启动接口服务。
-3.2 修改 captcha\view\vue\config\dev.env.js 中 BASE_API: '"http://localhost:8000"' ,取值与 3.1中启动的接口服务地址一致。
-3.3 开启命令行窗口,进入 captcha\view\vue 目录,执行 `npm install` 命令安装依赖,执行 `npm run dev` 命令启动前端项目。
-
-
-#### 项目结构
-> 本软件包基于整洁架构理念,设计了下文的目录结构。Domain(领域层)作为内层同心圆承担所有业务逻辑功能,Service(服务层)并向最外层Controller(需自行实现)提供粗颗粒度服务。
- 区别于DDD(领域驱动设计),本软件包的领域层不含Entity(实体),以Logic(逻辑层)实现单元逻辑,为了方便管理作者将逻辑层的数据处理与图形处理分隔,以达到整洁效果。
-```
-AJ-Captcha for php
-│
-├─resources 资源
-│ │
-│ ├─defaultImages 图片资源
-│ │
-│ └─fonts 字体
-│
-├─src 源码
-│ │
-│ ├─Domian 领域层
-│ │
-│ ├─Exception 异常
-│ │
-│ ├─Service 服务层
-│ │
-│ └─Utils 工具类
-│
-├─test 测试实例
-│ │
-│ ├─thinkphp thinkphp框架测试示例
-│ │
-│ ├─laravel laravel框架测试示例
-│ │
-│ └─*.php 原生测试文件 配置文件
-└─config.php 配置参考
-
-```
-
-#### [更新日志](./changelog.md)
-
-若此软件对您有所帮助,您可以点右上角 💘Star💘支持
diff --git a/service/php/sizes.json b/service/php/sizes.json
new file mode 100644
index 0000000000000000000000000000000000000000..331630b67105305fa79722a85a46863c5c35e6e9
Binary files /dev/null and b/service/php/sizes.json differ
diff --git a/service/php/slider.php b/service/php/slider.php
new file mode 100644
index 0000000000000000000000000000000000000000..2e1f76a2805494825fd0acb8c4644a1c1c3e1712
--- /dev/null
+++ b/service/php/slider.php
@@ -0,0 +1,94 @@
+= 1.24*$PI; $a -= 0.03 / $scale) {
+ $points[] = $cx + ($sliderR + 0.4) * $scale * cos($a);
+ $points[] = $cy + ($sliderR + 0.4) * $scale * sin($a);
+}
+
+// 闭合
+$points[] = $px; $points[] = $py;
+
+// 绘制阴影(填充 + 描边模拟 stroke)
+imagefilledpolygon($big, $points, count($points)/2, $shadowColor);
+imagepolygon($big, $points, count($points)/2, $shadowColor);
+
+// 创建最终尺寸画布并缩放(关键:高质量重采样产生优秀抗锯齿)
+$block = imagecreatetruecolor($L, $L);
+imagesavealpha($block, true);
+$transFinal = imagecolorallocatealpha($block, 0, 0, 0, 127);
+imagefill($block, 0, 0, $transFinal);
+
+imagecopyresampled($block, $big, 0, 0, 0, 0, $L, $L, $bigL, $bigL);
+
+// 输出
+imagepng($block, null, 9);
+
+imagedestroy($big);
+imagedestroy($block);
\ No newline at end of file
diff --git a/service/php/src/Domain/Factory.php b/service/php/src/Domain/Factory.php
index f4657e5e580cd5c097a5ed0f7d005752d0701e65..b63187ef505759e48b1a220fde8564f2eea75165 100644
--- a/service/php/src/Domain/Factory.php
+++ b/service/php/src/Domain/Factory.php
@@ -10,8 +10,10 @@ use Fastknife\Domain\Logic\Cache;
use Fastknife\Domain\Logic\WordImage;
use Fastknife\Domain\Logic\BlockData;
use Fastknife\Domain\Logic\WordData;
+use Fastknife\Domain\Template\DrawingTemplateProvider;
+use Fastknife\Domain\Template\ResourceTemplateProvider;
+use Fastknife\Domain\Template\TemplateProviderInterface;
use Fastknife\Domain\Vo\ImageVo;
-use Intervention\Image\ImageManagerStatic;
class Factory
{
@@ -29,7 +31,7 @@ class Factory
*/
public function makeBlockImage(): BlockImage
{
- $data = new BlockData();
+ $data = $this->makeBlockData();
$image = new BlockImage();
$this->setCommon($image, $data);
$this->setBlock($image, $data);
@@ -41,7 +43,7 @@ class Factory
*/
public function makeWordImage(): WordImage
{
- $data = new WordData();
+ $data = $this->makeWordData();
$image = new WordImage();
$this->setCommon($image, $data);
$this->setWord($image, $data);
@@ -49,17 +51,13 @@ class Factory
}
-
/**
* 设置公共配置
* @param BaseImage $image
* @param BaseData $data
*/
- protected function setCommon(BaseImage $image, BaseData $data)
+ protected function setCommon(BaseImage $image, BaseData $data)
{
- //固定驱动,少量图片处理场景gd性能远远大于imagick
- ImageManagerStatic::configure(['driver' => 'gd']);
-
//获得字体数据
$fontFile = $data->getFontFile($this->config['font_file']);
$image
@@ -72,37 +70,25 @@ class Factory
* @param BlockImage $image
* @param BlockData $data
*/
- protected function setBlock(BlockImage $image, BlockData $data)
+ protected function setBlock(BlockImage $image, BlockData $data)
{
//设置背景
$backgroundVo = $data->getBackgroundVo($this->config['block_puzzle']['backgrounds']);
$image->setBackgroundVo($backgroundVo);
- $templateVo = $data->getTemplateVo($backgroundVo, $this->config['block_puzzle']['templates']);
-
- $interfereVo = $data->getInterfereVo($backgroundVo, $templateVo, $this->config['block_puzzle']['templates']);
-
- if(isset($this->config['block_puzzle']['is_cache_pixel']) &&
- $this->config['block_puzzle']['is_cache_pixel'] === true){
- $cache = $this->getCacheInstance();
- foreach ([$backgroundVo, $templateVo, $interfereVo] as $vo){
- /**@var ImageVo $vo**/
- $key = 'image_pixel_map_'.$vo->src;
- $result = $cache->get($key);
- if(!empty($result) && is_array($result)){
- $vo->setPickMaps($result);
- }else{
- $vo->preparePickMaps();
- $vo->setFinishCallback(function(ImageVo $imageVo)use($cache, $key){
- $cache->set($key, $imageVo->getPickMaps(),0);
- });
- }
- }
- }
+ // 使用注入的 Provider 获取 TemplateVo
+ $templateVo = $data->getTemplateVo($backgroundVo);
- $image
- ->setTemplateVo($templateVo)
- ->setInterfereVo($interfereVo);
+ $image->setTemplateVo($templateVo);
+
+ // 干扰图逻辑 (已适配 Drawing/Resource 双模式)
+ if (
+ isset($this->config['block_puzzle']['is_interfere']) &&
+ $this->config['block_puzzle']['is_interfere'] == true
+ ) {
+ $interfereVo = $data->getInterfereVo($backgroundVo, $templateVo);
+ $image->setInterfereVo($interfereVo);
+ }
}
/**
@@ -113,20 +99,38 @@ class Factory
protected function setWord(WordImage $image, WordData $data)
{
//设置背景
- $backgroundVo = $data->getBackgroundVo($this->config['click_world']['backgrounds']);
+ $backgroundVo = $data->getBackgroundVo($this->config['click_word']['backgrounds']);
$image->setBackgroundVo($backgroundVo);
- //随机文字坐标
+ // 干扰字数量
+ $distractNum = $this->config['click_word']['distract_num'] ?? 2;
+ // 目标字数量
+ $wordNum = $this->config['click_word']['word_num'] ?? 3;
+
+ // 限制
+ if($wordNum > 5) $wordNum = 5;
+ if($wordNum < 2) $wordNum = 2;
+
+ // 总字数
+ $totalNum = $wordNum + $distractNum;
+
+ // 获取文字列表 (目标 + 干扰)
+ $wordList = $data->getWordList($totalNum);
+
+ // 随机文字坐标 (碰撞检测)
$pointList = $data->getPointList(
- $image->getBackgroundVo()->image->getWidth(),
- $image->getBackgroundVo()->image->getHeight(),
- 3
+ imagesx($image->getBackgroundVo()->image),
+ imagesy($image->getBackgroundVo()->image),
+ $totalNum
);
- $worldList = $data->getWordList(count($pointList));
+
+ // WordImage 需要渲染所有字
$image
- ->setWordList($worldList)
- ->setWordList($worldList)
+ ->setWordList($wordList)
->setPoint($pointList);
+
+ // 我们可以在 WordImage 中增加一个属性 targetCount
+ $image->setTargetCount($wordNum);
}
/**
@@ -134,10 +138,10 @@ class Factory
*/
public function getCacheInstance(): Cache
{
- if(empty($this->cacheInstance)){
+ if (empty($this->cacheInstance)) {
$this->cacheInstance = new Cache($this->config['cache']);
}
- return $this->cacheInstance;
+ return $this->cacheInstance;
}
public function makeWordData(): WordData
@@ -147,6 +151,33 @@ class Factory
public function makeBlockData(): BlockData
{
- return (new BlockData())->setFaultOffset($this->config['block_puzzle']['offset']);
+ $blockData = new BlockData();
+ $blockData->setFaultOffset($this->config['block_puzzle']['offset']);
+
+ // 注入 TemplateProvider
+ $provider = $this->makeTemplateProvider();
+ $blockData->setTemplateProvider($provider);
+
+ return $blockData;
}
+
+ public function makeTemplateProvider(): TemplateProviderInterface
+ {
+ $mode = $this->config['block_puzzle']['mode'] ?? 'drawing';
+ if ($mode === 'resource') {
+ $provider = new ResourceTemplateProvider($this->config);
+ $provider->setCache($this->getCacheInstance());
+ return $provider;
+ }
+ return new DrawingTemplateProvider($this->config);
+ }
+
+ /**
+ * @return array
+ */
+ public function getConfig(): array
+ {
+ return $this->config;
+ }
+
}
diff --git a/service/php/src/Domain/Logic/BaseData.php b/service/php/src/Domain/Logic/BaseData.php
index 0cbee61e68c7796700b62ab6099b8145661c7bb4..43c83de4902036c9de23cf52b2345dcee2ec7f68 100644
--- a/service/php/src/Domain/Logic/BaseData.php
+++ b/service/php/src/Domain/Logic/BaseData.php
@@ -42,7 +42,7 @@ class BaseData
/**
* 获取默认图片
* @param $dir
- * @param $images
+ * @param array|string $images
* @return array|false
*/
protected function getDefaultImage($dir, $images)
diff --git a/service/php/src/Domain/Logic/BaseImage.php b/service/php/src/Domain/Logic/BaseImage.php
index df6b07f646338185f66fb2e1db44307c97d0a67b..912754133bfc5fac5f3f76870933737b6d3ac53b 100644
--- a/service/php/src/Domain/Logic/BaseImage.php
+++ b/service/php/src/Domain/Logic/BaseImage.php
@@ -5,8 +5,7 @@ namespace Fastknife\Domain\Logic;
use Fastknife\Domain\Vo\BackgroundVo;
-use Intervention\Image\AbstractFont as Font;
-use Intervention\Image\Image;
+use Fastknife\Utils\ImageUtils;
abstract class BaseImage
{
@@ -30,7 +29,7 @@ abstract class BaseImage
/**
* @param $point
- * @return WordImage
+ * @return self
*/
public function setPoint($point):self
{
@@ -39,22 +38,75 @@ abstract class BaseImage
}
- protected function makeWatermark(Image $image)
+ /**
+ * 绘制水印
+ * @param resource|\GdImage $image
+ */
+ protected function makeWatermark($image)
{
if (! empty($this->watermark)) {
- //1汉字3个字节。 汉字长宽比约0.618; fontsize是以高度来计算像素的。
- $offsetX = intval(strlen($this->watermark['text']) / 3 * $this->watermark['fontsize'] * 0.618);
- $offsetY = intval($this->watermark['fontsize'] / 2);
- $x = $image->getWidth() - $offsetX;
- $y = $image->getHeight() - $offsetY;
- $image->text($this->watermark['text'], $x, $y, function (Font $font) {
- $font->file($this->fontFile);
- $font->size($this->watermark['fontsize']);
- $font->color($this->watermark['color']);
- $font->align('center');
- $font->valign('center');
- });
+ // 计算文字包围盒,用于确定位置
+ $fontSize = $this->watermark['fontsize'];
+ $text = $this->watermark['text'];
+
+ $info = imagettfbbox($fontSize, 0, $this->fontFile, $text);
+ $minX = min($info[0], $info[2], $info[4], $info[6]);
+ $maxX = max($info[0], $info[2], $info[4], $info[6]);
+ $minY = min($info[1], $info[3], $info[5], $info[7]);
+ $maxY = max($info[1], $info[3], $info[5], $info[7]);
+
+ $textW = $maxX - $minX;
+ $textH = $maxY - $minY;
+
+ $imgW = imagesx($image);
+ $imgH = imagesy($image);
+
+ // 目标:右下角,留出一点余白
+ // 余白:fontSize / 2
+ $margin = $fontSize / 2;
+
+ // ImageUtils::text 默认 align=left, valign=bottom (基线)
+ // 如果我们使用 align=right, valign=bottom
+ // 则 x 应该是 imgW - margin
+ // y 应该是 imgH - margin
+
+ // 原逻辑:
+ // $x += $image->getWidth() - $this->watermark['fontsize']/2;
+ // $y += $image->getHeight() - $h;
+ // $image->text(..., align='right', valign='bottom')
+
+ // 使用 ImageUtils
+ // 颜色 hex to rgb
+ $color = $this->hex2rgb($this->watermark['color']);
+
+ ImageUtils::text(
+ $image,
+ $text,
+ (int)($imgW - $margin),
+ (int)($imgH - $margin), // 大概位置,ImageUtils 内部 valign='bottom' 会修正为基线
+ $this->fontFile,
+ $fontSize,
+ [$color[0], $color[1], $color[2], 0], // alpha 0 opaque
+ 0,
+ 'right',
+ 'bottom'
+ );
+ }
+ }
+
+ private function hex2rgb($hexColor)
+ {
+ $hex = str_replace("#", "", $hexColor);
+ if (strlen($hex) == 3) {
+ $r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
+ $g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
+ $b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
+ } else {
+ $r = hexdec(substr($hex, 0, 2));
+ $g = hexdec(substr($hex, 2, 2));
+ $b = hexdec(substr($hex, 4, 2));
}
+ return [$r, $g, $b];
}
diff --git a/service/php/src/Domain/Logic/BlockData.php b/service/php/src/Domain/Logic/BlockData.php
index 89011c899cfb2b5aebdafcf431343cdfa71d4870..9da7041ce1a7ec81da3a1bdf984fe7f2073f06a5 100644
--- a/service/php/src/Domain/Logic/BlockData.php
+++ b/service/php/src/Domain/Logic/BlockData.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Fastknife\Domain\Logic;
+use Fastknife\Domain\Template\TemplateProviderInterface;
use Fastknife\Domain\Vo\BackgroundVo;
use Fastknife\Domain\Vo\OffsetVo;
use Fastknife\Domain\Vo\TemplateVo;
@@ -17,6 +18,11 @@ class BlockData extends BaseData
protected $faultOffset;
+ /**
+ * @var TemplateProviderInterface
+ */
+ protected $templateProvider;
+
/**
* @return mixed
*/
@@ -34,83 +40,45 @@ class BlockData extends BaseData
return $this;
}
-
/**
- * 获取剪切模板Vo
- * @param BackgroundVo $backgroundVo
- * @param array $templates
- * @return TemplateVo
+ * 设置模板提供者
+ * @param TemplateProviderInterface $provider
*/
- public function getTemplateVo(BackgroundVo $backgroundVo, array $templates = []): TemplateVo
+ public function setTemplateProvider(TemplateProviderInterface $provider)
{
- $background = $backgroundVo->image;
- //初始偏移量,让模板图在背景的右1/2位置
- $bgWidth = intval($background->getWidth() / 2);
- //随机获取一张图片
- $src = $this->getRandImage($this->getTemplateImages($templates));
-
- $templateVo = new TemplateVo($src);
-
- //随机获取偏移量
- $offset = RandomUtils::getRandomInt(0, $bgWidth - $templateVo->image->getWidth() - 1);
-
- $templateVo->setOffset(new OffsetVo($offset + $bgWidth, 0));
- return $templateVo;
+ $this->templateProvider = $provider;
}
-
- public function getInterfereVo(BackgroundVo $backgroundVo, TemplateVo $templateVo, $templates = []): TemplateVo
+ /**
+ * 获取剪切模板Vo
+ * @param BackgroundVo $backgroundVo
+ * @return TemplateVo
+ */
+ public function getTemplateVo(BackgroundVo $backgroundVo): TemplateVo
{
- //背景
$background = $backgroundVo->image;
- //模板库去重
- $templates = $this->exclude($this->getTemplateImages($templates), $templateVo->src);
-
- //随机获取一张模板图
- $src = $this->getRandImage($templates);
-
- $interfereVo = new TemplateVo($src);
-
- $maxOffsetX = intval($templateVo->image->getWidth()/2);
- do {
- //随机获取偏移量
- $offsetX = RandomUtils::getRandomInt(0, $background->getWidth() - $templateVo->image->getWidth() - 1);
+ $bgWidth = imagesx($background);
+ $bgHeight = imagesy($background);
- //不与原模板重复
- if (
- abs($templateVo->offset->x - $offsetX) > $maxOffsetX
- ) {
- $offsetVO = new OffsetVo($offsetX, 0);
- $interfereVo->setOffset($offsetVO);
- return $interfereVo;
- }
- } while (true);
- }
-
-
- protected function getTemplateImages(array $templates = [])
- {
- $dir = dirname(__DIR__, 3) . '/resources/defaultImages/jigsaw/slidingBlock/';
- return $this->getDefaultImage($dir, $templates);
+ return $this->templateProvider->getTemplateVo($bgWidth, $bgHeight);
}
/**
- * 排除
- * @param $templates
- * @param $exclude
- * @return array
+ * 获取干扰模板Vo
+ * @param BackgroundVo $backgroundVo
+ * @param TemplateVo $targetVo
+ * @return TemplateVo
*/
- protected function exclude($templates, $exclude): array
+ public function getInterfereVo(BackgroundVo $backgroundVo, TemplateVo $targetVo): TemplateVo
{
- if (false !== ($key = array_search($exclude, $templates))) {
- array_splice($templates,$key,1);
- }
- return $templates;
+ $background = $backgroundVo->image;
+ $bgWidth = imagesx($background);
+ $bgHeight = imagesy($background);
+
+ return $this->templateProvider->getInterfereVo($bgWidth, $bgHeight, $targetVo);
}
-
-
-
+
/**
* @param $originPoint
* @param $targetPoint
diff --git a/service/php/src/Domain/Logic/BlockImage.php b/service/php/src/Domain/Logic/BlockImage.php
index c440109c804ad6035f5c0b7a7db20483c41286d0..0ccd1f367f1b5549582c4081c9204643ec578676 100644
--- a/service/php/src/Domain/Logic/BlockImage.php
+++ b/service/php/src/Domain/Logic/BlockImage.php
@@ -8,10 +8,11 @@ use Fastknife\Domain\Vo\BackgroundVo;
use Fastknife\Domain\Vo\ImageVo;
use Fastknife\Domain\Vo\PointVo;
use Fastknife\Domain\Vo\TemplateVo;
+use Fastknife\Utils\ImageUtils;
class BlockImage extends BaseImage
{
- const WHITE = [255, 255, 255, 1];
+ const WHITE = [255, 255, 255, 1]; // 1 means opaque in Intervention, but in ImageVo we convert to GD.
/**
* @var TemplateVo
@@ -64,40 +65,78 @@ class BlockImage extends BaseImage
public function run()
{
$flag = false;
+ // 核心改造:使用 Alpha Blending 替代硬性 cut
$this->cutByTemplate($this->templateVo, $this->backgroundVo, function ($param) use (&$flag) {
- if (! $flag) {
+ if (!$flag) {
//记录第一个点
$this->setPoint(new PointVo($param[0], 5));//前端已将y值写死
$flag = true;
}
});
- $this->cutByTemplate($this->interfereVo, $this->backgroundVo);
+
+ if (!empty($this->interfereVo)) {
+ // 干扰图也使用同样的逻辑
+ $this->cutByTemplate($this->interfereVo, $this->backgroundVo);
+ }
$this->makeWatermark($this->backgroundVo->image);
}
- public function cutByTemplate(TemplateVo $templateVo,BackgroundVo $backgroundVo, $callable = null){
+ public function cutByTemplate(TemplateVo $templateVo, BackgroundVo $backgroundVo, $callable = null)
+ {
$template = $templateVo->image;
- $width = $template->getWidth();
- $height = $template->getHeight();
+ $width = imagesx($template);
+ $height = imagesy($template);
+
+ $offsetX = $templateVo->offset->x;
+ $offsetY = $templateVo->offset->y;
+
+ // 记录坐标 (仅针对主模板,即有回调的情况)
+ if ($callable instanceof \Closure) {
+ $callable([$offsetX, $offsetY]);
+ }
+
+ // 遍历模板像素
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
- //背景图对应的坐标
- $bgX = $x + $templateVo->offset->x;
- $bgY = $y + $templateVo->offset->y;
- //是否不透明
- $isOpacity = $templateVo->isOpacity($x, $y);
- if ($isOpacity) { //如果不透明
- if ($callable instanceof \Closure) {
- $callable([$bgX, $bgY]);
- }
- $backgroundVo->vagueImage($bgX, $bgY);//模糊背景图选区
-
- $this->copyPickColor($backgroundVo,$bgX,$bgY, $templateVo, $x, $y);
+ // 1. 获取模板当前像素的 Alpha 透明度
+ $maskColor = $templateVo->getPickColor($x, $y);
+ $maskAlpha = $maskColor[3]; // 0.0 (transparent) ~ 1.0 (opaque)
+
+ if ($maskAlpha <= 0.01) {
+ continue; // 几乎完全透明,跳过
}
- if ($templateVo->isBoundary($isOpacity, $x, $y)) {
- $backgroundVo->setPixel(self::WHITE, $bgX, $bgY);
- $templateVo->setPixel(self::WHITE, $x, $y);
+
+ // 背景图对应的坐标
+ $bgX = $x + $offsetX;
+ $bgY = $y + $offsetY;
+
+ // 2. 从背景图取色
+ $bgColor = $backgroundVo->getPickColor($bgX, $bgY);
+
+ // 3. 混合 (Alpha Blending) - 生成滑块
+ // 最终滑块像素的 Alpha = MaskAlpha * BackgroundAlpha
+ $finalAlpha = $maskAlpha * $bgColor[3];
+ $templateVo->setPixel([$bgColor[0], $bgColor[1], $bgColor[2], $finalAlpha], $x, $y);
+
+ // 4. 处理背景图的凹槽 (Digging the hole)
+ // 视觉效果:将背景图对应区域变暗 (Darken),模拟凹槽阴影
+ // 仅当 maskAlpha 足够大时才处理 (避免边缘过度黑化)
+ if ($maskAlpha > 0.2) {
+ // 变暗系数:0.8 (越小越黑,0.8意味着亮度只剩20%)
+ // 结合 MaskAlpha,边缘渐变变暗
+ $darkenFactor = 1.0 - (0.8 * $maskAlpha);
+
+ $newR = $bgColor[0] * $darkenFactor;
+ $newG = $bgColor[1] * $darkenFactor;
+ $newB = $bgColor[2] * $darkenFactor;
+
+ // 也可以叠加一层半透明黑,这里直接修改 RGB 简单有效
+ // Alpha 保持不变 (通常背景是不透明的)
+ $backgroundVo->setPixel([$newR, $newG, $newB, $bgColor[3]], $bgX, $bgY);
+
+ // 可选:叠加轻微模糊 (vagueImage),如果需要更柔和的效果
+ // $backgroundVo->vagueImage($bgX, $bgY);
}
}
}
@@ -105,25 +144,22 @@ class BlockImage extends BaseImage
/**
* 把$source的颜色复制到$target上
- * @param ImageVo $source
- * @param ImageVo $target
+ * @deprecated 新逻辑已内联到 cutByTemplate
*/
-
- protected function copyPickColor(ImageVo $source, $sourceX, $sourceY,ImageVo $target, $targetX, $targetY){
+ protected function copyPickColor(ImageVo $source, $sourceX, $sourceY, ImageVo $target, $targetX, $targetY)
+ {
$bgRgba = $source->getPickColor($sourceX, $sourceY);
- $target->setPixel($bgRgba, $targetX, $targetY);//复制背景图片给模板
+ $target->setPixel($bgRgba, $targetX, $targetY);
}
/**
* 返回前端需要的格式
- * @return false|string[]
+ * @return string Base64
*/
public function response($type = 'background')
{
$image = $type == 'background' ? $this->backgroundVo->image : $this->templateVo->image;
- $result = $image->encode('data-url')->getEncoded();
- //返回图片base64的第二部分
- return explode(',', $result)[1];
+ return ImageUtils::outputBase64($image, 'png');
}
/**
@@ -132,6 +168,8 @@ class BlockImage extends BaseImage
public function echo($type = 'background')
{
$image = $type == 'background' ? $this->backgroundVo->image : $this->templateVo->image;
- die($image->response());
+ header('Content-Type: image/png');
+ imagepng($image);
+ die;
}
}
diff --git a/service/php/src/Domain/Logic/Cache.php b/service/php/src/Domain/Logic/Cache.php
index cf35db12e8f1f52f67c169085e29d1def9afaa4a..032477c923e36075cd46acd4b664332a743efc7a 100644
--- a/service/php/src/Domain/Logic/Cache.php
+++ b/service/php/src/Domain/Logic/Cache.php
@@ -108,7 +108,7 @@ class Cache
}
protected function execute(string $method, array $params){
- return $this->driver->$method(...$params);
+ return $this->driver->$method(urlencode(array_shift($params)),...$params);
}
}
diff --git a/service/php/src/Domain/Logic/WordData.php b/service/php/src/Domain/Logic/WordData.php
index e4fba23fdf9efc73ead085b37dfeeb0094e5e868..4164cad3acad4fd1c8dca7d72fdb1e96f0e1ba8a 100644
--- a/service/php/src/Domain/Logic/WordData.php
+++ b/service/php/src/Domain/Logic/WordData.php
@@ -18,42 +18,77 @@ class WordData extends BaseData
/**
- * @param $width
- * @param $height
- * @param $index
- * @param $wordCount
- * @return PointVo
+ * 获取随机且不重叠的坐标列表
+ * @param int $width 画布宽度
+ * @param int $height 画布高度
+ * @param int $number 文字数量
+ * @return PointVo[]
*/
- protected function getPoint($width, $height, $index, $wordCount)
+ public function getPointList($width, $height, $number = 3): array
{
- $avgWidth = $width / ($wordCount + 1);
- if ($avgWidth < self::FONTSIZE) {
- $x = RandomUtils::getRandomInt(1 + self::FONTSIZE, $width);
- } else {
- if ($index == 0) {
- $x = RandomUtils::getRandomInt(1 + self::FONTSIZE, $avgWidth * ($index + 1) - self::FONTSIZE);
- } else {
- $x = RandomUtils::getRandomInt($avgWidth * $index + self::FONTSIZE, $avgWidth * ($index + 1) - self::FONTSIZE);
+ $pointList = [];
+ $maxRetries = 100; // 最大重试次数
+ $fontSize = self::FONTSIZE;
+ // 碰撞检测距离阈值 (增加一点 buffer)
+ $collisionDistance = $fontSize * 1.2;
+
+ for ($i = 0; $i < $number; $i++) {
+ $retry = 0;
+ $success = false;
+
+ while ($retry < $maxRetries) {
+ // 随机生成坐标 (考虑文字绘制基准点和边界)
+ // 文字通常以左下角为基准,或者左上角,取决于 ImageUtils 实现。
+ // ImageUtils::text 修正了对齐,如果 align=left, valign=bottom (默认)
+ // x: 0 ~ width - fontSize
+ // y: fontSize ~ height
+
+ $x = RandomUtils::getRandomInt($fontSize, $width - $fontSize);
+ $y = RandomUtils::getRandomInt($fontSize, $height - $fontSize);
+
+ $currentPoint = new PointVo($x, $y);
+
+ // 碰撞检测
+ if (!$this->isColliding($currentPoint, $pointList, $collisionDistance)) {
+ $pointList[] = $currentPoint;
+ $success = true;
+ break;
+ }
+ $retry++;
+ }
+
+ // 如果重试多次仍失败(可能是字太多图太小),强制添加一个(可能会重叠),或者抛异常。
+ // 为了健壮性,我们允许轻微重叠或尝试放宽条件,这里简单处理:强制添加。
+ if (!$success) {
+ // 兜底:尝试网格化或直接添加
+ // 简单添加,避免死循环
+ $pointList[] = new PointVo(
+ RandomUtils::getRandomInt($fontSize, $width - $fontSize),
+ RandomUtils::getRandomInt($fontSize, $height - $fontSize)
+ );
}
}
- $y = RandomUtils::getRandomInt(self::FONTSIZE, $height - self::FONTSIZE);
- return new PointVo($x, $y);
+
+ return $pointList;
}
-
+
/**
- * @param $width
- * @param $height
- * @param int $number
- * @return array
+ * 检测是否碰撞
+ * @param PointVo $current
+ * @param PointVo[] $existingList
+ * @param float $minDist
+ * @return bool
*/
- public function getPointList($width, $height, $number = 3): array
+ private function isColliding(PointVo $current, array $existingList, float $minDist): bool
{
- $pointList = [];
- for ($i = 0; $i < $number; $i++) {
- $pointList[] = $this->getPoint($width, $height, $i, $number);
+ foreach ($existingList as $point) {
+ // 计算欧氏距离
+ $dist = sqrt(pow($current->x - $point->x, 2) + pow($current->y - $point->y, 2));
+ if ($dist < $minDist) {
+ return true;
+ }
}
- shuffle($pointList); //随机排序
- return $pointList;
+ return false;
}
@@ -83,7 +118,12 @@ class WordData extends BaseData
public function check(array $originPointList, array $targetPointList)
{
foreach ($originPointList as $key => $originPoint) {
+ if (!isset($targetPointList[$key])) {
+ throw new WordException('验证失败: 坐标数量不匹配');
+ }
$targetPoint = $targetPointList[$key];
+ // 校验逻辑:目标点是否在原始点的一定范围内
+ // FONTSIZE 作为容错半径
if ($targetPoint->x - self::FONTSIZE > $originPoint->x
|| $targetPoint->x > $originPoint->x + self::FONTSIZE
|| $targetPoint->y - self::FONTSIZE > $originPoint->y
diff --git a/service/php/src/Domain/Logic/WordImage.php b/service/php/src/Domain/Logic/WordImage.php
index 96d600c530fb8203254322f55e1b4aa27ee7b31d..2136964a2f660bbdb58c5964eee860497cc7262c 100644
--- a/service/php/src/Domain/Logic/WordImage.php
+++ b/service/php/src/Domain/Logic/WordImage.php
@@ -4,8 +4,7 @@ declare(strict_types=1);
namespace Fastknife\Domain\Logic;
use Fastknife\Domain\Vo\PointVo;
-use Intervention\Image\ImageManagerStatic as ImageManager;
-use Intervention\Image\AbstractFont as Font;
+use Fastknife\Utils\ImageUtils;
use Fastknife\Utils\RandomUtils;
/**
@@ -20,6 +19,11 @@ class WordImage extends BaseImage
* @var array
*/
protected $wordList;
+
+ /**
+ * @var int 目标字数 (Service 层需要缓存前 N 个)
+ */
+ protected $targetCount = 0;
/**
@@ -35,6 +39,34 @@ class WordImage extends BaseImage
{
return $this->wordList;
}
+
+ public function setTargetCount(int $count)
+ {
+ $this->targetCount = $count;
+ return $this;
+ }
+
+ /**
+ * 获取仅包含目标字的列表 (供 Service 使用)
+ */
+ public function getTargetWordList()
+ {
+ if ($this->targetCount > 0) {
+ return array_slice($this->wordList, 0, $this->targetCount);
+ }
+ return $this->wordList;
+ }
+
+ /**
+ * 获取仅包含目标字的坐标 (供 Service 使用)
+ */
+ public function getTargetPointList()
+ {
+ if ($this->targetCount > 0) {
+ return array_slice($this->point, 0, $this->targetCount);
+ }
+ return $this->point;
+ }
@@ -50,26 +82,31 @@ class WordImage extends BaseImage
protected function inputWords(){
foreach ($this->wordList as $key => $word) {
$point = $this->point[$key];
- $this->backgroundVo->image->text($word, $point->x, $point->y, function (Font $font) {
- $font->file($this->fontFile);
- $font->size(BaseData::FONTSIZE);
- $font->color(RandomUtils::getRandomColor());
- $font->angle(RandomUtils::getRandomAngle());
- $font->align('center');
- $font->valign('center');
- });
+ // 使用 ImageUtils 替换 Intervention
+ ImageUtils::text(
+ $this->backgroundVo->image,
+ $word,
+ $point->x,
+ $point->y,
+ $this->fontFile,
+ BaseData::FONTSIZE,
+ RandomUtils::getRandomColor(), // [r, g, b, a]
+ (float)RandomUtils::getRandomAngle(), // angle
+ 'left', // align (ImageUtils::text 修正逻辑基于左下角,这里我们假设 point 是左下角或者中心,原逻辑是 center/center)
+ // 原逻辑 align('center') valign('center')。
+ // ImageUtils::text 实现了 center/center 修正。
+ 'center'
+ );
}
}
/**
* 返回前端需要的格式
- * @return false|string[]
+ * @return string Base64
*/
public function response()
{
- $result = $this->getBackgroundVo()->image->encode('data-url')->getEncoded();
- //返回图片base64的第二部分
- return explode(',', $result)[1];
+ return ImageUtils::outputBase64($this->getBackgroundVo()->image, 'png');
}
/**
@@ -77,7 +114,9 @@ class WordImage extends BaseImage
*/
public function echo()
{
- die($this->getBackgroundVo()->image->response());
+ header('Content-Type: image/png');
+ imagepng($this->getBackgroundVo()->image);
+ die;
}
}
diff --git a/service/php/src/Domain/Template/DrawingTemplateProvider.php b/service/php/src/Domain/Template/DrawingTemplateProvider.php
new file mode 100644
index 0000000000000000000000000000000000000000..47787cf6e6f75942ff0d8c06d06611dcb7004dc1
--- /dev/null
+++ b/service/php/src/Domain/Template/DrawingTemplateProvider.php
@@ -0,0 +1,132 @@
+shapeType = $config['block_puzzle']['shape_type'] ?? 'jigsaw';
+ $this->sliderWidth = $config['block_puzzle']['slider_width'] ?? 47;
+ }
+
+ public function getTemplateVo(int $bgWidth, int $bgHeight): TemplateVo
+ {
+ // 1. 获取或生成高质量 Mask(原始尺寸,仅形状高度)
+ $maskImage = $this->getMaskImage();
+ $maskImage = ImageUtils::resize($maskImage, $this->sliderWidth, $this->sliderWidth);
+
+ $tmplW = imagesx($maskImage);
+ $tmplH = imagesy($maskImage);
+
+ $padded = ImageUtils::create($tmplW, $bgHeight);
+ imagecopy($padded, $maskImage, 0, 5, 0, 0, $tmplW, $tmplH);
+
+ ImageUtils::destroy($maskImage);
+
+ $templateVo = new TemplateVo(null); // src 为 null
+ $templateVo->image = $padded; // 注入已填充到背景高度的资源
+
+ $bgHalfWidth = intval($bgWidth / 2);
+ $tmplWidth = imagesx($padded);
+
+ $maxOffsetX = $bgHalfWidth - $tmplWidth - 1;
+ $maxOffsetX = max(0, $maxOffsetX);
+
+ $offset = RandomUtils::getRandomInt(0, $maxOffsetX);
+
+ $templateVo->setOffset(new OffsetVo($offset + $bgHalfWidth, 0));
+
+ return $templateVo;
+ }
+
+ public function getInterfereVo(int $bgWidth, int $bgHeight, TemplateVo $targetVo): TemplateVo
+ {
+ $maskImage = $this->getMaskImage();
+ $maskImage = ImageUtils::resize($maskImage, $this->sliderWidth, $this->sliderWidth);
+
+ $tmplW = imagesx($maskImage);
+ $tmplH = imagesy($maskImage);
+ $padded = ImageUtils::create($tmplW, $bgHeight);
+ imagecopy($padded, $maskImage, 0, 0, 0, 0, $tmplW, $tmplH);
+ ImageUtils::destroy($maskImage);
+
+ $interfereVo = new TemplateVo(null);
+ $interfereVo->image = $padded;
+
+ $bgHalfWidth = intval($bgWidth / 2);
+ $tmplWidth = imagesx($padded);
+
+ $maxOffsetX = $bgHalfWidth - $tmplWidth - 5;
+ $maxOffsetX = max(0, $maxOffsetX);
+
+ $offset = RandomUtils::getRandomInt(5, $maxOffsetX);
+
+ $tmplHeight = $tmplH;
+ $maxOffsetY = $bgHeight - $tmplHeight;
+ $maxOffsetY = max(0, $maxOffsetY);
+
+ $minDistance = $tmplHeight;
+ $targetY = $targetVo->offset->y;
+ $maxRetries = 20;
+ $retry = 0;
+
+ do {
+ $y = RandomUtils::getRandomInt(0, $maxOffsetY);
+ $retry++;
+ } while (abs($y - $targetY) < $minDistance && $retry < $maxRetries);
+
+ $interfereVo->setOffset(new OffsetVo($offset, $y));
+
+ return $interfereVo;
+ }
+
+
+ /**
+ * 获取 Mask 图像资源 (单例缓存)
+ * @return resource|\GdImage
+ */
+ private function getMaskImage()
+ {
+ return $this->drawMask();
+ }
+
+ private function drawMask()
+ {
+ // 使用 ShapeFactory 创建 Drawer
+ $drawer = ShapeFactory::create($this->shapeType);
+
+ // 获取未缩放的大图
+ $big = $drawer->createMask($this->scale);
+
+ // 高斯模糊 (进一步平滑边缘,去除锯齿)
+ imagefilter($big, IMG_FILTER_GAUSSIAN_BLUR);
+
+ // 获取原始尺寸
+ $originalSize = $drawer->getOriginalSize();
+ $targetW = $originalSize[0];
+ $targetH = $originalSize[1];
+
+ // 5. 下采样缩放 (Super Sampling)
+ $block = ImageUtils::resize($big, $targetW, $targetH);
+
+ // 6. 清理大图
+ ImageUtils::destroy($big);
+
+ return $block;
+ }
+}
diff --git a/service/php/src/Domain/Template/ResourceTemplateProvider.php b/service/php/src/Domain/Template/ResourceTemplateProvider.php
new file mode 100644
index 0000000000000000000000000000000000000000..81f672b0a6f969f8cc0d5f3d4947ff626f6ba7dd
--- /dev/null
+++ b/service/php/src/Domain/Template/ResourceTemplateProvider.php
@@ -0,0 +1,134 @@
+templates = $config['block_puzzle']['templates'] ?? [];
+ $this->isCachePixel = $config['block_puzzle']['is_cache_pixel'] ?? false;
+ }
+
+ public function setCache(Cache $cache)
+ {
+ $this->cache = $cache;
+ }
+
+ public function getTemplateVo(int $bgWidth, int $bgHeight): TemplateVo
+ {
+ // 初始偏移量,让模板图在背景的右1/2位置
+ $bgHalfWidth = intval($bgWidth / 2);
+
+ // 随机获取一张图片
+ $src = $this->getRandImage($this->getTemplateImages($this->templates));
+
+ $templateVo = new TemplateVo($src);
+
+ // 处理像素缓存
+ $this->handlePixelCache($templateVo, $src);
+
+ // 随机获取偏移量
+ // x: 在右半部分随机
+ $maxOffsetX = $bgHalfWidth - imagesx($templateVo->image) - 1;
+ // 防止负数(图片太宽时)
+ $maxOffsetX = max(0, $maxOffsetX);
+
+ $offset = RandomUtils::getRandomInt(0, $maxOffsetX);
+
+ $templateVo->setOffset(new OffsetVo($offset + $bgHalfWidth, 0));
+
+ return $templateVo;
+ }
+
+ public function getInterfereVo(int $bgWidth, int $bgHeight, TemplateVo $targetVo): TemplateVo
+ {
+ // 干扰图逻辑 (复用旧逻辑)
+ // 1. 随机选一张图
+ $src = $this->getRandImage($this->getTemplateImages($this->templates));
+ $interfereVo = new TemplateVo($src);
+
+ // 处理像素缓存
+ $this->handlePixelCache($interfereVo, $src);
+
+ // 2. 随机位置 (要避开目标)
+ $width = imagesx($interfereVo->image);
+ $bgHalfWidth = intval($bgWidth / 2);
+
+ $maxOffsetX = $bgHalfWidth - $width - 5;
+ $maxOffsetX = max(0, $maxOffsetX);
+
+ $x = RandomUtils::getRandomInt(5, $maxOffsetX); // 左侧
+
+ // y 轴随机 (0 ~ bgHeight - tmplHeight)
+ $height = imagesy($interfereVo->image);
+ $maxOffsetY = $bgHeight - $height;
+ $maxOffsetY = max(0, $maxOffsetY);
+
+ // 确保 Y 轴不与目标重叠 (minDistance = height)
+ $minDistance = $height;
+ $targetY = $targetVo->offset->y;
+ $maxRetries = 20;
+ $retry = 0;
+
+ do {
+ $y = RandomUtils::getRandomInt(0, $maxOffsetY);
+ $retry++;
+ } while (abs($y - $targetY) < $minDistance && $retry < $maxRetries);
+
+ $interfereVo->setOffset(new OffsetVo($x, $y));
+
+ return $interfereVo;
+ }
+
+
+ protected function getTemplateImages($templates = [])
+ {
+ $dir = dirname(__DIR__, 3) . '/resources/defaultImages/jigsaw/slidingBlock/';
+ return $this->getDefaultImage($dir, $templates);
+ }
+
+ /**
+ * 处理像素缓存逻辑
+ */
+ private function handlePixelCache(TemplateVo $vo, string $src)
+ {
+ // 只有开启了缓存且 Cache 实例已注入才执行
+ if (!$this->isCachePixel || !$this->cache) {
+ return;
+ }
+
+ // 生成缓存 Key (避免文件名冲突)
+ $cacheKey = 'aj_pixel_' . md5($src);
+
+ // 尝试从缓存读取
+ $pickMaps = $this->cache->get($cacheKey);
+
+ if (!empty($pickMaps) && is_array($pickMaps)) {
+ $vo->setPickMaps($pickMaps);
+ return;
+ }
+
+ // 缓存未命中,计算并写入
+ $vo->preparePickMaps();
+ $pickMaps = $vo->getPickMaps();
+
+ // 永久缓存 (或者设置一个较长的过期时间,如 30 天)
+ $this->cache->set($cacheKey, $pickMaps, 86400 * 30);
+ }
+}
diff --git a/service/php/src/Domain/Template/Shape/ClubShapeDrawer.php b/service/php/src/Domain/Template/Shape/ClubShapeDrawer.php
new file mode 100644
index 0000000000000000000000000000000000000000..c24c0775a32f60d55f4b50aef5331ba6ccf1d4fd
--- /dev/null
+++ b/service/php/src/Domain/Template/Shape/ClubShapeDrawer.php
@@ -0,0 +1,104 @@
+width, $this->height];
+ }
+
+ public function createMask(int $scale)
+ {
+ $w = $this->width * $scale;
+ $h = $this->height * $scale;
+
+ $big = ImageUtils::create($w, $h);
+ imageantialias($big, true);
+
+ $contentColor = imagecolorallocatealpha($big, 220, 220, 220, 40);
+ $shadowColor = imagecolorallocatealpha($big, 255, 255, 255, 50);
+
+ $cx = $w / 2;
+ $cy = $h / 2 - 4 * $scale;
+
+ // 3个圆的半径
+ $r = 11 * $scale;
+
+ // 顶部圆心
+ $c1x = $cx;
+ $c1y = $cy - $r + 2 * $scale;
+
+ // 左下圆心 (30度偏移)
+ $c2x = $cx - $r * 0.9;
+ $c2y = $cy + $r * 0.6;
+
+ // 右下圆心
+ $c3x = $cx + $r * 0.9;
+ $c3y = $cy + $r * 0.6;
+
+ // 绘制3个圆 (填充 + 描边)
+ // 为了消除重叠部分的描边,我们先画描边,再画填充?
+ // 不,应该先画所有实心,再画所有描边。
+ // 但是 GD 没有 "union" 操作。
+ // 简单的模拟:先画3个带描边的圆。重叠处会有交叉线。
+ // 然后再画3个略小一点的圆(或同等大小)只填充内容色,覆盖掉内部的交叉线。
+
+ // 1. 画描边 (实心+描边)
+ // imagefilledellipse + imageellipse
+ $this->drawCircle($big, $c1x, $c1y, $r, $contentColor, $shadowColor);
+ $this->drawCircle($big, $c2x, $c2y, $r, $contentColor, $shadowColor);
+ $this->drawCircle($big, $c3x, $c3y, $r, $contentColor, $shadowColor);
+
+ // 2. 绘制柄
+ $stemW = 5 * $scale;
+ $stemH = 15 * $scale;
+ $stemTopY = $cy;
+ $stemBottomY = $h - 2 * $scale;
+
+ $stemPoints = [
+ $cx, $stemTopY,
+ $cx + $stemW, $stemBottomY,
+ $cx - $stemW, $stemBottomY
+ ];
+ imagefilledpolygon($big, $stemPoints, 3, $contentColor);
+ imagepolygon($big, $stemPoints, 3, $shadowColor);
+
+ // 3. 再次填充内容色 (覆盖内部重叠的线条)
+ // 注意:contentColor 是半透明的。叠加会变深。
+ // 这是一个问题。如果再次叠加,颜色会不对。
+ // 除非我们用一个完全不透明的颜色画 Mask,最后再转为半透明?
+ // 或者,我们不画圆的描边,而是画一个外轮廓。
+ // 计算外轮廓太复杂。
+
+ // 妥协方案:
+ // 草花比较复杂,我们接受内部有轻微的交叉线(视为纹理),
+ // 或者调整 contentColor 的 Alpha,让叠加不那么明显。
+ // 但目前架构中,maskAlpha 决定了最终的透明度。
+
+ // 另一种方案:只画填充,不画描边。
+ // 描边由 BlockImage 的 RGB 识别逻辑处理。
+ // 如果我们不画白色描边,BlockImage 就识别不到描边。
+
+ // 最佳方案:用 filledellipse 画内容。
+ // 然后手动画圆弧(arc)来做描边,只画外侧部分。
+ // 这需要计算角度。
+
+ // 简化版:接受交叉线。草花本身就是三叶草,叶瓣之间有纹理也很正常。
+
+ return $big;
+ }
+
+ private function drawCircle($img, $cx, $cy, $r, $fill, $stroke) {
+ $d = $r * 2;
+ imagefilledellipse($img, (int)$cx, (int)$cy, (int)$d, (int)$d, $fill);
+ imageellipse($img, (int)$cx, (int)$cy, (int)$d, (int)$d, $stroke);
+ }
+}
diff --git a/service/php/src/Domain/Template/Shape/DiamondShapeDrawer.php b/service/php/src/Domain/Template/Shape/DiamondShapeDrawer.php
new file mode 100644
index 0000000000000000000000000000000000000000..c41552ea090ff2dc72cad5eebcbcb70bd50f8e58
--- /dev/null
+++ b/service/php/src/Domain/Template/Shape/DiamondShapeDrawer.php
@@ -0,0 +1,51 @@
+width, $this->height];
+ }
+
+ public function createMask(int $scale)
+ {
+ $w = $this->width * $scale;
+ $h = $this->height * $scale;
+
+ $big = ImageUtils::create($w, $h);
+ imageantialias($big, true);
+
+ $contentColor = imagecolorallocatealpha($big, 220, 220, 220, 40);
+ $shadowColor = imagecolorallocatealpha($big, 255, 255, 255, 50);
+
+ // 绘制方片 (菱形)
+ $cx = $w / 2;
+ $cy = $h / 2;
+
+ // 留一点边距
+ $margin = 2 * $scale;
+ $halfW = ($w / 2) - $margin;
+ $halfH = ($h / 2) - $margin;
+
+ $points = [
+ $cx, $margin, // Top
+ $w - $margin, $cy, // Right
+ $cx, $h - $margin, // Bottom
+ $margin, $cy // Left
+ ];
+
+ $numPoints = count($points) / 2;
+ imagefilledpolygon($big, $points, (int)$numPoints, $contentColor);
+ imagepolygon($big, $points, (int)$numPoints, $shadowColor);
+
+ return $big;
+ }
+}
diff --git a/service/php/src/Domain/Template/Shape/JigsawShapeDrawer.php b/service/php/src/Domain/Template/Shape/JigsawShapeDrawer.php
new file mode 100644
index 0000000000000000000000000000000000000000..b019a3dce2cf8f9a32c948db42cef372233bf444
--- /dev/null
+++ b/service/php/src/Domain/Template/Shape/JigsawShapeDrawer.php
@@ -0,0 +1,88 @@
+sliderL + $this->sliderR * 2 + 3;
+ return [$L, $L];
+ }
+
+ public function createMask(int $scale)
+ {
+ $L = $this->getOriginalSize()[0];
+ $bigL = $L * $scale;
+
+ // 1. 创建放大画布
+ $big = ImageUtils::create($bigL, $bigL);
+ imageantialias($big, true);
+
+ // 2. 绘制参数
+ $sliderL = $this->sliderL;
+ $sliderR = $this->sliderR;
+
+ // 浅灰半透明内容占位
+ $contentColor = imagecolorallocatealpha($big, 220, 220, 220, 40);
+ // 白色半透明阴影
+ $shadowColor = imagecolorallocatealpha($big, 255, 255, 255, 50);
+
+ // 3. 计算路径点
+ $px = 3 * $scale;
+ $py = ($sliderR * 2 + 1) * $scale;
+ $PI = M_PI;
+ $points = [];
+
+ // 起点
+ $points[] = $px; $points[] = $py;
+
+ // 上方凸弧
+ $cx = $px + ($sliderL / 2) * $scale;
+ $cy = $py - $sliderR * $scale + 2 * $scale;
+ for ($a = 0.72*$PI; $a <= 2.26*$PI; $a += 0.03 / $scale) {
+ $points[] = $cx + $sliderR * $scale * cos($a);
+ $points[] = $cy + $sliderR * $scale * sin($a);
+ }
+
+ // 右上角
+ $points[] = $px + $sliderL * $scale;
+ $points[] = $py;
+
+ // 右侧凸弧
+ $cx = $px + $sliderL * $scale + $sliderR * $scale - 2 * $scale;
+ $cy = $py + ($sliderL / 2) * $scale;
+ for ($a = 1.21*$PI; $a <= 2.78*$PI; $a += 0.03 / $scale) {
+ $points[] = $cx + $sliderR * $scale * cos($a);
+ $points[] = $cy + $sliderR * $scale * sin($a);
+ }
+
+ // 右下 -> 左下
+ $points[] = $px + $sliderL * $scale; $points[] = $py + $sliderL * $scale;
+ $points[] = $px; $points[] = $py + $sliderL * $scale;
+
+ // 下方凹弧 (逆向)
+ $cx = $px + $sliderR * $scale - 2 * $scale;
+ $cy = $py + ($sliderL / 2) * $scale;
+ for ($a = 2.76*$PI; $a >= 1.24*$PI; $a -= 0.03 / $scale) {
+ $points[] = $cx + ($sliderR + 0.4) * $scale * cos($a);
+ $points[] = $cy + ($sliderR + 0.4) * $scale * sin($a);
+ }
+
+ // 闭合
+ $points[] = $px; $points[] = $py;
+
+ // 4. 绘制多边形
+ $numPoints = count($points) / 2;
+ imagefilledpolygon($big, $points, (int)$numPoints, $contentColor);
+ imagepolygon($big, $points, (int)$numPoints, $shadowColor);
+
+ return $big;
+ }
+}
diff --git a/service/php/src/Domain/Template/Shape/RedHeartShapeDrawer.php b/service/php/src/Domain/Template/Shape/RedHeartShapeDrawer.php
new file mode 100644
index 0000000000000000000000000000000000000000..e5e20443cf4e6a460d9a84a7a159013a2a6ec715
--- /dev/null
+++ b/service/php/src/Domain/Template/Shape/RedHeartShapeDrawer.php
@@ -0,0 +1,61 @@
+width, $this->height];
+ }
+
+ public function createMask(int $scale)
+ {
+ $w = $this->width * $scale;
+ $h = $this->height * $scale;
+
+ $big = ImageUtils::create($w, $h);
+ imageantialias($big, true);
+
+ $contentColor = imagecolorallocatealpha($big, 220, 220, 220, 40);
+ $shadowColor = imagecolorallocatealpha($big, 255, 255, 255, 50);
+
+ // 绘制心形 (贝塞尔曲线模拟)
+ // 心形方程:
+ // x = 16 * sin^3(t)
+ // y = 13 * cos(t) - 5 * cos(2t) - 2 * cos(3t) - cos(4t)
+
+ // 归一化并缩放到画布
+ $centerX = $w / 2;
+ $centerY = $h / 2; // 稍微偏上一点?心形尖端在下
+ // 心形高度约 34单位 (-17~+17),宽度约 32单位 (-16~+16)
+ // 我们需要把它撑满 $w, $h
+ // 放大系数 R
+ $R = min($w, $h) / 35;
+
+ $points = [];
+ for ($t = 0; $t <= 2 * M_PI; $t += 0.01) {
+ $x = 16 * pow(sin($t), 3);
+ $y = 13 * cos($t) - 5 * cos(2*$t) - 2 * cos(3*$t) - cos(4*$t);
+
+ // 翻转Y轴 (GD y向下增加)
+ $px = $centerX + $x * $R;
+ $py = $centerY - $y * $R;
+
+ $points[] = $px;
+ $points[] = $py;
+ }
+
+ $numPoints = count($points) / 2;
+ imagefilledpolygon($big, $points, (int)$numPoints, $contentColor);
+ imagepolygon($big, $points, (int)$numPoints, $shadowColor);
+
+ return $big;
+ }
+}
diff --git a/service/php/src/Domain/Template/Shape/ShapeDrawerInterface.php b/service/php/src/Domain/Template/Shape/ShapeDrawerInterface.php
new file mode 100644
index 0000000000000000000000000000000000000000..10daffd0f495394db35690d957fdfff751a5ccb1
--- /dev/null
+++ b/service/php/src/Domain/Template/Shape/ShapeDrawerInterface.php
@@ -0,0 +1,20 @@
+width, $this->height];
+ }
+
+ public function createMask(int $scale)
+ {
+ $w = $this->width * $scale;
+ $h = $this->height * $scale;
+
+ $big = ImageUtils::create($w, $h);
+ imageantialias($big, true);
+
+ $contentColor = imagecolorallocatealpha($big, 220, 220, 220, 40);
+ $shadowColor = imagecolorallocatealpha($big, 255, 255, 255, 50);
+
+ $centerX = $w / 2;
+ $centerY = $h / 2 - 5 * $scale; // 心形主体稍微上移
+
+ // 放大系数 R
+ $R = min($w, $h) / 38;
+
+ $points = [];
+
+ // 1. 倒置心形主体
+ // t 从 PI 到 -PI (或者 0 到 2PI)
+ // 倒置:y 取反
+ for ($t = 0; $t <= 2 * M_PI; $t += 0.02) {
+ $x = 16 * pow(sin($t), 3);
+ $y = 13 * cos($t) - 5 * cos(2*$t) - 2 * cos(3*$t) - cos(4*$t);
+
+ // 倒置心形
+ $y = -$y;
+
+ $px = $centerX + $x * $R;
+ $py = $centerY - $y * $R;
+
+ $points[] = $px;
+ $points[] = $py;
+ }
+
+ // 2. 底部柄 (三角形/梯形)
+ // 倒置心形的尖端在上方,凹陷在下方
+ // 这里的方程生成的倒置心形,尖端(0, 0)其实是在坐标系原点。
+ // 原方程 t=0 时 y=13-5-2-1=5 (最高点)。倒置后 y=-5 (最低点)。
+ // 实际上我们需要根据图形调整。
+ // 为了简化,我们直接绘制一个倒置心形,然后再画一个三角形柄。
+
+ // 重新计算主体点集,这次我们要更精细控制,以便和柄融合。
+ // 但为了简单,我们可以分别画两个形状。
+ // 不过为了描边(stroke)连续,最好合并点集。这比较复杂。
+ // 简单的做法:画两个 filledpolygon,然后画两个 polygon 描边。虽然重叠处会有双重描边,但在 Mask 缩放后不太明显。
+
+ // 绘制主体
+ $numPoints = count($points) / 2;
+ imagefilledpolygon($big, $points, (int)$numPoints, $contentColor);
+ imagepolygon($big, $points, (int)$numPoints, $shadowColor);
+
+ // 绘制柄 (梯形)
+ $stemW = 6 * $scale;
+ $stemH = 10 * $scale;
+ $stemTopY = $centerY + 10 * $scale; // 这里的数值需要微调以接合心形底部
+ $stemBottomY = $h - 2 * $scale;
+
+ // 计算心形底部凹陷点的大致位置
+ // 倒置心形底部是两个圆弧的交界?不,原方程心形尖端在下。倒置后尖端在上。
+ // 那么底部就是两个圆弧。
+ // 实际上黑桃是:尖端在上,底部两个圆弧,中间伸出一个柄。
+ // 等等,扑克牌黑桃 ♠ 是尖端朝上的。
+ // 原心形方程:尖端朝下。
+ // 所以倒置后,尖端朝上。正确。
+ // 底部是两个圆弧的凹陷处。
+
+ // 绘制柄
+ $stemPoints = [
+ $centerX, $stemTopY - 5 * $scale, // 插入心形内部一点
+ $centerX + $stemW, $stemBottomY,
+ $centerX - $stemW, $stemBottomY
+ ];
+
+ imagefilledpolygon($big, $stemPoints, 3, $contentColor);
+ imagepolygon($big, $stemPoints, 3, $shadowColor);
+
+ // 修复:为了遮盖重叠处的描边,再次填充一次主体和柄的内部(无描边)
+ imagefilledpolygon($big, $points, (int)$numPoints, $contentColor);
+ imagefilledpolygon($big, $stemPoints, 3, $contentColor);
+
+ return $big;
+ }
+}
diff --git a/service/php/src/Domain/Template/TemplateProviderInterface.php b/service/php/src/Domain/Template/TemplateProviderInterface.php
new file mode 100644
index 0000000000000000000000000000000000000000..dd81a768cb39639d0e9c81a7c7bd409ae9c3c263
--- /dev/null
+++ b/service/php/src/Domain/Template/TemplateProviderInterface.php
@@ -0,0 +1,26 @@
+image = ImageManagerStatic::make($src);
+ // 如果 $src 是 null (Drawing 模式手动注入) 则不处理
+ if ($src !== null) {
+ $this->image = ImageUtils::read($src);
+ }
}
/**
* 获取图片中某一个位置的rgba值
* @param $x
* @param $y
- * @return array
+ * @return array [r, g, b, a] (a: 0-1 float for compat, or 0-127 int? Intervention v2 returns a as 0-1 float where 0 is transparent?)
+ * Intervention v2 pickColor:
+ * array(4) {
+ * [0] => int(255)
+ * [1] => int(255)
+ * [2] => int(255)
+ * [3] => float(1) // 1 is opaque, 0 is transparent? Or 0 is opaque?
+ * }
+ * Intervention v2: alpha 0 (transparent) -> 1 (opaque).
+ * GD: 0 (opaque) -> 127 (transparent).
+ *
+ * 为了兼容旧代码 check 逻辑: $this->getPickColor($x, $y)[3] > 0.5 (opaque)
+ * 我们需要把 GD 的 0-127 转换为 0-1 (opaque).
+ * GD: 0 -> 1.0, 127 -> 0.0
*/
public function getPickColor($x, $y): array
{
if (!isset($this->pickMaps[$x][$y])) {
- $this->pickMaps[$x][$y] = $this->image->pickColor($x, $y);
+ $rgb = imagecolorat($this->image, (int)$x, (int)$y);
+ $colors = imagecolorsforindex($this->image, $rgb);
+
+ // Convert GD alpha (0-127 transparent) to Intervention alpha (0-1 opaque)
+ // 127 (transparent) -> 0
+ // 0 (opaque) -> 1
+ $alpha = 1 - ($colors['alpha'] / 127);
+
+ $this->pickMaps[$x][$y] = [
+ $colors['red'],
+ $colors['green'],
+ $colors['blue'],
+ $alpha
+ ];
}
return $this->pickMaps[$x][$y];
}
@@ -47,10 +75,23 @@ abstract class ImageVo
/**
* 设置图片指定位置的颜色值
+ * @param array $color [r, g, b, a] (Intervention format)
+ * @param int $x
+ * @param int $y
*/
public function setPixel($color, $x, $y)
{
- $this->image->pixel($color, $x, $y);
+ // Convert Intervention alpha to GD alpha
+ // 1 (opaque) -> 0
+ // 0 (transparent) -> 127
+ $alpha = 0;
+ if (isset($color[3])) {
+ $alpha = (int)((1 - $color[3]) * 127);
+ }
+
+ $col = imagecolorallocatealpha($this->image, $color[0], $color[1], $color[2], $alpha);
+ imagesetpixel($this->image, (int)$x, (int)$y, $col);
+ // imagecolorallocatealpha 可能会耗尽调色板 (对于真彩色不需要担心)
}
/**
@@ -65,6 +106,9 @@ abstract class ImageVo
$green = [];
$blue = [];
$alpha = [];
+ $w = imagesx($image);
+ $h = imagesy($image);
+
foreach ([
[0, 1], [0, -1],
[1, 0], [-1, 0],
@@ -74,7 +118,7 @@ abstract class ImageVo
{
$pointX = $x + $distance[0];
$pointY = $y + $distance[1];
- if ($pointX < 0 || $pointX >= $image->getWidth() || $pointY < 0 || $pointY >= $image->height()) {
+ if ($pointX < 0 || $pointX >= $w || $pointY < 0 || $pointY >= $h) {
continue;
}
[$r, $g, $b, $a] = $this->getPickColor($pointX, $pointY);
@@ -83,7 +127,12 @@ abstract class ImageVo
$blue[] = $b;
$alpha[] = $a;
}
- return [MathUtils::avg($red), MathUtils::avg($green), MathUtils::avg($blue), MathUtils::avg($alpha)];
+ return [MathUtils::avg($red), MathUtils::avg($green), MathUtils::avg($blue), MathUtils::avg($alpha)]; // Note: avg returns int, but alpha is float. MathUtils::avg casts to int?
+ // MathUtils::avg returns intval. So alpha 0.5 -> 0.
+ // 这会导致半透明信息丢失。
+ // 原有逻辑: MathUtils::avg($alpha) -> intval.
+ // 看来原有逻辑本身就不支持半透明模糊。
+ // 暂时保持兼容。
}
@@ -108,7 +157,10 @@ abstract class ImageVo
public function isBoundary(bool $isOpacity, int $x, int $y): bool
{
$image = $this->image;
- if ($x >= $image->width() - 1 || $y >= $image->height() - 1) {
+ $w = imagesx($image);
+ $h = imagesy($image);
+
+ if ($x >= $w - 1 || $y >= $h - 1) {
return false;
}
$right = [$x + 1, $y];
@@ -157,8 +209,8 @@ abstract class ImageVo
*/
public function preparePickMaps()
{
- $width = $this->image->getWidth();
- $height = $this->image->getHeight();
+ $width = imagesx($this->image);
+ $height = imagesy($this->image);
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$this->getPickColor($x, $y);
@@ -175,5 +227,7 @@ abstract class ImageVo
if(!empty($this->finishCallback) && $this->finishCallback instanceof \Closure){
($this->finishCallback)($this);
}
+ // 释放 GD 资源
+ ImageUtils::destroy($this->image);
}
-}
\ No newline at end of file
+}
diff --git a/service/php/src/Service/BlockPuzzleCaptchaService.php b/service/php/src/Service/BlockPuzzleCaptchaService.php
index 2eaffd1bec2c7e27ec574ee5e19ee76798524f5e..d5302a29b7d9ea28c33afeb65d1979a05899f21d 100644
--- a/service/php/src/Service/BlockPuzzleCaptchaService.php
+++ b/service/php/src/Service/BlockPuzzleCaptchaService.php
@@ -27,20 +27,17 @@ class BlockPuzzleCaptchaService extends Service
$cacheEntity->set($data['token'], [
'secretKey' => $data['secretKey'],
'point' => $blockImage->getPoint()
- ], 7200);
+ ], $this->factory->getConfig()['cache']['options']['expire'] ?? 300);
return $data;
}
-
-
/**
* 验证
* @param string $token
* @param string $pointJson
- * @param null $callback
*/
- public function validate( $token, $pointJson, $callback = null)
+ public function validate($token, $pointJson)
{
//获取并设置 $this->originData
$this->setOriginData($token);
@@ -49,13 +46,10 @@ class BlockPuzzleCaptchaService extends Service
$blockData = $this->factory->makeBlockData();
//解码出来的前端坐标
- $targetPoint = $this->encodePoint($this->originData['secretKey'], $pointJson);;
+ $targetPoint = $this->encodePoint($this->originData['secretKey'], $pointJson);
$targetPoint = new PointVo($targetPoint['x'], $targetPoint['y']);
//检查
$blockData->check($this->originData['point'], $targetPoint);
- if($callback instanceof \Closure){
- $callback();
- }
}
}
diff --git a/service/php/src/Service/ClickWordCaptchaService.php b/service/php/src/Service/ClickWordCaptchaService.php
index 8a0483afe1bc09cff4e22786db325849421bb237..5b367f8ae3e3e76463cbbebb60f136d665831e42 100644
--- a/service/php/src/Service/ClickWordCaptchaService.php
+++ b/service/php/src/Service/ClickWordCaptchaService.php
@@ -24,13 +24,13 @@ class ClickWordCaptchaService extends Service
'originalImageBase64' => $wordImage->response(),
'secretKey' => RandomUtils::getRandomCode(16, 3),
'token' => RandomUtils::getUUID(),
- 'wordList' => $wordImage->getWordList()
+ 'wordList' => $wordImage->getTargetWordList()
];
//缓存
$cacheEntity->set($data['token'], [
'secretKey' => $data['secretKey'],
- 'point' => $wordImage->getPoint()
- ],7200);
+ 'point' => $wordImage->getTargetPointList()
+ ],$this->factory->getConfig()['cache']['options']['expire'] ?? 300);
return $data;
}
@@ -39,9 +39,8 @@ class ClickWordCaptchaService extends Service
* 验证
* @param $token
* @param $pointJson
- * @param null $callback
*/
- public function validate($token, $pointJson, $callback = null)
+ public function validate($token, $pointJson)
{
//获取并设置 $this->originData
$this->setOriginData($token);
@@ -54,9 +53,6 @@ class ClickWordCaptchaService extends Service
//检查
$wordData->check($this->originData['point'], $targetPointList);
- if ($callback instanceof \Closure) {
- $callback();
- }
}
diff --git a/service/php/src/Service/Service.php b/service/php/src/Service/Service.php
index 035e14aa428ad5c92138a5d2c48447c697127662..0f7e96a7f646c9760615f36f5c719acc1c9e29db 100644
--- a/service/php/src/Service/Service.php
+++ b/service/php/src/Service/Service.php
@@ -27,18 +27,24 @@ abstract class Service
abstract public function get();
- abstract public function validate( $token, $pointJson, $callback = null);
+ abstract public function validate( $token, $pointJson);
/**
* 一次验证
* @param $token
* @param $pointJson
+ * @return string|null 返回加密的验证凭证 captchaVerification
*/
public function check($token, $pointJson)
{
- $this->validate($token, $pointJson, function () use ($token, $pointJson) {
- $this->setEncryptCache($token, $pointJson);
- });
+ try {
+ $this->validate($token, $pointJson);
+ }catch (\RuntimeException $e){
+ $cacheEntity = $this->factory->getCacheInstance();
+ $cacheEntity->delete($token);
+ throw $e;
+ }
+ return $this->setEncryptCache($token, $pointJson);
}
private function setEncryptCache($token, $pointJson){
@@ -50,8 +56,9 @@ abstract class Service
'token' => $token,
'point' => $pointJson
],
- 600
+ $this->factory->getConfig()['cache']['options']['expire'] ?? 300
);
+ return $key;
}
@@ -62,10 +69,12 @@ abstract class Service
*/
public function verification($token, $pointJson)
{
- $this->validate($token, $pointJson, function () use ($token) {
+ try {
+ $this->validate($token, $pointJson);
+ } finally {
$cacheEntity = $this->factory->getCacheInstance();
$cacheEntity->delete($token);
- });
+ }
}
/**
@@ -75,17 +84,20 @@ abstract class Service
*/
public function verificationByEncryptCode(string $encryptCode)
{
- $result = $this->factory->getCacheInstance()->get($encryptCode);
+ $cacheEntity = $this->factory->getCacheInstance();
+ $result = $cacheEntity->get($encryptCode);
if(empty($result)){
throw new ParamException('参数错误!');
}
- $this->validate($result['token'], $result['point'], function () use ($result,$encryptCode) {
- $cacheEntity = $this->factory->getCacheInstance();
- $cacheEntity->delete($result['token']);
- $cacheEntity->delete($encryptCode);
- });
+ // 立即删除二次验证码,防止重放
+ $cacheEntity->delete($encryptCode);
+ try {
+ $this->validate($result['token'], $result['point']);
+ } finally {
+ $cacheEntity->delete($result['token']);
+ }
}
/**
diff --git a/service/php/src/Utils/AesUtils.php b/service/php/src/Utils/AesUtils.php
index 6552aeaf6cafc84dc902cbb7a5706794f359c67a..6c6e193d261cccfecafcde01c63c6d293ed8c197 100644
--- a/service/php/src/Utils/AesUtils.php
+++ b/service/php/src/Utils/AesUtils.php
@@ -15,7 +15,7 @@ class AesUtils
* @param $secretKey string 只有长度等于16位才能与前端CryptoJS加密一致
* @return string
*/
- public static function encrypt($str, $secretKey)
+ public static function encrypt($str, string $secretKey)
{
return base64_encode(openssl_encrypt($str, 'AES-128-ECB', $secretKey, OPENSSL_RAW_DATA));
@@ -24,12 +24,16 @@ class AesUtils
/**
* 解密
* @param $str
- * @param $secretKey
+ * @param $secretKey string 只有长度等于16位才能与前端CryptoJS加密一致
* @return string
*/
- public static function decrypt($str, $secretKey): string
+ public static function decrypt($str, string $secretKey): string
{
- return openssl_decrypt(base64_decode($str), 'AES-128-ECB', $secretKey,OPENSSL_RAW_DATA);
+ $ret = openssl_decrypt(base64_decode($str), 'AES-128-ECB', $secretKey,OPENSSL_RAW_DATA);
+ if($ret === false){
+ throw new \RuntimeException('请检查密钥是否正确!');
+ }
+ return $ret;
}
}
diff --git a/service/php/src/Utils/ImageUtils.php b/service/php/src/Utils/ImageUtils.php
new file mode 100644
index 0000000000000000000000000000000000000000..0ed6e280f396f64219555ea8a83545dfe8f33372
--- /dev/null
+++ b/service/php/src/Utils/ImageUtils.php
@@ -0,0 +1,200 @@
+ 0 (transparent). No.
+ // Intervention v2: 0 (transparent) -> 1 (opaque).
+ // GD: 0 (opaque) -> 127 (transparent).
+ // So: GD_Alpha = (1 - Input_Alpha) * 127
+ } else {
+ // 假设已经是 GD 格式或者不带 alpha
+ $alpha = 0;
+ }
+
+ $col = imagecolorallocatealpha($image, $color[0], $color[1], $color[2], $alpha);
+
+ // 计算文字包围盒
+ $bbox = imagettfbbox($fontSize, $angle, $fontFile, $text);
+ // $bbox: 0,1 (LL), 2,3 (LR), 4,5 (UR), 6,7 (UL)
+ $textWidth = abs($bbox[4] - $bbox[0]);
+ $textHeight = abs($bbox[5] - $bbox[1]); // approximate
+
+ // 水平对齐修正
+ if ($align === 'center') {
+ $x -= ($textWidth / 2);
+ } elseif ($align === 'right') {
+ $x -= $textWidth;
+ }
+
+ // 垂直对齐修正 (GD 基准线是文字底部)
+ // imagettftext 的 x,y 是第一个字符的左下角
+ if ($valign === 'top') {
+ $y += $textHeight;
+ } elseif ($valign === 'center') {
+ $y += ($textHeight / 2);
+ }
+ // bottom 不需要修正
+
+ imagettftext($image, $fontSize, $angle, (int)$x, (int)$y, $col, $fontFile, $text);
+ }
+
+ /**
+ * 缩放/重采样
+ * @param resource|\GdImage $srcImage
+ * @param int $targetW
+ * @param int $targetH
+ * @return resource|\GdImage
+ */
+ public static function resize($srcImage, int $targetW, int $targetH)
+ {
+ $srcW = imagesx($srcImage);
+ $srcH = imagesy($srcImage);
+
+ $dstImage = self::create($targetW, $targetH);
+
+ imagecopyresampled(
+ $dstImage, $srcImage,
+ 0, 0, 0, 0,
+ $targetW, $targetH,
+ $srcW, $srcH
+ );
+
+ return $dstImage;
+ }
+
+ /**
+ * 输出图片 Base64 (不带前缀)
+ * @param resource|\GdImage $image
+ * @param string $format 'png', 'jpeg'
+ * @param int $quality
+ * @return string
+ */
+ public static function outputBase64($image, string $format = 'png', int $quality = 90): string
+ {
+ ob_start();
+ if ($format === 'jpeg' || $format === 'jpg') {
+ imagejpeg($image, null, $quality);
+ } else {
+ imagepng($image);
+ }
+ $data = ob_get_clean();
+ return base64_encode($data);
+ }
+
+ /**
+ * 安全销毁图片资源
+ * 兼容 PHP 8.0+ (GdImage) 和 PHP 8.5+ (imagedestroy deprecated)
+ * @param mixed $image
+ */
+ public static function destroy($image)
+ {
+ // PHP < 8.0: resource, 必须调用 imagedestroy
+ // PHP >= 8.0: GdImage object, 自动回收,imagedestroy 无效但无害 (直到 8.5)
+ // PHP >= 8.5: imagedestroy deprecated
+
+ if (PHP_VERSION_ID < 80000) {
+ if (is_resource($image) && get_resource_type($image) === 'gd') {
+ imagedestroy($image);
+ }
+ }
+ // PHP 8.0+ 让 GC 自动处理
+ }
+}
diff --git a/service/php/src/Utils/RandomUtils.php b/service/php/src/Utils/RandomUtils.php
index 542d983d93ba1c1509169b506c9225b035c4079b..560fe193057da2b42112c23a381f627cc251cfce 100644
--- a/service/php/src/Utils/RandomUtils.php
+++ b/service/php/src/Utils/RandomUtils.php
@@ -100,7 +100,7 @@ class RandomUtils
if ($type === 3){
$maps = "{$numbs}{$chars}";
}
- $string = $maps[self::getRandomInt(1, strlen($maps) - 1)];
+ $string = $maps[self::getRandomInt(0, strlen($maps) - 1)];
while (strlen($string) < $length) {
$string .= $maps[self::getRandomInt(0, strlen($maps) - 1)];
}
diff --git a/service/php/src/config.php b/service/php/src/config.php
index 0110beeac72c640c767fb97e5573383e974b36d5..ed17ef47be81c29a92eb239f049190cfe5d953a7 100644
--- a/service/php/src/config.php
+++ b/service/php/src/config.php
@@ -4,31 +4,57 @@ declare(strict_types=1);
return [
'font_file' => '', //自定义字体包路径, 不填使用默认值
//文字验证码
- 'click_world' => [
- 'backgrounds' => []
+ 'click_word' => [
+ 'backgrounds' => [],
+ 'word_num' => 3, //目标字数量(2-5)
+ 'distract_num' => 2, //干扰字数量
],
//滑动验证码
'block_puzzle' => [
+ // 模式: 'drawing' (原生绘图, 抗锯齿, 推荐), 'resource' (原图模板)
+ 'mode' => 'drawing',
+
+ // 形状类型 (仅在 mode=drawing 时生效):
+ // 'jigsaw' (拼图), 'red_heart' (红桃), 'diamond' (方片), 'spade' (黑桃), 'club' (草花)
+ 'shape_type' => 'jigsaw',
+
/*背景图片路径, 不填使用默认值, 支持string与array两种数据结构。string为默认图片的目录,array索引数组则为具体图片的地址*/
'backgrounds' => [],
- /*模板图,格式同上支持string与array*/
+ /*模板图,格式同上支持string与array (仅在 mode=resource 时生效)*/
'templates' => [],
- 'offset' => 10, //容错偏移量
+ 'offset' => 5, //容错偏移量
- 'is_cache_pixel' => true, //是否开启缓存图片像素值,开启后能提升服务端响应性能(但要注意更换图片时,需要清除缓存)
+ // 是否开启像素缓存 (仅在 mode=resource 时生效,能提升响应性能)
+ 'is_cache_pixel' => true,
+
+ 'is_interfere' => true, //开启干扰图 (仅在 mode=resource 时生效, Drawing 模式暂不支持干扰)
],
//水印
'watermark' => [
'fontsize' => 12,
- 'color' => '#ffffff',
+ 'color' => '#000000',
'text' => '我的水印'
],
'cache' => [
- 'constructor' => \Fastknife\Utils\CacheUtils::class,//建议使用您自己项目框架的缓存驱动
- 'options' => [
- // Fastknife\Utils\CacheUtils::class 中的配置
+ //若您使用了框架,并且想使用类似于redis这样的缓存驱动,则应换成框架的中的缓存驱动
+ 'constructor' => \Fastknife\Utils\CacheUtils::class,
+ 'method' => [
+ //遵守PSR-16规范不需要设置此项(tp6, laravel,hyperf)。如tp5就不支持(tp5缓存方法是rm,所以要配置为"delete" => "rm")
+ /**
+ 'get' => 'get', //获取
+ 'set' => 'set', //设置
+ 'delete' => 'delete',//删除
+ 'has' => 'has' //key是否存在
+ */
],
+ 'options' => [
+ //如果您依然使用\Fastknife\Utils\CacheUtils做为您的缓存驱动,那么您可以自定义缓存配置。
+ 'expire' => 300,//缓存有效期 (默认为0 表示永久缓存)
+ 'prefix' => '', //缓存前缀
+ 'path' => '', //缓存目录
+ 'serialize' => [], //缓存序列化和反序列化方法
+ ]
]
];
diff --git a/service/php/test/BlockPuzzleController.php b/service/php/test/BlockPuzzleController.php
index fd35f3be6811da15a77c2eab666349263a2ef28b..24c5bb85ef10e1e59d199086c8dedc4f29a6bdec 100644
--- a/service/php/test/BlockPuzzleController.php
+++ b/service/php/test/BlockPuzzleController.php
@@ -28,8 +28,9 @@ class BlockPuzzleController
$msg = null;
$error = false;
$repCode = '0000';
+ $captchaVerification = null;
try {
- $service->check($data['token'], $data['pointJson']);
+ $captchaVerification = $service->check($data['token'], $data['pointJson']);
} catch (\Exception $e) {
$msg = $e->getMessage();
$error = true;
@@ -38,7 +39,7 @@ class BlockPuzzleController
echo json_encode([
'error' => $error,
'repCode' => $repCode,
- 'repData' => null,
+ 'repData' => $captchaVerification ? ['captchaVerification' => $captchaVerification] : null,
'repMsg' => $msg,
'success' => ! $error,
]);
diff --git a/service/php/test/ClickWordController.php b/service/php/test/ClickWordController.php
index dca5048cc2cbe5dbaa480c0b55fac507893b3c2f..235926a16f5f237446047e4a460ff6e1c1ec5ef0 100644
--- a/service/php/test/ClickWordController.php
+++ b/service/php/test/ClickWordController.php
@@ -31,8 +31,9 @@ class ClickWordController
$msg = null;
$error = false;
$repCode = '0000';
+ $captchaVerification = null;
try {
- $service->check($data['token'], $data['pointJson']);
+ $captchaVerification = $service->check($data['token'], $data['pointJson']);
} catch (\Exception $e) {
$msg = $e->getMessage();
$error = true;
@@ -41,7 +42,7 @@ class ClickWordController
echo json_encode([
'error' => $error,
'repCode' => $repCode,
- 'repData' => null,
+ 'repData' => $captchaVerification ? ['captchaVerification' => $captchaVerification] : null,
'repMsg' => $msg,
'success' => ! $error,
]);
diff --git a/service/php/test/css/verify.css b/service/php/test/css/verify.css
new file mode 100644
index 0000000000000000000000000000000000000000..64e5472493e00c6f99847f3fc8ace1e855e8d975
--- /dev/null
+++ b/service/php/test/css/verify.css
@@ -0,0 +1,252 @@
+/* 需要引入的css文件 */
+html{
+ touch-action:none;
+ touch-action:pan-y;
+}
+.verify-code {
+ font-size: 20px;
+ text-align: center;
+ cursor: pointer;
+ margin-bottom: 5px;
+ border: 1px solid #ddd;
+}
+
+.cerify-code-panel {
+ height:100%;
+ overflow:hidden;
+}
+
+.verify-code-area {
+ float:left;
+}
+
+.verify-input-area {
+ float: left;
+ width: 60%;
+ padding-right: 10px;
+
+}
+
+.verify-change-area {
+ line-height: 30px;
+ float: left;
+}
+
+.varify-input-code {
+ display:inline-block;
+ width: 100%;
+ height: 25px;
+}
+
+.verify-change-code {
+ color: #337AB7;
+ cursor: pointer;
+}
+
+.verify-btn {
+ width: 200px;
+ height: 30px;
+ background-color: #337AB7;
+ color:#FFFFFF;
+ border:none;
+ margin-top: 10px;
+}
+
+.verifybox{
+ position: relative;
+ box-sizing: border-box;
+ border-radius: 2px;
+ border: 1px solid #e4e7eb;
+ background-color: #fff;
+ box-shadow: 0 0 10px rgba(0,0,0,.3);
+ left: 50%;
+ top:50%;
+ transform: translate(-50%,-50%);
+}
+.verifybox-top{
+ padding: 0 15px;
+ height: 50px;
+ line-height: 50px;
+ text-align: left;
+ font-size: 16px;
+ color: #45494c;
+ border-bottom: 1px solid #e4e7eb;
+ box-sizing: border-box;
+}
+.verifybox-bottom{
+ padding: 15px;
+ box-sizing: border-box;
+}
+.verifybox-close{
+ position: absolute;
+ top: 13px;
+ right: 9px;
+ width: 24px;
+ height: 24px;
+ line-height: 24px;
+ text-align: center;
+ cursor: pointer;
+}
+.mask{
+ position: fixed;
+ top: 0;
+ left:0;
+ z-index: 1001;
+ width: 100%;
+ height: 100vh;
+ background: rgba(0,0,0,.3);
+ /* display: none; */
+ transition: all .5s;
+ display: none;
+}
+
+.verify-tips{
+ text-indent: 10px;
+ position: absolute;
+ /* display: none; */
+ left: 0px;
+ bottom:-35px;
+ width: 100%;
+ height: 30px;
+ /* transition: all .5s; */
+ line-height:30px;
+ color: #fff;
+ /* animation:move 1.5s linear; */
+}
+
+@keyframes move {
+ 0%{
+ bottom:-35px;
+ }
+ 50%,80%{
+ bottom:0px;
+ }
+ 100%{
+ bottom:-35px;
+ }
+}
+
+.suc-bg{
+ background-color:rgba(92, 184, 92,.5);
+ filter: progid:DXImageTransform.Microsoft.gradient(startcolorstr=#7f5CB85C, endcolorstr=#7f5CB85C);
+}
+.err-bg{
+ background-color:rgba(217, 83, 79,.5);
+ filter: progid:DXImageTransform.Microsoft.gradient(startcolorstr=#7fD9534F, endcolorstr=#7fD9534F);
+}
+
+/*滑动验证码*/
+.verify-bar-area {
+ position: relative;
+ background: #FFFFFF;
+ text-align: center;
+ -webkit-box-sizing: content-box;
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
+ border: 1px solid #ddd;
+ -webkit-border-radius: 4px;
+}
+
+.verify-bar-area .verify-move-block {
+ position: absolute;
+ top: 0px;
+ left: 0;
+ background: #fff;
+ cursor: pointer;
+ -webkit-box-sizing: content-box;
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
+ box-shadow: 0 0 2px #888888;
+ -webkit-border-radius: 1px;
+}
+
+.verify-bar-area .verify-move-block:hover {
+ background-color: #337ab7;
+ color: #FFFFFF;
+}
+
+.verify-bar-area .verify-left-bar {
+ position: absolute;
+ top: -1px;
+ left: -1px;
+ background: #f0fff0;
+ cursor: pointer;
+ -webkit-box-sizing: content-box;
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
+ border: 1px solid #ddd;
+}
+
+.verify-img-panel {
+ margin:0;
+ -webkit-box-sizing: content-box;
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
+ border: 1px solid #ddd;
+ border-radius: 3px;
+ position: relative;
+}
+
+.verify-img-panel .verify-refresh {
+ width: 25px;
+ height: 25px;
+ text-align:center;
+ padding: 5px;
+ cursor: pointer;
+ position: absolute;
+ top: 0;
+ right: 0;
+ z-index: 2;
+}
+
+.verify-img-panel .icon-refresh {
+ font-size: 20px;
+ color: #fff;
+}
+
+.verify-img-panel .verify-gap {
+ background-color: #fff;
+ position: relative;
+ z-index: 2;
+ border:1px solid #fff;
+}
+
+.verify-bar-area .verify-move-block .verify-sub-block {
+ position: absolute;
+ text-align: center;
+ z-index: 3;
+ /* border: 1px solid #fff; */
+}
+
+.verify-bar-area .verify-move-block .verify-icon {
+ font-size: 18px;
+}
+
+.verify-bar-area .verify-msg {
+ z-index : 3;
+}
+
+/*字体图标的css*/
+@font-face {font-family: "iconfont";
+ src: url('../fonts/iconfont.eot?t=1508229193188'); /* IE9*/
+ src: url('../fonts/iconfont.eot?t=1508229193188#iefix') format('embedded-opentype'), /* IE6-IE8 */
+ url('data:application/x-font-woff;charset=utf-8;base64,d09GRgABAAAAAAaAAAsAAAAACUwAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABHU1VCAAABCAAAADMAAABCsP6z7U9TLzIAAAE8AAAARAAAAFZW7kiSY21hcAAAAYAAAAB3AAABuM+qBlRnbHlmAAAB+AAAAnQAAALYnrUwT2hlYWQAAARsAAAALwAAADYPNwajaGhlYQAABJwAAAAcAAAAJAfeA4dobXR4AAAEuAAAABMAAAAYF+kAAGxvY2EAAATMAAAADgAAAA4CvAGsbWF4cAAABNwAAAAfAAAAIAEVAF1uYW1lAAAE/AAAAUUAAAJtPlT+fXBvc3QAAAZEAAAAPAAAAE3oPPXPeJxjYGRgYOBikGPQYWB0cfMJYeBgYGGAAJAMY05meiJQDMoDyrGAaQ4gZoOIAgCKIwNPAHicY2Bk/sM4gYGVgYOpk+kMAwNDP4RmfM1gxMjBwMDEwMrMgBUEpLmmMDgwVDxbwtzwv4EhhrmBoQEozAiSAwAw1A0UeJzFkcENgCAMRX8RjCGO4gTe9eQcnhzAfXC2rqG/hYsT8MmD9gdS0gJIAAaykAjIBYHppCvuD8juR6zMJ67A89Zdn/f1aNPikUn8RvYo8G20CjKim6Rf6b9m34+WWd/vBr+oW8V6q3vF5qKlYrPRp4L0Ad5nGL8AeJxFUc9rE0EYnTezu8lMsrvtbrqb3TRt0rS7bdOmdI0JbWmCtiItIv5oi14qevCk9SQVLFiQgqAF8Q9QLKIHLx48FkHo3ZNnFUXwD5C2B6dO6sFhmI83w7z3fe8RnZCjb2yX5YlLhskkmScXCIFRxYBFiyjH9Rqtoqes9/g5i8WVuJyqDNTYLPwBI+cljXrkGynDhoU+nCgnjbhGY5yst+gMEq8IBIXwsjPU67CnEPm4b0su0h309Fd67da4XBhr55KSm17POk7gOE/Shq6nKdVsC7d9j+tcGPKVboc9u/0jtB/ZIA7PXTVLBef6o/paccjnwOYm3ELJetPuDrvV3gg91wlSXWY6H5qVwRzWf2TybrYYfSdqoXOwh/Qa8RWIjBTiSI3h614/vKSNRhONOrsnQi6Xf4nQFQDTmJE1NKbhI6crHEJO/+S5QPxhYJRRyvBFBP+5T9EPpEAIVzzRQIrjmJ6jY1WTo+NXTMchuBsKuS8PRZATSMl9oTA4uNLkeIA0V1UeqOoGQh7IAxGo+7T83fn3T+voqCNPPAUazUYUI7LgKSV1Jk2oUeghYGhZ+cKOe2FjVu5ZKEY2VkE13AK1+jI4r1KLbPlZfrKiPhOXKPRj7q9sj9XJ7LFHNmrKJS3VCdhXGSdKrtmoQaWeMjQVt0KD6sGPOx0oH2fgtzoNROxtNq8F3tzYM/n+TjKSX5qf2jx941276TIr9FjXxKr8eX/6bK4yuopwo9py1sw8F9kdw4AmurRpLUM3tYx5ZnKpfHPi8dzz19vJ6MjyxYUrpqeb1uLs3eGV6vr21pSqpeWkqonAN9oUyIiXpv8XvlN5e3icY2BkYGAA4n0vN4fG89t8ZeBmYQCBa9wPPRH0/wcsDMwmQC4HAxNIFABAfAqaAHicY2BkYGBu+N/AEMPCAAJAkpEBFbABAEcMAm94nGNhYGBgfsnAwMKAigESnwEBAAAAAAAAdgCkANoBCAFsAAB4nGNgZGBgYGMIZGBlAAEmIOYCQgaG/2A+AwARSAFzAHicZY9NTsMwEIVf+gekEqqoYIfkBWIBKP0Rq25YVGr3XXTfpk6bKokjx63UA3AejsAJOALcgDvwSCebNpbH37x5Y08A3OAHHo7fLfeRPVwyO3INF7gXrlN/EG6QX4SbaONVuEX9TdjHM6bCbXRheYPXuGL2hHdhDx18CNdwjU/hOvUv4Qb5W7iJO/wKt9Dx6sI+5l5XuI1HL/bHVi+cXqnlQcWhySKTOb+CmV7vkoWt0uqca1vEJlODoF9JU51pW91T7NdD5yIVWZOqCas6SYzKrdnq0AUb5/JRrxeJHoQm5Vhj/rbGAo5xBYUlDowxQhhkiMro6DtVZvSvsUPCXntWPc3ndFsU1P9zhQEC9M9cU7qy0nk6T4E9XxtSdXQrbsuelDSRXs1JErJCXta2VELqATZlV44RelzRiT8oZ0j/AAlabsgAAAB4nGNgYoAALgbsgI2RiZGZkYWRlZGNkZ2BsYI1OSM1OZs1OSe/OJW1KDM9o4S9KDWtKLU4g4EBAJ79CeQ=') format('woff'),
+ url('../fonts/iconfont.ttf?t=1508229193188') format('truetype'), /* chrome, firefox, opera, Safari, Android, iOS 4.2+*/
+ url('../fonts/iconfont.svg?t=1508229193188#iconfont') format('svg'); /* iOS 4.1- */
+}
+
+.iconfont {
+ font-family:"iconfont" !important;
+ font-size:16px;
+ font-style:normal;
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+}
+
+.icon-check:before { content: "\e645"; }
+
+.icon-close:before { content: "\e646"; }
+
+.icon-right:before { content: "\e6a3"; }
+
+.icon-refresh:before { content: "\e6a4"; }
diff --git a/service/php/test/index.html b/service/php/test/index.html
new file mode 100644
index 0000000000000000000000000000000000000000..346425fb79bbe71e5563196eac30bb8d41290549
--- /dev/null
+++ b/service/php/test/index.html
@@ -0,0 +1,164 @@
+
+
+
+
+
+ verify插件demo
+
+
+
+
+
+
+