diff --git a/native/wordpress/maple-carts-wp/LICENSE b/native/wordpress/maple-carts-wp/LICENSE new file mode 100644 index 0000000..b59c538 --- /dev/null +++ b/native/wordpress/maple-carts-wp/LICENSE @@ -0,0 +1,232 @@ +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS + +0. Definitions. + +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on the Program. + +To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. + +A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. + + maple-carts-wp + Copyright (C) 2025 mapleopentech + + 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: + + maple-carts-wp Copyright (C) 2025 mapleopentech + 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/native/wordpress/maple-carts-wp/README.md b/native/wordpress/maple-carts-wp/README.md new file mode 100644 index 0000000..05159fd --- /dev/null +++ b/native/wordpress/maple-carts-wp/README.md @@ -0,0 +1,248 @@ +# Maple Carts + +A lightweight abandoned cart recovery plugin for WooCommerce. No bloat, no tracking, no upsells. + +## Features + +- **Cart Tracking** - Captures email and cart data on checkout via AJAX +- **Automated Emails** - Configurable email sequences with customizable delays +- **Coupon Generation** - Auto-generate unique discount codes per email +- **Cart Recovery** - Tokenized URLs restore cart contents with one click +- **SMTP Compatible** - Works with any SMTP plugin (Mailjet, Mailchimp, SendGrid, etc.) +- **Privacy Focused** - No external requests, no analytics, no phone-home behavior +- **HPOS Compatible** - Works with WooCommerce High-Performance Order Storage +- **Blocks Compatible** - Works with WooCommerce Checkout Blocks + +## Email Modes + +Maple Carts supports two email modes: + +### Built-in Emails (Default) +Send timed recovery emails directly through WordPress/SMTP. Configure email templates with delays (1 hour, 24 hours, 3 days, etc.) and the plugin sends them automatically. + +### Mailjet Sync +Instead of sending emails directly, sync abandoned cart data to Mailjet as contact properties. This allows you to: +- Use Mailjet's powerful automation builder +- Create complex multi-step workflows +- Combine with other Mailjet segments and triggers +- Use Mailjet's analytics and A/B testing + +#### Mailjet Contact Properties +When a cart is abandoned, these properties are synced to the contact in Mailjet: + +| Property | Type | Description | +|----------|------|-------------| +| `maple_has_abandoned_cart` | Boolean | True when cart is abandoned, false when recovered | +| `maple_cart_total` | Float | Cart total value | +| `maple_cart_currency` | String | Currency code (USD, EUR, etc.) | +| `maple_cart_product_count` | Integer | Number of items in cart | +| `maple_cart_product_names` | String | Product names (comma separated) | +| `maple_cart_categories` | String | Product categories (comma separated) | +| `maple_cart_value_level` | String | `low` (<$20), `medium` ($20-80), `high` ($80+) | +| `maple_abandonment_type` | String | `checkout` (email only) or `payment` (filled billing) | +| `maple_cart_recovery_url` | String | Recovery URL with coupon and UTM tracking | +| `maple_cart_first_seen_at` | DateTime | When cart was first created (funnel entry) | +| `maple_cart_abandoned_at` | DateTime | When the cart was abandoned | +| `maple_cart_coupon_code` | String | Generated coupon code (if enabled) | +| `maple_customer_first_name` | String | Customer first name | +| `maple_customer_last_name` | String | Customer last name | +| `maple_recovered_via` | String | Attribution: `mailjet`, `email_link`, `direct`, `purchase` | + +#### Example Mailjet Automation Conditions +``` +maple_has_abandoned_cart equals true +maple_cart_total is greater than 50 +maple_cart_value_level equals high +maple_cart_categories contains "Electronics" +maple_abandonment_type equals payment +maple_cart_abandoned_at is less than 24 hours ago +``` + +#### Recovery Attribution +Recovery URLs include UTM parameters for analytics attribution: +- Built-in emails: `utm_source=maple_carts&utm_medium=email&utm_campaign=cart_recovery` +- Mailjet: `utm_source=mailjet` + +The plugin tracks recovery source both in the database and syncs to Mailjet: + +| `maple_recovered_via` | Description | +|-----------------------|-------------| +| `mailjet` | Recovered via Mailjet automation email | +| `builtin_email` | Recovered via built-in email system | +| `email_link` | Recovered via generic/shared recovery link | +| `direct` | Customer returned without clicking a recovery link | +| `purchase` | Direct purchase (cart was never abandoned) | + +This enables full recovery performance analysis across channels. + +#### Setup +1. Go to Settings → Email Mode → Mailjet Sync +2. Enter your Mailjet API Key and Secret Key +3. Click "Test Connection" to verify credentials +4. Click "Setup Contact Properties" to create the properties in Mailjet +5. Save settings +6. In Mailjet, create a Segment using `maple_has_abandoned_cart equals true` +7. Use that Segment in your automation workflows + +## Developer Hooks + +Maple Carts provides action hooks for integrations like Facebook CAPI, custom analytics, etc. + +### Available Actions + +```php +// Fires whenever a cart is created or updated (for retargeting pixels) +do_action( 'maple_carts_cart_updated', $cart ); + +// Fires when a cart is marked as abandoned +do_action( 'maple_carts_cart_abandoned', $cart_id, $cart ); + +// Fires when an abandoned cart is recovered +do_action( 'maple_carts_cart_recovered', $cart_id, $cart ); + +// Fires when a cart converts to an order +do_action( 'maple_carts_cart_converted', $cart_id, $cart ); +``` + +### Example: Facebook CAPI Integration + +```php +add_action( 'maple_carts_cart_updated', function( $cart ) { + // Send AddToCart event to Facebook CAPI + if ( ! empty( $cart->email ) ) { + // Your Facebook CAPI code here + } +}); + +add_action( 'maple_carts_cart_abandoned', function( $cart_id, $cart ) { + // Send custom event for abandoned cart +}, 10, 2 ); +``` + +## GDPR Compliance + +Maple Carts includes built-in GDPR compliance features: + +### Privacy Tools Integration +- **Data Export**: Integrates with WordPress Privacy Tools (Tools → Export Personal Data) +- **Data Erasure**: Integrates with WordPress Privacy Tools (Tools → Erase Personal Data) +- **Privacy Policy**: Adds suggested text to your Privacy Policy page + +### Consent Management +- **Optional Consent Checkbox**: Enable in Settings → Privacy to require explicit opt-in +- **Consent Text**: Customizable checkbox label +- **Session-based Consent**: Consent is remembered for the checkout session + +### User Rights +- **Unsubscribe**: One-click unsubscribe link in every email +- **Delete Data**: Optional one-click data deletion link in emails (enable in Settings → Privacy) +- **Automatic Cleanup**: Data automatically deleted after configurable retention period (default 90 days) + +**Note**: The "Delete my data" link is optional and disabled by default. Enable it in Settings → Privacy if you have customers in the EU or other regions with data deletion requirements. + +### Data Collected +When enabled, Maple Carts collects: +- Email address, name, phone number +- Billing address +- Cart contents and total +- IP address and browser information + +All data is stored locally in your WordPress database. No data is sent to external servers. + +## Requirements + +- WordPress 5.8+ +- WooCommerce 5.0+ +- PHP 7.4+ + +## Installation + +1. Upload the `maple-carts` folder to `/wp-content/plugins/` +2. Activate the plugin through the 'Plugins' menu in WordPress +3. Go to **Maple Carts > Settings** to configure +4. Go to **Maple Carts > Email Templates** to activate your email sequence + +## Email Placeholders + +Use these in your email templates: + +| Placeholder | Description | +|------------|-------------| +| `{{customer_name}}` | Customer's first name | +| `{{customer_email}}` | Customer's email address | +| `{{cart_contents}}` | HTML table of cart items | +| `{{cart_total}}` | Formatted cart total | +| `{{product_names}}` | Comma-separated product names | +| `{{recovery_url}}` | Link to restore cart | +| `{{coupon_code}}` | Generated coupon code | +| `{{coupon_amount}}` | Discount amount (e.g., "10%" or "$5.00") | +| `{{coupon_expires}}` | Days until coupon expires | +| `{{site_name}}` | Your site name | +| `{{unsubscribe_link}}` | Unsubscribe link | +| `{{delete_data_link}}` | GDPR data deletion link (only shown if enabled in settings) | + +## SMTP Integration + +Maple Carts uses WordPress's native `wp_mail()` function, which means it automatically works with any SMTP plugin: + +- **Mailjet** - Install "Mailjet for WordPress" plugin +- **Mailchimp/Mandrill** - Install "Mailchimp Transactional Email" plugin +- **SendGrid** - Install "SendGrid" plugin +- **Amazon SES** - Install "WP Mail SMTP" and configure SES +- **Any SMTP** - Use "WP Mail SMTP" or similar + +Just install and configure your preferred SMTP plugin - Maple Carts will use it automatically. + +## Database Tables + +The plugin creates 3 custom tables: + +- `wp_maple_carts` - Abandoned cart data +- `wp_maple_carts_emails` - Email templates +- `wp_maple_carts_email_log` - Sent email history + +## Hooks & Filters + +### Actions + +```php +// After a recovery email is sent +do_action( 'maple_carts_email_sent', $email_data, $subject ); +``` + +### Filters + +```php +// Modify email placeholders +add_filter( 'maple_carts_email_replacements', function( $replacements, $email_data ) { + $replacements['{{custom}}'] = 'Custom Value'; + return $replacements; +}, 10, 2 ); + +// Modify email before sending +add_filter( 'maple_carts_before_send_email', function( $email ) { + // $email contains: to, subject, body, headers + return $email; +} ); +``` + +## Comparison with Original Plugin + +| Feature | Original (CartFlows) | Maple Carts | +|---------|---------------------|-------------| +| Size | 4.2 MB | ~150 KB | +| PHP Files | 64 | 8 | +| Lines of Code | 17,205 | ~2,500 | +| External Requests | Yes (analytics) | None | +| React Admin | Yes (1.8 MB) | No (PHP) | +| NPS Surveys | Yes | No | +| Upsells | Yes | No | + +## License + +GPL v2 or later + +## Changelog + +### 1.0.0 +- Initial release diff --git a/native/wordpress/maple-carts-wp/assets/css/admin.css b/native/wordpress/maple-carts-wp/assets/css/admin.css new file mode 100644 index 0000000..bad0e70 --- /dev/null +++ b/native/wordpress/maple-carts-wp/assets/css/admin.css @@ -0,0 +1,284 @@ +/** + * Maple Carts - Admin Styles + */ + +/* General */ +.maple-carts-wrap { + max-width: 1200px; +} + +.maple-carts-wrap h1 { + display: flex; + align-items: center; + gap: 10px; +} + +/* Period Selector */ +.maple-carts-period-selector { + margin: 20px 0; + display: flex; + gap: 10px; +} + +.maple-carts-period-selector a { + padding: 8px 16px; + text-decoration: none; + border: 1px solid #ddd; + border-radius: 4px; + background: #fff; + color: #333; +} + +.maple-carts-period-selector a:hover { + background: #f5f5f5; +} + +.maple-carts-period-selector a.active { + background: #2271b1; + border-color: #2271b1; + color: #fff; +} + +/* Stats Grid */ +.maple-carts-stats-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: 20px; + margin: 20px 0; +} + +.maple-carts-stat-box { + background: #fff; + border: 1px solid #ddd; + border-radius: 8px; + padding: 24px; + text-align: center; +} + +.maple-carts-stat-box .stat-number { + display: block; + font-size: 36px; + font-weight: 600; + color: #1d2327; + line-height: 1.2; +} + +.maple-carts-stat-box .stat-label { + display: block; + font-size: 14px; + color: #666; + margin-top: 8px; +} + +.maple-carts-stat-box .stat-value { + display: block; + font-size: 16px; + color: #2271b1; + margin-top: 8px; + font-weight: 500; +} + +.maple-carts-stat-box.stat-success { + border-color: #00a32a; +} + +.maple-carts-stat-box.stat-success .stat-number { + color: #00a32a; +} + +.maple-carts-stat-box.stat-muted { + opacity: 0.7; +} + +/* Quick Links */ +.maple-carts-quick-links { + margin-top: 30px; + padding: 20px; + background: #fff; + border: 1px solid #ddd; + border-radius: 8px; +} + +.maple-carts-quick-links h2 { + margin-top: 0; + margin-bottom: 15px; + font-size: 16px; +} + +.maple-carts-quick-links .button { + margin-right: 10px; +} + +/* Badges */ +.maple-carts-badge { + display: inline-block; + padding: 3px 8px; + font-size: 11px; + font-weight: 500; + border-radius: 3px; + text-transform: uppercase; +} + +.maple-carts-badge.badge-success { + background: #d4edda; + color: #155724; +} + +.maple-carts-badge.badge-muted { + background: #e9ecef; + color: #6c757d; +} + +.maple-carts-badge.badge-warning { + background: #fff3cd; + color: #856404; +} + +/* Table Styles */ +.maple-carts-wrap .wp-list-table td { + vertical-align: middle; +} + +.maple-carts-wrap .button-link { + color: #2271b1; + cursor: pointer; +} + +.maple-carts-wrap .button-link:hover { + color: #135e96; +} + +/* Modal */ +.maple-carts-modal { + display: none; + position: fixed; + z-index: 100000; + left: 0; + top: 0; + width: 100%; + height: 100%; + background-color: rgba(0, 0, 0, 0.5); +} + +.maple-carts-modal-content { + background-color: #fff; + margin: 10% auto; + padding: 30px; + border-radius: 8px; + width: 90%; + max-width: 500px; + position: relative; + max-height: 80vh; + overflow-y: auto; +} + +.maple-carts-modal-large { + max-width: 800px; +} + +.maple-carts-modal-close { + position: absolute; + right: 15px; + top: 10px; + font-size: 28px; + font-weight: bold; + cursor: pointer; + color: #666; + line-height: 1; +} + +.maple-carts-modal-close:hover { + color: #000; +} + +.maple-carts-modal h3 { + margin-top: 0; + margin-bottom: 20px; + padding-bottom: 15px; + border-bottom: 1px solid #eee; +} + +/* Preview Modal */ +.maple-carts-preview-subject { + padding: 10px 15px; + background: #f5f5f5; + border-radius: 4px; + margin-bottom: 15px; + font-weight: 500; +} + +/* Template Editor */ +.maple-carts-template-editor { + background: #fff; + padding: 20px; + border: 1px solid #ddd; + border-radius: 8px; + margin-top: 20px; +} + +.maple-carts-template-editor .form-table th { + width: 180px; + padding-top: 20px; +} + +.maple-carts-template-editor .form-table td { + padding-top: 15px; +} + +.maple-carts-template-editor .wp-editor-container { + border: 1px solid #ddd; +} + +.maple-carts-template-editor code { + background: #f0f0f0; + padding: 2px 6px; + border-radius: 3px; + font-size: 12px; +} + +/* Settings */ +.maple-carts-wrap .form-table input[type="number"].small-text { + width: 70px; +} + +/* Test Result */ +.maple-carts-test-result { + margin-top: 15px; +} + +.maple-carts-test-result p { + margin: 0; + padding: 10px 15px; + border-radius: 4px; +} + +.maple-carts-test-result p[style*="green"] { + background: #d4edda; +} + +.maple-carts-test-result p[style*="red"] { + background: #f8d7da; +} + +/* Responsive */ +@media screen and (max-width: 782px) { + .maple-carts-stats-grid { + grid-template-columns: 1fr 1fr; + } + + .maple-carts-modal-content { + margin: 5% auto; + width: 95%; + padding: 20px; + } + + .maple-carts-period-selector { + flex-wrap: wrap; + } +} + +@media screen and (max-width: 480px) { + .maple-carts-stats-grid { + grid-template-columns: 1fr; + } +} diff --git a/native/wordpress/maple-carts-wp/assets/css/index.php b/native/wordpress/maple-carts-wp/assets/css/index.php new file mode 100644 index 0000000..84d32c8 --- /dev/null +++ b/native/wordpress/maple-carts-wp/assets/css/index.php @@ -0,0 +1,10 @@ +'; + html += 'ProductQtyPrice'; + + if (cart && cart.length) { + cart.forEach(function(item) { + html += ''; + html += '' + (item.name || 'Unknown Product') + ''; + html += '' + (item.quantity || 1) + ''; + html += '$' + (parseFloat(item.price) || 0).toFixed(2) + ''; + html += ''; + }); + } else { + html += 'No products'; + } + + html += ''; + + $('#maple-carts-products-list').html(html); + $('#maple-carts-products-modal').show(); + }, + + saveTemplate: function(e) { + e.preventDefault(); + + var $form = $(this); + var $btn = $form.find('button[type="submit"]'); + var originalText = $btn.text(); + + $btn.text(mapleCartsAdmin.saving).prop('disabled', true); + + // Get editor content. + var body = ''; + if (typeof tinymce !== 'undefined' && tinymce.get('template-body')) { + body = tinymce.get('template-body').getContent(); + } else { + body = $('#template-body').val(); + } + + var data = { + action: 'maple_carts_save_template', + nonce: mapleCartsAdmin.nonce, + id: $form.find('input[name="id"]').val(), + name: $form.find('input[name="name"]').val(), + subject: $form.find('input[name="subject"]').val(), + body: body, + delay_value: $form.find('input[name="delay_value"]').val(), + delay_unit: $form.find('select[name="delay_unit"]').val(), + is_active: $form.find('input[name="is_active"]').is(':checked') ? 1 : 0, + include_coupon: $form.find('input[name="include_coupon"]').is(':checked') ? 1 : 0, + coupon_type: $form.find('select[name="coupon_type"]').val(), + coupon_amount: $form.find('input[name="coupon_amount"]').val(), + coupon_expires_days: $form.find('input[name="coupon_expires_days"]').val() + }; + + $.post(mapleCartsAdmin.ajaxUrl, data, function(response) { + if (response.success) { + $btn.text(mapleCartsAdmin.saved); + setTimeout(function() { + window.location.href = 'admin.php?page=maple-carts-emails'; + }, 500); + } else { + alert('Error: ' + (response.data || 'Failed to save template')); + $btn.text(originalText).prop('disabled', false); + } + }); + }, + + toggleCouponSettings: function() { + var show = $(this).is(':checked'); + $('.coupon-settings').toggle(show); + }, + + deleteTemplate: function(e) { + e.preventDefault(); + + if (!confirm(mapleCartsAdmin.confirmDelete)) { + return; + } + + var $btn = $(this); + var templateId = $btn.data('id'); + var $row = $btn.closest('tr'); + + $.post(mapleCartsAdmin.ajaxUrl, { + action: 'maple_carts_delete_template', + nonce: mapleCartsAdmin.nonce, + template_id: templateId + }, function(response) { + if (response.success) { + $row.fadeOut(300, function() { + $(this).remove(); + }); + } else { + alert('Error: ' + (response.data || 'Failed to delete template')); + } + }); + }, + + toggleTemplate: function(e) { + e.preventDefault(); + + var $btn = $(this); + var templateId = $btn.data('id'); + var isActive = $btn.data('active'); + + $.post(mapleCartsAdmin.ajaxUrl, { + action: 'maple_carts_toggle_template', + nonce: mapleCartsAdmin.nonce, + template_id: templateId, + active: isActive + }, function(response) { + if (response.success) { + $btn.data('active', response.data.is_active); + var $badge = $btn.find('.maple-carts-badge'); + + if (response.data.is_active) { + $badge.removeClass('badge-muted').addClass('badge-success').text('Active'); + } else { + $badge.removeClass('badge-success').addClass('badge-muted').text('Inactive'); + } + } else { + alert('Error: ' + (response.data || 'Failed to update template')); + } + }); + }, + + previewEmail: function(e) { + e.preventDefault(); + + var body = ''; + if (typeof tinymce !== 'undefined' && tinymce.get('template-body')) { + body = tinymce.get('template-body').getContent(); + } else { + body = $('#template-body').val(); + } + + $.post(mapleCartsAdmin.ajaxUrl, { + action: 'maple_carts_preview_email', + nonce: mapleCartsAdmin.nonce, + template_id: $('input[name="id"]').val(), + subject: $('input[name="subject"]').val(), + body: body + }, function(response) { + if (response.success) { + $('.maple-carts-preview-subject').text('Subject: ' + response.data.subject); + + var iframe = document.getElementById('maple-carts-preview-frame'); + var iframeDoc = iframe.contentDocument || iframe.contentWindow.document; + iframeDoc.open(); + iframeDoc.write(response.data.body); + iframeDoc.close(); + + $('#maple-carts-preview-modal').show(); + } else { + alert('Error: ' + (response.data || 'Failed to generate preview')); + } + }); + }, + + openTestModal: function(e) { + e.preventDefault(); + $('#maple-carts-test-modal').show(); + $('.maple-carts-test-result').html(''); + }, + + sendTestEmail: function(e) { + e.preventDefault(); + + var $btn = $(this); + var email = $('#test-email-address').val(); + + if (!email) { + alert('Please enter an email address'); + return; + } + + var body = ''; + if (typeof tinymce !== 'undefined' && tinymce.get('template-body')) { + body = tinymce.get('template-body').getContent(); + } else { + body = $('#template-body').val(); + } + + $btn.prop('disabled', true).text('Sending...'); + + $.post(mapleCartsAdmin.ajaxUrl, { + action: 'maple_carts_send_test_email', + nonce: mapleCartsAdmin.nonce, + email: email, + subject: $('input[name="subject"]').val(), + body: body + }, function(response) { + $btn.prop('disabled', false).text('Send Test'); + + if (response.success) { + $('.maple-carts-test-result').html('

' + response.data + '

'); + } else { + $('.maple-carts-test-result').html('

' + response.data + '

'); + } + }); + }, + + closeModal: function() { + $('.maple-carts-modal').hide(); + } + }; + + $(document).ready(function() { + MapleCartsAdmin.init(); + + // Email mode toggle. + $('input[name="email_mode"]').on('change', function() { + var mode = $(this).val(); + if (mode === 'mailjet') { + $('#mailjet-settings').show(); + $('#builtin-email-settings').hide(); + } else { + $('#mailjet-settings').hide(); + $('#builtin-email-settings').show(); + } + }); + + // Test Mailjet connection. + $('#test-mailjet-connection').on('click', function() { + var $btn = $(this); + var $status = $('#mailjet-status'); + var apiKey = $('#mailjet_api_key').val(); + var secretKey = $('#mailjet_secret_key').val(); + + if (!apiKey || !secretKey) { + $status.html('Please enter API credentials first.'); + return; + } + + $btn.prop('disabled', true); + $status.html('Testing connection...'); + + $.post(mapleCartsAdmin.ajaxUrl, { + action: 'maple_carts_test_mailjet', + nonce: mapleCartsAdmin.nonce, + api_key: apiKey, + secret_key: secretKey + }, function(response) { + $btn.prop('disabled', false); + if (response.success) { + $status.html('✓ ' + response.data.message + ''); + } else { + $status.html('✗ ' + response.data + ''); + } + }).fail(function() { + $btn.prop('disabled', false); + $status.html('✗ Connection failed'); + }); + }); + + // Setup Mailjet properties. + $('#setup-mailjet-properties').on('click', function() { + var $btn = $(this); + var $status = $('#mailjet-status'); + + $btn.prop('disabled', true); + $status.html('Setting up contact properties...'); + + $.post(mapleCartsAdmin.ajaxUrl, { + action: 'maple_carts_setup_mailjet_properties', + nonce: mapleCartsAdmin.nonce + }, function(response) { + $btn.prop('disabled', false); + if (response.success) { + $status.html('✓ ' + response.data.message + ''); + } else { + $status.html('✗ ' + response.data + ''); + } + }).fail(function() { + $btn.prop('disabled', false); + $status.html('✗ Setup failed'); + }); + }); + }); + +})(jQuery); diff --git a/native/wordpress/maple-carts-wp/assets/js/index.php b/native/wordpress/maple-carts-wp/assets/js/index.php new file mode 100644 index 0000000..84d32c8 --- /dev/null +++ b/native/wordpress/maple-carts-wp/assets/js/index.php @@ -0,0 +1,10 @@ + 0) { + var notice = $('
' + mapleCartsData.gdprNotice + '
'); + $('.woocommerce-checkout').prepend(notice); + } + }, + + getFormData: function() { + var data = { + session_id: mapleCartsData.sessionId + }; + + // Check for consent checkbox if it exists. + var consentCheckbox = $('#maple_carts_consent'); + if (consentCheckbox.length > 0 && !consentCheckbox.is(':checked')) { + // Consent required but not given - don't save. + return null; + } + data.consent = consentCheckbox.length > 0 ? (consentCheckbox.is(':checked') ? '1' : '0') : '1'; + + // Get email - try multiple selectors for compatibility. + var email = $('#billing_email').val() || + $('[id^="email"]').val() || + $('input[autocomplete="email"]').val() || + $('input[type="email"]').first().val() || ''; + + data.email = email.trim().toLowerCase(); + + // Get billing fields. + var billingFields = [ + 'first_name', 'last_name', 'phone', 'address_1', 'address_2', + 'city', 'state', 'postcode', 'country' + ]; + + billingFields.forEach(function(field) { + var value = $('#billing_' + field).val(); + if (value) { + data['billing_' + field] = value; + } + }); + + // Try Blocks checkout fields. + if (!data.billing_first_name) { + data.billing_first_name = $('input[autocomplete="given-name"]').val() || ''; + } + if (!data.billing_last_name) { + data.billing_last_name = $('input[autocomplete="family-name"]').val() || ''; + } + if (!data.billing_phone) { + data.billing_phone = $('input[autocomplete="tel"]').val() || ''; + } + + return data; + }, + + saveCart: function() { + var data = MapleCarts.getFormData(); + + // Don't save if consent not given or data is null. + if (!data) { + return; + } + + // Don't save without email or session. + if (!data.email || !data.session_id) { + return; + } + + // Don't save if email is invalid. + if (!MapleCarts.isValidEmail(data.email)) { + return; + } + + // Don't save if data hasn't changed. + var dataHash = JSON.stringify(data); + if (dataHash === MapleCarts.lastSavedData) { + return; + } + + data.action = 'maple_carts_save'; + data.nonce = mapleCartsData.nonce; + + $.post(mapleCartsData.ajaxUrl, data, function(response) { + if (response.success) { + MapleCarts.lastSavedData = dataHash; + } + }); + }, + + isValidEmail: function(email) { + var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + return re.test(email); + }, + + debounce: function(func, wait) { + return function() { + var context = this, args = arguments; + clearTimeout(MapleCarts.saveTimeout); + MapleCarts.saveTimeout = setTimeout(function() { + func.apply(context, args); + }, wait); + }; + } + }; + + $(document).ready(function() { + MapleCarts.init(); + }); + +})(jQuery); diff --git a/native/wordpress/maple-carts-wp/includes/class-maple-carts-admin.php b/native/wordpress/maple-carts-wp/includes/class-maple-carts-admin.php new file mode 100644 index 0000000..72f43ab --- /dev/null +++ b/native/wordpress/maple-carts-wp/includes/class-maple-carts-admin.php @@ -0,0 +1,962 @@ + admin_url( 'admin-ajax.php' ), + 'nonce' => wp_create_nonce( 'maple_carts_admin' ), + 'confirmDelete' => __( 'Are you sure you want to delete this?', 'maple-carts' ), + 'saving' => __( 'Saving...', 'maple-carts' ), + 'saved' => __( 'Saved!', 'maple-carts' ), + ] ); + + // Enqueue WP editor for email templates. + if ( strpos( $hook, 'maple-carts-emails' ) !== false ) { + wp_enqueue_editor(); + } + } + + /** + * Handle form actions. + */ + public function handle_actions() { + // Save settings. + if ( isset( $_POST['maple_carts_save_settings'] ) && check_admin_referer( 'maple_carts_settings' ) ) { + $this->save_settings(); + } + } + + /** + * Save settings. + */ + private function save_settings() { + $settings = [ + 'enabled' => isset( $_POST['enabled'] ) ? 'yes' : 'no', + 'cart_cutoff_time' => absint( $_POST['cart_cutoff_time'] ?? 15 ), + 'delete_after_days' => absint( $_POST['delete_after_days'] ?? 90 ), + 'email_mode' => isset( $_POST['email_mode'] ) && 'mailjet' === $_POST['email_mode'] ? 'mailjet' : 'builtin', + 'mailjet_api_key' => sanitize_text_field( wp_unslash( $_POST['mailjet_api_key'] ?? '' ) ), + 'mailjet_secret_key'=> sanitize_text_field( wp_unslash( $_POST['mailjet_secret_key'] ?? '' ) ), + 'from_name' => sanitize_text_field( wp_unslash( $_POST['from_name'] ?? '' ) ), + 'from_email' => sanitize_email( wp_unslash( $_POST['from_email'] ?? '' ) ), + 'reply_to' => sanitize_email( wp_unslash( $_POST['reply_to'] ?? '' ) ), + 'notify_admin' => isset( $_POST['notify_admin'] ) ? 'yes' : 'no', + 'admin_email' => sanitize_email( wp_unslash( $_POST['admin_email'] ?? '' ) ), + 'require_consent' => isset( $_POST['require_consent'] ) ? 'yes' : 'no', + 'consent_text' => sanitize_text_field( wp_unslash( $_POST['consent_text'] ?? '' ) ), + 'show_delete_link' => isset( $_POST['show_delete_link'] ) ? 'yes' : 'no', + 'gdpr_notice' => sanitize_textarea_field( wp_unslash( $_POST['gdpr_notice'] ?? '' ) ), + 'exclude_roles' => isset( $_POST['exclude_roles'] ) ? array_map( 'sanitize_text_field', $_POST['exclude_roles'] ) : [], + ]; + + update_option( 'maple_carts_settings', $settings ); + + add_settings_error( 'maple_carts', 'settings_saved', __( 'Settings saved.', 'maple-carts' ), 'success' ); + } + + /** + * Render dashboard page. + */ + public function render_dashboard() { + $period = isset( $_GET['period'] ) ? sanitize_text_field( wp_unslash( $_GET['period'] ) ) : '30days'; + $stats = Maple_Carts_DB::get_stats( $period ); + ?> +
+

+ + + +
+
+ + + +
+ +
+ + + +
+ +
+ % + +
+ +
+ + +
+
+ + +
+ render_carts_table( 'abandoned', __( 'Abandoned Carts', 'maple-carts' ) ); + } + + /** + * Render recovered carts page. + */ + public function render_recovered_carts() { + $this->render_carts_table( 'recovered', __( 'Recovered Carts', 'maple-carts' ) ); + } + + /** + * Render carts table. + * + * @param string $status Page status. + * @param string $title Page title. + */ + private function render_carts_table( $status, $title ) { + $page = isset( $_GET['paged'] ) ? max( 1, absint( $_GET['paged'] ) ) : 1; + $limit = 20; + $offset = ( $page - 1 ) * $limit; + $carts = Maple_Carts_DB::get_carts_by_status( $status, $limit, $offset ); + $total = Maple_Carts_DB::count_carts_by_status( $status ); + $pages = ceil( $total / $limit ); + ?> +
+

+ + +

+ + + + + + + + + + + + + + cart_contents ); + $product_count = is_array( $cart_contents ) ? count( $cart_contents ) : 0; + ?> + + + + + + + + + + +
+ email ); ?> + unsubscribed ) : ?> + + + customer_name ?: '—' ); ?>cart_total, [ 'currency' => $cart->currency ] ); ?> + + + + recovered_at + ? $cart->recovered_at + : ( $cart->abandoned_at ?: $cart->created_at ); + echo esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $date ) ) ); + ?> + + +
+ + 1 ) : ?> +
+
+ add_query_arg( 'paged', '%#%' ), + 'format' => '', + 'prev_text' => '«', + 'next_text' => '»', + 'total' => $pages, + 'current' => $page, + ] ); + ?> +
+
+ + +
+ + + + +
+

+ + + + +

+ + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + include_coupon ) ? 'style="display:none;"' : ''; ?>> + + + + include_coupon ) ? 'style="display:none;"' : ''; ?>> + + + + include_coupon ) ? 'style="display:none;"' : ''; ?>> + + + + + + + +
+ +
+ +

+
+ body : '', + 'template-body', + [ + 'textarea_name' => 'body', + 'textarea_rows' => 15, + 'media_buttons' => false, + ] + ); + ?> +

+
+ {{customer_name}}, {{customer_email}}, {{cart_contents}}, {{cart_total}}, {{product_names}}, {{recovery_url}}, {{coupon_code}}, {{coupon_amount}}, {{coupon_expires}}, {{site_name}}, {{unsubscribe_link}}, {{delete_data_link}} +

+
+ + +

+
+ +
+ +
+ +
+ + +
+ +
+ +

+ + + + +

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
name ); ?>subject ); ?>delay_value . ' ' . $tmpl->delay_unit ); ?> + include_coupon ) : ?> + coupon_type === 'percent' + ? esc_html( $tmpl->coupon_amount . '%' ) + : wc_price( $tmpl->coupon_amount ); + ?> + + — + + + + + + + + | + +
+ +
+ + + + + + + +
+

+ +
+ + + + + + + + + + + + + + + +
+ +
+ + +

+
+ + +

+
+ +

+ + + + + +
+
+ +

+ +
+
+ + +
+

+

+ Mailjet API Keys' + ); + ?> +

+ + + + + + + + + + + + + + + + + +
+ +
+ +
+ + + +
+

+
    + get_available_properties() as $prop => $desc ) : ?> +
  • + +
+

+ + maple_has_abandoned_cart equals true +

+
+
+ + +
+

+ + + + + + + + + + + + + +
+ +
+ +
+ +
+ +

+ + + + + + + + + +
+ +
+ +
+
+ +

+

+ ' . esc_html__( 'Privacy Settings', 'maple-carts' ) . '' + ); + ?> +

+ + + + + + + + + + + + + + + + + + + + + +
+ +

+
+ +
+ +

+
+ +

+
+ roles as $role_key => $role ) : + ?> + + +

+
+ +

+ +

+
+
+ sanitize_text_field( wp_unslash( $_POST['name'] ?? '' ) ), + 'subject' => sanitize_text_field( wp_unslash( $_POST['subject'] ?? '' ) ), + 'body' => wp_kses_post( wp_unslash( $_POST['body'] ?? '' ) ), + 'delay_value' => absint( $_POST['delay_value'] ?? 1 ), + 'delay_unit' => $delay_unit, + 'is_active' => isset( $_POST['is_active'] ) ? 1 : 0, + 'include_coupon' => isset( $_POST['include_coupon'] ) ? 1 : 0, + 'coupon_type' => $coupon_type, + 'coupon_amount' => floatval( $_POST['coupon_amount'] ?? 10 ), + 'coupon_expires_days'=> absint( $_POST['coupon_expires_days'] ?? 7 ), + ]; + + if ( ! empty( $_POST['id'] ) ) { + $data['id'] = absint( $_POST['id'] ); + } + + $id = Maple_Carts_DB::save_email_template( $data ); + + if ( $id ) { + wp_send_json_success( [ 'id' => $id ] ); + } else { + wp_send_json_error( 'Failed to save template' ); + } + } + + /** + * AJAX: Delete template. + */ + public function ajax_delete_template() { + check_ajax_referer( 'maple_carts_admin', 'nonce' ); + + if ( ! current_user_can( 'manage_woocommerce' ) ) { + wp_send_json_error( 'Permission denied' ); + } + + $id = isset( $_POST['template_id'] ) ? absint( $_POST['template_id'] ) : 0; + + if ( ! $id ) { + wp_send_json_error( 'Invalid template ID' ); + } + + if ( Maple_Carts_DB::delete_email_template( $id ) ) { + wp_send_json_success(); + } else { + wp_send_json_error( 'Failed to delete template' ); + } + } + + /** + * AJAX: Toggle template active status. + */ + public function ajax_toggle_template() { + check_ajax_referer( 'maple_carts_admin', 'nonce' ); + + if ( ! current_user_can( 'manage_woocommerce' ) ) { + wp_send_json_error( 'Permission denied' ); + } + + $id = isset( $_POST['template_id'] ) ? absint( $_POST['template_id'] ) : 0; + $active = isset( $_POST['active'] ) ? absint( $_POST['active'] ) : 0; + + if ( ! $id ) { + wp_send_json_error( 'Invalid template ID' ); + } + + global $wpdb; + $result = $wpdb->update( + $wpdb->prefix . MAPLE_CARTS_EMAILS_TABLE, + [ 'is_active' => $active ? 0 : 1 ], + [ 'id' => $id ] + ); + + if ( false !== $result ) { + wp_send_json_success( [ 'is_active' => $active ? 0 : 1 ] ); + } else { + wp_send_json_error( 'Failed to update template' ); + } + } +} diff --git a/native/wordpress/maple-carts-wp/includes/class-maple-carts-db.php b/native/wordpress/maple-carts-wp/includes/class-maple-carts-db.php new file mode 100644 index 0000000..4d090b9 --- /dev/null +++ b/native/wordpress/maple-carts-wp/includes/class-maple-carts-db.php @@ -0,0 +1,795 @@ + 300, + 'display' => __( 'Every Five Minutes', 'maple-carts' ), + ]; + return $schedules; + } + + /** + * Create database tables. + */ + public static function create_tables() { + global $wpdb; + + $charset_collate = $wpdb->get_charset_collate(); + $carts_table = $wpdb->prefix . MAPLE_CARTS_TABLE; + $emails_table = $wpdb->prefix . MAPLE_CARTS_EMAILS_TABLE; + $log_table = $wpdb->prefix . MAPLE_CARTS_EMAIL_LOG_TABLE; + + require_once ABSPATH . 'wp-admin/includes/upgrade.php'; + + // Abandoned carts table. + $sql = "CREATE TABLE {$carts_table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + session_id VARCHAR(60) NOT NULL, + email VARCHAR(200) DEFAULT NULL, + cart_contents LONGTEXT, + cart_total DECIMAL(10,2) DEFAULT 0, + items_count INT DEFAULT 0, + currency VARCHAR(10) DEFAULT 'USD', + customer_name VARCHAR(200) DEFAULT NULL, + customer_phone VARCHAR(50) DEFAULT NULL, + billing_data LONGTEXT, + status ENUM('active','abandoned','recovered','lost','converted') DEFAULT 'active', + abandonment_type ENUM('browsing','checkout','payment') DEFAULT NULL, + recovery_url VARCHAR(255) DEFAULT NULL, + coupon_code VARCHAR(50) DEFAULT NULL, + recovery_source VARCHAR(50) DEFAULT NULL, + unsubscribed TINYINT(1) DEFAULT 0, + ip_address VARCHAR(45) DEFAULT NULL, + user_agent TEXT, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + first_seen_at DATETIME DEFAULT NULL, + last_tracked_at DATETIME DEFAULT NULL, + abandoned_at DATETIME DEFAULT NULL, + recovered_at DATETIME DEFAULT NULL, + PRIMARY KEY (id), + UNIQUE KEY session_id (session_id), + KEY email (email), + KEY status (status), + KEY created_at (created_at), + KEY updated_at (updated_at), + KEY last_tracked_at (last_tracked_at), + KEY status_tracked (status, last_tracked_at) + ) {$charset_collate};"; + dbDelta( $sql ); + + // Email templates table. + $sql = "CREATE TABLE {$emails_table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + name VARCHAR(200) NOT NULL, + subject VARCHAR(500) NOT NULL, + body LONGTEXT NOT NULL, + delay_value INT(11) DEFAULT 1, + delay_unit ENUM('minutes','hours','days') DEFAULT 'hours', + is_active TINYINT(1) DEFAULT 0, + include_coupon TINYINT(1) DEFAULT 0, + coupon_type ENUM('percent','fixed_cart') DEFAULT 'percent', + coupon_amount DECIMAL(10,2) DEFAULT 10, + coupon_expires_days INT(11) DEFAULT 7, + sort_order INT(11) DEFAULT 0, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (id), + KEY is_active (is_active), + KEY sort_order (sort_order) + ) {$charset_collate};"; + dbDelta( $sql ); + + // Email log table. + $sql = "CREATE TABLE {$log_table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + cart_id BIGINT(20) UNSIGNED NOT NULL, + email_template_id BIGINT(20) UNSIGNED NOT NULL, + scheduled_at DATETIME NOT NULL, + sent_at DATETIME DEFAULT NULL, + status ENUM('pending','sent','failed','cancelled') DEFAULT 'pending', + coupon_code VARCHAR(50) DEFAULT NULL, + error_message TEXT, + PRIMARY KEY (id), + KEY cart_id (cart_id), + KEY email_template_id (email_template_id), + KEY status (status), + KEY scheduled_at (scheduled_at) + ) {$charset_collate};"; + dbDelta( $sql ); + } + + /** + * Set default options. + */ + public static function set_default_options() { + $defaults = [ + 'enabled' => 'yes', + 'cart_cutoff_time' => 15, // Minutes before cart is considered abandoned. + 'delete_after_days' => 90, // Days to keep abandoned cart data. + 'email_mode' => 'builtin', // 'builtin' or 'mailjet'. + 'mailjet_api_key' => '', + 'mailjet_secret_key'=> '', + 'from_name' => get_bloginfo( 'name' ), + 'from_email' => get_option( 'admin_email' ), + 'reply_to' => get_option( 'admin_email' ), + 'notify_admin' => 'yes', + 'admin_email' => get_option( 'admin_email' ), + 'require_consent' => 'no', + 'consent_text' => __( 'I agree to receive cart reminder emails if I don\'t complete my purchase.', 'maple-carts' ), + 'show_delete_link' => 'no', + 'exclude_roles' => [], + 'gdpr_notice' => '', + ]; + + $existing = get_option( 'maple_carts_settings', [] ); + $merged = array_merge( $defaults, $existing ); + update_option( 'maple_carts_settings', $merged ); + } + + /** + * Seed default email templates. + */ + public static function seed_default_emails() { + global $wpdb; + + $table = $wpdb->prefix . MAPLE_CARTS_EMAILS_TABLE; + $count = $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); + + if ( $count > 0 ) { + return; + } + + $templates = [ + [ + 'name' => __( 'First Reminder', 'maple-carts' ), + 'subject' => __( '{{customer_name}}, you left something behind!', 'maple-carts' ), + 'body' => self::get_default_email_body( 1 ), + 'delay_value' => 1, + 'delay_unit' => 'hours', + 'is_active' => 0, + 'include_coupon' => 0, + 'sort_order' => 1, + ], + [ + 'name' => __( 'Second Reminder', 'maple-carts' ), + 'subject' => __( 'Your cart is waiting, {{customer_name}}', 'maple-carts' ), + 'body' => self::get_default_email_body( 2 ), + 'delay_value' => 24, + 'delay_unit' => 'hours', + 'is_active' => 0, + 'include_coupon' => 0, + 'sort_order' => 2, + ], + [ + 'name' => __( 'Final Reminder with Discount', 'maple-carts' ), + 'subject' => __( 'Last chance! {{coupon_amount}} off your cart', 'maple-carts' ), + 'body' => self::get_default_email_body( 3 ), + 'delay_value' => 3, + 'delay_unit' => 'days', + 'is_active' => 0, + 'include_coupon' => 1, + 'coupon_type' => 'percent', + 'coupon_amount' => 10, + 'sort_order' => 3, + ], + ]; + + foreach ( $templates as $template ) { + $wpdb->insert( $table, $template ); + } + } + + /** + * Get default email body. + * + * @param int $template_num Template number. + * @return string + */ + private static function get_default_email_body( $template_num ) { + $bodies = [ + 1 => '

Hi {{customer_name}},

+

We noticed you left some items in your cart at {{site_name}}. No worries — your cart is saved and ready when you are!

+

{{cart_contents}}

+

Complete Your Order

+

If you have any questions, just reply to this email.

+

Thanks,
{{site_name}}

+

{{unsubscribe_link}}{{delete_data_link}}

', + + 2 => '

Hi {{customer_name}},

+

Just a friendly reminder that your cart at {{site_name}} is still waiting for you.

+

{{cart_contents}}

+

Cart Total: {{cart_total}}

+

Return to Your Cart

+

Best,
{{site_name}}

+

{{unsubscribe_link}}{{delete_data_link}}

', + + 3 => '

Hi {{customer_name}},

+

This is your last reminder about the items in your cart. To help you complete your purchase, we\'re offering you an exclusive discount!

+

{{cart_contents}}

+

Use code {{coupon_code}} for {{coupon_amount}} off!

+

Claim Your Discount

+

This offer expires in {{coupon_expires}} days.

+

Thanks,
{{site_name}}

+

{{unsubscribe_link}}{{delete_data_link}}

', + ]; + + return $bodies[ $template_num ] ?? $bodies[1]; + } + + /** + * Get a cart by session ID. + * + * @param string $session_id Session ID. + * @return object|null + */ + public static function get_cart_by_session( $session_id ) { + global $wpdb; + $table = $wpdb->prefix . MAPLE_CARTS_TABLE; + return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE session_id = %s", $session_id ) ); + } + + /** + * Get a cart by email. + * + * @param string $email Email address. + * @param array $statuses Statuses to filter by. + * @return object|null + */ + public static function get_cart_by_email( $email, $statuses = [ 'active', 'abandoned' ] ) { + global $wpdb; + $table = $wpdb->prefix . MAPLE_CARTS_TABLE; + $placeholders = implode( ',', array_fill( 0, count( $statuses ), '%s' ) ); + $params = array_merge( [ $email ], $statuses ); + + return $wpdb->get_row( + $wpdb->prepare( + "SELECT * FROM {$table} WHERE email = %s AND status IN ({$placeholders}) ORDER BY created_at DESC LIMIT 1", + $params + ) + ); + } + + /** + * Insert or update a cart. + * + * @param array $data Cart data. + * @return int|false Cart ID or false on failure. + */ + public static function save_cart( $data ) { + global $wpdb; + $table = $wpdb->prefix . MAPLE_CARTS_TABLE; + + // Always update last_tracked_at when saving. + $data['last_tracked_at'] = current_time( 'mysql' ); + + $existing = null; + if ( ! empty( $data['session_id'] ) ) { + $existing = self::get_cart_by_session( $data['session_id'] ); + } + + if ( $existing ) { + $wpdb->update( $table, $data, [ 'id' => $existing->id ] ); + $cart_id = $existing->id; + } else { + // Set first_seen_at for new carts. + $data['first_seen_at'] = current_time( 'mysql' ); + $wpdb->insert( $table, $data ); + $cart_id = $wpdb->insert_id; + } + + // Fire webhook for integrations (Facebook CAPI, etc.). + if ( $cart_id ) { + $cart = self::get_cart_by_id( $cart_id ); + if ( $cart ) { + /** + * Fires when a cart is created or updated. + * Useful for Facebook CAPI, retargeting pixels, etc. + * + * @param object $cart Cart object. + */ + do_action( 'maple_carts_cart_updated', $cart ); + } + } + + return $cart_id; + } + + /** + * Update cart status. + * + * @param int $cart_id Cart ID. + * @param string $status New status. + * @param array $extra Extra data to update. + */ + public static function update_cart_status( $cart_id, $status, $extra = [] ) { + global $wpdb; + $table = $wpdb->prefix . MAPLE_CARTS_TABLE; + + $data = array_merge( [ 'status' => $status ], $extra ); + + if ( 'abandoned' === $status ) { + $data['abandoned_at'] = current_time( 'mysql' ); + } elseif ( 'recovered' === $status ) { + $data['recovered_at'] = current_time( 'mysql' ); + } + + $wpdb->update( $table, $data, [ 'id' => $cart_id ] ); + + // Fire hooks for integrations (Mailjet, etc.). + $cart = self::get_cart_by_id( $cart_id ); + if ( $cart ) { + if ( 'abandoned' === $status ) { + /** + * Fires when a cart is marked as abandoned. + * + * @param int $cart_id Cart ID. + * @param object $cart Cart object. + */ + do_action( 'maple_carts_cart_abandoned', $cart_id, $cart ); + } elseif ( 'recovered' === $status ) { + /** + * Fires when a cart is recovered. + * + * @param int $cart_id Cart ID. + * @param object $cart Cart object. + */ + do_action( 'maple_carts_cart_recovered', $cart_id, $cart ); + } elseif ( 'converted' === $status ) { + /** + * Fires when a cart is converted (order placed). + * + * @param int $cart_id Cart ID. + * @param object $cart Cart object. + */ + do_action( 'maple_carts_cart_converted', $cart_id, $cart ); + } + } + } + + /** + * Get cart by ID. + * + * @param int $cart_id Cart ID. + * @return object|null + */ + public static function get_cart_by_id( $cart_id ) { + global $wpdb; + $table = $wpdb->prefix . MAPLE_CARTS_TABLE; + + return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $cart_id ) ); + } + + /** + * Get carts by status. + * + * @param string $status Status. + * @param int $limit Limit. + * @param int $offset Offset. + * @return array + */ + public static function get_carts_by_status( $status, $limit = 50, $offset = 0 ) { + global $wpdb; + $table = $wpdb->prefix . MAPLE_CARTS_TABLE; + + return $wpdb->get_results( + $wpdb->prepare( + "SELECT * FROM {$table} WHERE status = %s ORDER BY created_at DESC LIMIT %d OFFSET %d", + $status, + $limit, + $offset + ) + ); + } + + /** + * Count carts by status. + * + * @param string $status Status. + * @return int + */ + public static function count_carts_by_status( $status ) { + global $wpdb; + $table = $wpdb->prefix . MAPLE_CARTS_TABLE; + + return (int) $wpdb->get_var( + $wpdb->prepare( "SELECT COUNT(*) FROM {$table} WHERE status = %s", $status ) + ); + } + + /** + * Get all email templates. + * + * @param bool $active_only Only active templates. + * @return array + */ + public static function get_email_templates( $active_only = false ) { + global $wpdb; + $table = $wpdb->prefix . MAPLE_CARTS_EMAILS_TABLE; + + $where = $active_only ? 'WHERE is_active = 1' : ''; + + return $wpdb->get_results( "SELECT * FROM {$table} {$where} ORDER BY sort_order ASC" ); + } + + /** + * Get email template by ID. + * + * @param int $id Template ID. + * @return object|null + */ + public static function get_email_template( $id ) { + global $wpdb; + $table = $wpdb->prefix . MAPLE_CARTS_EMAILS_TABLE; + + return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $id ) ); + } + + /** + * Save email template. + * + * @param array $data Template data. + * @return int|false Template ID or false. + */ + public static function save_email_template( $data ) { + global $wpdb; + $table = $wpdb->prefix . MAPLE_CARTS_EMAILS_TABLE; + + if ( ! empty( $data['id'] ) ) { + $id = $data['id']; + unset( $data['id'] ); + $wpdb->update( $table, $data, [ 'id' => $id ] ); + return $id; + } else { + $wpdb->insert( $table, $data ); + return $wpdb->insert_id; + } + } + + /** + * Delete email template. + * + * @param int $id Template ID. + * @return bool + */ + public static function delete_email_template( $id ) { + global $wpdb; + $table = $wpdb->prefix . MAPLE_CARTS_EMAILS_TABLE; + + return $wpdb->delete( $table, [ 'id' => $id ] ) !== false; + } + + /** + * Schedule emails for a cart. + * + * @param int $cart_id Cart ID. + */ + public static function schedule_emails( $cart_id ) { + global $wpdb; + + $log_table = $wpdb->prefix . MAPLE_CARTS_EMAIL_LOG_TABLE; + $cart = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}" . MAPLE_CARTS_TABLE . " WHERE id = %d", $cart_id ) ); + + if ( ! $cart || $cart->unsubscribed ) { + return; + } + + $templates = self::get_email_templates( true ); + if ( empty( $templates ) ) { + return; + } + + $base_time = $cart->abandoned_at ? $cart->abandoned_at : current_time( 'mysql' ); + + // Get all existing scheduled emails for this cart in one query. + $existing_template_ids = $wpdb->get_col( + $wpdb->prepare( + "SELECT email_template_id FROM {$log_table} WHERE cart_id = %d", + $cart_id + ) + ); + $existing_set = array_flip( $existing_template_ids ); + + foreach ( $templates as $template ) { + // Skip if already scheduled. + if ( isset( $existing_set[ $template->id ] ) ) { + continue; + } + + // Calculate scheduled time. + $delay_seconds = self::get_delay_seconds( $template->delay_value, $template->delay_unit ); + $scheduled_at = gmdate( 'Y-m-d H:i:s', strtotime( $base_time ) + $delay_seconds ); + + $wpdb->insert( + $log_table, + [ + 'cart_id' => $cart_id, + 'email_template_id' => $template->id, + 'scheduled_at' => $scheduled_at, + 'status' => 'pending', + ] + ); + } + } + + /** + * Get delay in seconds. + * + * @param int $value Delay value. + * @param string $unit Delay unit. + * @return int + */ + private static function get_delay_seconds( $value, $unit ) { + switch ( $unit ) { + case 'minutes': + return $value * 60; + case 'hours': + return $value * 3600; + case 'days': + return $value * 86400; + default: + return $value * 3600; + } + } + + /** + * Get pending emails to send. + * + * @return array + */ + public static function get_pending_emails() { + global $wpdb; + + $log_table = $wpdb->prefix . MAPLE_CARTS_EMAIL_LOG_TABLE; + $carts_table = $wpdb->prefix . MAPLE_CARTS_TABLE; + $email_table = $wpdb->prefix . MAPLE_CARTS_EMAILS_TABLE; + $now = current_time( 'mysql' ); + + return $wpdb->get_results( + $wpdb->prepare( + "SELECT l.*, c.email, c.customer_name, c.cart_contents, c.cart_total, c.currency, + c.session_id, c.coupon_code as cart_coupon, c.billing_data, + e.subject, e.body, e.include_coupon, e.coupon_type, e.coupon_amount, e.coupon_expires_days + FROM {$log_table} l + JOIN {$carts_table} c ON l.cart_id = c.id + JOIN {$email_table} e ON l.email_template_id = e.id + WHERE l.status = 'pending' + AND l.scheduled_at <= %s + AND c.status = 'abandoned' + AND c.unsubscribed = 0 + ORDER BY l.scheduled_at ASC + LIMIT 50", + $now + ) + ); + } + + /** + * Update email log status. + * + * @param int $id Log ID. + * @param string $status Status. + * @param array $extra Extra data. + */ + public static function update_email_log( $id, $status, $extra = [] ) { + global $wpdb; + $table = $wpdb->prefix . MAPLE_CARTS_EMAIL_LOG_TABLE; + + $data = array_merge( [ 'status' => $status ], $extra ); + + if ( 'sent' === $status ) { + $data['sent_at'] = current_time( 'mysql' ); + } + + $wpdb->update( $table, $data, [ 'id' => $id ] ); + } + + /** + * Cancel pending emails for a cart. + * + * @param int $cart_id Cart ID. + */ + public static function cancel_pending_emails( $cart_id ) { + global $wpdb; + $table = $wpdb->prefix . MAPLE_CARTS_EMAIL_LOG_TABLE; + + $wpdb->update( + $table, + [ 'status' => 'cancelled' ], + [ 'cart_id' => $cart_id, 'status' => 'pending' ] + ); + } + + /** + * Get cart statistics. + * + * @param string $period Period (7days, 30days, all). + * @return array + */ + public static function get_stats( $period = '30days' ) { + global $wpdb; + $table = $wpdb->prefix . MAPLE_CARTS_TABLE; + + $date_filter = ''; + if ( '7days' === $period ) { + $date_filter = "AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"; + } elseif ( '30days' === $period ) { + $date_filter = "AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)"; + } + + $stats = [ + 'abandoned' => 0, + 'recovered' => 0, + 'lost' => 0, + 'abandoned_value' => 0, + 'recovered_value' => 0, + 'recovery_rate' => 0, + ]; + + $results = $wpdb->get_results( + "SELECT status, COUNT(*) as count, SUM(cart_total) as total + FROM {$table} + WHERE 1=1 {$date_filter} + GROUP BY status" + ); + + foreach ( $results as $row ) { + if ( 'abandoned' === $row->status ) { + $stats['abandoned'] = (int) $row->count; + $stats['abandoned_value'] = (float) $row->total; + } elseif ( 'recovered' === $row->status ) { + $stats['recovered'] = (int) $row->count; + $stats['recovered_value'] = (float) $row->total; + } elseif ( 'lost' === $row->status ) { + $stats['lost'] = (int) $row->count; + } + } + + $total_actionable = $stats['abandoned'] + $stats['recovered'] + $stats['lost']; + if ( $total_actionable > 0 ) { + $stats['recovery_rate'] = round( ( $stats['recovered'] / $total_actionable ) * 100, 1 ); + } + + return $stats; + } + + /** + * Cleanup old data. + * Runs daily, processes in batches to prevent memory issues. + */ + public static function cleanup_old_data() { + global $wpdb; + + // Prevent overlapping runs. + if ( get_transient( 'maple_carts_cleanup_running' ) ) { + return; + } + set_transient( 'maple_carts_cleanup_running', 1, 3600 ); // 1 hour lock. + + $days = (int) Maple_Carts::get_option( 'delete_after_days', 90 ); + $carts_table = $wpdb->prefix . MAPLE_CARTS_TABLE; + $log_table = $wpdb->prefix . MAPLE_CARTS_EMAIL_LOG_TABLE; + $batch_size = 500; + + // Delete old carts in batches. + $wpdb->query( + $wpdb->prepare( + "DELETE FROM {$carts_table} WHERE created_at < DATE_SUB(NOW(), INTERVAL %d DAY) LIMIT %d", + $days, + $batch_size + ) + ); + + // Delete orphaned email logs in batches. + $wpdb->query( + "DELETE l FROM {$log_table} l + LEFT JOIN {$carts_table} c ON l.cart_id = c.id + WHERE c.id IS NULL + LIMIT {$batch_size}" + ); + + // Delete expired coupons created by this plugin (batched). + $expired_coupons = $wpdb->get_col( + $wpdb->prepare( + "SELECT ID FROM {$wpdb->posts} + WHERE post_type = 'shop_coupon' + AND ID IN ( + SELECT post_id FROM {$wpdb->postmeta} + WHERE meta_key = '_maple_carts_coupon' AND meta_value = '1' + ) + AND ID IN ( + SELECT post_id FROM {$wpdb->postmeta} + WHERE meta_key = 'date_expires' AND meta_value < UNIX_TIMESTAMP() + ) + LIMIT %d", + $batch_size + ) + ); + + foreach ( $expired_coupons as $coupon_id ) { + wp_delete_post( $coupon_id, true ); + } + + // Delete unused coupons older than 30 days (never used, cart may have converted another way). + $unused_old_coupons = $wpdb->get_col( + $wpdb->prepare( + "SELECT p.ID FROM {$wpdb->posts} p + INNER JOIN {$wpdb->postmeta} pm_maple ON p.ID = pm_maple.post_id + AND pm_maple.meta_key = '_maple_carts_coupon' AND pm_maple.meta_value = '1' + INNER JOIN {$wpdb->postmeta} pm_created ON p.ID = pm_created.post_id + AND pm_created.meta_key = '_maple_carts_created_at' AND pm_created.meta_value < %d + INNER JOIN {$wpdb->postmeta} pm_usage ON p.ID = pm_usage.post_id + AND pm_usage.meta_key = 'usage_count' AND pm_usage.meta_value = '0' + WHERE p.post_type = 'shop_coupon' + LIMIT %d", + strtotime( '-30 days' ), + $batch_size + ) + ); + + foreach ( $unused_old_coupons as $coupon_id ) { + wp_delete_post( $coupon_id, true ); + } + + delete_transient( 'maple_carts_cleanup_running' ); + } + + /** + * Delete a cart. + * + * @param int $cart_id Cart ID. + * @return bool + */ + public static function delete_cart( $cart_id ) { + global $wpdb; + + // Delete email logs first. + $wpdb->delete( $wpdb->prefix . MAPLE_CARTS_EMAIL_LOG_TABLE, [ 'cart_id' => $cart_id ] ); + + // Delete cart. + return $wpdb->delete( $wpdb->prefix . MAPLE_CARTS_TABLE, [ 'id' => $cart_id ] ) !== false; + } +} + +// Register cron interval early. +add_filter( 'cron_schedules', [ 'Maple_Carts_DB', 'add_cron_interval' ] ); diff --git a/native/wordpress/maple-carts-wp/includes/class-maple-carts-emails.php b/native/wordpress/maple-carts-wp/includes/class-maple-carts-emails.php new file mode 100644 index 0000000..3bac2e9 --- /dev/null +++ b/native/wordpress/maple-carts-wp/includes/class-maple-carts-emails.php @@ -0,0 +1,633 @@ +send_email( $email_data ); + } + + delete_transient( 'maple_carts_sending_emails' ); + } + + /** + * Send a recovery email. + * + * @param object $email_data Email data from database. + * @return bool + */ + public function send_email( $email_data ) { + // Validate email address. + if ( ! is_email( $email_data->email ) ) { + Maple_Carts_DB::update_email_log( $email_data->id, 'failed', [ 'error_message' => 'Invalid email address' ] ); + return false; + } + + // Check if cart still qualifies. + $cart = Maple_Carts_DB::get_cart_by_session( $email_data->session_id ); + if ( ! $cart || 'abandoned' !== $cart->status || $cart->unsubscribed ) { + Maple_Carts_DB::update_email_log( $email_data->id, 'cancelled' ); + return false; + } + + // Check for out-of-stock products. + $cart_contents = maybe_unserialize( $email_data->cart_contents ); + if ( $this->cart_has_out_of_stock( $cart_contents ) ) { + Maple_Carts_DB::update_email_log( $email_data->id, 'cancelled', [ 'error_message' => 'Products out of stock' ] ); + return false; + } + + // Generate coupon if needed. + $coupon_code = ''; + if ( $email_data->include_coupon ) { + $coupon_code = $this->generate_coupon( + $email_data->coupon_type, + $email_data->coupon_amount, + $email_data->coupon_expires_days, + $email_data->cart_id + ); + + // Store coupon code in log. + global $wpdb; + $wpdb->update( + $wpdb->prefix . MAPLE_CARTS_EMAIL_LOG_TABLE, + [ 'coupon_code' => $coupon_code ], + [ 'id' => $email_data->id ] + ); + } + + // Generate recovery URL with coupon. + $recovery_url = Maple_Carts_Tracking::instance()->generate_recovery_url( + $email_data->session_id, + $coupon_code + ); + + // Add UTM parameters for analytics attribution. + $recovery_url = add_query_arg( [ + 'utm_source' => 'maple_carts', + 'utm_medium' => 'email', + 'utm_campaign' => 'cart_recovery', + 'utm_content' => 'email_' . $email_data->email_template_id, + ], $recovery_url ); + + // Parse email content. + $subject = $this->parse_template( $email_data->subject, $email_data, $coupon_code, $recovery_url ); + $body = $this->parse_template( $email_data->body, $email_data, $coupon_code, $recovery_url ); + + // Send email. + $sent = $this->dispatch_email( $email_data->email, $subject, $body ); + + if ( $sent ) { + Maple_Carts_DB::update_email_log( $email_data->id, 'sent' ); + + /** + * Fires after a recovery email is sent. + * + * @param object $email_data Email data. + * @param string $subject Email subject. + */ + do_action( 'maple_carts_email_sent', $email_data, $subject ); + + return true; + } else { + Maple_Carts_DB::update_email_log( $email_data->id, 'failed', [ 'error_message' => 'Failed to send email' ] ); + return false; + } + } + + /** + * Parse email template with placeholders. + * + * @param string $template Template string. + * @param object $email_data Email data. + * @param string $coupon_code Coupon code. + * @param string $recovery_url Recovery URL. + * @return string + */ + private function parse_template( $template, $email_data, $coupon_code, $recovery_url ) { + $cart_contents = maybe_unserialize( $email_data->cart_contents ); + + // Customer name fallback. + $customer_name = $email_data->customer_name; + if ( empty( $customer_name ) ) { + $customer_name = __( 'there', 'maple-carts' ); + } + + // Generate cart contents HTML. + $cart_html = $this->generate_cart_html( $cart_contents, $email_data->currency ); + + // Generate product names list. + $product_names = []; + if ( is_array( $cart_contents ) ) { + foreach ( $cart_contents as $item ) { + $product_names[] = $item['name']; + } + } + + // Coupon display amount. + $coupon_display = ''; + if ( ! empty( $coupon_code ) ) { + if ( 'percent' === $email_data->coupon_type ) { + $coupon_display = $email_data->coupon_amount . '%'; + } else { + $coupon_display = wc_price( $email_data->coupon_amount ); + } + } + + // Unsubscribe link (using signed URL from Tracking class). + $unsubscribe_url = Maple_Carts_Tracking::instance()->generate_unsubscribe_url( $email_data->session_id ); + $unsubscribe_link = sprintf( + '%s', + esc_url( $unsubscribe_url ), + __( 'Unsubscribe from these emails', 'maple-carts' ) + ); + + // Delete data link for GDPR compliance (optional). + $delete_data_link = ''; + if ( 'yes' === Maple_Carts::get_option( 'show_delete_link', 'no' ) ) { + $delete_data_url = Maple_Carts_Privacy::generate_deletion_url( $email_data->session_id ); + $delete_data_link = sprintf( + ' | %s', + esc_url( $delete_data_url ), + __( 'Delete my data', 'maple-carts' ) + ); + } + + // Replacements. + $replacements = [ + '{{customer_name}}' => esc_html( $customer_name ), + '{{customer_email}}' => esc_html( $email_data->email ), + '{{cart_contents}}' => $cart_html, + '{{cart_total}}' => wc_price( $email_data->cart_total, [ 'currency' => $email_data->currency ] ), + '{{product_names}}' => esc_html( implode( ', ', $product_names ) ), + '{{recovery_url}}' => esc_url( $recovery_url ), + '{{coupon_code}}' => esc_html( $coupon_code ), + '{{coupon_amount}}' => $coupon_display, + '{{coupon_expires}}' => $email_data->coupon_expires_days, + '{{site_name}}' => esc_html( get_bloginfo( 'name' ) ), + '{{site_url}}' => esc_url( home_url() ), + '{{unsubscribe_link}}' => $unsubscribe_link, + '{{delete_data_link}}' => $delete_data_link, + '{{current_date}}' => date_i18n( get_option( 'date_format' ) ), + ]; + + /** + * Filter email template replacements. + * + * @param array $replacements Placeholder replacements. + * @param object $email_data Email data. + */ + $replacements = apply_filters( 'maple_carts_email_replacements', $replacements, $email_data ); + + return str_replace( array_keys( $replacements ), array_values( $replacements ), $template ); + } + + /** + * Generate cart contents HTML. + * + * @param array $cart_contents Cart contents. + * @param string $currency Currency code. + * @return string + */ + private function generate_cart_html( $cart_contents, $currency = 'USD' ) { + if ( empty( $cart_contents ) || ! is_array( $cart_contents ) ) { + return ''; + } + + $html = ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + + $total = 0; + foreach ( $cart_contents as $item ) { + $line_total = $item['price'] * $item['quantity']; + $total += $line_total; + + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + } + + $html .= '
' . __( 'Product', 'maple-carts' ) . '' . __( 'Qty', 'maple-carts' ) . '' . __( 'Price', 'maple-carts' ) . '
'; + + if ( ! empty( $item['image'] ) ) { + $html .= ''; + } + + $html .= '' . esc_html( $item['name'] ) . ''; + $html .= '' . esc_html( $item['quantity'] ) . '' . wc_price( $line_total, [ 'currency' => $currency ] ) . '
'; + + return $html; + } + + /** + * Check if cart has out of stock products. + * + * @param array $cart_contents Cart contents. + * @return bool + */ + private function cart_has_out_of_stock( $cart_contents ) { + if ( empty( $cart_contents ) || ! is_array( $cart_contents ) ) { + return false; + } + + foreach ( $cart_contents as $item ) { + $product_id = ! empty( $item['variation_id'] ) ? $item['variation_id'] : $item['product_id']; + $product = wc_get_product( $product_id ); + + if ( ! $product || ! $product->is_in_stock() ) { + return true; + } + } + + return false; + } + + /** + * Generate a coupon code. + * + * @param string $type Coupon type (percent, fixed_cart). + * @param float $amount Discount amount. + * @param int $expires_days Days until expiry. + * @param int $cart_id Cart ID for reference. + * @return string + */ + public function generate_coupon( $type, $amount, $expires_days, $cart_id ) { + // Check if cart already has a coupon (prevents double creation on cron misfire). + $existing_coupon = $this->get_cart_coupon( $cart_id ); + if ( $existing_coupon ) { + return $existing_coupon; + } + + $coupon_code = 'MAPLE-' . strtoupper( wp_generate_password( 8, false, false ) ); + + $coupon = new WC_Coupon(); + $coupon->set_code( $coupon_code ); + $coupon->set_discount_type( $type ); + $coupon->set_amount( $amount ); + $coupon->set_individual_use( true ); + $coupon->set_usage_limit( 1 ); + $coupon->set_usage_limit_per_user( 1 ); + + if ( $expires_days > 0 ) { + $expiry = strtotime( "+{$expires_days} days" ); + $coupon->set_date_expires( $expiry ); + } + + $coupon->save(); + + // Mark as Maple Carts coupon for cleanup with creation timestamp. + update_post_meta( $coupon->get_id(), '_maple_carts_coupon', '1' ); + update_post_meta( $coupon->get_id(), '_maple_carts_cart_id', $cart_id ); + update_post_meta( $coupon->get_id(), '_maple_carts_created_at', time() ); + + return $coupon_code; + } + + /** + * Get existing coupon for a cart (prevents double creation). + * + * @param int $cart_id Cart ID. + * @return string|null Coupon code or null. + */ + private function get_cart_coupon( $cart_id ) { + global $wpdb; + + // Check email log for existing coupon. + $log_table = $wpdb->prefix . MAPLE_CARTS_EMAIL_LOG_TABLE; + $coupon = $wpdb->get_var( $wpdb->prepare( + "SELECT coupon_code FROM {$log_table} + WHERE cart_id = %d AND coupon_code IS NOT NULL AND coupon_code != '' + LIMIT 1", + $cart_id + ) ); + + if ( $coupon ) { + // Verify coupon still exists in WooCommerce. + $coupon_id = wc_get_coupon_id_by_code( $coupon ); + if ( $coupon_id ) { + return $coupon; + } + } + + return null; + } + + /** + * Dispatch email using wp_mail (works with any SMTP plugin). + * + * @param string $to Recipient email. + * @param string $subject Email subject. + * @param string $body Email body (HTML). + * @return bool + */ + private function dispatch_email( $to, $subject, $body ) { + // Sanitize header values to prevent header injection. + $from_name = $this->sanitize_header_value( Maple_Carts::get_option( 'from_name', get_bloginfo( 'name' ) ) ); + $from_email = $this->sanitize_header_value( Maple_Carts::get_option( 'from_email', get_option( 'admin_email' ) ) ); + $reply_to = $this->sanitize_header_value( Maple_Carts::get_option( 'reply_to', get_option( 'admin_email' ) ) ); + + // Validate email addresses. + if ( ! is_email( $from_email ) ) { + $from_email = get_option( 'admin_email' ); + } + if ( ! is_email( $reply_to ) ) { + $reply_to = get_option( 'admin_email' ); + } + + // Wrap in basic HTML template. + $html_body = $this->wrap_email_html( $body ); + + // Generate plain text alternative for better spam scores. + $plain_body = $this->generate_plain_text( $body ); + + // Create multipart boundary. + $boundary = 'maple_carts_' . md5( uniqid( time() ) ); + + $headers = [ + "From: {$from_name} <{$from_email}>", + "Reply-To: {$reply_to}", + "Content-Type: multipart/alternative; boundary=\"{$boundary}\"", + ]; + + // Build multipart message. + $message = "--{$boundary}\r\n"; + $message .= "Content-Type: text/plain; charset=UTF-8\r\n"; + $message .= "Content-Transfer-Encoding: 8bit\r\n\r\n"; + $message .= $plain_body . "\r\n\r\n"; + $message .= "--{$boundary}\r\n"; + $message .= "Content-Type: text/html; charset=UTF-8\r\n"; + $message .= "Content-Transfer-Encoding: 8bit\r\n\r\n"; + $message .= $html_body . "\r\n\r\n"; + $message .= "--{$boundary}--"; + + /** + * Filter the email before sending. + * + * @param array $email Email data. + */ + $email = apply_filters( 'maple_carts_before_send_email', [ + 'to' => $to, + 'subject' => $subject, + 'body' => $message, + 'headers' => $headers, + ] ); + + // Use wp_mail which integrates with SMTP plugins. + $sent = wp_mail( $email['to'], $email['subject'], $email['body'], $email['headers'] ); + + // Retry once on failure. + if ( ! $sent ) { + sleep( 1 ); + $sent = wp_mail( $email['to'], $email['subject'], $email['body'], $email['headers'] ); + } + + return $sent; + } + + /** + * Generate plain text version of HTML email. + * + * @param string $html HTML content. + * @return string Plain text content. + */ + private function generate_plain_text( $html ) { + // Convert common HTML elements. + $text = $html; + + // Convert links to text format. + $text = preg_replace( '/]+href=["\']([^"\']+)["\'][^>]*>([^<]+)<\/a>/i', '$2 ($1)', $text ); + + // Convert line breaks and paragraphs. + $text = preg_replace( '//i', "\n", $text ); + $text = preg_replace( '/<\/p>/i', "\n\n", $text ); + $text = preg_replace( '/<\/div>/i', "\n", $text ); + $text = preg_replace( '/<\/h[1-6]>/i', "\n\n", $text ); + + // Convert list items. + $text = preg_replace( '/]*>/i', "• ", $text ); + $text = preg_replace( '/<\/li>/i', "\n", $text ); + + // Strip remaining tags. + $text = wp_strip_all_tags( $text ); + + // Decode HTML entities. + $text = html_entity_decode( $text, ENT_QUOTES, 'UTF-8' ); + + // Clean up whitespace. + $text = preg_replace( '/[ \t]+/', ' ', $text ); + $text = preg_replace( '/\n{3,}/', "\n\n", $text ); + $text = trim( $text ); + + return $text; + } + + /** + * Sanitize a value for use in email headers. + * Prevents header injection attacks by removing newlines and control characters. + * + * @param string $value The value to sanitize. + * @return string + */ + private function sanitize_header_value( $value ) { + // Remove any newlines, carriage returns, and null bytes. + $value = preg_replace( '/[\r\n\0]/', '', $value ); + // Remove any remaining control characters. + $value = preg_replace( '/[\x00-\x1F\x7F]/', '', $value ); + return trim( $value ); + } + + /** + * Wrap email content in HTML template. + * + * @param string $content Email content. + * @return string + */ + private function wrap_email_html( $content ) { + $template = ' + + + + + + + + + + +
+ + + + +
+ {{content}} +
+
+ +'; + + return str_replace( '{{content}}', wpautop( $content ), $template ); + } + + /** + * AJAX handler for email preview. + */ + public function ajax_preview_email() { + check_ajax_referer( 'maple_carts_admin', 'nonce' ); + + if ( ! current_user_can( 'manage_woocommerce' ) ) { + wp_send_json_error( 'Permission denied' ); + } + + $template_id = isset( $_POST['template_id'] ) ? absint( $_POST['template_id'] ) : 0; + $subject = isset( $_POST['subject'] ) ? sanitize_text_field( wp_unslash( $_POST['subject'] ) ) : ''; + $body = isset( $_POST['body'] ) ? wp_kses_post( wp_unslash( $_POST['body'] ) ) : ''; + + // Create dummy data for preview. + $dummy_data = (object) [ + 'email' => 'customer@example.com', + 'customer_name' => 'John Doe', + 'cart_contents' => maybe_serialize( [ + [ + 'product_id' => 1, + 'name' => 'Sample Product', + 'price' => 29.99, + 'quantity' => 2, + 'image' => '', + ], + ] ), + 'cart_total' => 59.98, + 'currency' => get_woocommerce_currency(), + 'session_id' => 'preview-session', + 'include_coupon' => true, + 'coupon_type' => 'percent', + 'coupon_amount' => 10, + 'coupon_expires_days' => 7, + ]; + + $parsed_subject = $this->parse_template( $subject, $dummy_data, 'PREVIEW10', '#' ); + $parsed_body = $this->parse_template( $body, $dummy_data, 'PREVIEW10', '#' ); + $html_body = $this->wrap_email_html( $parsed_body ); + + wp_send_json_success( [ + 'subject' => $parsed_subject, + 'body' => $html_body, + ] ); + } + + /** + * AJAX handler for sending test email. + */ + public function ajax_send_test_email() { + check_ajax_referer( 'maple_carts_admin', 'nonce' ); + + if ( ! current_user_can( 'manage_woocommerce' ) ) { + wp_send_json_error( 'Permission denied' ); + } + + $email = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : ''; + $subject = isset( $_POST['subject'] ) ? sanitize_text_field( wp_unslash( $_POST['subject'] ) ) : ''; + $body = isset( $_POST['body'] ) ? wp_kses_post( wp_unslash( $_POST['body'] ) ) : ''; + + if ( ! is_email( $email ) ) { + wp_send_json_error( __( 'Invalid email address', 'maple-carts' ) ); + } + + // Create dummy data. + $dummy_data = (object) [ + 'email' => $email, + 'customer_name' => 'Test Customer', + 'cart_contents' => maybe_serialize( [ + [ + 'product_id' => 1, + 'name' => 'Test Product', + 'price' => 49.99, + 'quantity' => 1, + 'image' => '', + ], + ] ), + 'cart_total' => 49.99, + 'currency' => get_woocommerce_currency(), + 'session_id' => 'test-session', + 'include_coupon' => true, + 'coupon_type' => 'percent', + 'coupon_amount' => 10, + 'coupon_expires_days' => 7, + ]; + + $parsed_subject = $this->parse_template( $subject, $dummy_data, 'TEST10OFF', '#' ); + $parsed_body = $this->parse_template( $body, $dummy_data, 'TEST10OFF', '#' ); + + $sent = $this->dispatch_email( $email, '[TEST] ' . $parsed_subject, $parsed_body ); + + if ( $sent ) { + wp_send_json_success( __( 'Test email sent successfully!', 'maple-carts' ) ); + } else { + wp_send_json_error( __( 'Failed to send test email. Check your email configuration.', 'maple-carts' ) ); + } + } +} diff --git a/native/wordpress/maple-carts-wp/includes/class-maple-carts-mailjet.php b/native/wordpress/maple-carts-wp/includes/class-maple-carts-mailjet.php new file mode 100644 index 0000000..1792117 --- /dev/null +++ b/native/wordpress/maple-carts-wp/includes/class-maple-carts-mailjet.php @@ -0,0 +1,534 @@ + 'bool', + 'maple_cart_total' => 'float', + 'maple_cart_currency' => 'str', + 'maple_cart_product_count' => 'int', + 'maple_cart_product_names' => 'str', + 'maple_cart_categories' => 'str', + 'maple_cart_value_level' => 'str', + 'maple_abandonment_type' => 'str', + 'maple_cart_recovery_url' => 'str', + 'maple_cart_first_seen_at' => 'datetime', + 'maple_cart_abandoned_at' => 'datetime', + 'maple_cart_coupon_code' => 'str', + 'maple_customer_first_name' => 'str', + 'maple_customer_last_name' => 'str', + 'maple_recovered_via' => 'str', + ]; + + /** + * Get instance. + * + * @return Maple_Carts_Mailjet + */ + public static function instance() { + if ( is_null( self::$instance ) ) { + self::$instance = new self(); + } + return self::$instance; + } + + /** + * Constructor. + */ + private function __construct() { + // Admin AJAX hooks - always register so settings page works. + add_action( 'wp_ajax_maple_carts_test_mailjet', [ $this, 'ajax_test_connection' ] ); + add_action( 'wp_ajax_maple_carts_setup_mailjet_properties', [ $this, 'ajax_setup_properties' ] ); + + // Only initialize sync hooks if Mailjet mode is enabled. + if ( 'mailjet' !== Maple_Carts::get_option( 'email_mode', 'builtin' ) ) { + return; + } + + // Hook into cart status changes. + add_action( 'maple_carts_cart_abandoned', [ $this, 'sync_abandoned_cart' ], 10, 2 ); + add_action( 'maple_carts_cart_recovered', [ $this, 'clear_abandoned_cart' ], 10, 2 ); + add_action( 'maple_carts_cart_converted', [ $this, 'clear_abandoned_cart' ], 10, 2 ); + } + + /** + * Check if Mailjet is configured. + * + * @return bool + */ + public function is_configured() { + $api_key = Maple_Carts::get_option( 'mailjet_api_key', '' ); + $secret_key = Maple_Carts::get_option( 'mailjet_secret_key', '' ); + + return ! empty( $api_key ) && ! empty( $secret_key ); + } + + /** + * Make API request to Mailjet. + * + * @param string $endpoint API endpoint. + * @param string $method HTTP method. + * @param array $data Request data. + * @return array|WP_Error + */ + private function api_request( $endpoint, $method = 'GET', $data = [] ) { + $api_key = Maple_Carts::get_option( 'mailjet_api_key', '' ); + $secret_key = Maple_Carts::get_option( 'mailjet_secret_key', '' ); + + if ( empty( $api_key ) || empty( $secret_key ) ) { + return new WP_Error( 'not_configured', __( 'Mailjet API credentials not configured.', 'maple-carts' ) ); + } + + $url = $this->api_url . $endpoint; + + $args = [ + 'method' => $method, + 'headers' => [ + 'Authorization' => 'Basic ' . base64_encode( $api_key . ':' . $secret_key ), + 'Content-Type' => 'application/json', + ], + 'timeout' => 30, + ]; + + if ( ! empty( $data ) && in_array( $method, [ 'POST', 'PUT' ], true ) ) { + $args['body'] = wp_json_encode( $data ); + } + + $response = wp_remote_request( $url, $args ); + + if ( is_wp_error( $response ) ) { + return $response; + } + + $code = wp_remote_retrieve_response_code( $response ); + $body = wp_remote_retrieve_body( $response ); + $data = json_decode( $body, true ); + + if ( $code >= 400 ) { + $error_message = isset( $data['ErrorMessage'] ) ? $data['ErrorMessage'] : __( 'Unknown API error', 'maple-carts' ); + return new WP_Error( 'api_error', $error_message, [ 'status' => $code ] ); + } + + return $data; + } + + /** + * Setup contact properties in Mailjet. + * Should be run once during initial setup. + * + * @return array|WP_Error + */ + public function setup_contact_properties() { + $results = []; + + foreach ( $this->contact_properties as $name => $type ) { + // Check if property already exists. + $existing = $this->api_request( '/contactmetadata/' . $name ); + + if ( ! is_wp_error( $existing ) && isset( $existing['Data'][0] ) ) { + $results[ $name ] = 'exists'; + continue; + } + + // Create the property. + $datatype = $this->get_mailjet_datatype( $type ); + $response = $this->api_request( '/contactmetadata', 'POST', [ + 'Name' => $name, + 'Datatype' => $datatype, + 'NameSpace' => 'static', + ] ); + + if ( is_wp_error( $response ) ) { + $results[ $name ] = 'error: ' . $response->get_error_message(); + } else { + $results[ $name ] = 'created'; + } + } + + return $results; + } + + /** + * Get Mailjet datatype from our type. + * + * @param string $type Our type. + * @return string Mailjet datatype. + */ + private function get_mailjet_datatype( $type ) { + $map = [ + 'bool' => 'bool', + 'int' => 'int', + 'float' => 'float', + 'str' => 'str', + 'datetime' => 'datetime', + ]; + + return isset( $map[ $type ] ) ? $map[ $type ] : 'str'; + } + + /** + * Sync abandoned cart data to Mailjet. + * + * @param int $cart_id Cart ID. + * @param object $cart Cart object. + */ + public function sync_abandoned_cart( $cart_id, $cart ) { + if ( empty( $cart->email ) ) { + return; + } + + // Parse cart contents for product names and categories. + $cart_contents = maybe_unserialize( $cart->cart_contents ); + $product_names = []; + $categories = []; + + if ( is_array( $cart_contents ) ) { + foreach ( $cart_contents as $item ) { + $product_names[] = $item['name'] ?? 'Product'; + + // Get product categories. + $product_id = $item['product_id'] ?? 0; + if ( $product_id ) { + $terms = get_the_terms( $product_id, 'product_cat' ); + if ( $terms && ! is_wp_error( $terms ) ) { + foreach ( $terms as $term ) { + $categories[ $term->name ] = true; // Use as keys to dedupe. + } + } + } + } + } + + // Parse billing data for name. + $billing_data = maybe_unserialize( $cart->billing_data ); + $first_name = $billing_data['first_name'] ?? ''; + $last_name = $billing_data['last_name'] ?? ''; + + // Calculate value level for segmentation. + $cart_total = (float) $cart->cart_total; + $value_level = $this->get_cart_value_level( $cart_total ); + + // Generate recovery URL with coupon and UTM source for attribution. + $recovery_url = Maple_Carts_Tracking::instance()->generate_recovery_url( + $cart->session_id, + $cart->coupon_code ?? '' + ); + // Add UTM source for recovery attribution. + $recovery_url = add_query_arg( 'utm_source', 'mailjet', $recovery_url ); + + // Prepare contact data using items_count from database (no JSON parsing needed). + $contact_data = [ + 'maple_has_abandoned_cart' => true, + 'maple_cart_total' => $cart_total, + 'maple_cart_currency' => $cart->currency ?? 'USD', + 'maple_cart_product_count' => (int) ( $cart->items_count ?? 0 ), + 'maple_cart_product_names' => implode( ', ', array_slice( $product_names, 0, 5 ) ), // Limit to 5. + 'maple_cart_categories' => implode( ', ', array_slice( array_keys( $categories ), 0, 5 ) ), // Limit to 5. + 'maple_cart_value_level' => $value_level, + 'maple_abandonment_type' => $cart->abandonment_type ?? 'checkout', + 'maple_cart_recovery_url' => $recovery_url, + 'maple_cart_first_seen_at' => $cart->first_seen_at ?? '', + 'maple_cart_abandoned_at' => $cart->abandoned_at ?? current_time( 'c' ), + 'maple_cart_coupon_code' => $cart->coupon_code ?? '', + 'maple_customer_first_name' => $first_name, + 'maple_customer_last_name' => $last_name, + 'maple_recovered_via' => '', // Clear any previous recovery. + ]; + + $this->update_contact( $cart->email, $contact_data ); + } + + /** + * Get cart value level for segmentation. + * + * @param float $total Cart total. + * @return string Value level: low, medium, or high. + */ + private function get_cart_value_level( $total ) { + if ( $total < 20 ) { + return 'low'; + } elseif ( $total < 80 ) { + return 'medium'; + } else { + return 'high'; + } + } + + /** + * Clear abandoned cart data from Mailjet contact. + * + * @param int $cart_id Cart ID. + * @param object $cart Cart object. + */ + public function clear_abandoned_cart( $cart_id, $cart ) { + if ( empty( $cart->email ) ) { + return; + } + + // Map recovery_source to Mailjet-friendly value. + $recovered_via = ''; + if ( 'recovered' === $cart->status && ! empty( $cart->recovery_source ) ) { + $recovered_via = $cart->recovery_source; // mailjet, builtin_email, email_link, direct. + } elseif ( 'converted' === $cart->status ) { + $recovered_via = 'purchase'; // Direct purchase without abandonment. + } + + // Clear the abandoned cart flag and data, but record recovery attribution. + $contact_data = [ + 'maple_has_abandoned_cart' => false, + 'maple_cart_total' => 0, + 'maple_cart_currency' => '', + 'maple_cart_product_count' => 0, + 'maple_cart_product_names' => '', + 'maple_cart_categories' => '', + 'maple_cart_value_level' => '', + 'maple_abandonment_type' => '', + 'maple_cart_recovery_url' => '', + 'maple_cart_first_seen_at' => '', + 'maple_cart_abandoned_at' => '', + 'maple_cart_coupon_code' => '', + 'maple_customer_first_name' => '', + 'maple_customer_last_name' => '', + 'maple_recovered_via' => $recovered_via, + ]; + + $this->update_contact( $cart->email, $contact_data ); + } + + /** + * Update or create contact in Mailjet. + * + * @param string $email Contact email. + * @param array $contact_data Contact properties. + * @return array|WP_Error + */ + private function update_contact( $email, $contact_data ) { + // First, ensure contact exists. + $contact = $this->get_or_create_contact( $email ); + + if ( is_wp_error( $contact ) ) { + $this->log_error( 'Failed to get/create contact: ' . $contact->get_error_message() ); + return $contact; + } + + // Format data for Mailjet. + $formatted_data = []; + foreach ( $contact_data as $name => $value ) { + $formatted_data[] = [ + 'Name' => $name, + 'Value' => $value, + ]; + } + + // Update contact data. + $response = $this->api_request( + '/contactdata/' . $contact['ID'], + 'PUT', + [ 'Data' => $formatted_data ] + ); + + if ( is_wp_error( $response ) ) { + $this->log_error( 'Failed to update contact data: ' . $response->get_error_message() ); + } + + return $response; + } + + /** + * Get or create contact in Mailjet. + * + * @param string $email Contact email. + * @return array|WP_Error + */ + private function get_or_create_contact( $email ) { + // Try to get existing contact. + $response = $this->api_request( '/contact/' . urlencode( $email ) ); + + if ( ! is_wp_error( $response ) && isset( $response['Data'][0] ) ) { + return $response['Data'][0]; + } + + // Create new contact. + $response = $this->api_request( '/contact', 'POST', [ + 'Email' => $email, + ] ); + + if ( is_wp_error( $response ) ) { + return $response; + } + + if ( isset( $response['Data'][0] ) ) { + return $response['Data'][0]; + } + + return new WP_Error( 'create_failed', __( 'Failed to create contact', 'maple-carts' ) ); + } + + /** + * Test Mailjet connection. + * + * @return array|WP_Error + */ + public function test_connection() { + return $this->api_request( '/user' ); + } + + /** + * AJAX handler for testing Mailjet connection. + */ + public function ajax_test_connection() { + check_ajax_referer( 'maple_carts_admin', 'nonce' ); + + if ( ! current_user_can( 'manage_woocommerce' ) ) { + wp_send_json_error( 'Unauthorized' ); + } + + // Temporarily set credentials from POST for testing. + $api_key = isset( $_POST['api_key'] ) ? sanitize_text_field( wp_unslash( $_POST['api_key'] ) ) : ''; + $secret_key = isset( $_POST['secret_key'] ) ? sanitize_text_field( wp_unslash( $_POST['secret_key'] ) ) : ''; + + if ( empty( $api_key ) || empty( $secret_key ) ) { + wp_send_json_error( __( 'Please enter both API Key and Secret Key.', 'maple-carts' ) ); + } + + // Make test request. + $url = $this->api_url . '/user'; + + $response = wp_remote_get( $url, [ + 'headers' => [ + 'Authorization' => 'Basic ' . base64_encode( $api_key . ':' . $secret_key ), + ], + 'timeout' => 15, + ] ); + + if ( is_wp_error( $response ) ) { + wp_send_json_error( $response->get_error_message() ); + } + + $code = wp_remote_retrieve_response_code( $response ); + $body = json_decode( wp_remote_retrieve_body( $response ), true ); + + if ( 200 === $code && isset( $body['Data'][0] ) ) { + $user = $body['Data'][0]; + wp_send_json_success( [ + 'message' => sprintf( + /* translators: %s: Mailjet username */ + __( 'Connected successfully! Account: %s', 'maple-carts' ), + $user['Username'] ?? $user['Email'] ?? 'Unknown' + ), + ] ); + } else { + wp_send_json_error( __( 'Authentication failed. Please check your API credentials.', 'maple-carts' ) ); + } + } + + /** + * AJAX handler for setting up Mailjet contact properties. + */ + public function ajax_setup_properties() { + check_ajax_referer( 'maple_carts_admin', 'nonce' ); + + if ( ! current_user_can( 'manage_woocommerce' ) ) { + wp_send_json_error( 'Unauthorized' ); + } + + $results = $this->setup_contact_properties(); + + if ( is_wp_error( $results ) ) { + wp_send_json_error( $results->get_error_message() ); + } + + $created = 0; + $existed = 0; + $errors = 0; + + foreach ( $results as $status ) { + if ( 'created' === $status ) { + $created++; + } elseif ( 'exists' === $status ) { + $existed++; + } else { + $errors++; + } + } + + wp_send_json_success( [ + 'message' => sprintf( + /* translators: %1$d: created count, %2$d: existed count, %3$d: error count */ + __( 'Properties setup complete. Created: %1$d, Already existed: %2$d, Errors: %3$d', 'maple-carts' ), + $created, + $existed, + $errors + ), + 'details' => $results, + ] ); + } + + /** + * Log error for debugging. + * + * @param string $message Error message. + */ + private function log_error( $message ) { + if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { + error_log( 'Maple Carts Mailjet: ' . $message ); + } + } + + /** + * Get available contact properties for display. + * + * @return array + */ + public function get_available_properties() { + return [ + 'maple_has_abandoned_cart' => __( 'Has abandoned cart (true/false)', 'maple-carts' ), + 'maple_cart_total' => __( 'Cart total value', 'maple-carts' ), + 'maple_cart_currency' => __( 'Cart currency code', 'maple-carts' ), + 'maple_cart_product_count' => __( 'Number of items in cart', 'maple-carts' ), + 'maple_cart_product_names' => __( 'Product names (comma separated)', 'maple-carts' ), + 'maple_cart_categories' => __( 'Product categories (comma separated)', 'maple-carts' ), + 'maple_cart_value_level' => __( 'Cart value: low (<$20), medium ($20-80), high ($80+)', 'maple-carts' ), + 'maple_abandonment_type' => __( 'Abandonment stage: checkout or payment', 'maple-carts' ), + 'maple_cart_recovery_url' => __( 'Recovery URL with coupon', 'maple-carts' ), + 'maple_cart_first_seen_at' => __( 'First seen date/time (funnel entry)', 'maple-carts' ), + 'maple_cart_abandoned_at' => __( 'Abandonment date/time', 'maple-carts' ), + 'maple_cart_coupon_code' => __( 'Generated coupon code', 'maple-carts' ), + 'maple_customer_first_name' => __( 'Customer first name', 'maple-carts' ), + 'maple_customer_last_name' => __( 'Customer last name', 'maple-carts' ), + 'maple_recovered_via' => __( 'Recovery attribution: mailjet, builtin_email, email_link, direct, purchase', 'maple-carts' ), + ]; + } +} diff --git a/native/wordpress/maple-carts-wp/includes/class-maple-carts-privacy.php b/native/wordpress/maple-carts-wp/includes/class-maple-carts-privacy.php new file mode 100644 index 0000000..77f516e --- /dev/null +++ b/native/wordpress/maple-carts-wp/includes/class-maple-carts-privacy.php @@ -0,0 +1,502 @@ +get_privacy_policy_content(); + wp_add_privacy_policy_content( 'Maple Carts', $content ); + } + + /** + * Get privacy policy suggested content. + * + * @return string + */ + private function get_privacy_policy_content() { + $retention_days = Maple_Carts::get_option( 'delete_after_days', 90 ); + + return sprintf( + '

%s

+

%s

+

%s

+

%s

+
    +
  • %s
  • +
  • %s
  • +
  • %s
  • +
  • %s
  • +
  • %s
  • +
  • %s
  • +
+

%s

+

%s

+

%s

+

%s

+

%s

+

%s

+

%s

+

%s

', + __( 'Abandoned Cart Recovery', 'maple-carts' ), + __( 'We use abandoned cart recovery technology to help remind you about items left in your shopping cart. This section explains what data we collect and how we use it.', 'maple-carts' ), + __( 'What data we collect', 'maple-carts' ), + __( 'When you begin the checkout process, we may collect:', 'maple-carts' ), + __( 'Email address', 'maple-carts' ), + __( 'Name and phone number', 'maple-carts' ), + __( 'Billing address', 'maple-carts' ), + __( 'Cart contents and total', 'maple-carts' ), + __( 'IP address', 'maple-carts' ), + __( 'Browser information', 'maple-carts' ), + __( 'Why we collect this data', 'maple-carts' ), + __( 'We collect this data to send you reminder emails if you leave items in your cart without completing your purchase. These emails may include a discount code to encourage you to complete your order.', 'maple-carts' ), + __( 'How long we retain your data', 'maple-carts' ), + sprintf( + /* translators: %d: number of days */ + __( 'Abandoned cart data is automatically deleted after %d days. You can request immediate deletion at any time.', 'maple-carts' ), + $retention_days + ), + __( 'Your rights', 'maple-carts' ), + __( 'You can unsubscribe from abandoned cart emails at any time by clicking the unsubscribe link in any email. You can also request a copy of your data or request deletion through our privacy tools.', 'maple-carts' ), + __( 'Third-party sharing', 'maple-carts' ), + __( 'We do not share your abandoned cart data with any third parties. Emails are sent through our own email system or your configured SMTP provider.', 'maple-carts' ) + ); + } + + /** + * Register data exporter. + * + * @param array $exporters Existing exporters. + * @return array + */ + public function register_data_exporter( $exporters ) { + $exporters['maple-carts'] = [ + 'exporter_friendly_name' => __( 'Maple Carts Abandoned Cart Data', 'maple-carts' ), + 'callback' => [ $this, 'export_personal_data' ], + ]; + return $exporters; + } + + /** + * Register data eraser. + * + * @param array $erasers Existing erasers. + * @return array + */ + public function register_data_eraser( $erasers ) { + $erasers['maple-carts'] = [ + 'eraser_friendly_name' => __( 'Maple Carts Abandoned Cart Data', 'maple-carts' ), + 'callback' => [ $this, 'erase_personal_data' ], + ]; + return $erasers; + } + + /** + * Export personal data for a user. + * + * @param string $email_address Email address. + * @param int $page Page number. + * @return array + */ + public function export_personal_data( $email_address, $page = 1 ) { + global $wpdb; + + $export_items = []; + $table = $wpdb->prefix . MAPLE_CARTS_TABLE; + $per_page = 10; + $offset = ( $page - 1 ) * $per_page; + + $carts = $wpdb->get_results( + $wpdb->prepare( + "SELECT * FROM {$table} WHERE email = %s LIMIT %d OFFSET %d", + $email_address, + $per_page, + $offset + ) + ); + + foreach ( $carts as $cart ) { + $cart_contents = maybe_unserialize( $cart->cart_contents ); + $product_names = []; + + if ( is_array( $cart_contents ) ) { + foreach ( $cart_contents as $item ) { + $product_names[] = $item['name'] ?? 'Unknown Product'; + } + } + + $data = [ + [ + 'name' => __( 'Email', 'maple-carts' ), + 'value' => $cart->email, + ], + [ + 'name' => __( 'Name', 'maple-carts' ), + 'value' => $cart->customer_name ?: __( 'Not provided', 'maple-carts' ), + ], + [ + 'name' => __( 'Phone', 'maple-carts' ), + 'value' => $cart->customer_phone ?: __( 'Not provided', 'maple-carts' ), + ], + [ + 'name' => __( 'Cart Contents', 'maple-carts' ), + 'value' => implode( ', ', $product_names ), + ], + [ + 'name' => __( 'Cart Total', 'maple-carts' ), + 'value' => wc_price( $cart->cart_total, [ 'currency' => $cart->currency ] ), + ], + [ + 'name' => __( 'Status', 'maple-carts' ), + 'value' => ucfirst( $cart->status ), + ], + [ + 'name' => __( 'IP Address', 'maple-carts' ), + 'value' => $cart->ip_address ?: __( 'Not recorded', 'maple-carts' ), + ], + [ + 'name' => __( 'Created', 'maple-carts' ), + 'value' => $cart->created_at, + ], + [ + 'name' => __( 'Unsubscribed', 'maple-carts' ), + 'value' => $cart->unsubscribed ? __( 'Yes', 'maple-carts' ) : __( 'No', 'maple-carts' ), + ], + ]; + + // Add billing data if present. + $billing_data = maybe_unserialize( $cart->billing_data ); + if ( ! empty( $billing_data ) ) { + $address_parts = array_filter( [ + $billing_data['address_1'] ?? '', + $billing_data['address_2'] ?? '', + $billing_data['city'] ?? '', + $billing_data['state'] ?? '', + $billing_data['postcode'] ?? '', + $billing_data['country'] ?? '', + ] ); + + if ( ! empty( $address_parts ) ) { + $data[] = [ + 'name' => __( 'Billing Address', 'maple-carts' ), + 'value' => implode( ', ', $address_parts ), + ]; + } + } + + $export_items[] = [ + 'group_id' => 'maple-carts', + 'group_label' => __( 'Abandoned Cart Data', 'maple-carts' ), + 'group_description' => __( 'Cart data collected during checkout.', 'maple-carts' ), + 'item_id' => 'cart-' . $cart->id, + 'data' => $data, + ]; + } + + // Check if there are more records. + $total = $wpdb->get_var( + $wpdb->prepare( + "SELECT COUNT(*) FROM {$table} WHERE email = %s", + $email_address + ) + ); + + $done = ( $page * $per_page ) >= $total; + + return [ + 'data' => $export_items, + 'done' => $done, + ]; + } + + /** + * Erase personal data for a user. + * + * @param string $email_address Email address. + * @param int $page Page number. + * @return array + */ + public function erase_personal_data( $email_address, $page = 1 ) { + global $wpdb; + + $table = $wpdb->prefix . MAPLE_CARTS_TABLE; + $log_table = $wpdb->prefix . MAPLE_CARTS_EMAIL_LOG_TABLE; + $per_page = 50; + $items_removed = 0; + $items_retained = 0; + + // Get carts to delete. + $carts = $wpdb->get_results( + $wpdb->prepare( + "SELECT id FROM {$table} WHERE email = %s LIMIT %d", + $email_address, + $per_page + ) + ); + + foreach ( $carts as $cart ) { + // Delete email logs first. + $wpdb->delete( $log_table, [ 'cart_id' => $cart->id ] ); + + // Delete cart. + $deleted = $wpdb->delete( $table, [ 'id' => $cart->id ] ); + + if ( $deleted ) { + $items_removed++; + } else { + $items_retained++; + } + } + + // Check if there are more records. + $remaining = $wpdb->get_var( + $wpdb->prepare( + "SELECT COUNT(*) FROM {$table} WHERE email = %s", + $email_address + ) + ); + + $done = ( $remaining == 0 ); + + return [ + 'items_removed' => $items_removed, + 'items_retained' => $items_retained, + 'messages' => [], + 'done' => $done, + ]; + } + + /** + * Add consent checkbox to checkout. + */ + public function add_consent_checkbox() { + $consent_text = Maple_Carts::get_option( + 'consent_text', + __( 'I agree to receive cart reminder emails if I don\'t complete my purchase.', 'maple-carts' ) + ); + + woocommerce_form_field( + 'maple_carts_consent', + [ + 'type' => 'checkbox', + 'class' => [ 'form-row maple-carts-consent' ], + 'label' => esc_html( $consent_text ), + 'required' => false, + ] + ); + } + + /** + * Validate consent checkbox. + */ + public function validate_consent_checkbox() { + // If consent is required and not given, we don't track the cart. + // This is handled in the tracking class. + } + + /** + * Check if user has given consent. + * + * @return bool + */ + public static function has_consent() { + // If consent is not required, always return true. + if ( 'yes' !== Maple_Carts::get_option( 'require_consent', 'no' ) ) { + return true; + } + + // Check if consent checkbox was checked. + if ( isset( $_POST['maple_carts_consent'] ) ) { + return true; + } + + // Check session for previous consent. + if ( WC()->session && WC()->session->get( 'maple_carts_consent' ) ) { + return true; + } + + return false; + } + + /** + * Record consent. + */ + public static function record_consent() { + if ( WC()->session ) { + WC()->session->set( 'maple_carts_consent', true ); + WC()->session->set( 'maple_carts_consent_time', current_time( 'mysql' ) ); + } + } + + /** + * Handle data deletion request from unsubscribe page. + */ + public function handle_data_deletion_request() { + if ( ! isset( $_GET['maple_delete_data'] ) ) { + return; + } + + $token = sanitize_text_field( wp_unslash( $_GET['maple_delete_data'] ) ); + + // Verify signed token (same as unsubscribe). + $tracking = Maple_Carts_Tracking::instance(); + $data = $this->verify_deletion_token( $token ); + + if ( ! $data || empty( $data['sid'] ) ) { + wc_add_notice( __( 'This data deletion link has expired or is invalid.', 'maple-carts' ), 'error' ); + wp_safe_redirect( wc_get_page_permalink( 'shop' ) ); + exit; + } + + $session_id = sanitize_text_field( $data['sid'] ); + $cart = Maple_Carts_DB::get_cart_by_session( $session_id ); + + if ( $cart ) { + // Delete all data for this cart. + Maple_Carts_DB::delete_cart( $cart->id ); + + wc_add_notice( __( 'Your cart data has been permanently deleted.', 'maple-carts' ), 'success' ); + } + + wp_safe_redirect( wc_get_page_permalink( 'shop' ) ); + exit; + } + + /** + * Verify deletion token (reuses tracking token verification). + * + * @param string $token Token to verify. + * @return array|false + */ + private function verify_deletion_token( $token ) { + $decoded = base64_decode( $token, true ); + if ( ! $decoded || strpos( $decoded, '|' ) === false ) { + return false; + } + + $parts = explode( '|', $decoded, 2 ); + if ( count( $parts ) !== 2 ) { + return false; + } + + list( $payload, $signature ) = $parts; + + // Verify HMAC signature. + $secret = wp_salt( 'auth' ) . 'maple_carts'; + $expected_signature = hash_hmac( 'sha256', $payload, $secret ); + + if ( ! hash_equals( $expected_signature, $signature ) ) { + return false; + } + + $data = json_decode( $payload, true ); + if ( ! $data ) { + return false; + } + + // Token valid for 90 days. + if ( isset( $data['t'] ) && ( time() - $data['t'] ) > ( 90 * DAY_IN_SECONDS ) ) { + return false; + } + + return $data; + } + + /** + * Generate data deletion URL. + * + * @param string $session_id Session ID. + * @return string + */ + public static function generate_deletion_url( $session_id ) { + $data = [ + 'sid' => $session_id, + 't' => time(), + ]; + + $payload = wp_json_encode( $data ); + $secret = wp_salt( 'auth' ) . 'maple_carts'; + $signature = hash_hmac( 'sha256', $payload, $secret ); + $token = base64_encode( $payload . '|' . $signature ); + + return add_query_arg( 'maple_delete_data', $token, home_url() ); + } + + /** + * Get anonymized data (for when full deletion isn't required). + * + * @param int $cart_id Cart ID. + */ + public static function anonymize_cart( $cart_id ) { + global $wpdb; + $table = $wpdb->prefix . MAPLE_CARTS_TABLE; + + $wpdb->update( + $table, + [ + 'email' => 'deleted@anonymized.invalid', + 'customer_name' => 'Anonymized', + 'customer_phone' => null, + 'billing_data' => null, + 'ip_address' => '0.0.0.0', + 'user_agent' => null, + ], + [ 'id' => $cart_id ] + ); + } +} diff --git a/native/wordpress/maple-carts-wp/includes/class-maple-carts-tracking.php b/native/wordpress/maple-carts-wp/includes/class-maple-carts-tracking.php new file mode 100644 index 0000000..e53cacb --- /dev/null +++ b/native/wordpress/maple-carts-wp/includes/class-maple-carts-tracking.php @@ -0,0 +1,767 @@ +should_skip_tracking() ) { + return; + } + + wp_enqueue_script( + 'maple-carts-tracking', + MAPLE_CARTS_URL . 'assets/js/tracking.js', + [ 'jquery' ], + MAPLE_CARTS_VERSION, + true + ); + + $session_id = $this->get_or_create_session_id(); + + wp_localize_script( + 'maple-carts-tracking', + 'mapleCartsData', + [ + 'ajaxUrl' => admin_url( 'admin-ajax.php' ), + 'nonce' => wp_create_nonce( 'maple_carts_nonce' ), + 'sessionId' => $session_id, + 'gdprNotice' => Maple_Carts::get_option( 'gdpr_notice', '' ), + ] + ); + } + + /** + * Check if tracking should be skipped. + * + * @return bool + */ + private function should_skip_tracking() { + // Skip if disabled via cookie. + if ( isset( $_COOKIE['maple_carts_skip'] ) ) { + return true; + } + + // Skip for excluded roles. + if ( is_user_logged_in() ) { + $user = wp_get_current_user(); + $exclude_roles = Maple_Carts::get_option( 'exclude_roles', [] ); + + if ( ! empty( $exclude_roles ) && array_intersect( $user->roles, $exclude_roles ) ) { + return true; + } + } + + return false; + } + + /** + * Get or create session ID. + * + * @return string + */ + private function get_or_create_session_id() { + if ( WC()->session ) { + $session_id = WC()->session->get( 'maple_carts_session_id' ); + + if ( ! $session_id ) { + $session_id = wp_generate_uuid4(); + WC()->session->set( 'maple_carts_session_id', $session_id ); + } + + return $session_id; + } + + // Fallback to cookie when WC session is unavailable. + if ( isset( $_COOKIE['maple_carts_session'] ) ) { + return sanitize_text_field( wp_unslash( $_COOKIE['maple_carts_session'] ) ); + } + + // Generate new session ID and persist to cookie. + $session_id = wp_generate_uuid4(); + $this->set_session_cookie( $session_id ); + + return $session_id; + } + + /** + * Set session cookie for fallback persistence. + * + * @param string $session_id Session ID. + */ + private function set_session_cookie( $session_id ) { + if ( headers_sent() ) { + return; + } + + $secure = is_ssl(); + $httponly = true; + $samesite = 'Lax'; + $expire = time() + YEAR_IN_SECONDS; + + if ( PHP_VERSION_ID >= 70300 ) { + setcookie( 'maple_carts_session', $session_id, [ + 'expires' => $expire, + 'path' => '/', + 'domain' => '', + 'secure' => $secure, + 'httponly' => $httponly, + 'samesite' => $samesite, + ] ); + } else { + setcookie( 'maple_carts_session', $session_id, $expire, '/; SameSite=' . $samesite, '', $secure, $httponly ); + } + + // Also set in $_COOKIE for immediate availability. + $_COOKIE['maple_carts_session'] = $session_id; + } + + /** + * AJAX handler for saving cart data. + * Includes rate limiting for security. + */ + public function ajax_save_cart() { + check_ajax_referer( 'maple_carts_nonce', 'nonce' ); + + // Rate limiting: max 10 requests per minute per IP. + $ip = $this->get_client_ip(); + $rate_key = 'maple_carts_rate_' . md5( $ip ); + $requests = (int) get_transient( $rate_key ); + + if ( $requests >= 10 ) { + wp_send_json_error( 'Rate limit exceeded. Please try again later.' ); + } + + set_transient( $rate_key, $requests + 1, MINUTE_IN_SECONDS ); + + // Check for consent if required. + if ( ! Maple_Carts_Privacy::has_consent() ) { + wp_send_json_error( 'Consent not given' ); + } + + // Record consent. + Maple_Carts_Privacy::record_consent(); + + $session_id = isset( $_POST['session_id'] ) ? sanitize_text_field( wp_unslash( $_POST['session_id'] ) ) : ''; + $email = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : ''; + + if ( empty( $session_id ) ) { + wp_send_json_error( 'Missing session ID' ); + } + + // Get cart data from WooCommerce. + $cart = WC()->cart; + if ( ! $cart || $cart->is_empty() ) { + wp_send_json_error( 'Cart is empty' ); + } + + $cart_contents = []; + foreach ( $cart->get_cart() as $key => $item ) { + $product = $item['data']; + $cart_contents[] = [ + 'product_id' => $item['product_id'], + 'variation_id' => $item['variation_id'] ?? 0, + 'quantity' => $item['quantity'], + 'name' => $product->get_name(), + 'price' => $product->get_price(), + 'image' => wp_get_attachment_image_url( $product->get_image_id(), 'thumbnail' ), + 'permalink' => $product->get_permalink(), + ]; + } + + // Collect billing data. + $billing_data = []; + $billing_fields = [ + 'first_name', 'last_name', 'phone', 'address_1', 'address_2', + 'city', 'state', 'postcode', 'country' + ]; + + foreach ( $billing_fields as $field ) { + $key = 'billing_' . $field; + if ( isset( $_POST[ $key ] ) ) { + $billing_data[ $field ] = sanitize_text_field( wp_unslash( $_POST[ $key ] ) ); + } + } + + $first_name = $billing_data['first_name'] ?? ''; + $last_name = $billing_data['last_name'] ?? ''; + $customer_name = trim( "$first_name $last_name" ); + + // Calculate items count. + $items_count = 0; + foreach ( $cart_contents as $item ) { + $items_count += $item['quantity']; + } + + // Prepare cart data. + $data = [ + 'session_id' => $session_id, + 'email' => $email, + 'cart_contents' => maybe_serialize( $cart_contents ), + 'cart_total' => $cart->get_cart_contents_total(), + 'items_count' => $items_count, + 'currency' => get_woocommerce_currency(), + 'customer_name' => $customer_name ?: null, + 'customer_phone' => $billing_data['phone'] ?? null, + 'billing_data' => maybe_serialize( $billing_data ), + 'ip_address' => $this->get_client_ip(), + 'user_agent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : null, + ]; + + // Generate recovery URL. + $data['recovery_url'] = $this->generate_recovery_url( $session_id ); + + $cart_id = Maple_Carts_DB::save_cart( $data ); + + if ( $cart_id ) { + wp_send_json_success( [ 'cart_id' => $cart_id ] ); + } else { + wp_send_json_error( 'Failed to save cart' ); + } + } + + /** + * Get client IP address. + * + * @return string + */ + private function get_client_ip() { + $ip_keys = [ 'HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR' ]; + + foreach ( $ip_keys as $key ) { + if ( ! empty( $_SERVER[ $key ] ) ) { + $ip = sanitize_text_field( wp_unslash( $_SERVER[ $key ] ) ); + // Handle comma-separated IPs. + if ( strpos( $ip, ',' ) !== false ) { + $ip = trim( explode( ',', $ip )[0] ); + } + if ( filter_var( $ip, FILTER_VALIDATE_IP ) ) { + return $ip; + } + } + } + + return '0.0.0.0'; + } + + /** + * Generate recovery URL with HMAC signature. + * + * @param string $session_id Session ID. + * @param string $coupon Optional coupon code. + * @return string + */ + public function generate_recovery_url( $session_id, $coupon = '' ) { + $data = [ + 'sid' => $session_id, + 'c' => $coupon, + 't' => time(), + ]; + + // Sign the token with HMAC. + $payload = wp_json_encode( $data ); + $signature = hash_hmac( 'sha256', $payload, $this->get_token_secret() ); + $token = base64_encode( $payload . '|' . $signature ); + + return add_query_arg( 'maple_recover', $token, wc_get_checkout_url() ); + } + + /** + * Generate unsubscribe URL with HMAC signature. + * + * @param string $session_id Session ID. + * @return string + */ + public function generate_unsubscribe_url( $session_id ) { + $data = [ + 'sid' => $session_id, + 't' => time(), + ]; + + $payload = wp_json_encode( $data ); + $signature = hash_hmac( 'sha256', $payload, $this->get_token_secret() ); + $token = base64_encode( $payload . '|' . $signature ); + + return add_query_arg( 'maple_unsubscribe', $token, home_url() ); + } + + /** + * Verify and decode a signed token. + * + * @param string $token The token to verify. + * @param int $max_age Maximum age in seconds (0 = no expiry). + * @return array|false Decoded data or false if invalid. + */ + private function verify_token( $token, $max_age = 0 ) { + $decoded = base64_decode( $token, true ); + if ( ! $decoded || strpos( $decoded, '|' ) === false ) { + return false; + } + + $parts = explode( '|', $decoded, 2 ); + if ( count( $parts ) !== 2 ) { + return false; + } + + list( $payload, $signature ) = $parts; + + // Verify HMAC signature (timing-safe comparison). + $expected_signature = hash_hmac( 'sha256', $payload, $this->get_token_secret() ); + if ( ! hash_equals( $expected_signature, $signature ) ) { + return false; + } + + $data = json_decode( $payload, true ); + if ( ! $data ) { + return false; + } + + // Check token age if max_age is set. + if ( $max_age > 0 && isset( $data['t'] ) ) { + if ( ( time() - $data['t'] ) > $max_age ) { + return false; + } + } + + return $data; + } + + /** + * Get secret key for token signing. + * + * @return string + */ + private function get_token_secret() { + // Use WordPress auth key + salt for signing. + return wp_salt( 'auth' ) . 'maple_carts'; + } + + /** + * Handle cart recovery. + */ + public function handle_recovery() { + if ( ! isset( $_GET['maple_recover'] ) ) { + return; + } + + $token = sanitize_text_field( wp_unslash( $_GET['maple_recover'] ) ); + + // Verify signed token (valid for 30 days). + $data = $this->verify_token( $token, 30 * DAY_IN_SECONDS ); + + if ( ! $data || empty( $data['sid'] ) ) { + wc_add_notice( __( 'This recovery link has expired or is invalid.', 'maple-carts' ), 'error' ); + wp_safe_redirect( wc_get_page_permalink( 'shop' ) ); + exit; + } + + $session_id = sanitize_text_field( $data['sid'] ); + $cart = Maple_Carts_DB::get_cart_by_session( $session_id ); + + if ( ! $cart || ! in_array( $cart->status, [ 'abandoned', 'active' ], true ) ) { + return; + } + + // Restore cart contents. + $cart_contents = maybe_unserialize( $cart->cart_contents ); + + if ( ! empty( $cart_contents ) && is_array( $cart_contents ) ) { + WC()->cart->empty_cart(); + + foreach ( $cart_contents as $item ) { + $product_id = $item['product_id']; + $quantity = $item['quantity']; + $variation_id = $item['variation_id'] ?? 0; + + // Check if product exists and is in stock. + $product = wc_get_product( $variation_id ? $variation_id : $product_id ); + if ( $product && $product->is_in_stock() ) { + WC()->cart->add_to_cart( $product_id, $quantity, $variation_id ); + } + } + } + + // Pre-fill billing data. + $billing_data = maybe_unserialize( $cart->billing_data ); + if ( ! empty( $billing_data ) ) { + WC()->session->set( 'maple_carts_billing', $billing_data ); + add_filter( 'woocommerce_checkout_get_value', [ $this, 'prefill_checkout_fields' ], 10, 2 ); + } + + // Apply coupon if provided. + $coupon = ! empty( $data['c'] ) ? sanitize_text_field( $data['c'] ) : ''; + if ( $coupon && ! WC()->cart->has_discount( $coupon ) ) { + WC()->cart->apply_coupon( $coupon ); + } + + // Store session ID for tracking. + WC()->session->set( 'maple_carts_session_id', $session_id ); + WC()->session->set( 'maple_carts_recovering', true ); + + // Redirect to clean URL. + wp_safe_redirect( wc_get_checkout_url() ); + exit; + } + + /** + * Pre-fill checkout fields. + * + * @param mixed $value Default value. + * @param string $input Field name. + * @return mixed + */ + public function prefill_checkout_fields( $value, $input ) { + $billing_data = WC()->session->get( 'maple_carts_billing' ); + + if ( ! $billing_data ) { + return $value; + } + + $field = str_replace( 'billing_', '', $input ); + + if ( isset( $billing_data[ $field ] ) ) { + return $billing_data[ $field ]; + } + + return $value; + } + + /** + * Handle unsubscribe. + */ + public function handle_unsubscribe() { + if ( ! isset( $_GET['maple_unsubscribe'] ) ) { + return; + } + + $token = sanitize_text_field( wp_unslash( $_GET['maple_unsubscribe'] ) ); + + // Verify signed token (valid for 90 days). + $data = $this->verify_token( $token, 90 * DAY_IN_SECONDS ); + + if ( ! $data || empty( $data['sid'] ) ) { + wc_add_notice( __( 'This unsubscribe link has expired or is invalid.', 'maple-carts' ), 'error' ); + wp_safe_redirect( wc_get_page_permalink( 'shop' ) ); + exit; + } + + $session_id = sanitize_text_field( $data['sid'] ); + $cart = Maple_Carts_DB::get_cart_by_session( $session_id ); + + if ( $cart ) { + global $wpdb; + $wpdb->update( + $wpdb->prefix . MAPLE_CARTS_TABLE, + [ 'unsubscribed' => 1 ], + [ 'id' => $cart->id ] + ); + + // Cancel pending emails. + Maple_Carts_DB::cancel_pending_emails( $cart->id ); + + // Set cookie to skip future tracking (with security flags). + $secure = is_ssl(); + $httponly = true; + $samesite = 'Lax'; + + if ( PHP_VERSION_ID >= 70300 ) { + setcookie( 'maple_carts_skip', '1', [ + 'expires' => time() + YEAR_IN_SECONDS, + 'path' => '/', + 'secure' => $secure, + 'httponly' => $httponly, + 'samesite' => $samesite, + ] ); + } else { + setcookie( 'maple_carts_skip', '1', time() + YEAR_IN_SECONDS, '/; SameSite=' . $samesite, '', $secure, $httponly ); + } + + wc_add_notice( __( 'You have been unsubscribed from cart reminder emails.', 'maple-carts' ), 'success' ); + } + + wp_safe_redirect( wc_get_page_permalink( 'shop' ) ); + exit; + } + + /** + * Handle new order creation. + * + * @param int $order_id Order ID. + */ + public function handle_new_order( $order_id ) { + $this->process_order_completion( $order_id ); + } + + /** + * Handle order complete (thank you page). + * + * @param int $order_id Order ID. + */ + public function handle_order_complete( $order_id ) { + $this->process_order_completion( $order_id ); + } + + /** + * Process order completion. + * + * @param int $order_id Order ID. + */ + private function process_order_completion( $order_id ) { + $order = wc_get_order( $order_id ); + if ( ! $order ) { + return; + } + + $email = $order->get_billing_email(); + if ( ! $email ) { + return; + } + + // Check session first. + $session_id = null; + $is_recovery = false; + if ( WC()->session ) { + $session_id = WC()->session->get( 'maple_carts_session_id' ); + $is_recovery = WC()->session->get( 'maple_carts_recovering' ); + } + + $cart = null; + if ( $session_id ) { + $cart = Maple_Carts_DB::get_cart_by_session( $session_id ); + } + + if ( ! $cart ) { + $cart = Maple_Carts_DB::get_cart_by_email( $email ); + } + + if ( ! $cart ) { + return; + } + + // Determine new status and recovery source. + $new_status = 'converted'; + $recovery_source = null; + + if ( in_array( $cart->status, [ 'abandoned' ], true ) ) { + $new_status = 'recovered'; + + // Determine recovery source from UTM parameters. + if ( $is_recovery ) { + // Came via recovery link - check UTM source for attribution. + // phpcs:ignore WordPress.Security.NonceVerification.Recommended + $utm_source = isset( $_GET['utm_source'] ) ? sanitize_text_field( wp_unslash( $_GET['utm_source'] ) ) : ''; + + switch ( $utm_source ) { + case 'mailjet': + $recovery_source = 'mailjet'; + break; + case 'maple_carts': + $recovery_source = 'builtin_email'; + break; + default: + // Generic recovery link (e.g., shared, bookmarked). + $recovery_source = 'email_link'; + break; + } + } else { + // Returned directly without clicking recovery link. + $recovery_source = 'direct'; + } + + // Notify admin of recovery. + if ( 'yes' === Maple_Carts::get_option( 'notify_admin', 'yes' ) ) { + $this->send_admin_recovery_notification( $order, $cart ); + } + } + + Maple_Carts_DB::update_cart_status( $cart->id, $new_status, [ 'recovery_source' => $recovery_source ] ); + Maple_Carts_DB::cancel_pending_emails( $cart->id ); + + // Clear session data. + if ( WC()->session ) { + WC()->session->__unset( 'maple_carts_session_id' ); + WC()->session->__unset( 'maple_carts_recovering' ); + WC()->session->__unset( 'maple_carts_billing' ); + } + } + + /** + * Handle order status change. + * + * @param int $order_id Order ID. + * @param string $old_status Old status. + * @param string $new_status New status. + */ + public function handle_order_status_change( $order_id, $old_status, $new_status ) { + // Handle completed/processing orders. + $completed_statuses = [ 'completed', 'processing' ]; + if ( in_array( $new_status, $completed_statuses, true ) ) { + $this->process_order_completion( $order_id ); + } + } + + /** + * Mark carts as abandoned. + * Processes in batches to prevent memory issues. + */ + public function mark_abandoned_carts() { + global $wpdb; + + // Prevent overlapping cron runs. + if ( get_transient( 'maple_carts_marking_abandoned' ) ) { + return; + } + set_transient( 'maple_carts_marking_abandoned', 1, 300 ); // 5 minute lock. + + $table = $wpdb->prefix . MAPLE_CARTS_TABLE; + $cutoff_time = (int) Maple_Carts::get_option( 'cart_cutoff_time', 15 ); + $cutoff = gmdate( 'Y-m-d H:i:s', strtotime( "-{$cutoff_time} minutes" ) ); + $batch_size = 100; // Process 100 at a time. + + // Get active carts that should be marked as abandoned (limited batch). + // Use COALESCE to handle existing carts that don't have last_tracked_at set yet. + $carts = $wpdb->get_results( + $wpdb->prepare( + "SELECT id, email, billing_data FROM {$table} + WHERE status = 'active' + AND email IS NOT NULL + AND email != '' + AND COALESCE(last_tracked_at, updated_at) < %s + LIMIT %d", + $cutoff, + $batch_size + ) + ); + + foreach ( $carts as $cart ) { + // Determine abandonment type. + $abandonment_type = $this->detect_abandonment_type( $cart ); + + Maple_Carts_DB::update_cart_status( $cart->id, 'abandoned', [ + 'abandonment_type' => $abandonment_type, + ] ); + Maple_Carts_DB::schedule_emails( $cart->id ); + } + + delete_transient( 'maple_carts_marking_abandoned' ); + } + + /** + * Detect abandonment type based on cart data. + * + * @param object $cart Cart object (minimal data from query). + * @return string Abandonment type: browsing, checkout, or payment. + */ + private function detect_abandonment_type( $cart ) { + // No email = browsing abandonment (but we don't track these, so this shouldn't happen). + if ( empty( $cart->email ) ) { + return 'browsing'; + } + + // Check billing data for payment indicators. + $billing_data = maybe_unserialize( $cart->billing_data ); + + // If we have address data, they got further into checkout. + $has_address = ! empty( $billing_data['address_1'] ) || + ! empty( $billing_data['city'] ) || + ! empty( $billing_data['postcode'] ); + + if ( $has_address ) { + // They filled out billing = likely payment abandonment. + return 'payment'; + } + + // Just email = checkout abandonment. + return 'checkout'; + } + + /** + * Send admin recovery notification. + * + * @param WC_Order $order Order object. + * @param object $cart Cart object. + */ + private function send_admin_recovery_notification( $order, $cart ) { + $admin_email = Maple_Carts::get_option( 'admin_email', get_option( 'admin_email' ) ); + $site_name = get_bloginfo( 'name' ); + + $subject = sprintf( + /* translators: %1$s: Site name, %2$d: Order ID */ + __( '[%1$s] Recovered Order #%2$d', 'maple-carts' ), + $site_name, + $order->get_id() + ); + + $message = sprintf( + /* translators: %1$d: Order ID, %2$s: Cart total, %3$s: Order link */ + __( "Great news! An abandoned cart has been recovered.\n\nOrder #%1\$d\nRecovered Value: %2\$s\n\nView order: %3\$s", 'maple-carts' ), + $order->get_id(), + wc_price( $order->get_total() ), + admin_url( 'post.php?post=' . $order->get_id() . '&action=edit' ) + ); + + wp_mail( $admin_email, $subject, $message ); + } +} diff --git a/native/wordpress/maple-carts-wp/includes/index.php b/native/wordpress/maple-carts-wp/includes/index.php new file mode 100644 index 0000000..84d32c8 --- /dev/null +++ b/native/wordpress/maple-carts-wp/includes/index.php @@ -0,0 +1,10 @@ +includes(); + $this->init_hooks(); + } + + /** + * Include required files. + */ + private function includes() { + require_once MAPLE_CARTS_PATH . 'includes/class-maple-carts-db.php'; + require_once MAPLE_CARTS_PATH . 'includes/class-maple-carts-tracking.php'; + require_once MAPLE_CARTS_PATH . 'includes/class-maple-carts-emails.php'; + require_once MAPLE_CARTS_PATH . 'includes/class-maple-carts-privacy.php'; + require_once MAPLE_CARTS_PATH . 'includes/class-maple-carts-mailjet.php'; + + if ( is_admin() ) { + require_once MAPLE_CARTS_PATH . 'includes/class-maple-carts-admin.php'; + } + } + + /** + * Initialize hooks. + */ + private function init_hooks() { + register_activation_hook( MAPLE_CARTS_FILE, [ 'Maple_Carts_DB', 'activate' ] ); + register_deactivation_hook( MAPLE_CARTS_FILE, [ $this, 'deactivate' ] ); + + add_action( 'plugins_loaded', [ $this, 'on_plugins_loaded' ] ); + add_action( 'before_woocommerce_init', [ $this, 'declare_hpos_compatibility' ] ); + } + + /** + * On plugins loaded. + */ + public function on_plugins_loaded() { + if ( ! class_exists( 'WooCommerce' ) ) { + add_action( 'admin_notices', [ $this, 'woocommerce_missing_notice' ] ); + return; + } + + // Initialize components. + Maple_Carts_Tracking::instance(); + Maple_Carts_Emails::instance(); + Maple_Carts_Privacy::instance(); + Maple_Carts_Mailjet::instance(); + + if ( is_admin() ) { + Maple_Carts_Admin::instance(); + } + + // Load textdomain. + load_plugin_textdomain( 'maple-carts', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' ); + } + + /** + * Deactivation. + */ + public function deactivate() { + wp_clear_scheduled_hook( 'maple_carts_send_emails' ); + wp_clear_scheduled_hook( 'maple_carts_cleanup' ); + } + + /** + * HPOS compatibility. + */ + public function declare_hpos_compatibility() { + if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) { + \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', MAPLE_CARTS_FILE, true ); + } + } + + /** + * WooCommerce missing notice. + */ + public function woocommerce_missing_notice() { + ?> +
+

+
+ prefix . 'maple_carts_email_log', + $wpdb->prefix . 'maple_carts_emails', + $wpdb->prefix . 'maple_carts', +]; + +foreach ( $tables as $table ) { + $wpdb->query( "DROP TABLE IF EXISTS {$table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared +} + +// Delete coupons created by this plugin. +$coupon_ids = $wpdb->get_col( + "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_maple_carts_coupon' AND meta_value = '1'" +); + +foreach ( $coupon_ids as $coupon_id ) { + wp_delete_post( $coupon_id, true ); +} + +// Clear scheduled events. +wp_clear_scheduled_hook( 'maple_carts_send_emails' ); +wp_clear_scheduled_hook( 'maple_carts_cleanup' );