license.txt000064400000104515151710730040006733 0ustar00 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . gosmtp-pro.php000064400000004354151710730040007370 0ustar00 30)); if(!is_array($resp)){ gosmtp_notify(__('The response was malformed
'.var_export($resp, true)), 'error'); return; } $json = json_decode($resp['body'], true); if(empty($json['license'])){ gosmtp_notify(__('The license key is invalid'), 'error'); return; } $json['last_update'] = time(); update_option('gosmtp_license', $json); gosmtp_notify(__('Successfully updated the license key')); gosmtp_pro_load_license(); } function gosmtp_notify($message, $type = 'updated', $dismissible = true){ $is_dismissible = ''; if(!empty($dismissible)){ $is_dismissible = 'is-dismissible'; } if(!empty($message)){ echo '

'.$message.'

'; } } if(isset($_REQUEST['save_gosmtp_license'])){ gosmtp_license(); } ?>

license['license']) ? 'Unlicensed    ' : '')?>  
license['license'])){ $expires = $gosmtp->license['expires']; $expires = substr($expires, 0, 4).'/'.substr($expires, 4, 2).'/'.substr($expires, 6); echo '
License Status : '.(empty($gosmtp->license['status_txt']) ? 'N.A.' : wp_kses_post($gosmtp->license['status_txt'])).'       License Expires : '.($gosmtp->license['expires'] <= date('Ymd') ? ''.esc_attr($expires).'' : esc_attr($expires)).'
'; }?>
URL
Path
.htaccess Yes' : 'No');?>
main/settings.php000064400000025656151710730040010055 0ustar00 __('Logs Settings'), 'gosmtp-connections-settings' => __('Additional Connections') ); // Add the $_navs array in 1 position of $navs; $navs = array_slice( $navs, 0, $offset, true ) + $_navs + array_slice( $navs, $offset, null, true ); return $navs; } // Add settings tab panel add_action('gosmtp_after_settings_tab_panel', 'gosmtp_pro_after_settings_tab_panel'); function gosmtp_pro_after_settings_tab_panel(){ $smtp_options = get_option('gosmtp_options', array()); $mailer_count = !empty($smtp_options['mailer']) ? count($smtp_options['mailer']) : 0; // Default mailer set mail if(!isset($smtp_options['mailer']) || !is_array($smtp_options['mailer']) || empty($smtp_options['mailer'][0])){ $smtp_options['mailer'] = []; $smtp_options['mailer'][0]['mail_type'] = 'mail'; } ?>
options['weekly_reports']['timestamp'] <= time()) && $send_email){ return; } if(!function_exists('gosmtp_group_by')){ include_once GOSMTP_PRO_DIR .'/main/email-reports.php'; } $logger = new GOSMTP\Logger(); $week = $gosmtp->options['weekly_reports']['weekday']; $last_week = date("Y-m-d", strtotime('last '.$week, strtotime('tomorrow'))); $start = date('Y-m-d', strtotime($last_week. ' -7 days')); $end = $last_week; $multiselect = array('subject'); $options = array( 'interval' => array( 'start' => $start, 'end' => $end ), 'pagination' => false, ); $email_logs = $logger->get_logs('records', '', $options); $mails = gosmtp_group_by($email_logs, array(), $multiselect); $sent = $failed = $total = 0; foreach($mails as $key =>$val){ $sent = $sent + $val['total']['sent']; $failed = $failed + $val['total']['failed']; $total = $total + $val['total']['total']; } echo'
"'; $email = ' GOSMTP Weekly Email Summary
'; if(!empty($mails)){ foreach($mails as $key => $val){ $email .= ""; // Print Only 5 Rows if($key == 4){ break; } } }else{ $email .=""; } $email .='

Hi there,

Let\'s take a look at how your emails performed over the last week.

Total Emails

'.$total.'

▲'.gosmtp_cal_percentage($total, $total).'

Sent

'.$sent.'

▲'.gosmtp_cal_percentage($sent, $total).'

Failed

'.$failed.'

▼'.gosmtp_cal_percentage($failed, $total).'

Last Weeks Emails

View all Emails

".$val['total']['subject']."
".$val['total']['total']."
".$val['total']['sent']."(".gosmtp_cal_percentage($val['total']['sent'], $val['total']['total']).")"."
".$val['total']['failed']."(".gosmtp_cal_percentage($val['total']['failed'], $val['total']['total']).")"."

Email Records were not found this week!

'; if($send_email || isset($_GET['test_reports'])){ $headers = array( 'Content-Type: text/html; charset=UTF-8' ); $admin_email = get_option('admin_email'); if(!empty($admin_email)){ $title = 'Weekly Report'; if(wp_mail($admin_email, $title, $email, $headers)){ echo '

'.__('Email Sent successfully to ').' '.$admin_email.'.

'.__('Weekly email reports were sent from: '.$start.' to: '.$end.'').'

'; }else{ echo '

'.__('Failed to send email to ').' '.__($admin_email).''.__('. Plesae check ').''. __(' Email logs ').''.__('for more info.').'

'; } }else{ echo ""; } } // Update Timestamp if($send_email){ $gosmtp->options['weekly_reports']['timestamp'] = strtotime("next ".$gosmtp->options['weekly_reports']['weekday']); update_option( 'gosmtp_options', $gosmtp->options ); return; } $email.= '

'. __('Note: Test weekly report will be sent to admin email') .'

'; echo $email; } ?> main/gosmtp-init.php000064400000012167151710730040010460 0ustar00addQueryArgFilter('gosmtp_pro_updater_filter_args'); // Show the text to install the license key add_filter('puc_manual_final_check_link-gosmtp-pro', 'gosmtp_pro_updater_check_link', 10, 1); // Nag informing the user to install the free version. if(current_user_can('activate_plugins')){ add_action('admin_notices', 'gosmtp_pro_free_version_nag', 9); add_action('admin_menu', 'gosmtp_pro_add_menu', 9); } $is_network_wide = gosmtp_pro_is_network_active('gosmtp-pro'); $_do_version = get_option('gosmtp_version'); $req_free_update = !empty($_do_version) && version_compare($_do_version, '1.0.7', '<'); if($is_network_wide){ $free_installed = get_site_option('gosmtp_free_installed'); }else{ $free_installed = get_option('gosmtp_free_installed'); } if(!empty($free_installed)){ return; } // Include the necessary stuff include_once(ABSPATH . 'wp-admin/includes/plugin-install.php'); include_once(ABSPATH . 'wp-admin/includes/plugin.php'); include_once(ABSPATH . 'wp-admin/includes/file.php'); if(file_exists(WP_PLUGIN_DIR . '/gosmtp/gosmtp.php') && is_plugin_inactive('/gosmtp/gosmtp.php') && empty($req_free_update)) { if($is_network_wide){ update_site_option('gosmtp_free_installed', time()); }else{ update_option('gosmtp_free_installed', time()); } activate_plugin('/gosmtp/gosmtp.php', '', $is_network_wide); remove_action('admin_notices', 'gosmtp_pro_free_version_nag', 9); remove_action('admin_menu', 'gosmtp_pro_add_menu', 9); return; } // Includes necessary for Plugin_Upgrader and Plugin_Installer_Skin include_once(ABSPATH . 'wp-admin/includes/misc.php'); include_once(ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'); // Filter to prevent the activate text add_filter('install_plugin_complete_actions', 'gosmtp_pro_prevent_activation_text', 10, 3); $upgrader = new Plugin_Upgrader(new WP_Ajax_Upgrader_Skin()); // Upgrade the plugin to the latest version of free already installed. if(!empty($req_free_update)){ $installed = $upgrader->upgrade('gosmtp/gosmtp.php'); }else{ $installed = $upgrader->install('https://downloads.wordpress.org/plugin/gosmtp.zip'); } if(!is_wp_error($installed) && $installed){ if($is_network_wide){ update_site_option('gosmtp_free_installed', time()); }else{ update_option('gosmtp_free_installed', time()); } activate_plugin('gosmtp/gosmtp.php', '', $is_network_wide); remove_action('admin_notices', 'gosmtp_pro_free_version_nag', 9); remove_action('admin_menu', 'gosmtp_pro_add_menu', 9); } } // Do not shows the activation text if function gosmtp_pro_prevent_activation_text($install_actions, $api, $plugin_file){ if($plugin_file == 'gosmtp/gosmtp.php'){ return array(); } return $install_actions; } function gosmtp_pro_free_version_nag(){ $go_version = get_option('gosmtp_version'); $lower_version = __('You have not installed the free version of GoSMTP. GoSMTP Pro depends on the free version, so you must install it first in order to use GoSMTP Pro.'); if(!empty($go_version) && version_compare($go_version, '1.0.7', '<')){ $lower_version = __('You are using an older version of the free version of GoSMTP, please update GoSMTP to work without any issues'); } echo '

'.esc_html($lower_version).' Install/Update Now

'; } function gosmtp_pro_add_menu(){ add_menu_page('GoSMTP Settings', 'GoSMTP', 'activate_plugins', 'gosmtp', 'gosmtp_pro_menu_page'); } function gosmtp_pro_menu_page(){ echo '

GoSMTP Free version is not installed / outdated!

GoSMTP Pro depends on the free version of GoSMTP, so you need to install / update the free version first.

Install/Update Now

'; }main/email-reports.php000064400000022520151710730040010763 0ustar00 options['logs']['enable_logs']) ){ echo '

Email report is disabled

'.__('To view email reports, please enable email logs from GoSMTP').' '.__('settings').'.

'; return; } $date = gosmtp_optget('date'); $custom_start = gosmtp_optget('start-date'); $custom_end = gosmtp_optget('end-date'); $search = gosmtp_optget('search_email_reports'); $multiselect = gosmtp_optget('multiselect'); $all_data = array(); $logger = new GOSMTP\Logger(); // Appropriate date setup if($date == 'custom_date'){ $start = $custom_start; $end = $custom_end; if($start != '' && $end == ''){ $end = date("Y-m-d"); } }else if($date == 'all' || $date == ''){ $start = ''; $end = ''; }else{ $start = date('Y-m-d', strtotime('-'.$date.' days')); $end = date("Y-m-d"); } // Assign all data in option array $options = array( 'interval' => array( 'start' => $start, 'end' => $end ), 'search' => $search, 'multiselect' => $multiselect, 'pagination' => false, ); $email_logs = $logger->get_logs('records', 0, $options); // TODO: Get only records as paged $mails = gosmtp_group_by($email_logs); // Pagination $perpage = 10; $curpage = (int) gosmtp_optget('paged', 1); $records_ct = count($mails); $tpages = ceil($records_ct / $perpage); $offset = ($curpage - 1) * $perpage; $args = array( 'base' => '%_%', 'format' => '?paged=%#%', 'total' => $tpages, 'current' => $curpage, 'show_all' => false, 'end_size' => 1, 'mid_size' => 2, 'prev_next' => true, 'type' => 'array', 'add_args' => false ); // Set limit value $limit = array( 'perpage' => $perpage, 'offset' => $offset, ); $pages = paginate_links( $args ); $table_cols = array( 'subject' => __('Subject'), 'from' => __('From'), 'to' => __('To'), 'resent_count' => __('Resent'), 'retries' => __('Retry'), 'sent' => __('Sent'), 'failed' => __('Failed'), 'total' => __('Total') ); ?>

'.$col.''; } ?> $mail){ $mail_array = $mail['total']; echo ""; foreach($table_cols as $ck => $col){ echo ''; } echo ''; // Add by date data in all data array_push($all_data, $mail['by_dates']); } }else{ // Empty all data when no result found $all_data = array(); ?>

'.$mail_array[$ck].'
    '; foreach ( $pages as $page ) { echo ''; } echo '
'; } ?> $vv){ switch($kk){ case 'to': $tos = maybe_unserialize($vv); $to_list = []; foreach($tos as $keys => $to){ $to_list[] = $to[0]; } $return['total']['to'] = implode(',', $to_list); break; case 'status': if($vv == 'sent'){ $return['total']['sent'] = 1; $return['total']['failed'] = 0; }elseif($vv == 'failed'){ $return['total']['sent'] = 0; $return['total']['failed'] = 1; } break; case 'subject': $return['total'][$kk] = empty($vv) ? '[No Subject]' : $vv; break; default: $return['total'][$kk] = $vv; } } $return['total']['total'] = $return['total']['sent'] + $return['total']['failed']; $return['by_dates'][$val->created_at] = array( 'sent' => $return['total']['sent'], 'failed' => $return['total']['failed'], 'retries' => $return['total']['retries'], 'resent_count' => $return['total']['resent_count'], 'total' => $return['total']['total'], ); return $return; } // Generate Array with group by function gosmtp_group_by($logs, $limit = array(), $multiselect = array('subject', 'from', 'to')){ $groups = array(); $i = 0; $key_array = array(); if(empty($logs)){ return array(); } foreach($logs as $val){ $val = gosmtp_set_custom_array($val); $total = $val['total']; $groups_val = array(); foreach($multiselect as $multi_val){ array_push($groups_val, $total[$multi_val]); } // Add new group if(!in_array($groups_val, $key_array)){ $key_array[$i] = $groups_val; $groups[$i]['total'] = $val['total']; $groups[$i]['by_dates'] = $val['by_dates']; $i++; }else{ foreach($key_array as $kk => $vv){ if($groups_val != $vv){ continue; } $group_total = $groups[$kk]['total']; $total['sent'] = $group_total['sent'] + $total['sent']; $total['failed'] = $group_total['failed'] + $total['failed']; $total['retries'] = $group_total['retries'] + $total['retries']; $total['resent_count'] = $group_total['resent_count'] + $total['resent_count']; $total['total'] = $group_total['total'] + $total['total']; $groups[$kk]['total'] = $total; $groups[$kk]['by_dates'][array_keys($val['by_dates'])[0]] = $val['by_dates'][array_keys($val['by_dates'])[0]]; } } } // Set limit for Pagination if(!empty($limit)){ $limit_res = array(); for($i = 0; $i< $limit['perpage']; $i++){ $j = $i+$limit['offset']; if(isset($groups[$j])){ array_push($limit_res, $groups[$j] ); } } $groups = $limit_res; } return $groups; } main/ajax.php000064400000022343151710730040007126 0ustar00get_logs('records', $id); if(empty($mail_data)){ $resp['error'] = __('Records not found!'); gosmtp_json_output($resp); } $mail = $mail_data[0]; $tos = maybe_unserialize($mail->to); $attachments = maybe_unserialize($mail->attachments); $_attachments = array(); $to_list = array(); foreach($attachments as $key => $attachment){ $_attachments[] = array( 'Filename' => $attachment[1], 'Content-Transfer-Encoding' => $attachment[3], 'Content-Disposition' => $attachment[6], 'Content-Type' => $attachment[4] ); } $headers = maybe_unserialize($mail->headers); if(is_array($tos)){ foreach($tos as $key => $to){ $to_list[] = $to[0]; } }else{ $to_list[] = $tos; } $created_time = strtotime($mail->created_at); $created_at = date("M d, Y", $created_time).' at '. date('h:i A', $created_time); $backup_text = !empty($mail->parent_id) ? __('(Backup)') : ''; $tmp = array( 'id' => $mail->id, 'to' => implode(',', $to_list), 'from' => $mail->from, 'subject' => $mail->subject, 'source' => $mail->source, 'status' => $mail->status == 'sent' ? __('Sent') : __('Failed'), 'created' => $created_at, 'headers' => gosmtp_header_format($headers, 'array', true), 'attachments' => $_attachments, 'body' => $mail->body, 'provider' => !empty($mail->provider) ? ucfirst($mail->provider).' '.$backup_text : '', 'response' => maybe_unserialize($mail->response) ); $resp['response']['data'] = $tmp; gosmtp_json_output($resp); } add_action('wp_ajax_gosmtp_resend_mail','gosmtp_resend_mail'); function gosmtp_resend_mail(){ check_admin_referer( 'gosmtp_ajax' , 'gosmtp_nonce' ); $resp = array(); $id = gosmtp_optpost('id'); if(empty($id)){ $resp['error'] = __('Log ID Invalid!'); gosmtp_json_output($resp); } $mail_headers = array(); $id = (int)gosmtp_optpost('id'); $logger = new GOSMTP\Logger(); $response = $logger->get_logs('records', $id); if(!isset($response[0])){ $resp['error'] = __('Something Wents To Wrong!'); gosmtp_json_output($resp); } $response = $response[0]; $tos = maybe_unserialize($response->to); $subject = $response->subject; $attachments = maybe_unserialize($response->attachments); $_attachments = array(); $tos_list = array(); $body = $response->body; if(count($tos) > 0){ foreach($tos as $key => $to){ $tos_list[] = $to[0]; } } if(isset($_POST['recipient_email'])){ $tos_list = gosmtp_optpost('recipient_email'); } if(count($attachments) > 0){ foreach($attachments as $key => $attachment){ $_attachments[] = $attachment[0]; } } $headers = maybe_unserialize($response->headers); $headers = gosmtp_header_format($headers, 'text'); $result = wp_mail($tos_list, $subject, $body, $headers, $_attachments); if(!$result){ $resp['error'] = 'Unable to send mail!'; }else{ $resp['response'] = 'Message sent successfully!'; } gosmtp_json_output($resp); } add_action('wp_ajax_gosmtp_delete_log', 'gosmtp_delete_log'); function gosmtp_delete_log(){ check_admin_referer( 'gosmtp_ajax' , 'gosmtp_nonce' ); $resp = array(); $ids = gosmtp_optpost('id'); if(empty($ids)){ $resp['error'] = __('Log ID Invalid!'); gosmtp_json_output($resp); } $logger = new GOSMTP\Logger(); if(is_array($ids)){ foreach($ids as $k => $id){ $response = (int)$logger->delete_log($id); if(!empty($response)){ continue; } $resp['error'] = __('Some logs have not been removed for some reason!'); } }else{ $response = $logger->delete_log((int)$ids); } if(!empty($resp['error'])){ $resp['error'] = $resp['error']; gosmtp_json_output($resp); } if($response){ $resp['response'] = __('Log Removed Successfully!'); }else{ $resp['error'] = __('Unable to Remove logs for some reason!'); } gosmtp_json_output($resp); } // Miscellaneous function gosmtp_header_format($headers, $output = 'text', $replace_chars = false){ $heads = array(); if(empty($headers) || count($headers) < 1){ return $heads; } foreach($headers as $type => $header){ switch($output){ case 'text': $tmp_qry = $type.': '; if(is_array($header)){ foreach($header as $k => $vals){ $format = ($type != 'Reply-To' ? $vals[1].' <'.$vals[0].'>' : '<'.$vals[0].'>'); if($replace_chars){ $format = htmlspecialchars($format); } $tmp_qry .= $format; } $heads[] = $tmp_qry; }else{ $heads[] = $tmp_qry.' '.$header; } break; default: $tmp_qry = []; if(is_array($header)){ foreach($header as $k => $vals){ $format = ($type != 'Reply-To' ? $vals[1].' <'.$vals[0].'>' : '<'.$vals[0].'>'); if($replace_chars){ $format = htmlspecialchars($format); } $tmp_qry[] = $format; } $heads[$type] = $tmp_qry; }else{ $heads[$type] = $header; } } } return $heads; } add_action('wp_ajax_gosmtp_export_data', 'gosmtp_export_data'); function gosmtp_export_data(){ check_admin_referer( 'gosmtp_ajax' , 'gosmtp_nonce' ); $error = array(); if(!class_exists('GOSMTP\Logger')){ $error['error'] = __('logger class not found'); } if(!current_user_can('activate_plugins')){ $error['error'] = __('Permission Denied'); } if(!empty($error)){ $json_error = json_encode($error); header("x-error: $json_error"); wp_die(); } $common_info = gosmtp_optreq('common_information', array()); $addtional_info = gosmtp_optreq('addtional_information', array()); $export_key = explode(',', gosmtp_optreq('all_field')); if(!empty($_REQUEST['custom-field'])){ $export_key = array_merge($common_info, $addtional_info); } // Assign all data in option array $options = array( 'interval' => array( 'start' => gosmtp_optreq('start-date'), 'end' => gosmtp_optreq('end-date', date("Y-m-d")) ), 'search' => gosmtp_optreq('search'), 'multiselect' => gosmtp_optreq('search_type'), 'pagination' => false, ); $logger = new GOSMTP\Logger(); $email_logs = $logger->get_logs('records', 0, $options); $custom_data = array($export_key); if(empty($email_logs)){ $error['error'] = __('No Data Found'); $json_error = json_encode($error); header("x-error: $json_error"); wp_die(); } $export_data = []; foreach($email_logs as $val){ $temp_array = []; foreach($val as $inner_key => $inner_val){ $_data = maybe_unserialize($inner_val); if($inner_key == 'headers' && is_array($_data) ){ foreach($_data as $header_key => $header_val){ if(!in_array(strtolower($header_key), $export_key)){ continue; } if(is_array($header_val)){ $header_list = []; foreach($header_val as $header_inner_val){ $header_list[] = $header_inner_val[0]; } $header_val = implode(', ', $header_list); } $temp_array[array_search(strtolower($header_key), $export_key, true)] = $header_val; } continue; } if(!in_array($inner_key, $export_key)){ continue; } // Is array? if(is_array($_data)){ $unerialize_list = []; foreach($_data as $unserialize_keys => $unserialize_val){ switch ($inner_key) { case 'to': $unerialize_list[] = $unserialize_val[0]; break; case 'response': if($unserialize_keys == 'message'){ if(is_array($unserialize_val)){ $unserialize_val = implode(', ', $unserialize_val); } $unerialize_list[] = $unserialize_val; } break; case 'attachments': if(is_array($unserialize_val)){ $unserialize_val = implode('*', $unserialize_val); } $unerialize_list[] = $unserialize_val; break; default: $unerialize_list[] = $unserialize_val; } } $inner_val = implode(', ', $unerialize_list); } $temp_array[array_search($inner_key, $export_key, true)] = $inner_val; } ksort($temp_array); array_push($custom_data, $temp_array); } // Export format $func = 'gosmtp_export_'. gosmtp_optreq('format', 'csv'); include_once GOSMTP_PRO_DIR .'/main/export.php'; if(!function_exists($func) || !count($custom_data)>1){ $error['error'] = __('No Data Found Or '.$func.' function is not defined'); $json_error = json_encode($error); header("x-error: $json_error"); wp_die(); } $func($custom_data); wp_die(); } add_action('wp_ajax_gosmtp_pro_version_notice', 'gosmtp_pro_version_notice'); function gosmtp_pro_version_notice(){ check_admin_referer('gosmtp_version_notice', 'security'); if(!current_user_can('activate_plugins')){ wp_send_json_error(__('You do not have required access to do this action', 'gosmtp')); } $type = ''; if(!empty($_REQUEST['type'])){ $type = sanitize_text_field(wp_unslash($_REQUEST['type'])); } if(empty($type)){ wp_send_json_error(__('Unknow version difference type', 'gosmtp')); } update_option('gosmtp_version_'. $type .'_nag', time() + WEEK_IN_SECONDS); wp_send_json_success(); } main/plugin-update-checker.php000064400000150555151710730040012372 0ustar00metadataUrl = $metadataUrl; $this->pluginAbsolutePath = $pluginFile; $this->pluginFile = plugin_basename($this->pluginAbsolutePath); $this->muPluginFile = $muPluginFile; $this->slug = $slug; $this->optionName = $optionName; $this->debugMode = (bool)(constant('WP_DEBUG')); //If no slug is specified, use the name of the main plugin file as the slug. //For example, 'my-cool-plugin/cool-plugin.php' becomes 'cool-plugin'. if ( empty($this->slug) ){ $this->slug = basename($this->pluginFile, '.php'); } //Plugin slugs must be unique. $slugCheckFilter = 'puc_is_slug_in_use-' . $this->slug; $slugUsedBy = apply_filters($slugCheckFilter, false); if ( $slugUsedBy ) { $this->triggerError(sprintf( 'Plugin slug "%s" is already in use by %s. Slugs must be unique.', htmlentities($this->slug), htmlentities($slugUsedBy) ), E_USER_ERROR); } add_filter($slugCheckFilter, array($this, 'getAbsolutePath')); if ( empty($this->optionName) ){ $this->optionName = 'external_updates-' . $this->slug; } //Backwards compatibility: If the plugin is a mu-plugin but no $muPluginFile is specified, assume //it's the same as $pluginFile given that it's not in a subdirectory (WP only looks in the base dir). if ( (strpbrk($this->pluginFile, '/\\') === false) && $this->isUnknownMuPlugin() ) { $this->muPluginFile = $this->pluginFile; } $this->scheduler = $this->createScheduler($checkPeriod); $this->upgraderStatus = new Gosmtp_PucUpgraderStatus_3_2(); $this->installHooks(); } /** * Create an instance of the scheduler. * * This is implemented as a method to make it possible for plugins to subclass the update checker * and substitute their own scheduler. * * @param int $checkPeriod * @return Gosmtp_PucScheduler_3_2 */ protected function createScheduler($checkPeriod) { return new Gosmtp_PucScheduler_3_2($this, $checkPeriod); } /** * Install the hooks required to run periodic update checks and inject update info * into WP data structures. * * @return void */ protected function installHooks(){ //Override requests for plugin information add_filter('plugins_api', array($this, 'injectInfo'), 20, 3); //Insert our update info into the update array maintained by WP. add_filter('site_transient_update_plugins', array($this,'injectUpdate')); //WP 3.0+ add_filter('transient_update_plugins', array($this,'injectUpdate')); //WP 2.8+ add_filter('site_transient_update_plugins', array($this, 'injectTranslationUpdates')); add_filter('plugin_row_meta', array($this, 'addCheckForUpdatesLink'), 10, 2); add_action('admin_init', array($this, 'handleManualCheck')); add_action('all_admin_notices', array($this, 'displayManualCheckResult')); //Clear the version number cache when something - anything - is upgraded or WP clears the update cache. add_filter('upgrader_post_install', array($this, 'clearCachedVersion')); add_action('delete_site_transient_update_plugins', array($this, 'clearCachedVersion')); //Clear translation updates when WP clears the update cache. //This needs to be done directly because the library doesn't actually remove obsolete plugin updates, //it just hides them (see getUpdate()). We can't do that with translations - too much disk I/O. add_action('delete_site_transient_update_plugins', array($this, 'clearCachedTranslationUpdates')); if ( did_action('plugins_loaded') ) { $this->initDebugBarPanel(); } else { add_action('plugins_loaded', array($this, 'initDebugBarPanel')); } //Rename the update directory to be the same as the existing directory. add_filter('upgrader_source_selection', array($this, 'fixDirectoryName'), 10, 3); //Enable language support (i18n). load_plugin_textdomain('plugin-update-checker', false, plugin_basename(dirname(__FILE__)) . '/languages'); //Allow HTTP requests to the metadata URL even if it's on a local host. $this->metadataHost = @parse_url($this->metadataUrl, PHP_URL_HOST); add_filter('http_request_host_is_external', array($this, 'allowMetadataHost'), 10, 2); } /** * Explicitly allow HTTP requests to the metadata URL. * * WordPress has a security feature where the HTTP API will reject all requests that are sent to * another site hosted on the same server as the current site (IP match), a local host, or a local * IP, unless the host exactly matches the current site. * * This feature is opt-in (at least in WP 4.4). Apparently some people enable it. * * That can be a problem when you're developing your plugin and you decide to host the update information * on the same server as your test site. Update requests will mysteriously fail. * * We fix that by adding an exception for the metadata host. * * @param bool $allow * @param string $host * @return bool */ public function allowMetadataHost($allow, $host) { if ( strtolower($host) === strtolower($this->metadataHost) ) { return true; } return $allow; } /** * Retrieve plugin info from the configured API endpoint. * * @uses wp_remote_get() * * @param array $queryArgs Additional query arguments to append to the request. Optional. * @return GosmtpInfo_3_2 */ public function requestInfo($queryArgs = array()){ //Query args to append to the URL. Plugins can add their own by using a filter callback (see addQueryArgFilter()). $installedVersion = $this->getInstalledVersion(); $queryArgs['installed_version'] = ($installedVersion !== null) ? $installedVersion : ''; $queryArgs = apply_filters('puc_request_info_query_args-'.$this->slug, $queryArgs); //Various options for the wp_remote_get() call. Plugins can filter these, too. $options = array( 'timeout' => 10, //seconds 'headers' => array( 'Accept' => 'application/json' ), ); $options = apply_filters('puc_request_info_options-'.$this->slug, $options); //The plugin info should be at 'http://your-api.com/url/here/$slug/info.json' $url = $this->metadataUrl; if ( !empty($queryArgs) ){ $url = add_query_arg($queryArgs, $url); } $result = wp_remote_get( $url, $options ); //Try to parse the response $status = $this->validateApiResponse($result); $pluginInfo = null; if ( !is_wp_error($status) ){ $pluginInfo = GosmtpInfo_3_2::fromJson($result['body']); if ( $pluginInfo !== null ) { $pluginInfo->filename = $this->pluginFile; $pluginInfo->slug = $this->slug; } } else { $this->triggerError( sprintf('The URL %s does not point to a valid plugin metadata file. ', $url) . $status->get_error_message(), E_USER_WARNING ); } $pluginInfo = apply_filters('puc_request_info_result-'.$this->slug, $pluginInfo, $result); return $pluginInfo; } /** * Check if $result is a successful update API response. * * @param array|WP_Error $result * @return true|WP_Error */ private function validateApiResponse($result) { if ( is_wp_error($result) ) { /** @var WP_Error $result */ return new WP_Error($result->get_error_code(), 'WP HTTP Error: ' . $result->get_error_message()); } if ( !isset($result['response']['code']) ) { return new WP_Error('puc_no_response_code', 'wp_remote_get() returned an unexpected result.'); } if ( $result['response']['code'] !== 200 ) { return new WP_Error( 'puc_unexpected_response_code', 'HTTP response code is ' . $result['response']['code'] . ' (expected: 200)' ); } if ( empty($result['body']) ) { return new WP_Error('puc_empty_response', 'The metadata file appears to be empty.'); } return true; } /** * Retrieve the latest update (if any) from the configured API endpoint. * * @uses GosmtpUpdateChecker::requestInfo() * * @return GosmtpUpdate_3_2 An instance of GosmtpUpdate, or NULL when no updates are available. */ public function requestUpdate(){ //For the sake of simplicity, this function just calls requestInfo() //and transforms the result accordingly. $pluginInfo = $this->requestInfo(array('checking_for_updates' => '1')); if ( $pluginInfo == null ){ return null; } $update = GosmtpUpdate_3_2::fromGosmtpInfo($pluginInfo); //Keep only those translation updates that apply to this site. $update->translations = $this->filterApplicableTranslations($update->translations); return $update; } /** * Filter a list of translation updates and return a new list that contains only updates * that apply to the current site. * * @param array $translations * @return array */ private function filterApplicableTranslations($translations) { $languages = array_flip(array_values(get_available_languages())); $installedTranslations = wp_get_installed_translations('plugins'); if ( isset($installedTranslations[$this->slug]) ) { $installedTranslations = $installedTranslations[$this->slug]; } else { $installedTranslations = array(); } $applicableTranslations = array(); foreach($translations as $translation) { //Does it match one of the available core languages? $isApplicable = array_key_exists($translation->language, $languages); //Is it more recent than an already-installed translation? if ( isset($installedTranslations[$translation->language]) ) { $updateTimestamp = strtotime($translation->updated); $installedTimestamp = strtotime($installedTranslations[$translation->language]['PO-Revision-Date']); $isApplicable = $updateTimestamp > $installedTimestamp; } if ( $isApplicable ) { $applicableTranslations[] = $translation; } } return $applicableTranslations; } /** * Get the currently installed version of the plugin. * * @return string Version number. */ public function getInstalledVersion(){ if ( isset($this->cachedInstalledVersion) ) { return $this->cachedInstalledVersion; } $pluginHeader = $this->getPluginHeader(); if ( isset($pluginHeader['Version']) ) { $this->cachedInstalledVersion = $pluginHeader['Version']; return $pluginHeader['Version']; } else { //This can happen if the filename points to something that is not a plugin. $this->triggerError( sprintf( "Can't to read the Version header for '%s'. The filename is incorrect or is not a plugin.", $this->pluginFile ), E_USER_WARNING ); return null; } } /** * Get plugin's metadata from its file header. * * @return array */ protected function getPluginHeader() { if ( !is_file($this->pluginAbsolutePath) ) { //This can happen if the plugin filename is wrong. $this->triggerError( sprintf( "Can't to read the plugin header for '%s'. The file does not exist.", $this->pluginFile ), E_USER_WARNING ); return array(); } if ( !function_exists('get_plugin_data') ){ /** @noinspection PhpIncludeInspection */ require_once( ABSPATH . '/wp-admin/includes/plugin.php' ); } return get_plugin_data($this->pluginAbsolutePath, false, false); } /** * Check for plugin updates. * The results are stored in the DB option specified in $optionName. * * @return GosmtpUpdate_3_2|null */ public function checkForUpdates(){ $installedVersion = $this->getInstalledVersion(); //Fail silently if we can't find the plugin or read its header. if ( $installedVersion === null ) { $this->triggerError( sprintf('Skipping update check for %s - installed version unknown.', $this->pluginFile), E_USER_WARNING ); return null; } $state = $this->getUpdateState(); if ( empty($state) ){ $state = new stdClass; $state->lastCheck = 0; $state->checkedVersion = ''; $state->update = null; } $state->lastCheck = time(); $state->checkedVersion = $installedVersion; $this->setUpdateState($state); //Save before checking in case something goes wrong $state->update = $this->requestUpdate(); $this->setUpdateState($state); return $this->getUpdate(); } /** * Load the update checker state from the DB. * * @return stdClass|null */ public function getUpdateState() { $state = get_site_option($this->optionName, null); if ( empty($state) || !is_object($state)) { $state = null; } if ( isset($state, $state->update) && is_object($state->update) ) { $state->update = GosmtpUpdate_3_2::fromObject($state->update); } return $state; } /** * Persist the update checker state to the DB. * * @param StdClass $state * @return void */ private function setUpdateState($state) { if ( isset($state->update) && is_object($state->update) && method_exists($state->update, 'toStdClass') ) { $update = $state->update; /** @var GosmtpUpdate_3_2 $update */ $state->update = $update->toStdClass(); } update_site_option($this->optionName, $state); } /** * Reset update checker state - i.e. last check time, cached update data and so on. * * Call this when your plugin is being uninstalled, or if you want to * clear the update cache. */ public function resetUpdateState() { delete_site_option($this->optionName); } /** * Intercept plugins_api() calls that request information about our plugin and * use the configured API endpoint to satisfy them. * * @see plugins_api() * * @param mixed $result * @param string $action * @param array|object $args * @return mixed */ public function injectInfo($result, $action = null, $args = null){ $relevant = ($action == 'plugin_information') && isset($args->slug) && ( ($args->slug == $this->slug) || ($args->slug == dirname($this->pluginFile)) ); if ( !$relevant ) { return $result; } $pluginInfo = $this->requestInfo(); $pluginInfo = apply_filters('puc_pre_inject_info-' . $this->slug, $pluginInfo); if ( $pluginInfo ) { return $pluginInfo->toWpFormat(); } return $result; } /** * Insert the latest update (if any) into the update list maintained by WP. * * @param StdClass $updates Update list. * @return StdClass Modified update list. */ public function injectUpdate($updates){ //Is there an update to insert? $update = $this->getUpdate(); //No update notifications for mu-plugins unless explicitly enabled. The MU plugin file //is usually different from the main plugin file so the update wouldn't show up properly anyway. if ( $this->isUnknownMuPlugin() ) { $update = null; } if ( !empty($update) ) { //Let plugins filter the update info before it's passed on to WordPress. $update = apply_filters('puc_pre_inject_update-' . $this->slug, $update); $updates = $this->addUpdateToList($updates, $update); } else { //Clean up any stale update info. $updates = $this->removeUpdateFromList($updates); } return $updates; } /** * @param StdClass|null $updates * @param GosmtpUpdate_3_2 $updateToAdd * @return StdClass */ private function addUpdateToList($updates, $updateToAdd) { if ( !is_object($updates) ) { $updates = new stdClass(); $updates->response = array(); } $wpUpdate = $updateToAdd->toWpFormat(); $pluginFile = $this->pluginFile; if ( $this->isMuPlugin() ) { //WP does not support automatic update installation for mu-plugins, but we can still display a notice. $wpUpdate->package = null; $pluginFile = $this->muPluginFile; } $updates->response[$pluginFile] = $wpUpdate; return $updates; } /** * @param stdClass|null $updates * @return stdClass|null */ private function removeUpdateFromList($updates) { if ( isset($updates, $updates->response) ) { unset($updates->response[$this->pluginFile]); if ( !empty($this->muPluginFile) ) { unset($updates->response[$this->muPluginFile]); } } return $updates; } /** * Insert translation updates into the list maintained by WordPress. * * @param stdClass $updates * @return stdClass */ public function injectTranslationUpdates($updates) { $translationUpdates = $this->getTranslationUpdates(); if ( empty($translationUpdates) ) { return $updates; } //Being defensive. if ( !is_object($updates) ) { $updates = new stdClass(); } if ( !isset($updates->translations) ) { $updates->translations = array(); } //In case there's a name collision with a plugin hosted on wordpress.org, //remove any preexisting updates that match our plugin. $translationType = 'plugin'; $filteredTranslations = array(); foreach($updates->translations as $translation) { if ( ($translation['type'] === $translationType) && ($translation['slug'] === $this->slug) ) { continue; } $filteredTranslations[] = $translation; } $updates->translations = $filteredTranslations; //Add our updates to the list. foreach($translationUpdates as $update) { $convertedUpdate = array_merge( array( 'type' => $translationType, 'slug' => $this->slug, 'autoupdate' => 0, //AFAICT, WordPress doesn't actually use the "version" field for anything. //But lets make sure it's there, just in case. 'version' => isset($update->version) ? $update->version : ('1.' . strtotime($update->updated)), ), (array)$update ); $updates->translations[] = $convertedUpdate; } return $updates; } /** * Rename the update directory to match the existing plugin directory. * * When WordPress installs a plugin or theme update, it assumes that the ZIP file will contain * exactly one directory, and that the directory name will be the same as the directory where * the plugin/theme is currently installed. * * GitHub and other repositories provide ZIP downloads, but they often use directory names like * "project-branch" or "project-tag-hash". We need to change the name to the actual plugin folder. * * This is a hook callback. Don't call it from a plugin. * * @param string $source The directory to copy to /wp-content/plugins. Usually a subdirectory of $remoteSource. * @param string $remoteSource WordPress has extracted the update to this directory. * @param WP_Upgrader $upgrader * @return string|WP_Error */ public function fixDirectoryName($source, $remoteSource, $upgrader) { global $wp_filesystem; /** @var WP_Filesystem_Base $wp_filesystem */ //Basic sanity checks. if ( !isset($source, $remoteSource, $upgrader, $upgrader->skin, $wp_filesystem) ) { return $source; } //If WordPress is upgrading anything other than our plugin, leave the directory name unchanged. if ( !$this->isPluginBeingUpgraded($upgrader) ) { return $source; } //Rename the source to match the existing plugin directory. $pluginDirectoryName = dirname($this->pluginFile); if ( $pluginDirectoryName === '.' ) { return $source; } $correctedSource = trailingslashit($remoteSource) . $pluginDirectoryName . '/'; if ( $source !== $correctedSource ) { //The update archive should contain a single directory that contains the rest of plugin files. Otherwise, //WordPress will try to copy the entire working directory ($source == $remoteSource). We can't rename //$remoteSource because that would break WordPress code that cleans up temporary files after update. if ( $this->isBadDirectoryStructure($remoteSource) ) { return new WP_Error( 'puc-incorrect-directory-structure', sprintf( 'The directory structure of the update is incorrect. All plugin files should be inside ' . 'a directory named %s, not at the root of the ZIP file.', htmlentities($this->slug) ) ); } /** @var WP_Upgrader_Skin $upgrader->skin */ $upgrader->skin->feedback(sprintf( 'Renaming %s to %s…', '' . basename($source) . '', '' . $pluginDirectoryName . '' )); if ( $wp_filesystem->move($source, $correctedSource, true) ) { $upgrader->skin->feedback('Plugin directory successfully renamed.'); return $correctedSource; } else { return new WP_Error( 'puc-rename-failed', 'Unable to rename the update to match the existing plugin directory.' ); } } return $source; } /** * Check for incorrect update directory structure. An update must contain a single directory, * all other files should be inside that directory. * * @param string $remoteSource Directory path. * @return bool */ private function isBadDirectoryStructure($remoteSource) { global $wp_filesystem; /** @var WP_Filesystem_Base $wp_filesystem */ $sourceFiles = $wp_filesystem->dirlist($remoteSource); if ( is_array($sourceFiles) ) { $sourceFiles = array_keys($sourceFiles); $firstFilePath = trailingslashit($remoteSource) . $sourceFiles[0]; return (count($sourceFiles) > 1) || (!$wp_filesystem->is_dir($firstFilePath)); } //Assume it's fine. return false; } /** * Is there and update being installed RIGHT NOW, for this specific plugin? * * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update. * @return bool */ public function isPluginBeingUpgraded($upgrader = null) { return $this->upgraderStatus->isPluginBeingUpgraded($this->pluginFile, $upgrader); } /** * Get the details of the currently available update, if any. * * If no updates are available, or if the last known update version is below or equal * to the currently installed version, this method will return NULL. * * Uses cached update data. To retrieve update information straight from * the metadata URL, call requestUpdate() instead. * * @return GosmtpUpdate_3_2|null */ public function getUpdate() { $state = $this->getUpdateState(); /** @var StdClass $state */ //Is there an update available? if ( isset($state, $state->update) ) { $update = $state->update; //Check if the update is actually newer than the currently installed version. $installedVersion = $this->getInstalledVersion(); if ( ($installedVersion !== null) && version_compare($update->version, $installedVersion, '>') ){ $update->filename = $this->pluginFile; return $update; } } return null; } /** * Get a list of available translation updates. * * This method will return an empty array if there are no updates. * Uses cached update data. * * @return array */ public function getTranslationUpdates() { $state = $this->getUpdateState(); if ( isset($state, $state->update, $state->update->translations) ) { return $state->update->translations; } return array(); } /** * Remove all cached translation updates. * * @see wp_clean_update_cache */ public function clearCachedTranslationUpdates() { $state = $this->getUpdateState(); if ( isset($state, $state->update, $state->update->translations) ) { $state->update->translations = array(); $this->setUpdateState($state); } } /** * Add a "Check for updates" link to the plugin row in the "Plugins" page. By default, * the new link will appear after the "Visit plugin site" link. * * You can change the link text by using the "puc_manual_check_link-$slug" filter. * Returning an empty string from the filter will disable the link. * * @param array $pluginMeta Array of meta links. * @param string $pluginFile * @return array */ public function addCheckForUpdatesLink($pluginMeta, $pluginFile) { $isRelevant = ($pluginFile == $this->pluginFile) || (!empty($this->muPluginFile) && $pluginFile == $this->muPluginFile); if ( $isRelevant && current_user_can('update_plugins') ) { $linkUrl = wp_nonce_url( add_query_arg( array( 'puc_check_for_updates' => 1, 'puc_slug' => $this->slug, ), self_admin_url('plugins.php') ), 'puc_check_for_updates' ); $linkText = apply_filters('puc_manual_check_link-' . $this->slug, __('Check for updates', 'plugin-update-checker')); if ( !empty($linkText) ) { $final_link = sprintf('%s', esc_attr($linkUrl), $linkText); $pluginMeta[] = apply_filters('puc_manual_final_check_link-' . $this->slug, $final_link); } } return $pluginMeta; } /** * Check for updates when the user clicks the "Check for updates" link. * @see self::addCheckForUpdatesLink() * * @return void */ public function handleManualCheck() { $shouldCheck = isset($_GET['puc_check_for_updates'], $_GET['puc_slug']) && $_GET['puc_slug'] == $this->slug && current_user_can('update_plugins') && check_admin_referer('puc_check_for_updates'); if ( $shouldCheck ) { $update = $this->checkForUpdates(); $status = ($update === null) ? 'no_update' : 'update_available'; wp_redirect(add_query_arg( array( 'puc_update_check_result' => $status, 'puc_slug' => $this->slug, ), self_admin_url('plugins.php') )); } } /** * Display the results of a manual update check. * @see self::handleManualCheck() * * You can change the result message by using the "puc_manual_check_message-$slug" filter. */ public function displayManualCheckResult() { if ( isset($_GET['puc_update_check_result'], $_GET['puc_slug']) && ($_GET['puc_slug'] == $this->slug) ) { $status = strval($_GET['puc_update_check_result']); if ( $status == 'no_update' ) { $message = __('This plugin is up to date.', 'plugin-update-checker'); } else if ( $status == 'update_available' ) { $message = __('A new version of this plugin is available.', 'plugin-update-checker'); } else { $message = sprintf(__('Unknown update checker status "%s"', 'plugin-update-checker'), htmlentities($status)); } printf( '

%s

', apply_filters('puc_manual_check_message-' . $this->slug, $message, $status) ); } } /** * Check if the plugin file is inside the mu-plugins directory. * * @return bool */ protected function isMuPlugin() { static $cachedResult = null; if ( $cachedResult === null ) { //Convert both paths to the canonical form before comparison. $muPluginDir = realpath(WPMU_PLUGIN_DIR); $pluginPath = realpath($this->pluginAbsolutePath); if(!empty($muPluginDir)){ $cachedResult = (strpos($pluginPath, $muPluginDir) === 0); }else{ $cachedResult = false; } } return $cachedResult; } /** * MU plugins are partially supported, but only when we know which file in mu-plugins * corresponds to this plugin. * * @return bool */ protected function isUnknownMuPlugin() { return empty($this->muPluginFile) && $this->isMuPlugin(); } /** * Clear the cached plugin version. This method can be set up as a filter (hook) and will * return the filter argument unmodified. * * @param mixed $filterArgument * @return mixed */ public function clearCachedVersion($filterArgument = null) { $this->cachedInstalledVersion = null; return $filterArgument; } /** * Get absolute path to the main plugin file. * * @return string */ public function getAbsolutePath() { return $this->pluginAbsolutePath; } /** * Register a callback for filtering query arguments. * * The callback function should take one argument - an associative array of query arguments. * It should return a modified array of query arguments. * * @uses add_filter() This method is a convenience wrapper for add_filter(). * * @param callable $callback * @return void */ public function addQueryArgFilter($callback){ add_filter('puc_request_info_query_args-'.$this->slug, $callback); } /** * Register a callback for filtering arguments passed to wp_remote_get(). * * The callback function should take one argument - an associative array of arguments - * and return a modified array or arguments. See the WP documentation on wp_remote_get() * for details on what arguments are available and how they work. * * @uses add_filter() This method is a convenience wrapper for add_filter(). * * @param callable $callback * @return void */ public function addHttpRequestArgFilter($callback){ add_filter('puc_request_info_options-'.$this->slug, $callback); } /** * Register a callback for filtering the plugin info retrieved from the external API. * * The callback function should take two arguments. If the plugin info was retrieved * successfully, the first argument passed will be an instance of GosmtpInfo. Otherwise, * it will be NULL. The second argument will be the corresponding return value of * wp_remote_get (see WP docs for details). * * The callback function should return a new or modified instance of GosmtpInfo or NULL. * * @uses add_filter() This method is a convenience wrapper for add_filter(). * * @param callable $callback * @return void */ public function addResultFilter($callback){ add_filter('puc_request_info_result-'.$this->slug, $callback, 10, 2); } /** * Register a callback for one of the update checker filters. * * Identical to add_filter(), except it automatically adds the "puc_" prefix * and the "-$plugin_slug" suffix to the filter name. For example, "request_info_result" * becomes "puc_request_info_result-your_plugin_slug". * * @param string $tag * @param callable $callback * @param int $priority * @param int $acceptedArgs */ public function addFilter($tag, $callback, $priority = 10, $acceptedArgs = 1) { add_filter('puc_' . $tag . '-' . $this->slug, $callback, $priority, $acceptedArgs); } /** * Initialize the update checker Debug Bar plugin/add-on thingy. */ public function initDebugBarPanel() { $debugBarPlugin = dirname(__FILE__) . '/debug-bar-plugin.php'; if ( class_exists('Debug_Bar', false) && file_exists($debugBarPlugin) ) { /** @noinspection PhpIncludeInspection */ require_once $debugBarPlugin; $this->debugBarPlugin = new Gosmtp_PucDebugBarPlugin_3_2($this); } } /** * Trigger a PHP error, but only when $debugMode is enabled. * * @param string $message * @param int $errorType */ protected function triggerError($message, $errorType) { if ( $this->debugMode ) { trigger_error($message, $errorType); } } } endif; if ( !class_exists('GosmtpInfo_3_2', false) ): /** * A container class for holding and transforming various plugin metadata. * * @author Janis Elsts * @copyright 2016 * @version 3.2 * @access public */ class GosmtpInfo_3_2 { //Most fields map directly to the contents of the plugin's info.json file. //See the relevant docs for a description of their meaning. public $name; public $slug; public $version; public $homepage; public $sections = array(); public $banners; public $translations = array(); public $download_url; public $author; public $author_homepage; public $requires; public $tested; public $upgrade_notice; public $rating; public $num_ratings; public $downloaded; public $active_installs; public $last_updated; public $id = 0; //The native WP.org API returns numeric plugin IDs, but they're not used for anything. public $filename; //Plugin filename relative to the plugins directory. /** * Create a new instance of GosmtpInfo from JSON-encoded plugin info * returned by an external update API. * * @param string $json Valid JSON string representing plugin info. * @return GosmtpInfo_3_2|null New instance of GosmtpInfo, or NULL on error. */ public static function fromJson($json){ /** @var StdClass $apiResponse */ $apiResponse = json_decode($json); if ( empty($apiResponse) || !is_object($apiResponse) ){ trigger_error( "Failed to parse plugin metadata. Try validating your .json file with http://jsonlint.com/", E_USER_NOTICE ); return null; } $valid = self::validateMetadata($apiResponse); if ( is_wp_error($valid) ){ trigger_error($valid->get_error_message(), E_USER_NOTICE); return null; } $info = new self(); foreach(get_object_vars($apiResponse) as $key => $value){ $info->$key = $value; } //json_decode decodes assoc. arrays as objects. We want it as an array. $info->sections = (array)$info->sections; return $info; } /** * Very, very basic validation. * * @param StdClass $apiResponse * @return bool|WP_Error */ protected static function validateMetadata($apiResponse) { if ( !isset($apiResponse->name, $apiResponse->version) || empty($apiResponse->name) || empty($apiResponse->version) ) { return new WP_Error( 'puc-invalid-metadata', "The plugin metadata file does not contain the required 'name' and/or 'version' keys." ); } return true; } /** * Transform plugin info into the format used by the native WordPress.org API * * @return object */ public function toWpFormat(){ $info = new stdClass; //The custom update API is built so that many fields have the same name and format //as those returned by the native WordPress.org API. These can be assigned directly. $sameFormat = array( 'name', 'slug', 'version', 'requires', 'tested', 'rating', 'upgrade_notice', 'num_ratings', 'downloaded', 'active_installs', 'homepage', 'last_updated', ); foreach($sameFormat as $field){ if ( isset($this->$field) ) { $info->$field = $this->$field; } else { $info->$field = null; } } //Other fields need to be renamed and/or transformed. $info->download_link = $this->download_url; $info->author = $this->getFormattedAuthor(); $info->sections = array_merge(array('description' => ''), $this->sections); if ( !empty($this->banners) ) { //WP expects an array with two keys: "high" and "low". Both are optional. //Docs: https://wordpress.org/plugins/about/faq/#banners $info->banners = is_object($this->banners) ? get_object_vars($this->banners) : $this->banners; $info->banners = array_intersect_key($info->banners, array('high' => true, 'low' => true)); } return $info; } protected function getFormattedAuthor() { if ( !empty($this->author_homepage) ){ return sprintf('%s', $this->author_homepage, $this->author); } return $this->author; } } endif; if ( !class_exists('GosmtpUpdate_3_2', false) ): /** * A simple container class for holding information about an available update. * * @author Janis Elsts * @copyright 2016 * @version 3.2 * @access public */ class GosmtpUpdate_3_2 { public $id = 0; public $slug; public $version; public $homepage; public $download_url; public $upgrade_notice; public $tested; public $translations = array(); public $filename; //Plugin filename relative to the plugins directory. private static $fields = array( 'id', 'slug', 'version', 'homepage', 'tested', 'download_url', 'upgrade_notice', 'filename', 'translations' ); /** * Create a new instance of GosmtpUpdate from its JSON-encoded representation. * * @param string $json * @return GosmtpUpdate_3_2|null */ public static function fromJson($json){ //Since update-related information is simply a subset of the full plugin info, //we can parse the update JSON as if it was a plugin info string, then copy over //the parts that we care about. $pluginInfo = GosmtpInfo_3_2::fromJson($json); if ( $pluginInfo != null ) { return self::fromGosmtpInfo($pluginInfo); } else { return null; } } /** * Create a new instance of GosmtpUpdate based on an instance of GosmtpInfo. * Basically, this just copies a subset of fields from one object to another. * * @param GosmtpInfo_3_2 $info * @return GosmtpUpdate_3_2 */ public static function fromGosmtpInfo($info){ return self::fromObject($info); } /** * Create a new instance of GosmtpUpdate by copying the necessary fields from * another object. * * @param StdClass|GosmtpInfo_3_2|GosmtpUpdate_3_2 $object The source object. * @return GosmtpUpdate_3_2 The new copy. */ public static function fromObject($object) { $update = new self(); $fields = self::$fields; if ( !empty($object->slug) ) { $fields = apply_filters('puc_retain_fields-' . $object->slug, $fields); } foreach($fields as $field){ if (property_exists($object, $field)) { $update->$field = $object->$field; } } return $update; } /** * Create an instance of StdClass that can later be converted back to * a GosmtpUpdate. Useful for serialization and caching, as it avoids * the "incomplete object" problem if the cached value is loaded before * this class. * * @return StdClass */ public function toStdClass() { $object = new stdClass(); $fields = self::$fields; if ( !empty($this->slug) ) { $fields = apply_filters('puc_retain_fields-' . $this->slug, $fields); } foreach($fields as $field){ if (property_exists($this, $field)) { $object->$field = $this->$field; } } return $object; } /** * Transform the update into the format used by WordPress native plugin API. * * @return object */ public function toWpFormat(){ $update = new stdClass; $update->id = $this->id; $update->slug = $this->slug; $update->new_version = $this->version; $update->url = $this->homepage; $update->package = $this->download_url; $update->tested = $this->tested; $update->plugin = $this->filename; if ( !empty($this->upgrade_notice) ){ $update->upgrade_notice = $this->upgrade_notice; } return $update; } } endif; if ( !class_exists('Gosmtp_PucScheduler_3_2', false) ): /** * The scheduler decides when and how often to check for updates. * It calls @see GosmtpUpdateChecker::checkForUpdates() to perform the actual checks. * * @version 3.2 */ class Gosmtp_PucScheduler_3_2 { public $checkPeriod = 12; //How often to check for updates (in hours). public $throttleRedundantChecks = false; //Check less often if we already know that an update is available. public $throttledCheckPeriod = 72; /** * @var GosmtpUpdateChecker_3_2 */ protected $updateChecker; private $cronHook = null; /** * Scheduler constructor. * * @param GosmtpUpdateChecker_3_2 $updateChecker * @param int $checkPeriod How often to check for updates (in hours). */ public function __construct($updateChecker, $checkPeriod) { $this->updateChecker = $updateChecker; $this->checkPeriod = $checkPeriod; //Set up the periodic update checks $this->cronHook = 'check_plugin_updates-' . $this->updateChecker->slug; if ( $this->checkPeriod > 0 ){ //Trigger the check via Cron. //Try to use one of the default schedules if possible as it's less likely to conflict //with other plugins and their custom schedules. $defaultSchedules = array( 1 => 'hourly', 12 => 'twicedaily', 24 => 'daily', ); if ( array_key_exists($this->checkPeriod, $defaultSchedules) ) { $scheduleName = $defaultSchedules[$this->checkPeriod]; } else { //Use a custom cron schedule. $scheduleName = 'every' . $this->checkPeriod . 'hours'; add_filter('cron_schedules', array($this, '_addCustomSchedule')); } if ( !wp_next_scheduled($this->cronHook) && !defined('WP_INSTALLING') ) { wp_schedule_event(time(), $scheduleName, $this->cronHook); } add_action($this->cronHook, array($this, 'maybeCheckForUpdates')); register_deactivation_hook($this->updateChecker->pluginFile, array($this, '_removeUpdaterCron')); //In case Cron is disabled or unreliable, we also manually trigger //the periodic checks while the user is browsing the Dashboard. add_action( 'admin_init', array($this, 'maybeCheckForUpdates') ); //Like WordPress itself, we check more often on certain pages. /** @see wp_update_plugins */ add_action('load-update-core.php', array($this, 'maybeCheckForUpdates')); add_action('load-plugins.php', array($this, 'maybeCheckForUpdates')); add_action('load-update.php', array($this, 'maybeCheckForUpdates')); //This hook fires after a bulk update is complete. add_action('upgrader_process_complete', array($this, 'maybeCheckForUpdates'), 11, 0); } else { //Periodic checks are disabled. wp_clear_scheduled_hook($this->cronHook); } } /** * Check for updates if the configured check interval has already elapsed. * Will use a shorter check interval on certain admin pages like "Dashboard -> Updates" or when doing cron. * * You can override the default behaviour by using the "puc_check_now-$slug" filter. * The filter callback will be passed three parameters: * - Current decision. TRUE = check updates now, FALSE = don't check now. * - Last check time as a Unix timestamp. * - Configured check period in hours. * Return TRUE to check for updates immediately, or FALSE to cancel. * * This method is declared public because it's a hook callback. Calling it directly is not recommended. */ public function maybeCheckForUpdates(){ if ( empty($this->checkPeriod) ){ return; } $state = $this->updateChecker->getUpdateState(); $shouldCheck = empty($state) || !isset($state->lastCheck) || ( (time() - $state->lastCheck) >= $this->getEffectiveCheckPeriod() ); //Let plugin authors substitute their own algorithm. $shouldCheck = apply_filters( 'puc_check_now-' . $this->updateChecker->slug, $shouldCheck, (!empty($state) && isset($state->lastCheck)) ? $state->lastCheck : 0, $this->checkPeriod ); if ( $shouldCheck ) { $this->updateChecker->checkForUpdates(); } } /** * Calculate the actual check period based on the current status and environment. * * @return int Check period in seconds. */ protected function getEffectiveCheckPeriod() { $currentFilter = current_filter(); if ( in_array($currentFilter, array('load-update-core.php', 'upgrader_process_complete')) ) { //Check more often when the user visits "Dashboard -> Updates" or does a bulk update. $period = 60; } else if ( in_array($currentFilter, array('load-plugins.php', 'load-update.php')) ) { //Also check more often on the "Plugins" page and /wp-admin/update.php. $period = 3600; } else if ( $this->throttleRedundantChecks && ($this->updateChecker->getUpdate() !== null) ) { //Check less frequently if it's already known that an update is available. $period = $this->throttledCheckPeriod * 3600; } else if ( defined('DOING_CRON') && constant('DOING_CRON') ) { //WordPress cron schedules are not exact, so lets do an update check even //if slightly less than $checkPeriod hours have elapsed since the last check. $cronFuzziness = 20 * 60; $period = $this->checkPeriod * 3600 - $cronFuzziness; } else { $period = $this->checkPeriod * 3600; } return $period; } /** * Add our custom schedule to the array of Cron schedules used by WP. * * @param array $schedules * @return array */ public function _addCustomSchedule($schedules){ if ( $this->checkPeriod && ($this->checkPeriod > 0) ){ $scheduleName = 'every' . $this->checkPeriod . 'hours'; $schedules[$scheduleName] = array( 'interval' => $this->checkPeriod * 3600, 'display' => sprintf('Every %d hours', $this->checkPeriod), ); } return $schedules; } /** * Remove the scheduled cron event that the library uses to check for updates. * * @return void */ public function _removeUpdaterCron(){ wp_clear_scheduled_hook($this->cronHook); } /** * Get the name of the update checker's WP-cron hook. Mostly useful for debugging. * * @return string */ public function getCronHookName() { return $this->cronHook; } } endif; if ( !class_exists('Gosmtp_PucUpgraderStatus_3_2', false) ): /** * A utility class that helps figure out which plugin WordPress is upgrading. * * It may seem strange to have an separate class just for that, but the task is surprisingly complicated. * Core classes like Plugin_Upgrader don't expose the plugin file name during an in-progress update (AFAICT). * This class uses a few workarounds and heuristics to get the file name. */ class Gosmtp_PucUpgraderStatus_3_2 { private $upgradedPluginFile = null; //The plugin that is currently being upgraded by WordPress. public function __construct() { //Keep track of which plugin WordPress is currently upgrading. add_filter('upgrader_pre_install', array($this, 'setUpgradedPlugin'), 10, 2); add_filter('upgrader_package_options', array($this, 'setUpgradedPluginFromOptions'), 10, 1); add_filter('upgrader_post_install', array($this, 'clearUpgradedPlugin'), 10, 1); add_action('upgrader_process_complete', array($this, 'clearUpgradedPlugin'), 10, 1); } /** * Is there and update being installed RIGHT NOW, for a specific plugin? * * Caution: This method is unreliable. WordPress doesn't make it easy to figure out what it is upgrading, * and upgrader implementations are liable to change without notice. * * @param string $pluginFile The plugin to check. * @param WP_Upgrader|null $upgrader The upgrader that's performing the current update. * @return bool True if the plugin identified by $pluginFile is being upgraded. */ public function isPluginBeingUpgraded($pluginFile, $upgrader = null) { if ( isset($upgrader) ) { $upgradedPluginFile = $this->getPluginBeingUpgradedBy($upgrader); if ( !empty($upgradedPluginFile) ) { $this->upgradedPluginFile = $upgradedPluginFile; } } return ( !empty($this->upgradedPluginFile) && ($this->upgradedPluginFile === $pluginFile) ); } /** * Get the file name of the plugin that's currently being upgraded. * * @param Plugin_Upgrader|WP_Upgrader $upgrader * @return string|null */ private function getPluginBeingUpgradedBy($upgrader) { if ( !isset($upgrader, $upgrader->skin) ) { return null; } //Figure out which plugin is being upgraded. $pluginFile = null; $skin = $upgrader->skin; if ( $skin instanceof Plugin_Upgrader_Skin ) { if ( isset($skin->plugin) && is_string($skin->plugin) && ($skin->plugin !== '') ) { $pluginFile = $skin->plugin; } } elseif ( isset($skin->plugin_info) && is_array($skin->plugin_info) ) { //This case is tricky because Bulk_Plugin_Upgrader_Skin (etc) doesn't actually store the plugin //filename anywhere. Instead, it has the plugin headers in $plugin_info. So the best we can //do is compare those headers to the headers of installed plugins. $pluginFile = $this->identifyPluginByHeaders($skin->plugin_info); } return $pluginFile; } /** * Identify an installed plugin based on its headers. * * @param array $searchHeaders The plugin file header to look for. * @return string|null Plugin basename ("foo/bar.php"), or NULL if we can't identify the plugin. */ private function identifyPluginByHeaders($searchHeaders) { if ( !function_exists('get_plugins') ){ /** @noinspection PhpIncludeInspection */ require_once( ABSPATH . '/wp-admin/includes/plugin.php' ); } $installedPlugins = get_plugins(); $matches = array(); foreach($installedPlugins as $pluginBasename => $headers) { $diff1 = array_diff_assoc($headers, $searchHeaders); $diff2 = array_diff_assoc($searchHeaders, $headers); if ( empty($diff1) && empty($diff2) ) { $matches[] = $pluginBasename; } } //It's possible (though very unlikely) that there could be two plugins with identical //headers. In that case, we can't unambiguously identify the plugin that's being upgraded. if ( count($matches) !== 1 ) { return null; } return reset($matches); } /** * @access private * * @param mixed $input * @param array $hookExtra * @return mixed Returns $input unaltered. */ public function setUpgradedPlugin($input, $hookExtra) { if (!empty($hookExtra['plugin']) && is_string($hookExtra['plugin'])) { $this->upgradedPluginFile = $hookExtra['plugin']; } else { $this->upgradedPluginFile = null; } return $input; } /** * @access private * * @param array $options * @return array */ public function setUpgradedPluginFromOptions($options) { if (isset($options['hook_extra']['plugin']) && is_string($options['hook_extra']['plugin'])) { $this->upgradedPluginFile = $options['hook_extra']['plugin']; } else { $this->upgradedPluginFile = null; } return $options; } /** * @access private * * @param mixed $input * @return mixed Returns $input unaltered. */ public function clearUpgradedPlugin($input = null) { $this->upgradedPluginFile = null; return $input; } } endif; if ( !class_exists('Gosmtp_PucFactory', false) ): /** * A factory that builds instances of other classes from this library. * * When multiple versions of the same class have been loaded (e.g. GosmtpUpdateChecker 1.2 * and 1.3), this factory will always use the latest available version. Register class * versions by calling {@link Gosmtp_PucFactory::addVersion()}. * * At the moment it can only build instances of the GosmtpUpdateChecker class. Other classes * are intended mainly for internal use and refer directly to specific implementations. If you * want to instantiate one of them anyway, you can use {@link Gosmtp_PucFactory::getLatestClassVersion()} * to get the class name and then create it with new $class(...). */ class Gosmtp_PucFactory { protected static $classVersions = array(); protected static $sorted = false; /** * Create a new instance of GosmtpUpdateChecker. * * @see GosmtpUpdateChecker::__construct() * * @param $metadataUrl * @param $pluginFile * @param string $slug * @param int $checkPeriod * @param string $optionName * @param string $muPluginFile * @return GosmtpUpdateChecker_3_2 */ public static function buildUpdateChecker($metadataUrl, $pluginFile, $slug = '', $checkPeriod = 12, $optionName = '', $muPluginFile = '') { $class = self::getLatestClassVersion('GosmtpUpdateChecker'); return new $class($metadataUrl, $pluginFile, $slug, $checkPeriod, $optionName, $muPluginFile); } /** * Get the specific class name for the latest available version of a class. * * @param string $class * @return string|null */ public static function getLatestClassVersion($class) { if ( !self::$sorted ) { self::sortVersions(); } if ( isset(self::$classVersions[$class]) ) { return reset(self::$classVersions[$class]); } else { return null; } } /** * Sort available class versions in descending order (i.e. newest first). */ protected static function sortVersions() { foreach ( self::$classVersions as $class => $versions ) { uksort($versions, array(__CLASS__, 'compareVersions')); self::$classVersions[$class] = $versions; } self::$sorted = true; } protected static function compareVersions($a, $b) { return -version_compare($a, $b); } /** * Register a version of a class. * * @access private This method is only for internal use by the library. * * @param string $generalClass Class name without version numbers, e.g. 'GosmtpUpdateChecker'. * @param string $versionedClass Actual class name, e.g. 'GosmtpUpdateChecker_1_2'. * @param string $version Version number, e.g. '1.2'. */ public static function addVersion($generalClass, $versionedClass, $version) { if ( !isset(self::$classVersions[$generalClass]) ) { self::$classVersions[$generalClass] = array(); } self::$classVersions[$generalClass][$version] = $versionedClass; self::$sorted = false; } } endif; //Register classes defined in this file with the factory. Gosmtp_PucFactory::addVersion('GosmtpUpdateChecker', 'GosmtpUpdateChecker_3_2', '3.2'); Gosmtp_PucFactory::addVersion('GosmtpUpdate', 'GosmtpUpdate_3_2', '3.2'); Gosmtp_PucFactory::addVersion('GosmtpInfo', 'GosmtpInfo_3_2', '3.2'); Gosmtp_PucFactory::addVersion('Gosmtp_PucGitHubChecker', 'Gosmtp_PucGitHubChecker_3_2', '3.2'); main/logger.php000064400000011173151710730040007461 0ustar00table = $wpdb->prefix . GOSMTP_DB_PREFIX .'email_logs'; } public function create_table(){ global $wpdb; $charsetCollate = $wpdb->get_charset_collate(); if($wpdb->get_var("SHOW TABLES LIKE '$this->table'") == $this->table){ return; } $sql = "CREATE TABLE $this->table ( `id` INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, `site_id` INT UNSIGNED NULL, `message_id` VARCHAR(255) NULL, `to` VARCHAR(255), `from` VARCHAR(255), `subject` VARCHAR(255), `body` LONGTEXT NULL, `headers` LONGTEXT NULL, `attachments` LONGTEXT NULL, `status` VARCHAR(20) DEFAULT 'pending', `response` TEXT NULL, `extra` TEXT NULL, `retries` INT UNSIGNED NULL DEFAULT 0, `resent_count` INT UNSIGNED NULL DEFAULT 0, `provider` TEXT NULL, `source` VARCHAR(255) NULL, `created_at` TIMESTAMP NULL, `updated_at` TIMESTAMP NULL, `parent_id` INT UNSIGNED NULL DEFAULT 0 ) $charsetCollate;"; // Make Sitepad compatible $upgrade = ABSPATH . 'site-admin/includes/upgrade.php'; $upgrade = file_exists($upgrade) ? $upgrade : ABSPATH . 'wp-admin/includes/upgrade.php'; require_once( $upgrade ); dbDelta($sql); } public function add_logs($data){ global $wpdb; if(empty($data)){ return false; } $result = $wpdb->insert($this->table, $data); if($result){ return $wpdb->insert_id; } return false; } public function update_logs($data, $id){ global $wpdb; if(empty($data) || empty($id)){ return false; } $result = $wpdb->update( $this->table, $data, array( 'id' => $id ) ); if($result){ return true; } return false; } public function delete_log($id){ global $wpdb; $data['id'] = $id; $result = $wpdb->delete($this->table, $data); if(!empty($result)){ return true; } return false; } public function get_logs($for = 'records', $id = '', $args = array()){ global $wpdb; $defaults = array( 'interval' => array(), 'limit' => 10, 'offset' => 0, 'pagination' => true, 'multiselect' => array(), ); $args = wp_parse_args( $args, $defaults ); $query = ''; $start = ''; $end = date('y-m-d').' 23:59:59'; if(!empty($args['filter'])){ $query .= 'status="'.$args['filter'].'"'; } if(!empty($args['interval']) && !empty($args['interval']['start'])){ $start = $args['interval']['start'].' 00:00:00'; if(!empty($args['interval']['end'])){ $end = $args['interval']['end'].' 23:59:59'; } $query .= (!empty($query) ? ' and (' : '').'`created_at` between "'.$start.'" and "'.$end.'" '.(!empty($query) ? ') ' : ' '); } if(!empty($args['search']) && empty($args['multiselect'])){ $query .= (!empty($query) ? ' and ' : '').' ( `from` like "%'. $args['search'] .'%" or `subject` like "%'. $args['search'] .'%" or `to` like "%'. $args['search'] .'%" or `body` like "%'. $args['search'] .'%" )'; }else if(!empty($args['search'])){ $search_qry =''; foreach($args['multiselect'] as $key => $value){ $search_qry .= '`'.$value.'` like "%'.$args['search'].'%"'; if(count($args['multiselect']) - 1 > $key){ $search_qry .= ' or '; } } $query .= (!empty($query) ? ' and ' : '').' ('.$search_qry.')'; } if(!empty($query)){ $query = ' where '.$query; } if(!empty($id)){ $query = ' where id='.$id; }else if(!empty($args['pagination'])){ $query .= $for != 'count' ? ' order by id desc LIMIT '.$args['limit'].' OFFSET '.$args['offset'] : ' '; } // echo "SELECT * FROM ".$this->table. $query; try{ if($for == 'count'){ $result = $wpdb->get_results("SELECT count(*) as records FROM ".$this->table. $query)[0]; }else{ $result = $wpdb->get_results("SELECT * FROM ".$this->table. $query); if( count($result) == 0 ){ return false; } } return $result; }catch(\Exception $e){} return false; } public function clear_records( $period = 0 ){ if( empty($period) || $period == 0 ) return; global $wpdb; $date = ( new \DateTime( '-'.$period.' seconds' ))->format('Y-m-d H:i:s'); $query = 'DELETE FROM `'.$this->table.'` WHERE created_at < %s'; if( $period == -1 ){ $query = 'TRUNCATE TABLE '.$this->table; $date = ''; } $wpdb->query( $wpdb->prepare( $query , $date) ); } public static function retention_logs(){ global $gosmtp; if(empty($gosmtp->options['logs']['retention_period'])){ return; } $logger = new Logger(); // Clear logs $logger->clear_records($gosmtp->options['logs']['retention_period']); } }main/smtp-logs.php000064400000035147151710730040010136 0ustar00options['logs']['enable_logs']) ){ echo '

'.__('Email logs is disabled').'

'.__('To store and view email logs, please enable email logs from GoSMTP').' '.__('settings').'.

'; return; } // Styles and Scripts wp_enqueue_style( 'gosmtp-admin' ); wp_enqueue_script( 'gosmtp-admin' ); $filter = gosmtp_optget('filter'); $start = gosmtp_optget('from'); $end = gosmtp_optget('to'); $search = gosmtp_optget('search'); $default = array( 'subject' => 'on', 'date_send' => 'on', 'action' => 'on' ); $columns = !empty( $gosmtp->options['logs']['log_columns'] ) ? maybe_unserialize($gosmtp->options['logs']['log_columns']) : array(); $columns = array_merge($default, $columns); ?>

'', 'from' => '', 'to' => '', 'source' => '', 'provider' => '', 'date_send' => '', 'action' => '', ); foreach($logs_th as $key => $col ){ if(!empty($columns) && array_key_exists($key,$columns)){ echo $col; } } ?> !empty($filter) && $filter != 'all' ? ($filter == 'success' ? 'sent' : 'failed') : '', 'interval' => array( 'start' => $start, 'end' => $end ), 'search' => $search, ); // Pagination $perpage = 10; $records_ct = (int) $logger->get_logs('count', '', $options)->records; $tpages = ceil($records_ct / $perpage); $offset = ($curpage - 1) * $perpage; $options['limit'] = $perpage; $options['offset'] = $offset; $args = array( 'base' => '%_%', 'format' => '?paged=%#%', 'total' => $tpages, 'current' => $curpage, 'show_all' => false, 'end_size' => 1, 'mid_size' => 2, 'prev_next' => true, 'type' => 'array', 'add_args' => false ); $pagination = null; $pages = paginate_links( $args ); if( is_array( $pages ) ){ $paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var('paged'); $pagination .= '
    '; foreach ( $pages as $page ) { $pagination .= ''; } $pagination .= '
'; } $mails = $logger->get_logs('records', 0, $options); if(!empty($mails)){ foreach($mails as $key => $mail){ $id = $mail->id; $tos = maybe_unserialize($mail->to); $to_list = []; if(is_array($tos)){ foreach($tos as $key => $to){ $to_list[] = $to[0]; } $to_list = implode(',',$to_list); }else{ $to_list = $tos; } $created_at = date("M d, Y", strtotime($mail->created_at)).' at '. date('h:i A', strtotime($mail->created_at)); $status = $mail->status == 'sent' ? __('Sent') : __('Failed'); $resend_retry = $mail->status == 'sent' ? __('Resend') : __('Retry'); $backup_text = !empty($mail->parent_id) ? __('(Backup)') : ''; $logs_td = array( 'subject' => '', 'from' => '', 'to' => '', 'source' => '', 'provider' => '', 'date_send' => '', 'action' => '' ); ?> $col ){ if(!empty($columns) && array_key_exists($key,$columns)){ echo $col; } } ?>
'.__('Subject').''.__('From').''.__('To').''.__('Source').''.__('Provider').''.__('Date Send').''.__('Actions').'
'. (!empty($mail->subject) ? esc_attr($mail->subject) : __('[No Subject]')) .' '.(!empty($mail->from) ? esc_html($mail->from) : __('NA')).''.esc_html($to_list).''.(!empty($mail->source) ? esc_html($mail->source) : __('NA')).''.(!empty($mail->provider) ? ucwords(esc_html($mail->provider)).' '.$backup_text : __('NA')).''.esc_html($created_at).'

:

main/mailer/zoho.php000064400000037122151710730040010434 0ustar00lang = array( 'OK' => __('Mailer successfully configured!'), 'unauthorized_client' => __('OAuth Client is Invalid'), 'invalid_client' => __('Invalid Client ID (or) client Credentials did not match.'), 'invalid_code' => __('Code Expired (or) Invalid Refresh Token.'), 'invalid_redirect_uri' => __('Invalid Redirect Url configured'), 'invalid_client_secret' => __('Client Secret did not match.'), 'INVALID_TICKET' => __('Invalid Client Secret'), 'INVALID_OAUTHTOKEN' => __('Authtoken invalidated'), 'access_denied' => __('Multiple requests failed with same Refresh Token.'), 'general_error' => __('Something went wrong'), 'remote_token_error' => __('Error when getting the remote token.'), 'no_user' => __('No User present.'), 'token_limit_reached' => __('Refresh token limit reached.'), 'refresh_token_limit_reached' => __('The limit for refresh token reached.'), 'access_token_limit_reached' => __('The limit for access token reached.'), 'invalid_client_type' => __('Invalid client type'), 'invalid_authtoken' => __('Authtoken invalidated'), 'invalid_operation_type' => __('The scope has an invalid operation.'), 'URL_RULE_NOT_CONFIGURED' => __('Please configure zoho api.'), 'invalid_from' => __('Your zoho account does not match with the from mail.'), ); if(!isset($this->lang[$str])){ return $str; } return $this->lang[$str]; } public function getRedirectUrl($query = ''){ // TODO check and change this return admin_url().'admin.php?page=gosmtp'.$query; } public function send(){ global $phpmailer; $phpmailer->isMail(); $this->setConfig(); if($phpmailer->preSend()){ return $this->handle_response( $this->postSend() ); } return $this->handle_response(new \WP_Error(400, 'Unable to send mail for some reason!', [])); } public function setConfig(){ $domain_name = $this->getOption('domain_name', $this->mailer, 'com'); $this->api_url = 'https://mail.zoho.'.$domain_name.'/api/accounts'; $this->oauth_url = 'https://accounts.zoho.'.$domain_name.'/oauth/v2/'; } public function postSend(){ global $phpmailer; $options = $this->getMailerOption(); $options['access_token'] = $this->getAccessToken($options); $this->body['fromAddress'] = $phpmailer->FromName.'<'.$phpmailer->From.'>'; $this->body['subject'] = $phpmailer->Subject; $this->set_content($phpmailer->Body); $this->set_recipients( array( 'toAddress' => $phpmailer->getToAddresses(), 'ccAddress' => $phpmailer->getCcAddresses(), 'bccAddress' => $phpmailer->getBccAddresses(), 'replyTo' => $phpmailer->getReplyToAddresses() ) ); $attachments = $phpmailer->getAttachments(); if(!empty($attachments)){ $this->set_attachments($attachments); } $headers = [ 'Authorization' => 'Zoho-oauthtoken '.$options['access_token'], 'Content-Type' => 'application/json' ]; $params = array( 'headers' => $headers, 'body' => wp_json_encode($this->body) ); $accId = !empty($options['account_id']) ? $options['account_id'] : ''; $url = $this->api_url.'/'.$accId.'/messages'; // print_r(json_encode($this->body, JSON_PRETTY_PRINT)); $response = wp_safe_remote_post($url, $params); if(is_wp_error($response)){ $return_response = new \WP_Error($response->get_error_code(), $response->get_error_message(), $response->get_error_messages()); }else{ $resp_body = wp_remote_retrieve_body($response); $resp_code = wp_remote_retrieve_response_code($response); $isOk = $resp_code == $this->send_code; $resp_body = \json_decode($resp_body, true); if($isOk) { $msgId = isset( $resp_body['data']['messageId'] ) ? $resp_body['data']['messageId'] : ''; $status = isset($resp_body['status']['description']) ? $resp_body['status']['description'] : ''; $return_response = [ 'status' => true, 'code' => $resp_code, 'messageId' => $msgId, 'message' => $status ]; }else{ $msg = ($resp_code == 500 ) ? $resp_body['data']['moreInfo'] : $this->getLang($resp_body['data']['errorCode']); $return_response = new \WP_Error($resp_code, $msg , $resp_body); } } return $return_response; } public function set_content( $content ){ global $phpmailer; if( empty( $content ) ){ return; } if( is_array( $content ) ){ if( ! empty( $content['text'] ) ){ $this->body['mailFormat'] = 'plaintext'; } if( ! empty( $content['html'] ) ){ $this->body['mailFormat'] = 'html'; } $this->body['content'] = $content['text']; }else{ if( $phpmailer->ContentType === 'text/plain' ){ $this->body['mailFormat'] = 'plaintext'; }else{ $this->body['mailFormat'] = 'html'; } } $this->body['content'] = $content; } public function set_recipients( $recipients ) { global $phpmailer; if( empty( $recipients ) ){ return; } foreach( $recipients as $type => $emails ){ $tmp = ''; foreach( $emails as $key => $email ){ $tmp .= $type == 'replyTo' ? '<'.$email[0].'>' : ( empty($email[1]) ? $email[0] : $email[1].'<'.$email[0].'>' ); if( ( count($emails) - 1 ) != $key ){ $tmp .= ','; } } if(empty($tmp)){ continue; } $this->body[$type] = $tmp; } } public function set_attachments( $attachments = []){ $attachment_data = []; $count = 0; $ext = ''; foreach($attachments as $attachment){ if(!is_file($attachment[0]) || !is_readable($attachment[0])){ continue; } if(!empty($attachment[4])){ $ext = explode("/",$attachment[4])[1]; } $header = array( 'Authorization' => 'Zoho-oauthtoken '. $this->getOption('access_token', $this->mailer), 'Content-Type' => 'application/octet-stream' ); if(in_array($ext, $this->allowed_exts, true)){ $file_name = $attachment[2]; $content = file_get_contents($attachment[0]); $options = $this->getMailerOption(); $url = $this->api_url.'/'.$options['account_id'].'/messages/attachments'.'?fileName='.$file_name; $args = array( 'body' => $content, 'headers' => $header, 'method' => 'POST' ); $response = wp_remote_post($url, $args); $response_body = wp_remote_retrieve_body($response); $http_code = wp_remote_retrieve_response_code($response); $response_ = json_decode($response_body, true); if( isset($response_['data']['errorCode']) ){ $error = $response_['data']['errorCode']; } $attachments_ = array(); if($http_code == '200') { $attachments_['storeName'] = $response_['data']['storeName']; $attachments_['attachmentPath'] = $response_['data']['attachmentPath']; $attachments_['attachmentName'] = $response_['data']['attachmentName']; $attachment_data[$count] = $attachments_; $count = $count + 1; } } } if( count($attachment_data) > 0 ){ $this->body['attachments'] = $attachment_data; } } private function is_authorized(){ $options = $this->getMailerOption(); if(empty($options['refresh_token']) || empty($options['access_token']) || empty($options['account_id'])){ return false; } return true; } public function authentication_process(){ global $phpmailer; $options = $this->getMailerOption(); $response = $this->generate_tokens($options); if( !isset($response['access_token']) || !isset($response['refresh_token']) ){ return $response; } $access_token = $response['access_token']; $refresh_token = $response['refresh_token']; if( empty($options['account_id']) ){ $response = $this->zoho_account_id($access_token); if(!$response != true){ return $response; } } $this->delete_option('auth_code', $this->mailer); return 'OK'; } private function get_authcode_link($options){ $state = wp_create_nonce('redirect_url').($this->conn_id === 0 ? '' : '-'.$this->conn_id); $auth_url = $this->oauth_url ."auth?response_type=code&client_id=". $options['client_id'] ."&scope=". $this->scope ."&redirect_uri=".urlencode($this->getRedirectUrl('&auth=zoho'))."&prompt=consent&access_type=offline&state=". $state; return $auth_url; } public function generate_tokens($options){ $state = wp_create_nonce('redirect_url').($this->conn_id === 0 ? '' : '-'.$this->conn_id); $url = $this->oauth_url ."token?code=". $options['auth_code'] ."&client_id=". $options['client_id'] ."&client_secret=". $options['client_secret'] ."&redirect_uri=".urlencode($this->getRedirectUrl('&auth=zoho'))."&scope=".$this->scope."&grant_type=authorization_code&state=".$state; $response = wp_remote_retrieve_body(wp_remote_post( $url)); $response = json_decode($response, true); if(isset($response['error'])){ if($response['error'] == 'invalid_code'){ $this->delete_option('auth_code', $this->mailer); } return $response['error']; } $access_token = $response['access_token']; $refresh_token = $response['refresh_token']; $this->update_option('access_token', $access_token , $this->mailer); $this->update_option('refresh_token', $refresh_token, $this->mailer); return array( 'access_token' => $access_token, 'refresh_token' => $refresh_token ); } public function zoho_account_id($access_token = ''){ $from_email = $this->conn_id === 0 ? $this->getOption('from_email') : $this->getOption('from_email', $this->mailer,''); $accId = $this->getOption('account_id', $this->mailer, ''); if(!empty($accId)){ return; } $args = [ 'headers' => [ 'Authorization' => 'Zoho-oauthtoken '.$access_token ] ]; $response = wp_remote_retrieve_body(wp_remote_get( $this->api_url, $args)); $response = json_decode($response, true); if(empty($response)){ return 'general_error'; } if( isset($response['data']['errorCode']) ){ return $response['data']['errorCode']; } for($i=0; $iupdate_option('account_id', $response['data'][0]['accountId'], $this->mailer); }else{ return 'invalid_from'; } } } } public function getAccessToken( $options ){ $setup_time = $options['setup_timestamp']; $access_token = $options['access_token']; if(empty($setup_time) || time() - $setup_time > 3000){ $this->update_option('setup_timestamp', time(), $this->mailer); $url = $this->oauth_url.'token?refresh_token='.$options['refresh_token'].'&grant_type=refresh_token&client_id='.$options['client_id'].'&client_secret='.$options['client_secret'].'&redirect_uri='.urlencode($this->getRedirectUrl('&auth=zoho')).'&scope='.$this->scope; $response = wp_remote_retrieve_body( wp_remote_post( $url ) ); $response = json_decode($response); $access_token = $response->access_token; $this->update_option('access_token', $access_token, $this->mailer); } return $access_token; } public function load_field(){ $fields = array(); $options = $this->getMailerOption(); $client_id = $this->getOption('client_id', $this->mailer); $client_secret = $this->getOption('client_secret', $this->mailer); $opt_text = __('You need to save settings with Client ID and Client Secret before you can proceed.'); $opt_type = 'notice'; $opt_url = ''; $readonly = ''; $this->zoho_init(); $_button = ''; if(!empty($client_id) && !empty($client_secret) ){ $opt_type = $_button = 'button'; if(!$this->is_authorized()){ $opt_url = $this->get_authcode_link($options); $opt_text = __('Authorize Zoho Account'); }else{ $query = '&zoho-deactivate=1'; if(!is_numeric($this->conn_id)){ $query = '&type=edit&conn_id='.$this->conn_id.$query.'#gosmtp-connections-settings'; } $readonly = 'readonly=""'; $opt_url = $this->getRedirectUrl($query); $opt_text = 'Deactivate Access Token'; } } $fields = array( 'domain_name' => array( 'title' => __('Select domain name'), 'type' => 'select', 'list' => array( 'com' => '.com', 'eu' => '.eu', 'in' => '.in', 'com.cn' => '.com.cn', 'com.au' => '.com.au', 'jp' => '.jp', ), 'desc' => __( 'The name of the region the account is configured' ), ), 'client_id' => array( 'title' => __('Client Id'), 'type' => 'text', 'class'=>'zoho_client_id', 'desc' => __( 'Created in the developer console' ), 'attr' => $readonly ), 'client_secret' => array( 'title' => __('Client Secret'), 'type' => 'password', 'class'=>'zoho_client_secret', 'desc' => __( 'Created in the developer console' ), 'attr' => $readonly ), 'redirect_uri' => array( 'title' => __('Authorization Redirect URI'), 'type' => 'copy', 'id' => 'zoho_redirect_uri', 'attr' =>'readonly=""', 'default' => $this->getRedirectUrl('&auth=zoho'), 'desc' => __( 'Copy this URL into Redirect URI field of your Client Id creation' ), ), 'authorize' => array( 'title' => __('Authorize'), 'type' => $opt_type, 'default' => $opt_text, 'href' => $opt_url, 'class' => 'auth_class gosmtp-auto-width '.$_button, 'attr' => 'data-field=auth' ) ); return $fields; } public function zoho_deregister(){ if(!empty(gosmtp_optget('conn_id')) && $this->conn_id === 0){ return; } $this->delete_option('access_token', $this->mailer); $this->delete_option('refresh_token', $this->mailer); $this->delete_option('auth_code', $this->mailer); $this->delete_option('account_id', $this->mailer); $this->delete_option('setup_timestamp', $this->mailer); $query = ''; if(!is_numeric($this->conn_id)){ $query = '&type=edit&conn_id='.$this->conn_id.$query.'#gosmtp-connections-settings'; } if(isset($_GET['conn_id'])){ echo ''; } } public function zoho_init(){ $this->setConfig(); if(isset( $_GET['zoho-deactivate'] )){ $this->zoho_deregister(); return; } if( !$this->is_authorized() && isset( $_GET['auth_code'] ) && isset( $_GET['auth'] ) && $this->mailer == $_GET['auth'] && strlen($this->conn_id) > 0){ if( !empty(gosmtp_optget('conn_id')) && $this->conn_id === 0 ){ return; } // TODO sanitize $_GET['code'] $this->update_option('auth_code', gosmtp_optget('auth_code'), $this->mailer); $response = $this->authentication_process(); // var_dump($response); if( $response ){ $msg = is_array($this->getLang($response)) ? $this->getLang('general_error') : $this->getLang($response); } $query = ''; if(!is_numeric($this->conn_id)){ $query = '&type=edit&conn_id='.$this->conn_id.$query.'#gosmtp-connections-settings'; } echo ''; } } }main/mailer/amazonses/emailservicemessage.php000064400000045752151710730040015502 0ustar00to = array(); $this->cc = array(); $this->bcc = array(); $this->replyto = array(); $this->recipientsCharset = 'UTF-8'; $this->from = null; $this->returnpath = null; $this->subject = null; $this->messagetext = null; $this->messagehtml = null; $this->subjectCharset = 'UTF-8'; $this->messageTextCharset = 'UTF-8'; $this->messageHtmlCharset = 'UTF-8'; $this->attachments = array(); $this->customHeaders = array(); $this->configuration_set = null; $this->message_tags = array(); $this->is_clean = true; $this->raw_message = null; } /** * addTo, addCC, addBCC, and addReplyTo have the following behavior: * If a single address is passed, it is appended to the current list of addresses. * If an array of addresses is passed, that array is merged into the current list. * * @return EmailServiceMessage $this * @link http://docs.aws.amazon.com/ses/latest/APIReference/API_Destination.html */ public function addTo($to) { if (!is_array($to)) { $this->to[] = $to; } else { $this->to = array_unique(array_merge($this->to, $to)); } $this->is_clean = false; return $this; } /** * @return EmailServiceMessage $this */ public function setTo($to) { $this->to = (array) $to; $this->is_clean = false; return $this; } /** * Clear the To: email address(es) for the message * * @return EmailServiceMessage $this */ public function clearTo() { $this->to = array(); $this->is_clean = false; return $this; } /** * @return EmailServiceMessage $this * @see addTo() */ public function addCC($cc) { if (!is_array($cc)) { $this->cc[] = $cc; } else { $this->cc = array_merge($this->cc, $cc); } $this->is_clean = false; return $this; } /** * Clear the CC: email address(es) for the message * * @return EmailServiceMessage $this */ public function clearCC() { $this->cc = array(); $this->is_clean = false; return $this; } /** * @return EmailServiceMessage $this * @see addTo() */ public function addBCC($bcc) { if (!is_array($bcc)) { $this->bcc[] = $bcc; } else { $this->bcc = array_merge($this->bcc, $bcc); } $this->is_clean = false; return $this; } /** * Clear the BCC: email address(es) for the message * * @return EmailServiceMessage $this */ public function clearBCC() { $this->bcc = array(); $this->is_clean = false; return $this; } /** * @return EmailServiceMessage $this * @see addTo() */ public function addReplyTo($replyto) { if (!is_array($replyto)) { $this->replyto[] = $replyto; } else { $this->replyto = array_merge($this->replyto, $replyto); } $this->is_clean = false; return $this; } /** * Clear the Reply-To: email address(es) for the message * * @return EmailServiceMessage $this */ public function clearReplyTo() { $this->replyto = array(); $this->is_clean = false; return $this; } /** * Clear all of the message recipients in one go * * @return EmailServiceMessage $this * @uses clearTo() * @uses clearCC() * @uses clearBCC() * @uses clearReplyTo() */ public function clearRecipients() { $this->clearTo(); $this->clearCC(); $this->clearBCC(); $this->clearReplyTo(); $this->is_clean = false; return $this; } /** * @return EmailServiceMessage $this */ public function setFrom($from) { $this->from = $from; $this->is_clean = false; return $this; } /** * @return EmailServiceMessage $this */ public function setReturnPath($returnpath) { $this->returnpath = $returnpath; $this->is_clean = false; return $this; } /** * @return EmailServiceMessage $this */ public function setRecipientsCharset($charset) { $this->recipientsCharset = $charset; $this->is_clean = false; return $this; } /** * @return EmailServiceMessage $this */ public function setSubject($subject) { $this->subject = $subject; $this->is_clean = false; return $this; } /** * @return EmailServiceMessage $this */ public function setSubjectCharset($charset) { $this->subjectCharset = $charset; $this->is_clean = false; return $this; } /** * @return EmailServiceMessage $this * @link http://docs.aws.amazon.com/ses/latest/APIReference/API_Message.html */ public function setMessageFromString($text, $html = null) { $this->messagetext = $text; $this->messagehtml = $html; $this->is_clean = false; return $this; } /** * @return EmailServiceMessage $this */ public function setMessageFromFile($textfile, $htmlfile = null) { if (file_exists($textfile) && is_file($textfile) && is_readable($textfile)) { $this->messagetext = file_get_contents($textfile); } else { $this->messagetext = null; } if (file_exists($htmlfile) && is_file($htmlfile) && is_readable($htmlfile)) { $this->messagehtml = file_get_contents($htmlfile); } else { $this->messagehtml = null; } $this->is_clean = false; return $this; } /** * @return EmailServiceMessage $this */ public function setMessageFromURL($texturl, $htmlurl = null) { if ($texturl !== null) { $this->messagetext = file_get_contents($texturl); } else { $this->messagetext = null; } if ($htmlurl !== null) { $this->messagehtml = file_get_contents($htmlurl); } else { $this->messagehtml = null; } $this->is_clean = false; return $this; } /** * @return EmailServiceMessage $this */ public function setMessageCharset($textCharset, $htmlCharset = null) { $this->messageTextCharset = $textCharset; $this->messageHtmlCharset = $htmlCharset; $this->is_clean = false; return $this; } /** * @return EmailServiceMessage $this */ public function setConfigurationSet($configuration_set = null) { $this->configuration_set = $configuration_set; $this->is_clean = false; return $this; } /** * @return array $message_tags */ public function getMessageTags() { return $this->message_tags; } /** * @return null|mixed $message_tag */ public function getMessageTag($key) { return isset($this->message_tags[$key]) ? $this->message_tags[$key] : null; } /** * Add Message tag * * Both key and value can contain only ASCII letters (a-z, A-Z), numbers (0-9), underscores (_), or dashes (-) and be less than 256 characters. * * @param string $key * @param mixed $value * @return EmailServiceMessage $this * @link https://docs.aws.amazon.com/ses/latest/DeveloperGuide/event-publishing-send-email.html * @link https://docs.aws.amazon.com/ses/latest/APIReference/API_MessageTag.html */ public function setMessageTag($key, $value) { $this->message_tags[$key] = $value; $this->is_clean = false; return $this; } /** * @param string $key The key of the tag to be removed * @return EmailServiceMessage $this */ public function removeMessageTag($key) { unset($this->message_tags[$key]); $this->is_clean = false; return $this; } /** * @param array $message_tags * @return EmailServiceMessage $this */ public function setMessageTags($message_tags = array()) { $this->message_tags = array_merge($this->message_tags, $message_tags); $this->is_clean = false; return $this; } /** * @return EmailServiceMessage $this */ public function removeMessageTags() { $this->message_tags = array(); $this->is_clean = false; return $this; } /** * Add custom header - this works only with SendRawEmail * * @param string $header Your custom header * @return EmailServiceMessage $this * @link( Restrictions on headers, http://docs.aws.amazon.com/ses/latest/DeveloperGuide/header-fields.html) */ public function addCustomHeader($header) { $this->customHeaders[] = $header; $this->is_clean = false; return $this; } /** * Add email attachment by directly passing the content * * @param string $name The name of the file attachment as it will appear in the email * @param string $data The contents of the attachment file * @param string $mimeType Specify custom MIME type * @param string $contentId Content ID of the attachment for inclusion in the mail message * @param string $attachmentType Attachment type: attachment or inline * @return EmailServiceMessage $this */ public function addAttachmentFromData($name, $data, $mimeType = 'application/octet-stream', $contentId = null, $attachmentType = 'attachment') { $this->attachments[$name] = array( 'name' => $name, 'mimeType' => $mimeType, 'data' => $data, 'contentId' => $contentId, 'attachmentType' => ($attachmentType == 'inline' ? 'inline; filename="' . $name . '"' : $attachmentType), ); $this->is_clean = false; return $this; } /** * Add email attachment by passing file path * * @param string $name The name of the file attachment as it will appear in the email * @param string $path Path to the attachment file * @param string $mimeType Specify custom MIME type * @param string $contentId Content ID of the attachment for inclusion in the mail message * @param string $attachmentType Attachment type: attachment or inline * @return boolean Status of the operation */ public function addAttachmentFromFile($name, $path, $mimeType = 'application/octet-stream', $contentId = null, $attachmentType = 'attachment') { if (file_exists($path) && is_file($path) && is_readable($path)) { $this->addAttachmentFromData($name, file_get_contents($path), $mimeType, $contentId, $attachmentType); return true; } $this->is_clean = false; return false; } /** * Add email attachment by passing file path * * @param string $name The name of the file attachment as it will appear in the email * @param string $url URL to the attachment file * @param string $mimeType Specify custom MIME type * @param string $contentId Content ID of the attachment for inclusion in the mail message * @param string $attachmentType Attachment type: attachment or inline * @return boolean Status of the operation */ public function addAttachmentFromUrl($name, $url, $mimeType = 'application/octet-stream', $contentId = null, $attachmentType = 'attachment') { $data = file_get_contents($url); if ($data !== false) { $this->addAttachmentFromData($name, $data, $mimeType, $contentId, $attachmentType); return true; } $this->is_clean = false; return false; } /** * Get the existence of attached inline messages * * @return boolean */ public function hasInlineAttachments() { foreach ($this->attachments as $attachment) { if ($attachment['attachmentType'] != 'attachment') { return true; } } return false; } /** * Get the raw mail message * * @return string */ public function getRawMessage($encode = true) { if ($this->is_clean && !is_null($this->raw_message) && $encode) { return $this->raw_message; } $this->is_clean = true; $boundary = uniqid(rand(), true); $raw_message = count($this->customHeaders) > 0 ? join("\n", $this->customHeaders) . "\n" : ''; if (!empty($this->message_tags)) { $message_tags = array(); foreach ($this->message_tags as $key => $value) { $message_tags[] = "{$key}={$value}"; } $raw_message .= 'X-SES-MESSAGE-TAGS: ' . join(', ', $message_tags) . "\n"; } if (!is_null($this->configuration_set)) { $raw_message .= 'X-SES-CONFIGURATION-SET: ' . $this->configuration_set . "\n"; } $raw_message .= count($this->to) > 0 ? 'To: ' . $this->encodeRecipients($this->to) . "\n" : ''; $raw_message .= 'From: ' . $this->encodeRecipients($this->from) . "\n"; if (!empty($this->replyto)) { $raw_message .= 'Reply-To: ' . $this->encodeRecipients($this->replyto) . "\n"; } if (!empty($this->cc)) { $raw_message .= 'CC: ' . $this->encodeRecipients($this->cc) . "\n"; } if (!empty($this->bcc)) { $raw_message .= 'BCC: ' . $this->encodeRecipients($this->bcc) . "\n"; } if ($this->subject != null && strlen($this->subject) > 0) { $raw_message .= 'Subject: =?' . $this->subjectCharset . '?B?' . base64_encode($this->subject) . "?=\n"; } $raw_message .= 'MIME-Version: 1.0' . "\n"; $raw_message .= 'Content-type: ' . ($this->hasInlineAttachments() ? 'multipart/related' : 'Multipart/Mixed') . '; boundary="' . $boundary . '"' . "\n"; $raw_message .= "\n--{$boundary}\n"; $raw_message .= 'Content-type: Multipart/Alternative; boundary="alt-' . $boundary . '"' . "\n"; if ($this->messagetext != null && strlen($this->messagetext) > 0) { $charset = empty($this->messageTextCharset) ? '' : "; charset=\"{$this->messageTextCharset}\""; $raw_message .= "\n--alt-{$boundary}\n"; $raw_message .= 'Content-Type: text/plain' . $charset . "\n\n"; $raw_message .= $this->messagetext . "\n"; } if ($this->messagehtml != null && strlen($this->messagehtml) > 0) { $charset = empty($this->messageHtmlCharset) ? '' : "; charset=\"{$this->messageHtmlCharset}\""; $raw_message .= "\n--alt-{$boundary}\n"; $raw_message .= 'Content-Type: text/html' . $charset . "\n\n"; $raw_message .= $this->messagehtml . "\n"; } $raw_message .= "\n--alt-{$boundary}--\n"; foreach ($this->attachments as $attachment) { $raw_message .= "\n--{$boundary}\n"; $raw_message .= 'Content-Type: ' . $attachment['mimeType'] . '; name="' . $attachment['name'] . '"' . "\n"; $raw_message .= 'Content-Disposition: ' . $attachment['attachmentType'] . "\n"; if (!empty($attachment['contentId'])) { $raw_message .= 'Content-ID: ' . $attachment['contentId'] . '' . "\n"; } $raw_message .= 'Content-Transfer-Encoding: base64' . "\n"; $raw_message .= "\n" . chunk_split(base64_encode($attachment['data']), 76, "\n") . "\n"; } $raw_message .= "\n--{$boundary}--\n"; if (!$encode) { return $raw_message; } $this->raw_message = base64_encode($raw_message); return $this->raw_message; } /** * Encode recipient with the specified charset in `recipientsCharset` * * @return string Encoded recipients joined with comma */ public function encodeRecipients($recipient) { if (is_array($recipient)) { return join(', ', array_map(array($this, 'encodeRecipients'), $recipient)); } if (preg_match("/(.*)<(.*)>/", $recipient, $regs)) { $recipient = '=?' . $this->recipientsCharset . '?B?' . base64_encode($regs[1]) . '?= <' . $regs[2] . '>'; } return $recipient; } /** * Validates whether the message object has sufficient information to submit a request to SES. * * This does not guarantee the message will arrive, nor that the request will succeed; * instead, it makes sure that no required fields are missing. * * This is used internally before attempting a SendEmail or SendRawEmail request, * but it can be used outside of this file if verification is desired. * May be useful if e.g. the data is being populated from a form; developers can generally * use this function to verify completeness instead of writing custom logic. * * @return boolean */ public function validate() { // at least one destination is required if (count($this->to) == 0 && count($this->cc) == 0 && count($this->bcc) == 0) { return false; } // sender is required if ($this->from == null || strlen($this->from) == 0) { return false; } // subject is required if (($this->subject == null || strlen($this->subject) == 0)) { return false; } // message is required if ((empty($this->messagetext) || strlen((string) $this->messagetext) == 0) && (empty($this->messagehtml) || strlen((string) $this->messagehtml) == 0)) { return false; } return true; } } main/mailer/amazonses/amazonses.php000064400000011230151710730040013445 0ustar00preSend()) { $response = $this->postSend(); return $this->handle_response( $response ); } return $this->handle_response(new \WP_Error(400, 'Unable to send mail for some reason!', [])); } public function postSend(){ global $phpmailer; $mime = chunk_split(base64_encode($phpmailer->getSentMIMEMessage()), 76, "\n"); $options = $this->getMailerOption(); $region = 'email.' . $options['region'] . '.amazonaws.com'; $ses = new EmailService($options['access_key'], $options['secret_key'], $region, false); $response = $ses->sendRawEmail($mime); if(is_wp_error($response)){ $return_response = new \WP_Error($response->get_error_code(), $response->get_error_message(), $response->get_error_messages()); }else{ $resp_body = wp_remote_retrieve_body($response); $resp_code = wp_remote_retrieve_response_code($response); $resp_body = \json_decode($resp_body, true); if(!empty($response['MessageId'])){ $msgId = $response['MessageId']; $status = __('Email sent successfully'); $return_response = [ 'status' => true, 'code' => 200, 'messageId' => $msgId, 'message' => $status ]; }else{ $err_code = $resp_code; $error_text = ['']; if( ! empty( $resp_body['error'] ) && is_array( $resp_body['error'] ) ){ $message = $resp_body['error']['message']; $error_text[] = $this->message_formatting( $message, $code ); }else{ $error_text[] = $this->get_response_error_message($response); } $error_msg = implode( '\r\n', array_map( 'esc_textarea', array_filter( $error_text ) ) ); $return_response = new \WP_Error($err_code, $error_msg, $resp_body); } } return $return_response; } public function email_checker($data){ $region= 'email.' . $data['amazonses']['region'] . '.amazonaws.com'; set_error_handler(function ($errno, $errstr, $errfile, $errline) { throw new \ErrorException($errstr, 0, $errno, $errfile, $errline); }); $ses = new EmailService($data['amazonses']['access_key'], $data['amazonses']['secret_key'], $region, false); try{ $ses->listVerifiedEmailAddresses(); }catch(\Exception $e) { return new \WP_Error(423, $e->getMessage()); } return false; } public function load_field(){ $fields = array( 'access_key' => array( 'title' => __('Access Key'), 'type' => 'password', ), 'secret_key' => array( 'title' => __('Secret Key'), 'type' => 'password', 'desc' => __( 'Follow this link to get a Secret Key from AmazonSES: Secret Key.' ), ), 'region' => array( 'title' => __('Region'), 'type' => 'select', 'list' => array( 'us-east-1' => __('US East (N. Virginia)', 'gosmtp'), 'us-east-2' => __('US East (Ohio)', 'gosmtp'), 'us-west-1' => __('US West (N. California)', 'gosmtp'), 'us-west-2' => __('US West (Oregon)', 'gosmtp'), 'ca-central-1' => __('Canada (Central)', 'gosmtp'), 'eu-west-1' => __('EU (Ireland)', 'gosmtp'), 'eu-west-2' => __('EU (London)', 'gosmtp'), 'eu-west-3' => __('Europe (Paris)', 'gosmtp'), 'eu-central-1' => __('EU (Frankfurt)', 'gosmtp'), 'eu-south-1' => __('Europe (Milan)', 'gosmtp'), 'eu-north-1' => __('Europe (Stockholm)', 'gosmtp'), 'ap-south-1' => __('Asia Pacific (Mumbai)', 'gosmtp'), 'ap-northeast-2' => __('Asia Pacific (Seoul)', 'gosmtp'), 'ap-southeast-1' => __('Asia Pacific (Singapore)', 'gosmtp'), 'ap-southeast-2' => __('Asia Pacific (Sydney)', 'gosmtp'), 'ap-northeast-1' => __('Asia Pacific (Tokyo)', 'gosmtp'), 'sa-east-1' => __('South America (Sao Paulo)', 'gosmtp'), 'me-south-1' => __('Middle East (Bahrain)', 'gosmtp'), 'us-gov-west-1' => __('AWS GovCloud (US)', 'gosmtp'), 'af-south-1' => __('Africa (Cape Town)', 'gosmtp'), 'cn-northwest-1' => __('China (Ningxia)', 'gosmtp') ), 'desc' => __( 'Define which endpoint you want to use for sending messages.
If you are operating under EU laws, you may be required to use EU region. More information on aws.amazon.com.' ), ) ); return $fields; } } main/mailer/amazonses/emailservice.php000064400000056721151710730040014133 0ustar00setAuth($accessKey, $secretKey); } $this->__host = $host; $this->__trigger_errors = $trigger_errors; $this->__requestSignatureVersion = $requestSignatureVersion; } /** * Set the request signature version * * @param string $requestSignatureVersion * @return EmailService $this */ public function setRequestSignatureVersion($requestSignatureVersion) { $this->__requestSignatureVersion = $requestSignatureVersion; return $this; } /** * @return string */ public function getRequestSignatureVersion() { return $this->__requestSignatureVersion; } /** * Set AWS access key and secret key * * @param string $accessKey Access key * @param string $secretKey Secret key * @return EmailService $this */ public function setAuth($accessKey, $secretKey) { $this->__accessKey = $accessKey; $this->__secretKey = $secretKey; return $this; } /** * Set AWS Host * @param string $host AWS Host */ public function setHost($host = self::AWS_US_EAST_1) { $this->__host = $host; return $this; } /** * @deprecated */ public function enableVerifyHost($enable = true) { $this->__verifyHost = (bool)$enable; return $this; } /** * @deprecated */ public function enableVerifyPeer($enable = true) { $this->__verifyPeer = (bool)$enable; return $this; } /** * @deprecated */ public function verifyHost() { return $this->__verifyHost; } /** * @deprecated */ public function verifyPeer() { return $this->__verifyPeer; } /** * Get AWS target host * @return boolean */ public function getHost() { return $this->__host; } /** * Get AWS SES auth access key * @return string */ public function getAccessKey() { return $this->__accessKey; } /** * Get AWS SES auth secret key * @return string */ public function getSecretKey() { return $this->__secretKey; } /** * Get the verify peer CURL mode * @return boolean */ public function getVerifyPeer() { return $this->__verifyPeer; } /** * Get the verify host CURL mode * @return boolean */ public function getVerifyHost() { return $this->__verifyHost; } /** * Get bulk email sending mode * @return boolean * @deprecated */ public function getBulkMode() { return $this->__bulk_sending_mode; } /** * Enable/disable CURLOPT_SSL_VERIFYHOST for EmailServiceRequest's curl handler * verifyHost and verifyPeer determine whether curl verifies ssl certificates. * It may be necessary to disable these checks on certain systems. * These only have an effect if SSL is enabled. * * @param boolean $enable New status for the mode * @return EmailService $this */ public function setVerifyHost($enable = true) { $this->__verifyHost = (bool)$enable; return $this; } /** * Enable/disable CURLOPT_SSL_VERIFYPEER for EmailServiceRequest's curl handler * verifyHost and verifyPeer determine whether curl verifies ssl certificates. * It may be necessary to disable these checks on certain systems. * These only have an effect if SSL is enabled. * * @param boolean $enable New status for the mode * @return EmailService $this */ public function setVerifyPeer($enable = true) { $this->__verifyPeer = (bool)$enable; return $this; } /** * Enable/disable bulk email sending mode * * @param boolean $enable New status for the mode * @return EmailService $this * @deprecated */ public function setBulkMode($enable = true) { $this->__bulk_sending_mode = (bool)$enable; return $this; } /** * Lists the email addresses that have been verified and can be used as the 'From' address * * @return array An array containing two items: a list of verified email addresses, and the request id. */ public function listVerifiedEmailAddresses() { $ses_request = $this->getRequestHandler('GET'); $ses_request->setParameter('Action', 'ListIdentities'); $ses_response = $ses_request->getResponse(); if ($ses_response->error === false && $ses_response->code !== 200) { $ses_response->error = array('code' => $ses_response->code, 'message' => 'Unexpected HTTP status'); } if ($ses_response->error !== false) { $this->__triggerError('ListIdentities', $ses_response->error); return []; } $response = array(); if (!isset($ses_response->body)) { return $response; } $addresses = array(); foreach ($ses_response->body->ListIdentitiesResult->Identities->member as $address) { if(is_email($address)) { $addresses[] = (string)$address; } } $response['Addresses'] = $addresses; $response['RequestId'] = (string)$ses_response->body->ResponseMetadata->RequestId; return $response; } /** * Requests verification of the provided email address, so it can be used * as the 'From' address when sending emails through EmailService. * * After submitting this request, you should receive a verification email * from Amazon at the specified address containing instructions to follow. * * @param string $email The email address to get verified * @return array The request id for this request. */ public function verifyEmailAddress($email) { $ses_request = $this->getRequestHandler('POST'); $ses_request->setParameter('Action', 'VerifyEmailAddress'); $ses_request->setParameter('EmailAddress', $email); $ses_response = $ses_request->getResponse(); if ($ses_response->error === false && $ses_response->code !== 200) { $ses_response->error = array('code' => $ses_response->code, 'message' => 'Unexpected HTTP status'); } if ($ses_response->error !== false) { $this->__triggerError('verifyEmailAddress', $ses_response->error); return false; } $response['RequestId'] = (string)$ses_response->body->ResponseMetadata->RequestId; return $response; } /** * Removes the specified email address from the list of verified addresses. * * @param string $email The email address to remove * @return array The request id for this request. */ public function deleteVerifiedEmailAddress($email) { $ses_request = $this->getRequestHandler('DELETE'); $ses_request->setParameter('Action', 'DeleteVerifiedEmailAddress'); $ses_request->setParameter('EmailAddress', $email); $ses_response = $ses_request->getResponse(); if ($ses_response->error === false && $ses_response->code !== 200) { $ses_response->error = array('code' => $ses_response->code, 'message' => 'Unexpected HTTP status'); } if ($ses_response->error !== false) { $this->__triggerError('deleteVerifiedEmailAddress', $ses_response->error); return false; } $response['RequestId'] = (string)$ses_response->body->ResponseMetadata->RequestId; return $response; } /** * Retrieves information on the current activity limits for this account. * See http://docs.amazonwebservices.com/ses/latest/APIReference/API_GetSendQuota.html * * @return array An array containing information on this account's activity limits. */ public function getSendQuota() { $ses_request = $this->getRequestHandler('GET'); $ses_request->setParameter('Action', 'GetSendQuota'); $ses_response = $ses_request->getResponse(); if ($ses_response->error === false && $ses_response->code !== 200) { $ses_response->error = array('code' => $ses_response->code, 'message' => 'Unexpected HTTP status'); } if ($ses_response->error !== false) { $this->__triggerError('getSendQuota', $ses_response->error); return false; } $response = array(); if (!isset($ses_response->body)) { return $response; } $response['Max24HourSend'] = (string)$ses_response->body->GetSendQuotaResult->Max24HourSend; $response['MaxSendRate'] = (string)$ses_response->body->GetSendQuotaResult->MaxSendRate; $response['SentLast24Hours'] = (string)$ses_response->body->GetSendQuotaResult->SentLast24Hours; $response['RequestId'] = (string)$ses_response->body->ResponseMetadata->RequestId; return $response; } /** * Retrieves statistics for the last two weeks of activity on this account. * See http://docs.amazonwebservices.com/ses/latest/APIReference/API_GetSendStatistics.html * * @return array An array of activity statistics. Each array item covers a 15-minute period. */ public function getSendStatistics() { $ses_request = $this->getRequestHandler('GET'); $ses_request->setParameter('Action', 'GetSendStatistics'); $ses_response = $ses_request->getResponse(); if ($ses_response->error === false && $ses_response->code !== 200) { $ses_response->error = array('code' => $ses_response->code, 'message' => 'Unexpected HTTP status'); } if ($ses_response->error !== false) { $this->__triggerError('getSendStatistics', $ses_response->error); return false; } $response = array(); if (!isset($ses_response->body)) { return $response; } $datapoints = array(); foreach ($ses_response->body->GetSendStatisticsResult->SendDataPoints->member as $datapoint) { $p = array(); $p['Bounces'] = (string)$datapoint->Bounces; $p['Complaints'] = (string)$datapoint->Complaints; $p['DeliveryAttempts'] = (string)$datapoint->DeliveryAttempts; $p['Rejects'] = (string)$datapoint->Rejects; $p['Timestamp'] = (string)$datapoint->Timestamp; $datapoints[] = $p; } $response['SendDataPoints'] = $datapoints; $response['RequestId'] = (string)$ses_response->body->ResponseMetadata->RequestId; return $response; } /** * Given a EmailServiceMessage object, submits the message to the service for sending. * * @param EmailServiceMessage $sesMessage An instance of the message class * @param boolean $use_raw_request If this is true or there are attachments to the email `SendRawEmail` call will be used * @param boolean $trigger_error Optionally overwrite the class setting for triggering an error (with type check to true/false) * @return array An array containing the unique identifier for this message and a separate request id. * Returns false if the provided message is missing any required fields. * @link(AWS SES Response formats, http://docs.aws.amazon.com/ses/latest/DeveloperGuide/query-interface-responses.html) */ public function sendEmail($sesMessage, $use_raw_request = false, $trigger_error = null) { if (!$sesMessage->validate()) { $this->__triggerError('sendEmail', 'Message failed validation.'); return false; } $ses_request = $this->getRequestHandler('POST'); $action = !empty($sesMessage->attachments) || $use_raw_request ? 'SendRawEmail' : 'SendEmail'; $ses_request->setParameter('Action', $action); // Works with both calls if (!is_null($sesMessage->configuration_set)) { $ses_request->setParameter('ConfigurationSetName', $sesMessage->configuration_set); } if ($action == 'SendRawEmail') { // https://docs.aws.amazon.com/ses/latest/APIReference/API_SendRawEmail.html $ses_request->setParameter('RawMessage.Data', $sesMessage->mime); } else { $i = 1; foreach ($sesMessage->to as $to) { $ses_request->setParameter('Destination.ToAddresses.member.' . $i, $sesMessage->encodeRecipients($to)); $i++; } if (is_array($sesMessage->cc)) { $i = 1; foreach ($sesMessage->cc as $cc) { $ses_request->setParameter('Destination.CcAddresses.member.' . $i, $sesMessage->encodeRecipients($cc)); $i++; } } if (is_array($sesMessage->bcc)) { $i = 1; foreach ($sesMessage->bcc as $bcc) { $ses_request->setParameter('Destination.BccAddresses.member.' . $i, $sesMessage->encodeRecipients($bcc)); $i++; } } if (is_array($sesMessage->replyto)) { $i = 1; foreach ($sesMessage->replyto as $replyto) { $ses_request->setParameter('ReplyToAddresses.member.' . $i, $sesMessage->encodeRecipients($replyto)); $i++; } } $ses_request->setParameter('Source', $sesMessage->encodeRecipients($sesMessage->from)); if ($sesMessage->returnpath != null) { $ses_request->setParameter('ReturnPath', $sesMessage->returnpath); } if ($sesMessage->subject != null && strlen($sesMessage->subject) > 0) { $ses_request->setParameter('Message.Subject.Data', $sesMessage->subject); if ($sesMessage->subjectCharset != null && strlen($sesMessage->subjectCharset) > 0) { $ses_request->setParameter('Message.Subject.Charset', $sesMessage->subjectCharset); } } if ($sesMessage->messagetext != null && strlen($sesMessage->messagetext) > 0) { $ses_request->setParameter('Message.Body.Text.Data', $sesMessage->messagetext); if ($sesMessage->messageTextCharset != null && strlen($sesMessage->messageTextCharset) > 0) { $ses_request->setParameter('Message.Body.Text.Charset', $sesMessage->messageTextCharset); } } if ($sesMessage->messagehtml != null && strlen($sesMessage->messagehtml) > 0) { $ses_request->setParameter('Message.Body.Html.Data', $sesMessage->messagehtml); if ($sesMessage->messageHtmlCharset != null && strlen($sesMessage->messageHtmlCharset) > 0) { $ses_request->setParameter('Message.Body.Html.Charset', $sesMessage->messageHtmlCharset); } } $i = 1; foreach ($sesMessage->message_tags as $key => $value) { $ses_request->setParameter('Tags.member.' . $i . '.Name', $key); $ses_request->setParameter('Tags.member.' . $i . '.Value', $value); $i++; } } $ses_response = $ses_request->getResponse(); if ($ses_response->error === false && $ses_response->code !== 200) { $response = array( 'code' => $ses_response->code, 'error' => array('Error' => array('message' => 'Unexpected HTTP status')), ); return $response; } if ($ses_response->error !== false) { if (($this->__trigger_errors && ($trigger_error !== false)) || $trigger_error === true) { $this->__triggerError('sendEmail', $ses_response->error); return false; } return $ses_response; } $response = array( 'MessageId' => (string)$ses_response->body->{"{$action}Result"}->MessageId, 'RequestId' => (string)$ses_response->body->ResponseMetadata->RequestId, ); return $response; } public function sendRawEmail($sesMessage) { $ses_request = $this->getRequestHandler('POST'); $ses_request->setParameter('Action', 'SendRawEmail'); // https://docs.aws.amazon.com/ses/latest/APIReference/API_SendRawEmail.html $ses_request->setParameter('RawMessage.Data', $sesMessage); $ses_response = $ses_request->getResponse(); if (($ses_response->error === false && $ses_response->code !== 200) || $ses_response->error !== false) { return new \WP_Error($ses_response->code, $this->getErrorMessage('sendRawEmail', $ses_response->error), $ses_response->error); } return array( 'MessageId' => (string)$ses_response->body->SendRawEmailResult->MessageId, 'RequestId' => (string)$ses_response->body->ResponseMetadata->RequestId, ); } /** * Trigger an error message * * {@internal Used by member functions to output errors} * @param string $functionname The name of the function that failed * @param array $error Array containing error information * @return void */ public function __triggerError($functionname, $error) { trigger_error($this->getErrorMessage($functionname, $error), E_USER_WARNING); } public function getErrorMessage($functionname, $error) { if ($error == false) { return sprintf("EmailService::%s(): Encountered an error, but no description given", $functionname); } else if (isset($error['curl']) && $error['curl']) { return sprintf("EmailService::%s(): %s %s", $functionname, $error['code'], $error['message']); } else if (isset($error['Error'])) { $e = $error['Error']; return sprintf("EmailService::%s(): %s - %s: %s\nRequest Id: %s\n", $functionname, $e['Type'], $e['Code'], $e['Message'], $error['RequestId']); } return sprintf("EmailService::%s(): Encountered an error: %s", $functionname, $error); } /** * Set SES Request * * @param EmailServiceRequest $ses_request description * @return EmailService $this */ public function setRequestHandler(EmailServiceRequest $ses_request = null) { if (!is_null($ses_request)) { $ses_request->setSES($this); } $this->__ses_request = $ses_request; return $this; } /** * Get SES Request * * @param string $verb HTTP Verb: GET, POST, DELETE * @return EmailServiceRequest SES Request */ public function getRequestHandler($verb) { if (empty($this->__ses_request)) { $this->__ses_request = new EmailServiceRequest($this, $verb); } else { $this->__ses_request->setVerb($verb); } return $this->__ses_request; } } main/mailer/amazonses/emailservicerequest.php000064400000025556151710730040015546 0ustar00ses = $ses; $this->verb = $verb; $this->response = (object) array('body' => '', 'code' => 0, 'error' => false); } /** * Set SES class * * @param EmailService $ses * @return EmailServiceRequest $this */ public function setSES(EmailService $ses) { $this->ses = $ses; return $this; } /** * Set HTTP method * * @param string $verb * @return EmailServiceRequest $this */ public function setVerb($verb) { $this->verb = $verb; return $this; } /** * Set request parameter * * @param string $key Key * @param string $value Value * @param boolean $replace Whether to replace the key if it already exists (default true) * @return EmailServiceRequest $this */ public function setParameter($key, $value, $replace = true) { if(!$replace && isset($this->parameters[$key])) { $temp = (array)($this->parameters[$key]); $temp[] = $value; $this->parameters[$key] = $temp; } else { $this->parameters[$key] = $value; } return $this; } /** * Get the params for the request * * @return array $params */ public function getParametersEncoded() { $params = array(); foreach ($this->parameters as $var => $value) { if(is_array($value)) { foreach($value as $v) { $params[] = $var.'='.$this->__customUrlEncode($v); } } else { $params[] = $var.'='.$this->__customUrlEncode($value); } } sort($params, SORT_STRING); return $params; } /** * Clear the request parameters * @return EmailServiceRequest $this */ public function clearParameters() { $this->parameters = array(); return $this; } /** * Instantiate and setup CURL handler for sending requests. * Instance is cashed in `$this->curl_handler` * * @return resource $curl_handler */ protected function getCurlHandler() { if (!empty($this->curl_handler)) return $this->curl_handler; $curl = curl_init(); curl_setopt($curl, CURLOPT_USERAGENT, 'EmailService/php'); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, ($this->ses->verifyHost() ? 2 : 0)); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, ($this->ses->verifyPeer() ? 1 : 0)); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, false); curl_setopt($curl, CURLOPT_WRITEFUNCTION, array(&$this, '__responseWriteCallback')); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); foreach(self::$curlOptions as $option => $value) { curl_setopt($curl, $option, $value); } $this->curl_handler = $curl; return $this->curl_handler; } /** * Get the response * * @return object | false */ public function getResponse() { $url = 'https://'.$this->ses->getHost().'/'; $query = implode('&', $this->getParametersEncoded()); $headers = $this->getHeaders($query); $curl_handler = $this->getCurlHandler(); curl_setopt($curl_handler, CURLOPT_CUSTOMREQUEST, $this->verb); // Request types switch ($this->verb) { case 'GET': case 'DELETE': $url .= '?'.$query; break; case 'POST': curl_setopt($curl_handler, CURLOPT_POSTFIELDS, $query); $headers[] = 'Content-Type: application/x-www-form-urlencoded'; break; } curl_setopt($curl_handler, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl_handler, CURLOPT_URL, $url); // Execute, grab errors if (curl_exec($curl_handler)) { $this->response->code = curl_getinfo($curl_handler, CURLINFO_HTTP_CODE); } else { $this->response->error = array( 'curl' => true, 'code' => curl_errno($curl_handler), 'message' => curl_error($curl_handler), ); } // cleanup for reusing the current instance for multiple requests curl_setopt($curl_handler, CURLOPT_POSTFIELDS, ''); $this->parameters = array(); // Parse body into XML if ($this->response->error === false && !empty($this->response->body)) { $this->response->body = simplexml_load_string($this->response->body); // Grab SES errors if (!in_array($this->response->code, array(200, 201, 202, 204)) && isset($this->response->body->Error)) { $error = $this->response->body->Error; $output = array(); $output['curl'] = false; $output['Error'] = array(); $output['Error']['Type'] = (string)$error->Type; $output['Error']['Code'] = (string)$error->Code; $output['Error']['Message'] = (string)$error->Message; $output['RequestId'] = (string)$this->response->body->RequestId; $this->response->error = $output; unset($this->response->body); } } $response = $this->response; $this->response = (object) array('body' => '', 'code' => 0, 'error' => false); return $response; } /** * Get request headers * @param string $query * @return array */ protected function getHeaders($query) { $headers = array(); if ($this->ses->getRequestSignatureVersion() == EmailService::REQUEST_SIGNATURE_V4) { $date = (new \DateTime('now', new \DateTimeZone('UTC')))->format('Ymd\THis\Z'); $headers[] = 'X-Amz-Date: ' . $date; $headers[] = 'Host: ' . $this->ses->getHost(); $headers[] = 'Authorization: ' . $this->__getAuthHeaderV4($date, $query); } else { // must be in format 'Sun, 06 Nov 1994 08:49:37 GMT' $date = gmdate('D, d M Y H:i:s e'); $auth = 'AWS3-HTTPS AWSAccessKeyId='.$this->ses->getAccessKey(); $auth .= ',Algorithm=HmacSHA256,Signature='.$this->__getSignature($date); $headers[] = 'Date: ' . $date; $headers[] = 'Host: ' . $this->ses->getHost(); $headers[] = 'X-Amzn-Authorization: ' . $auth; } return $headers; } /** * Destroy any leftover handlers */ public function __destruct() { if (!empty($this->curl_handler)) @curl_close($this->curl_handler); } /** * CURL write callback * * @param resource $curl CURL resource * @param string $data Data * @return integer */ private function __responseWriteCallback($curl, $data) { if (!isset($this->response->body)) { $this->response->body = $data; } else { $this->response->body .= $data; } return strlen($data); } /** * Contributed by afx114 * URL encode the parameters as per http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/index.html?Query_QueryAuth.html * PHP's rawurlencode() follows RFC 1738, not RFC 3986 as required by Amazon. The only difference is the tilde (~), so convert it back after rawurlencode * See: http://www.morganney.com/blog/API/AWS-Product-Advertising-API-Requires-a-Signed-Request.php * * @param string $var String to encode * @return string */ private function __customUrlEncode($var) { return str_replace('%7E', '~', rawurlencode($var)); } /** * Generate the auth string using Hmac-SHA256 * * @internal Used by EmailServiceRequest::getResponse() * @param string $string String to sign * @return string */ private function __getSignature($string) { return base64_encode(hash_hmac('sha256', $string, $this->ses->getSecretKey(), true)); } /** * @param string $key * @param string $dateStamp * @param string $regionName * @param string $serviceName * @param string $algo * @return string */ private function __getSigningKey($key, $dateStamp, $regionName, $serviceName, $algo) { $kDate = hash_hmac($algo, $dateStamp, 'AWS4' . $key, true); $kRegion = hash_hmac($algo, $regionName, $kDate, true); $kService = hash_hmac($algo, $serviceName, $kRegion, true); return hash_hmac($algo,'aws4_request', $kService, true); } /** * Implementation of AWS Signature Version 4 * @see https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html * @param string $amz_datetime * @param string $query * @return string */ private function __getAuthHeaderV4($amz_datetime, $query) { $amz_date = substr($amz_datetime, 0, 8); $algo = 'sha256'; $aws_algo = 'AWS4-HMAC-' . strtoupper($algo); $host_parts = explode('.', $this->ses->getHost()); $service = $host_parts[0]; $region = $host_parts[1]; $canonical_uri = '/'; if($this->verb === 'POST') { $canonical_querystring = ''; $payload_data = $query; } else { $canonical_querystring = $query; $payload_data = ''; } // ************* TASK 1: CREATE A CANONICAL REQUEST ************* $canonical_headers_list = [ 'host:' . $this->ses->getHost(), 'x-amz-date:' . $amz_datetime ]; $canonical_headers = implode("\n", $canonical_headers_list) . "\n"; $signed_headers = 'host;x-amz-date'; $payload_hash = hash($algo, $payload_data, false); $canonical_request = implode("\n", array( $this->verb, $canonical_uri, $canonical_querystring, $canonical_headers, $signed_headers, $payload_hash )); // ************* TASK 2: CREATE THE STRING TO SIGN************* $credential_scope = $amz_date. '/' . $region . '/' . $service . '/' . 'aws4_request'; $string_to_sign = implode("\n", array( $aws_algo, $amz_datetime, $credential_scope, hash($algo, $canonical_request, false) )); // ************* TASK 3: CALCULATE THE SIGNATURE ************* // Create the signing key using the function defined above. $signing_key = $this->__getSigningKey($this->ses->getSecretKey(), $amz_date, $region, $service, $algo); // Sign the string_to_sign using the signing_key $signature = hash_hmac($algo, $string_to_sign, $signing_key, false); // ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST ************* return $aws_algo . ' ' . implode(', ', array( 'Credential=' . $this->ses->getAccessKey() . '/' . $credential_scope, 'SignedHeaders=' . $signed_headers , 'Signature=' . $signature )); } } main/mailer/gmail/auth.php000064400000013040151710730040011500 0ustar00client_id = $client_id; $this->client_secret = $client_secret; $this->redirect_uri = $redirect_uri; $this->state = $state; $this->options = $this->getConfig(); } private function getConfig(){ return array( 'client_id' => $this->client_id, 'client_secret' => $this->client_secret, 'redirect_uri' => $this->redirect_uri, 'urlAuthorize' => 'https://accounts.google.com/o/oauth2/auth', 'urlAccessToken' => 'https://www.googleapis.com/oauth2/v4/token', 'urlResourceOwnerDetails' => '', 'scopes' => 'https://www.googleapis.com/auth/gmail.compose', 'access_type' => 'offline', 'include_granted_scopes' => 'true', 'approval_prompt' => 'force', 'state' => $this->state, ); } public function setClientId($client_id){ $this->client_id= $client_id; return true; } public function setClientSecret($client_secret){ $this->client_secret = $client_secret; return true; } public function add_scope($scope){ if(is_array($scope)){ $separator = ','; $this->options['scope'] = implode($separator, $scope); return true; } $this->options['scope'] = $scope; return true; } public function set_access_type($access_type){ $this->options['access_type'] = $access_type; return true; } public function set_approval_prompt($approval_prompt){ $this->options['approval_prompt'] = $approval_prompt; return true; } public function getAuthUrl(){ return $this->getAuthorizationUrl(); } public function getAuthorizationUrl($options = []){ $base = $this->options['urlAuthorize']; $params = $this->getAuthorizationParameters($options); $query = http_build_query($params, null, '&', \PHP_QUERY_RFC3986); return $this->appendQuery($base, $query); } private function getAuthorizationParameters($options){ if(empty($options['scope'])){ $options['scope'] = $this->options['scopes']; } $options += [ 'access_type' => $this->options['access_type'], 'include_granted_scopes' => $this->options['include_granted_scopes'], 'response_type' => 'code', 'state' => $this->getRandomState().$this->options['state'], 'approval_prompt' => $this->options['approval_prompt'], ]; if(is_array($options['scope'])){ $separator = ','; $options['scope'] = implode($separator, $options['scope']); } // Store the state as it may need to be accessed later on. $this->options['state'] = $options['state']; // Business code layer might set a different redirect_uri parameter // depending on the context, leave it as-is if(!isset($options['redirect_uri'])){ $options['redirect_uri'] = $this->options['redirect_uri']; } $options['client_id'] = $this->options['client_id']; return $options; } protected function getRandomState($length = 32){ // Converting bytes to hex will always double length. Hence, we can reduce // the amount of bytes by half to produce the correct length. $state = bin2hex(random_bytes($length / 2)); update_option('_gosmtp_last_generated_state', $state); return $state; } protected function appendQuery($url, $query){ $query = trim($query, '?&'); if($query){ $glue = strstr($url, '?') === false ? '?' : '&'; return $url . $glue . $query; } return $url; } public function sendTokenRequest($type, $params){ try { $tokens = $this->getAccessToken($type, $params); return $tokens; } catch (\Exception $exception) { return new \WP_Error(423, $exception->getMessage()); } } /** * Requests an access token using a specified grant and option set. * * @param mixed $grant * @param array $options * @throws \Exception * @return array tokens */ public function getAccessToken($grant, array $options = []){ $params = [ 'client_id' => $this->options['client_id'], 'client_secret' => $this->options['client_secret'], 'redirect_uri' => $this->options['redirect_uri'], 'grant_type' => $grant, ]; $params += $options; $requestData = $this->getAccessTokenRequestDetails($params); $response = wp_remote_request($requestData['url'], $requestData['params']); if(is_wp_error($response)) { throw new \Exception( $response->get_error_message() ); return $response; } $responseBody = wp_remote_retrieve_body($response); if(false === is_array($response)){ throw new \Exception( 'Invalid response received from Authorization Server. Expected JSON.' ); } if(empty(['access_token'])){ throw new \Exception( 'Invalid response received from Authorization Server.' ); } return \json_decode($responseBody, true); } /** * Returns a prepared request for requesting an access token. * * @param array $params Query string parameters * @return array $requestDetails */ protected function getAccessTokenRequestDetails($params){ $method = $this->accessTokenMethod; $url = $this->options['urlAccessToken']; $options = http_build_query($params, null, '&', \PHP_QUERY_RFC3986); return [ 'url' => $url, 'params' => [ 'method' => $method, 'body' => $options, 'headers' => [ 'content-type' => 'application/x-www-form-urlencoded' ] ] ]; } }main/mailer/gmail/gmail.php000064400000025746151710730040011650 0ustar00preSend()){ $response = $this->postSend(); return $this->handle_response( $response ); } return $this->handle_response(new \WP_Error(400, 'Unable to send mail for some reason!', [])); } protected function postSend(){ global $phpmailer; try{ $access_token = $this->getAccessToken($this->getMailerOption()); if(is_wp_error($access_token)){ return $access_token->get_error_message(); } $mime = base64_encode($phpmailer->getSentMIMEMessage()); $body = array( "raw" =>$mime, ); $params = array( 'method' => 'POST', 'headers' => [ 'Authorization' => 'Bearer '. $access_token, 'Content-Type' => 'application/json', 'Accept' => 'application/json', ], 'body' => wp_json_encode($body) ); $response = wp_remote_request($this->url, $params); if(is_wp_error($response)){ $return_response = new \WP_Error($response->get_error_code(), $response->get_error_message(), $response->get_error_messages()); }else{ $resp_body = wp_remote_retrieve_body($response); $resp_code = wp_remote_retrieve_response_code($response); $resp_body = \json_decode($resp_body, true); if($this->isOk == $resp_code){ $msgId = isset( $resp_body['id'] ) ? $resp_body['id'] : ''; $status = 'Email sent successfully'; $return_response = [ 'status' => true, 'code' => $resp_code, 'messageId' => $msgId, 'message' => $status ]; }else{ $err_code = $resp_code; $error_text = ['']; if( ! empty( $resp_body['error'] ) && is_array( $resp_body['error'] ) ){ $message = $resp_body['error']['message']; $code = !empty( $resp_body['error']['code'] ) ? $resp_body['error']['code'] : ''; $error_text[] = $this->message_formatting( $message, $code ); }else{ $error_text[] = $this->get_response_error_message($response); } $error_msg = implode( '\r\n', array_map( 'esc_textarea', array_filter( $error_text ) ) ); $return_response = new \WP_Error($err_code, $error_msg, $resp_body); } } }catch(\Exception $e){ $return_Response = new \WP_Error(423, $e->getMessage(), []); } return $return_response; } // get access token private function getAccessToken($options){ $accessToken = $options['access_token']; // check if expired or will be expired in 300 seconds if( ($options['expire_stamp'] - 300) < time()){ $state = ($this->conn_id === 0 ? '' : '-'.$this->conn_id); $client_id = $this->getOption('client_id', $this->mailer); $client_secret = $this->getOption('client_secret', $this->mailer); $redirect_url = $this->getRedirectUrl('&auth=gmail'); $google_client = new \GOSMTP\mailer\gmail\Auth($client_id, $client_secret, $redirect_url, $state); $tokens = $google_client->sendTokenRequest('refresh_token', [ 'refresh_token' => $options['refresh_token'] ]); if(is_wp_error($tokens)) { return $tokens->get_error_message(); } $this->saveNewTokens($tokens); $accessToken = $tokens['access_token']; } return $accessToken; } //save new token when expire time exeed private function saveNewTokens($tokens){ $tokens['refresh_token'] = empty($tokens['refresh_token']) ? $this->getOption('refresh_token', $this->mailer) : $tokens['refresh_token']; if(empty($tokens['access_token']) || empty($tokens['refresh_token'])){ return false; } $this->update_option('access_token', $tokens['access_token'], $this->mailer); $this->update_option('refresh_token', $tokens['refresh_token'], $this->mailer); $this->update_option('expire_stamp', $tokens['expires_in'] + time(), $this->mailer); $this->update_option('expires_in', $tokens['expires_in'], $this->mailer); return true; } //generate access token and refresh token and update in data base. public function set_token(){ $errors = []; $clientId = $this->getOption('client_id', $this->mailer); $clientSecret = $this->getOption('client_secret', $this->mailer); $accessToken = $this->getOption('access_token', $this->mailer); $authToken = $this->getOption('auth_token', $this->mailer); if(!$accessToken && $authToken ){ $body = [ 'code' => $authToken, 'grant_type' => 'authorization_code', 'redirect_uri' => $this->getRedirectUrl('&auth=gmail'), 'client_id' => $clientId, 'client_secret' => $clientSecret ]; $tokens = $this->makeRequest('https://accounts.google.com/o/oauth2/token', $body, 'POST'); if(is_wp_error($tokens)){ return new \WP_Error(423, $tokens->get_error_message()); }else{ $this->update_option('access_token', $tokens['access_token'], $this->mailer); $this->update_option('refresh_token', $tokens['refresh_token'], $this->mailer); $this->update_option('auth_token', '', $this->mailer); $this->update_option('expire_stamp', time() + $tokens['expires_in'], $this->mailer); $this->update_option('expires_in', $tokens['expires_in'], $this->mailer); $this->update_option('version', 2, $this->mailer); } }elseif(!$authToken && !$accessToken){ return new \WP_Error(423, __('Please Provide Auth Token.', 'GOSMTP')); } return true; } private function makeRequest($url, $bodyArgs, $type = 'GET', $headers = false){ if(!$headers){ $headers = array( 'Content-Type' => 'application/http', 'Content-Transfer-Encoding' => 'binary', 'MIME-Version' => '1.0', ); } $args = array( 'headers' => $headers ); if($bodyArgs){ $args['body'] = json_encode($bodyArgs); } $args['method'] = $type; $request = wp_remote_request($url, $args); if(is_wp_error($request)){ $message = $request->get_error_message(); return new \WP_Error(423, $message); } $body = json_decode(wp_remote_retrieve_body($request), true); if(!empty($body['error'])){ $error = 'Unknown Error'; if(isset($body['error_description'])){ $error = $body['error_description']; }elseif(!empty($body['error']['message'])){ $error = $body['error']['message']; } return new \WP_Error(423, $error); } return $body; } public function get_auth_url() { $state = ($this->conn_id === 0 ? '' : '-'.$this->conn_id); $client_id = $this->getOption('client_id', $this->mailer); $client_secret = $this->getOption('client_secret', $this->mailer); $redirect_url = $this->getRedirectUrl('&auth=gmail'); $google_client = new \GOSMTP\mailer\gmail\Auth($client_id, $client_secret, $redirect_url, $state); if($google_client->getAuthUrl()){ return $google_client->getAuthUrl(); } } public function load_field(){ $this->gmail_init(); $access_token = $this->getOption('access_token', $this->mailer); $client_id = $this->getOption('client_id', $this->mailer); $client_secret = $this->getOption('client_secret', $this->mailer); $refresh_token = $this->getOption('refresh_token', $this->mailer); $mail_type = $this->getOption('mail_type', $this->mailer); $deactivate = !empty($refresh_token) && !empty($access_token) && $this->mailer == $mail_type; $activate = !empty($client_id) && !empty($client_secret) && empty($access_token) && empty($refresh_token); $readonly = $deactivate ? 'readonly' : ''; $fields = array( 'client_id' => array( 'title' => __('Client ID'), 'type' => 'text', 'desc' => '', 'attr'=> $readonly, ), 'client_secret' => array( 'title' => __('Client Secret'), 'type' => 'password', 'desc' => '', 'attr'=> $readonly, ), 'authorized_redirect_uri' => array( 'title' => __('Authorized redirect URI'), 'type' => 'copy', 'id' => 'gmail_redirect_uri', 'attr'=>'readonly', 'default' => $this->getRedirectUrl('&auth=gmail'), 'desc' => __('Please copy this URL into the "Authorized redirect URIs" field of your Google web application.') ), ); if($activate){ $fields['get_acces_token'] = array( 'title' => __('Get Access Token'), 'type' => 'button', 'class'=>'access_token', 'default' => 'Get Access Token', 'href' => $this->get_auth_url(), 'attr' => 'data-field=auth', ); }elseif($deactivate){ $fields['get_acces_token'] = array( 'title' => __('Deactivate Access Token'), 'type' => 'button', 'class'=>'deactivate_token', 'default' => 'Deactivate Access Token', 'href' => $this->getRedirectUrl().($this->conn_id !== 0 ? '&type=edit&conn_id='.$this->conn_id.'&act=deactivate_token#gosmtp-connections-settings' : '&act=deactivate_token'), 'attr' => 'data-field=auth', ); }else{ $fields['get_acces_token'] = array( 'title' => __('Get Access Token'), 'type' => 'notice', 'default' => __('You need to save settings with Client ID and Client Secret before you can proceed.'), ); } return $fields; } public function gmail_init(){ $options = $this->getMailerOption(); // Update auth URl when user succesfull regirect our page if( empty($options['access_token']) && empty($options['refresh_token']) && isset( $_GET['auth_code'] ) && isset( $_GET['auth'] ) && $this->mailer == $_GET['auth'] && strlen($this->conn_id) > 0 ){ if( !empty(gosmtp_optget('conn_id')) && $this->conn_id === 0 ){ return; } $auth_code = gosmtp_optget('auth_code'); $this->update_option('auth_token', $auth_code, $this->mailer); $resp = ''; if($this->set_token()){ $resp = __('Token Updated Sucessfully'); }elseif(is_wp_error($this->set_token())){ $resp = $this->set_token()->get_error_message(); }; $query = ''; if( !is_numeric($this->conn_id) ){ $query = '&type=edit&conn_id='.$this->conn_id.$query.'#gosmtp-connections-settings'; } echo ''; } // Delete all the tokens or expire stamp when user click deactivate access token if(isset($_GET['act']) && $_GET['act'] == 'deactivate_token'){ if(!empty(gosmtp_optget('conn_id')) && $this->conn_id === 0){ return; } $this->delete_option('refresh_token', $this->mailer); $this->delete_option('expire_stamp', $this->mailer); $this->delete_option('expires_in', $this->mailer); $this->delete_option('version', $this->mailer); $this->delete_option('access_token', $this->mailer); $query = ''; if(!is_numeric($this->conn_id)){ $query = '&type=edit&conn_id='.$this->conn_id.$query.'#gosmtp-connections-settings'; } if(isset($_GET['conn_id'])){ echo ''; } } } } main/mailer/outlook/outlook.php000064400000022316151710730040012644 0ustar00isMail(); $phpmailer->Encoding = 'base64'; if ($phpmailer->preSend()) { $response = $this->postSend(); return $this->handle_response( $response ); } return $this->handle_response(new \WP_Error(400, 'Unable to send mail for some reason!', [])); } public function postSend(){ global $phpmailer; try{ $access_token = $this->getAccessToken($this->getMailerOption()); if(is_wp_error($access_token)){ return $access_token->get_error_message(); } $mime = chunk_split(base64_encode($phpmailer->getSentMIMEMessage()), 76, "\n"); $params = array( 'method' => 'POST', 'headers' => [ 'Authorization' => 'Bearer '. $access_token, 'Content-Type' => 'text/plain' ], 'body' => $mime ); $response = wp_remote_request($this->url, $params); if(is_wp_error($response)){ $return_response = new \WP_Error($response->get_error_code(), $response->get_error_message(), $response->get_error_messages()); }else{ $resp_body = wp_remote_retrieve_body($response); $resp_code = wp_remote_retrieve_response_code($response); $resp_body = \json_decode($resp_body, true); if(202 == $resp_code){ $msgId = isset( $response['headers']['request-id'] ) ? $response['headers']['request-id'] : ''; $status = __('Email sent successfully'); $return_response = [ 'status' => true, 'code' => $resp_code, 'messageId' => $msgId, 'message' => $status ]; }else{ $err_code = $resp_code; $error_text = ['']; if(!empty( $resp_body['error']) && is_array($resp_body['error'])){ $message = $resp_body['error']['message']; $code = !empty( $resp_body['error']['code'] ) ? $resp_body['error']['code'] : ''; $desc = ''; if($code === 'ErrorAccessDenied'){ $desc = esc_html__( 'Note: This issue can also be caused by exceeding the total message size limit. If you are using large attachments, please remove the existing Outlook Mailer OAuth connection in WP Mail SMTP settings and reconnect it. We recently added support for large attachments, but oAuth re-connection is required.'); } $error_text[] = $this->message_formatting( $message, $code, $desc ); }else{ $error_text[] = $this->get_response_error_message($response); } $error_msg = implode( '\r\n', array_map( 'esc_textarea', array_filter( $error_text ) ) ); $return_response = new \WP_Error($err_code, $error_msg, $resp_body); } } }catch(\Exception $e){ $return_response = new \WP_Error(423, $e->getMessage(), []); } return $return_response; } public function getRedirectUrl($query = ''){ // TODO check and change this return admin_url().'admin.php?page=gosmtp'.$query; } private function getAccessToken($options){ $accessToken = $options['access_token']; // check if expired or will be expired in 300 seconds if( ($options['expire_stamp'] - 300) < time()){ $api = new \GOSMTP\mailer\outlook\Auth($options['client_id'], $options['client_secret']); $tokens = $api->sendTokenRequest('refresh_token', [ 'refresh_token' => $options['refresh_token'] ]); if(is_wp_error($tokens)) { return false; } $this->saveNewTokens($options, $tokens); $accessToken = $tokens['access_token']; } return $accessToken; } private function saveNewTokens($data, $tokens){ if (empty($tokens['access_token']) || empty($tokens['refresh_token'])) { return false; } $this->update_option('access_token', $tokens['access_token'], $this->mailer); $this->update_option('refresh_token', $tokens['refresh_token'], $this->mailer); $this->update_option('expire_stamp', $tokens['expires_in'] + time(), $this->mailer); } public function load_field(){ $this->outlook_init(); $client_id = $this->getOption('client_id', $this->mailer); $client_secret = $this->getOption('client_secret', $this->mailer); $access_token = $this->getOption('access_token', $this->mailer); $refresh_token = $this->getOption('refresh_token', $this->mailer); $mail_type = $this->getOption('mail_type', $this->mailer); $activate = !empty($client_id) && !empty($client_secret) && empty($access_token) && empty($refresh_token); $deactivate = !empty($refresh_token) && !empty($access_token) && $this->mailer == $mail_type; $readonly = $deactivate ? 'readonly' : ''; $state = ($this->conn_id === 0 ? '' : '-'.$this->conn_id); $api = new \GOSMTP\mailer\outlook\Auth($client_id, $client_secret, $state); $fields = array( 'client_id' => array( 'title' => __('Application Client ID'), 'type' => 'text', 'attr' => $readonly, ), 'client_secret' => array( 'title' => __('Application Client Secret'), 'type' => 'password', 'attr' => $readonly, 'desc' => __( 'Follow this link to get a Application Client Secret from Outlook: Application Client Secret.' ), ), 'redirect_uri' => array( 'title' => __('Outlook Callback URL'), 'type' => 'copy', 'id' => 'outlook_redirect_uri', 'attr'=>'readonly', 'default' => $api->getRedirectUrl(), 'desc' => __('Use this URL to your APP as Redirect URI.') ) ); if($activate){ $fields['get_access_token'] = array( 'title' => __('Get Access Token'), 'type' => 'button', 'class'=>'access_token', 'default' => __('Authenticate with outlook/Office365 & Get Access Token'), 'href' => $api->getAuthUrl(), 'attr' => 'data-field=auth', ); }elseif($deactivate){ $fields['get_access_token'] = array( 'title' => __('Deactivate Access Token'), 'type' => 'button', 'class'=>'deactivate_token', 'default' => 'Deactivate Access Token', 'href' => $this->getRedirectUrl().($this->conn_id !== 0 ? '&type=edit&conn_id='.$this->conn_id.'&act=deactivate_token#gosmtp-connections-settings' : '&act=deactivate_token'), 'attr' => 'data-field=auth', ); }else{ $fields['get_access_token'] = array( 'title' => __('Get Access Token'), 'type' => 'notice', 'default' => __('You need to save settings with Client ID and Client Secret before you can proceed.'), ); } return $fields; } // Generate access token and refresh token and update in data base. public function set_token(){ $errors = []; $options = $this->getMailerOption(); if(empty($options['access_token']) && !empty($options['auth_token'])){ $api = new \GOSMTP\mailer\outlook\Auth($options['client_id'], $options['client_secret']); $tokens = $api->generateToken($options['auth_token']); if(is_wp_error($tokens) || (is_array($tokens) && isset($tokens['error']))) { $err = is_wp_error($tokens) ? $tokens->get_error_message() : __('Mailer Authentication failed!'); return new \WP_Error(423, $err); } $this->saveNewTokens($options, $tokens); }elseif(!$authToken && !$accessToken){ return new \WP_Error(423, __('Please Provide Auth Token.', 'GOSMTP')); } return true; } public function outlook_init(){ $options = $this->getMailerOption(); // Update auth URl when user succesfull regirect our page if( empty($options['access_token']) && empty($options['refresh_token']) && isset( $_GET['auth_code'] ) && isset( $_GET['auth'] ) && $this->mailer == $_GET['auth'] && strlen($this->conn_id) > 0 ){ if( !empty(gosmtp_optget('conn_id')) && $this->conn_id === 0 ){ return; } $auth_code = gosmtp_optget('auth_code'); $this->update_option('auth_token', $auth_code, $this->mailer); $resp = ''; $set_token = $this->set_token(); if(is_wp_error($set_token)){ $resp = $set_token->get_error_message(); }else{ $resp = __('Mailer successfully configured!'); } $query = ''; if( !is_numeric($this->conn_id) ){ $query = '&type=edit&conn_id='.$this->conn_id.$query.'#gosmtp-connections-settings'; } echo ''; } // Delete all the tokens or expire stamp when user click deactivate access token if(isset($_GET['act']) && $_GET['act'] == 'deactivate_token'){ if(!empty(gosmtp_optget('conn_id')) && $this->conn_id === 0){ return; } $this->delete_option('refresh_token', $this->mailer); $this->delete_option('expire_stamp', $this->mailer); $this->delete_option('expires_in', $this->mailer); $this->delete_option('version', $this->mailer); $this->delete_option('access_token', $this->mailer); $query = ''; if(!is_numeric($this->conn_id)){ $query = '&type=edit&conn_id='.$this->conn_id.$query.'#gosmtp-connections-settings'; } if(isset($_GET['conn_id'])){ echo ''; } } } }main/mailer/outlook/auth.php000064400000015056151710730040012114 0ustar00clientId = $clientId; $this->clientSecret = $clientSecret; $this->state = $state; //$this->assertRequiredOptions($this->getConfig()); $this->options = $this->getConfig(); } public function getAuthUrl(){ return $this->getAuthorizationUrl(); } public function generateToken($authCode){ return $this->sendTokenRequest('authorization_code', [ 'code' => $authCode ]); } public function sendTokenRequest($type, $params){ try { $tokens = $this->getAccessToken($type, $params); return $tokens; } catch (\Exception $exception) { return new \WP_Error(423, $exception->getMessage()); } } public function getRedirectUrl(){ return rest_url('gosmtp-smtp/outlook_callback'); } private function getConfig(){ return array( 'clientId' => $this->clientId, 'clientSecret' => $this->clientSecret, 'redirectUri' => $this->getRedirectUrl(), 'urlAuthorize' => 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize', 'urlAccessToken' => 'https://login.microsoftonline.com/common/oauth2/v2.0/token', 'urlResourceOwnerDetails' => '', 'scopes' => 'offline_access user.read Mail.Send' ); } public function getAuthorizationUrl($options = []){ $base = $this->options['urlAuthorize']; $params = $this->getAuthorizationParameters($options); $query = $this->getAuthorizationQuery($params); return $this->appendQuery($base, $query); } private function getAuthorizationParameters($options){ if(empty($options['state'])){ $options['state'] = $this->getRandomState().$this->state; update_option('_gosmtp_last_generated_state', $options['state']); } if(empty($options['scope'])){ $options['scope'] = $this->options['scopes']; } $options += [ 'response_type' => 'code', 'approval_prompt' => 'auto' ]; if(is_array($options['scope'])){ $separator = ','; $options['scope'] = implode($separator, $options['scope']); } // Store the state as it may need to be accessed later on. $this->options['state'] = $options['state']; // Business code layer might set a different redirect_uri parameter // depending on the context, leave it as-is if(!isset($options['redirect_uri'])){ $options['redirect_uri'] = $this->options['redirectUri']; } $options['client_id'] = $this->options['clientId']; return $options; } /** * Appends a query string to a URL. * * @param string $url The URL to append the query to * @param string $query The HTTP query string * @return string The resulting URL */ protected function appendQuery($url, $query){ $query = trim($query, '?&'); if($query){ $glue = strstr($url, '?') === false ? '?' : '&'; return $url . $glue . $query; } return $url; } /** * Builds the authorization URL's query string. * * @param array $params Query parameters * @return string Query string */ protected function getAuthorizationQuery(array $params){ return $this->buildQueryString($params); } /** * Build a query string from an array. * * @param array $params * * @return string */ protected function buildQueryString(array $params){ return http_build_query($params, null, '&', \PHP_QUERY_RFC3986); } /** * Verifies that all required options have been passed. * * @param array $options * @return void * @throws \InvalidArgumentException */ private function assertRequiredOptions(array $options){ $missing = array_diff_key(array_flip($this->getRequiredOptions()), $options); if (!empty($missing)) { throw new \InvalidArgumentException( 'Required options not defined: ' . implode(', ', array_keys($missing)) ); } } /** * Returns all options that are required. * * @return array */ protected function getRequiredOptions(){ return [ 'urlAuthorize', 'urlAccessToken', 'urlResourceOwnerDetails', ]; } /** * Returns a new random string to use as the state parameter in an * authorization flow. * * @param int $length Length of the random string to be generated. * @return string */ protected function getRandomState($length = 32){ // Converting bytes to hex will always double length. Hence, we can reduce // the amount of bytes by half to produce the correct length. $state = bin2hex(random_bytes($length / 2)); update_option('_gosmtp_last_generated_state', $state); return $state; } /** * Requests an access token using a specified grant and option set. * * @param mixed $grant * @param array $options * @throws \Exception * @return array tokens */ public function getAccessToken($grant, array $options = []){ $params = [ 'client_id' => $this->options['clientId'], 'client_secret' => $this->options['clientSecret'], 'redirect_uri' => $this->options['redirectUri'], 'grant_type' => $grant, ]; $params += $options; $requestData = $this->getAccessTokenRequestDetails($params); $response = wp_remote_request($requestData['url'], $requestData['params']); if(is_wp_error($response)) { throw new \Exception( $response->get_error_message() ); } $responseBody = wp_remote_retrieve_body($response); if(false === is_array($response)){ throw new \Exception( 'Invalid response received from Authorization Server. Expected JSON.' ); } if(empty(['access_token'])){ throw new \Exception( 'Invalid response received from Authorization Server.' ); } return \json_decode($responseBody, true); } /** * Returns a prepared request for requesting an access token. * * @param array $params Query string parameters * @return array $requestDetails */ protected function getAccessTokenRequestDetails($params){ $method = $this->accessTokenMethod; $url = $this->getAccessTokenUrl($params); $options = $this->buildQueryString($params); return [ 'url' => $url, 'params' => [ 'method' => $method, 'body' => $options, 'headers' => [ 'content-type' => 'application/x-www-form-urlencoded' ] ] ]; } /** * Returns the full URL to use when requesting an access token. * * @param array $params Query parameters * @return string */ protected function getAccessTokenUrl($params){ $url = $this->options['urlAccessToken']; if($this->accessTokenMethod === 'GET'){ $query = $this->getAccessTokenQuery($params); return $this->appendQuery($url, $query); } return $url; } protected function getAccessTokenQuery(array $params){ return $this->buildQueryString($params); } } main/export.php000064400000025120151710730050007521 0ustar00 $val){ // Skip attachment explode for first row if( $kk != 0 && $attachment_key !== false && !empty($val[$attachment_key]) ){ $attachment = explode(',', $val[$attachment_key]); $attach = ''; foreach($attachment as $attach_val){ $attach .= explode('*', $attach_val)[2].', '; } $val[$attachment_key] = rtrim($attach, ', '); } fputcsv($file, array_values($val)); } fclose($file); wp_die(); } // Export XML files function gosmtp_export_xls($data){ $filename = "gosmtp_export_".date('Ymd') . ".xls"; header("Content-Type: application/vnd.ms-excel"); header("Content-Disposition: attachment; filename=\"$filename\""); // We have all the field sequences in the first line // Get the key of attachments form the sequences $attachment_key = array_search('attachments', $data[0], true); foreach($data as $kk => $val) { array_walk($val, 'gosmtp_filterData'); // Skip attachment explode for first row if( $kk != 0 && $attachment_key !== false && !empty($val[$attachment_key]) ){ $attachment = explode(',', $val[$attachment_key]); $attach =""; foreach($attachment as $attach_val){ $attach .= explode('*', $attach_val)[2].', '; } $val[$attachment_key] = rtrim($attach, ", "); } echo esc_html(implode("\t", array_values($val)) . "\n"); } wp_die(); } // Export EML files function gosmtp_export_eml($data){ $files = array(); $first_row = $data[0]; // Replace key with value $fields = array_flip($data[0]); $attachment_key = $fields['attachments']; foreach($data as $key => $value){ // Skip for first row if($key == 0){ continue; } $files[$key] = "gosmtp_export_".$key."_".date('Ymd') . ".eml"; header("Content-Type: application/application/eml"); header("Content-Disposition: attachment; filename=\"$files[$key]\""); $output_buffer = fopen('php://output', 'w'); $boundary = md5(uniqid(mt_rand())); $output_buffer = 'MIME-Version: 1.0 Date: '.date_format( date_create( $value[$fields['created_at']] ), 'd-m-y H:i:s').' +0100 From: '.$value[$fields['from']].' To: '.$value[$fields['to']].' Cc: '.$value[$fields['cc']].' Ccc: '.$value[$fields['bcc']].' Subject: '.$value[$fields['subject']].' Content-Type: multipart/mixed; boundary="'.$boundary.'" This is a message with multiple parts in MIME format. --'.$boundary.' Content-Type: '.$value[$fields['content-type']].' '.$value[$fields['body']]; // Added attachment if any if(isset($value[$attachment_key]) && !empty($value[$attachment_key])){ $attachment = explode(',', $value[$attachment_key]); foreach($attachment as $attach){ $all_attach = explode('*', $attach); $attachment_file = file_get_contents(trim($all_attach[0])); if(empty($attachment_file)){ continue; } $encoded_attach = base64_encode($attachment_file); $type = $all_attach[4]; $base_name = $all_attach[2]; $output_buffer .= ' --'.$boundary.' Content-Type: '.$type.';name="'.$base_name.'" Content-Transfer-Encoding: base64 Content-Disposition: attachment;filename="'.$base_name.'" '.$encoded_attach; } } file_put_contents($files[$key], $output_buffer); } $zipname = "gosmtp_export_".date('Ymd') . ".zip"; $zip = new ZipArchive; $zip->open($zipname, ZipArchive::CREATE); foreach($files as $file){ $zip->addFile($file); } $zip->close(); header('Content-Type: application/zip'); header('Content-disposition: attachment; filename='.$zipname); header('Content-Length: ' . filesize($zipname)); readfile($zipname); unlink($zipname); wp_die(); } // Export page HTML function gosmtp_export_page(){ // Styles and Scripts wp_enqueue_style( 'gosmtp-admin' ); wp_enqueue_script( 'gosmtp-admin' ); $common_field = array( 'to' => __('To Address'), 'from' => __('From Address'), 'subject' => __('Subject'), 'body' => __('Body'), 'created_at' => __('Created At'), 'attachments' => __('Attachments'), ); $addtition_field = array( 'status' => __('Status'), 'reply-to' => __('Reply To'), 'cc' => __('Carbon Copy (CC)'), 'bcc' => __('Blind Carbon Copy (BCC)'), 'provider' => __('Provider'), 'response' => __('Response'), 'source' => __('Source'), 'content-type' => __('Content Type') ); $search_field = array( 'from' => __('from'), 'to' => __('To'), 'subject' => __('Subject'), 'body' => __('Body'), ); $all_field = array_merge(array_keys($common_field), array_keys($addtition_field)); ?>


  • $val){ echo"
  • "; } ?>

  • $val){ echo "
  • "; } ?>

  • $val){ echo "
  • "; } ?>
license = get_option($license_field, array()); // Update license details as well if(!empty($gosmtp->license) && !empty($gosmtp->license['license']) && (time() - @$gosmtp->license['last_update']) >= 86400){ $resp = wp_remote_get($license_api_url.'license.php?license='.$gosmtp->license['license'].'&prods='.implode(',', $prods).'&url='.rawurlencode(site_url())); // Did we get a response ? if(is_array($resp)){ $tosave = json_decode($resp['body'], true); // Is it the license ? if(!empty($tosave['license'])){ $tosave['last_update'] = time(); update_option($license_field, $tosave); } } } // If the license is Free or Expired check for Softaculous Pro license if(empty($gosmtp->license) || empty($gosmtp->license['active'])){ if(function_exists('softaculous_pro_load_license')){ $softaculous_license = softaculous_pro_load_license(); if(!empty($softaculous_license['license']) && (!empty($softaculous_license['active']) || empty($gosmtp->license['license'])) ){ $gosmtp->license = $softaculous_license; } }elseif(empty($parent)){ $gosmtp->license = get_option('softaculous_pro_license', []); if(!empty($gosmtp->license)){ gosmtp_pro_load_license(1); } } } } add_filter('softaculous_pro_products', 'gosmtp_softaculous_pro_products', 10, 1); function gosmtp_softaculous_pro_products($r = []){ $r['gosmtp'] = 'gosmtp'; return $r; } // Add our license key if ANY function gosmtp_pro_updater_filter_args($queryArgs){ global $gosmtp; if (!empty($gosmtp->license['license'])){ $queryArgs['license'] = $gosmtp->license['license']; } $queryArgs['url'] = rawurlencode(site_url()); return $queryArgs; } // Handle the Check for update link and ask to install license key function gosmtp_pro_updater_check_link($final_link){ global $gosmtp; if(empty($gosmtp->license['license'])){ return 'Install GoSMTP Pro License Key'; } return $final_link; } // Prevent update of gosmtp free function gosmtp_pro_get_free_version_num(){ if(defined('GOSMTP_VERSION')){ return GOSMTP_VERSION; } // In case of gosmtp deactive return gosmtp_pro_file_get_version_num('gosmtp/gosmtp.php'); } // Prevent update of gosmtp free function gosmtp_pro_file_get_version_num($plugin){ // In case of gosmtp deactive include_once(ABSPATH . 'wp-admin/includes/plugin.php'); $plugin_data = get_plugin_data(WP_PLUGIN_DIR . '/'.$plugin); if(empty($plugin_data)){ return false; } return $plugin_data['Version']; } // Prevent update of gosmtp free function gosmtp_pro_disable_manual_update_for_plugin($transient){ $plugin = 'gosmtp/gosmtp.php'; // Is update available? if(!isset($transient->response) || !isset($transient->response[$plugin])){ return $transient; } $free_version = gosmtp_pro_get_free_version_num(); $pro_version = GOSMTP_PRO_VERSION; if(!empty($GLOBALS['gosmtp_pro_is_upgraded'])){ $pro_version = gosmtp_pro_file_get_version_num('gosmtp-pro/gosmtp-pro.php'); } // Update the gosmtp version to the equivalent of Pro version if(!empty($pro_version) && version_compare($free_version, $pro_version, '<')){ $transient->response[$plugin]->new_version = $pro_version; $transient->response[$plugin]->package = 'https://downloads.wordpress.org/plugin/gosmtp.'.$pro_version.'.zip'; }else{ unset($transient->response[$plugin]); } return $transient; } // Auto update free version after update pro version function gosmtp_pro_update_free_after_pro($upgrader_object, $options){ // Check if the action is an update for the plugins if($options['action'] != 'update' || $options['type'] != 'plugin'){ return; } // Define the slugs for the free and pro plugins $free_slug = 'gosmtp/gosmtp.php'; $pro_slug = 'gosmtp-pro/gosmtp-pro.php'; // Check if the pro plugin is in the list of updated plugins if( (isset($options['plugins']) && in_array($pro_slug, $options['plugins']) && !in_array($free_slug, $options['plugins'])) || (isset($options['plugin']) && $pro_slug == $options['plugin']) ){ // Trigger the update for the free plugin $current_version = gosmtp_pro_get_free_version_num(); if(empty($current_version)){ return; } $GLOBALS['gosmtp_pro_is_upgraded'] = true; // This will set the 'update_plugins' transient again wp_update_plugins(); // Check for updates for the free plugin $update_plugins = get_site_transient('update_plugins'); if(empty($update_plugins) || !isset($update_plugins->response[$free_slug]) || version_compare($update_plugins->response[$free_slug]->new_version, $current_version, '<=')){ return; } require_once(ABSPATH . 'wp-admin/includes/plugin.php'); require_once(ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'); $skin = wp_doing_ajax()? new WP_Ajax_Upgrader_Skin() : null; $upgrader = new Plugin_Upgrader($skin); $upgraded = $upgrader->upgrade($free_slug); if(!is_wp_error($upgraded) && $upgraded){ // Re-active free plugins if( file_exists( WP_PLUGIN_DIR . '/'. $free_slug ) && is_plugin_inactive($free_slug) ){ activate_plugin($free_slug); // TODO for network } // Re-active pro plugins if( file_exists( WP_PLUGIN_DIR . '/'. $pro_slug ) && is_plugin_inactive($pro_slug) ){ activate_plugin($pro_slug); // TODO for network } } } } function gosmtp_pro_api_url($main_server = 0, $suffix = 'gosmtp'){ global $gosmtp; $r = array( 'https://s0.softaculous.com/a/softwp/', 'https://s1.softaculous.com/a/softwp/', 'https://s2.softaculous.com/a/softwp/', 'https://s3.softaculous.com/a/softwp/', 'https://s4.softaculous.com/a/softwp/', 'https://s5.softaculous.com/a/softwp/', 'https://s7.softaculous.com/a/softwp/', 'https://s8.softaculous.com/a/softwp/' ); $mirror = $r[array_rand($r)]; // If the license is newly issued, we need to fetch from API only if(!empty($main_server) || empty($gosmtp->license['last_edit']) || (!empty($gosmtp->license['last_edit']) && (time() - 3600) < $gosmtp->license['last_edit']) ){ $mirror = GOSMTP_API; } if(!empty($suffix)){ $mirror = str_replace('/softwp', '/'.$suffix, $mirror); } return $mirror; }init.php000064400000012010151710730050006211 0ustar00addQueryArgFilter('gosmtp_pro_updater_filter_args'); // Show the text to install the license key add_filter('puc_manual_final_check_link-gosmtp-pro', 'gosmtp_pro_updater_check_link', 10, 1); // Is log enabled and retention period set? if(!empty($gosmtp->options['logs']['enable_logs']) && !empty($gosmtp->options['logs']['retention_period'])){ add_action( 'gosmtp_log_retention_cron', 'GOSMTP\Logger::retention_logs'); } // Is log enabled and retention period set? if(!empty($gosmtp->options['weekly_reports']['enable_weekly_reports']) && !function_exists('gosmtp_send_email_reports')){ include_once GOSMTP_PRO_DIR .'/main/weekly_email_reports.php'; add_action( 'gosmtp_weekly_email_reports_cron', 'gosmtp_send_email_reports', 10, 1 ); } } add_action('rest_api_init', 'outlook_api_init'); function outlook_api_init(){ register_rest_route('gosmtp-smtp', '/outlook_callback/', array( 'methods' => 'GET', 'callback' => function (\WP_REST_Request $request) { $url = parse_url($_SERVER['REQUEST_URI']); $redirect_uri = admin_url().'admin.php?page=gosmtp&'.$url['query'].'&auth=outlook'; wp_redirect($redirect_uri); die(); }, 'permission_callback' => function() { $state = $_REQUEST['state']; if($state != get_option('_gosmtp_last_generated_state')) { return false; } return true; } )); } function gosmtp_pro_free_version_nag(){ if(!defined('GOSMTP_VERSION')){ return; } $dismissed_free = (int) get_option('gosmtp_version_free_nag'); $dismissed_pro = (int) get_option('gosmtp_version_pro_nag'); // Checking if time has passed since the dismiss. if(!empty($dismissed_free) && time() < $dismissed_pro && !empty($dismissed_pro) && time() < $dismissed_pro){ return; } $showing_error = false; if(version_compare(GOSMTP_VERSION, GOSMTP_PRO_VERSION) > 0 && (empty($dismissed_pro) || time() > $dismissed_pro)){ $showing_error = true; echo '

'.esc_html__('You are using an older version of GoSMTP Pro. We recommend updating to the latest version to ensure seamless and uninterrupted use of the application.', 'gosmtp').'

'; }elseif(version_compare(GOSMTP_VERSION, GOSMTP_PRO_VERSION) < 0 && (empty($dismissed_free) || time() > $dismissed_free)){ $showing_error = true; echo '

'.esc_html__('You are using an older version of GoSMTP. We recommend updating to the latest free version to ensure smooth and uninterrupted use of the application.', 'gosmtp').'

'; } if(!empty($showing_error)){ wp_register_script('gosmtp-pro-version-notice', '', array('jquery'), GOSMTP_PRO_VERSION, true ); wp_enqueue_script('gosmtp-pro-version-notice'); wp_add_inline_script('gosmtp-pro-version-notice', ' function gosmtp_pro_dismiss_notice(e){ e.preventDefault(); let target = jQuery(e.target); if(!target.hasClass("notice-dismiss")){ return; } let jEle = target.closest("#gosmtp-pro-version-notice"), type = jEle.data("type"); jEle.slideUp(); jQuery.post("'.admin_url('admin-ajax.php').'", { security : "'.wp_create_nonce('gosmtp_version_notice').'", action: "gosmtp_pro_version_notice", type: type }, function(res){ if(!res["success"]){ alert(res["data"]); } }).fail(function(data){ alert("There seems to be some issue dismissing this alert"); }); }'); } } readme.txt000064400000013771151710730050006552 0ustar00=== GoSMTP - SMTP for WordPress === Contributors: softaculous, pagelayer Tags: smtp, wordpress smtp, gmail smtp, sendgrid smtp, aws smtp, gmail, outlook, zoho, aws, postmark, sparkpost, mail, mailer, phpmailer, wp_mail, email, mailgun, sendgrid, gmail, sendinblue, wp smtp, sendlayer Requires at least: 5.5 Tested up to: 6.7 Requires PHP: 5.5 Stable tag: 1.1.1 License: GPLv3 or later License URI: https://www.gnu.org/licenses/gpl-3.0.html Send emails from your WordPress site using your preferred SMTP provider like Gmail, Outlook, AWS, Zoho, SMTP.com, Sendinblue, Mailgun, Postmark, Sendgrid, Sparkpost, Sendlayer or any custom SMTP provider. == Description == GoSMTP allows you to send emails from your WordPress over SMTP or many of the popular email sending services. Many web hosting companies have strict mail sending rules and limitations which restrict email deliverability. With GoSMTP, you will not be using your hosting providers PHP email but rather sending emails over SMTP or using API's of various email providers. GoSMTP supports many of your preferred SMTP provider(s) : 1) Gmail, Gsuite, Google Workspace 2) Outlook / Office 365 3) AWS 4) Zoho 5) SMTP.com 6) Sendinblue 7) Mailgun, Postmark 8) Sendgrid 9) Sparkpost 10) Sendlayer 11) Or any custom SMTP provider WordPress uses the PHP mail function to send emails generated by WordPress. The PHP mail function sends emails over the IP of your hosting provider's servers which can have a bad reputation and be blacklisted by many email providers like Gmail, Yahoo, Office 365, Zoho, etc. causing your WordPress originated emails to land in the SPAM folder of your users. By using GoSMTP you ensure that your emails reach the inbox of your user(s). You can find our [official documentation](https://gosmtp.net/docs) on our Website [GoSMTP.net](https://gosmtp.net/) We are also active in our community support forums on wordpress.org if you are one of our free users. Our Premium Support Ticket System is at [https://softaculous.deskuss.com/open.php?topicId=17](https://softaculous.deskuss.com/open.php?topicId=17) [Home Page](https://gosmtp.net "GoSMTP Homepage") | [Support](https://softaculous.deskuss.com/open.php?topicId=17 "GoSMTP Support") | [Documents](http://gosmtp.net/docs "Documents") == GoSMTP PRO == GoSMTP Pro has many other powerful features and services. [Click here to purchase now !](https://gosmtp.net/pricing "Pricing") : === Email Logs === With Email Logging you view all emails sent from your site. This is necessary to keep email records and for auditing outgoing emails. Its also helpful to debug any outgoing email issues. === Resend Emails === You can resend any email, from the email log wizard. You can also resend multiple emails in bulk. === Premium Features === - Forward Emails - Email Reports === Coming Soon === - Backup Email Logs - Track Email Views - Track Clicks - Print Emails - Multi Email Provider Support - Export Logs - Multisite Support - Weekly Email Summary == Credits == GoSMTP's Mailer API connecters are derived from Fluent SMTP [https://wordpress.org/plugins/fluent-smtp/](https://wordpress.org/plugins/fluent-smtp/) == Frequently Asked Questions == Do you have questions related to GoSMTP ? Use the following links : 1. [Docs](https://gosmtp.net/docs) 3. [Help Desk](https://gosmtp.deskuss.com) 2. [Support Forum](http://wordpress.org/support/plugin/gosmtp) == How to install GoSMTP == Go To your WordPress install -> Plugins -> Add New Button -> In Search Box search For GoSMTP -> Click on Install. == Screenshots == 1. **Dashboard** of GoSMTP. 2. **Settings** has all options to set your SMTP / Email provider. 3. **Test Email Wizard** you can also send a test Email. 4. **Email Logs Wizard** check the emails sent with this wizard. == Changelog == = 1.1.1 (Nov 18, 2024) = * [Task] Licensing functionality has been further improved. = 1.1.0 (Oct 29, 2024) = * [Bug-Fix] In some cases, license loading was not working properly. This is fixed. = 1.0.9 (Oct 21, 2024) = * [Task] Licensing functionality has been further improved. = 1.0.7 (July 17, 2024) = * [Task] Structural changes in the plugin. * [Task] Tested with WordPress 6.6. = 1.0.6 (April 20, 2023) = * [Task] Tested compatibility with WordPress 6.5. The plugin is fully compatible with WordPress 6.5. * [Task] Changed the plugins License to GNU GPLv3 or later. = 1.0.5 (Nov 29, 2023) = * [Task] Tested compatibility with WordPress 6.4. The plugin is fully compatible with WordPress 6.4. * [Bug-Fix] Outlook mailer error handling has been further improved. = 1.0.4 (Aug 10, 2023) = * [Bug-Fix] In some cases, the recipients email was not configured properly with SendLayer Mailer. This is fixed. * [Bug-Fix] In some cases, the AmazonSES mailer secret key was not implemented correctly. This is fixed. = 1.0.3 (June 30, 2023) = * [Pro-Feature] Added option of additional connections in setting page, now users can add multiple connections and set them as secondary (backup) email. * [Bug-Fix] In some cases, emails were failing when sending emails from the default PHP. This is fixed. * [Bug-Fix] Changed the "Client Secret" field of Zoho Mailer from a text field to a password field. * [Bug-Fix] The authentication process for Outlook Mailer has been further improved. * [Bug-Fix] In some cases emails were not being sent properly from SMTP.com mailer. This is fixed. = 1.0.2 (Apr 21, 2023) = * [Pro-Feature] Added option to export email logs. * [Pro-Feature] Added option to send weekly email report via email to admin email. * [Bug-Fix] The email body with the HTML content type was showing in plain text when viewing email details in the email log. This is fixed. = 1.0.1 (March 09, 2023) = * [Pro-Feature] Added option to enable email log, now you can store email log and also manage email log. * [Pro-Feature] Added Email Report page. Now you can easily track your email status. * [Bug-Fix] The mailer error handler has been further improved. = 1.0.0 (FEB 21, 2023) = * Released Plugin