PluginProbe
Mailgun for WordPress / 2.1.0
Mailgun for WordPress v2.1.0
2.2.3 2.2.2 2.2.1 trunk 1.9.9 2.0.0 2.0.1 2.1.0 2.1.1 2.1.10 2.1.2 2.1.3 2.1.4 2.1.6 2.1.7 2.1.8 2.1.9 2.2.0
mailgun / mailgun.php

mailgun.php in Mailgun for WordPress 2.1.0, at mailgun.php

545 lines 18.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Plugin Name: Mailgun
4 * Plugin URI: http://wordpress.org/extend/plugins/mailgun/
5 * Description: Mailgun integration for WordPress
6 * Version: 2.1.0
7 * Requires PHP: 7.4
8 * Requires at least: 4.4
9 * Author: Mailgun
10 * Author URI: http://www.mailgun.com/
11 * License: GPLv2 or later
12 * Text Domain: mailgun
13 * Domain Path: /languages/.
14 */
15
16 /*
17 * mailgun-wordpress-plugin - Sending mail from Wordpress using Mailgun
18 * Copyright (C) 2016 Mailgun, et al.
19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License along
31 * with this program; if not, write to the Free Software Foundation, Inc.,
32 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
33 */
34
35 /**
36 * Entrypoint for the Mailgun plugin. Sets up the mailing "strategy" -
37 * either API or SMTP.
38 *
39 * Registers handlers for later actions and sets up config variables with
40 * WordPress.
41 */
42 class Mailgun
43 {
44 /**
45 * @var Mailgun $instance
46 */
47 private static $instance;
48
49 /**
50 * @var false|mixed|null
51 */
52 private $options;
53
54 /**
55 * @var string
56 */
57 protected $plugin_file;
58
59 /**
60 * @var string
61 */
62 protected $plugin_basename;
63
64 /**
65 * @var string
66 */
67 protected $assetsDir;
68
69 /**
70 * Setup shared functionality for Admin and Front End.
71 *
72 */
73 public function __construct()
74 {
75 $this->options = get_option('mailgun');
76 $this->plugin_file = __FILE__;
77 $this->plugin_basename = plugin_basename($this->plugin_file);
78 $this->assetsDir = plugin_dir_url($this->plugin_file) . 'assets/';
79
80 // Either override the wp_mail function or configure PHPMailer to use the
81 // Mailgun SMTP servers
82 // When using SMTP, we also need to inject a `wp_mail` filter to make "from" settings
83 // work properly. Fixed issues with 1.5.7+
84 if ($this->get_option('useAPI') || (defined('MAILGUN_USEAPI') && MAILGUN_USEAPI)) {
85 if (!function_exists('wp_mail')) {
86 if (!include_once(__DIR__ . '/includes/wp-mail-api.php')) {
87 $this->deactivate_and_die(__DIR__ . '/includes/wp-mail-api.php');
88 }
89 }
90 } else {
91 // Using SMTP, include the SMTP filter
92 if (!function_exists('mg_smtp_mail_filter')) {
93 if (!include __DIR__ . '/includes/wp-mail-smtp.php') {
94 $this->deactivate_and_die(__DIR__ . '/includes/wp-mail-smtp.php');
95 }
96 }
97 add_filter('wp_mail', 'mg_smtp_mail_filter');
98 add_action('phpmailer_init', [&$this, 'phpmailer_init']);
99 add_action('wp_mail_failed', 'wp_mail_failed');
100 }
101 }
102
103 /**
104 * @return static
105 */
106 public static function getInstance()
107 {
108 if (!isset(self::$instance)) {
109 self::$instance = new self();
110 }
111
112 return self::$instance;
113 }
114
115 /**
116 * Get specific option from the options table.
117 *
118 * @param string $option Name of option to be used as array key for retrieving the specific value
119 * @param array|null $options Array to iterate over for specific values
120 * @param bool $default False if no options are set
121 *
122 * @return mixed
123 *
124 */
125 public function get_option(string $option, ?array $options = null, bool $default = false)
126 {
127 if (is_null($options)) {
128 $options = &$this->options;
129 }
130
131 if (isset($options[$option])) {
132 return $options[$option];
133 }
134
135 return $default;
136 }
137
138 /**
139 * Hook into phpmailer to override SMTP based configurations
140 * to use the Mailgun SMTP server.
141 *
142 * @param object $phpmailer The PHPMailer object to modify by reference
143 *
144 * @return void
145 *
146 */
147 public function phpmailer_init(&$phpmailer)
148 {
149 $username = (defined('MAILGUN_USERNAME') && MAILGUN_USERNAME) ? MAILGUN_USERNAME : $this->get_option('username');
150 $domain = (defined('MAILGUN_DOMAIN') && MAILGUN_DOMAIN) ? MAILGUN_DOMAIN : $this->get_option('domain');
151 $username = preg_replace('/@.+$/', '', $username) . "@{$domain}";
152 $secure = (defined('MAILGUN_SECURE') && MAILGUN_SECURE) ? MAILGUN_SECURE : $this->get_option('secure');
153 $sectype = (defined('MAILGUN_SECTYPE') && MAILGUN_SECTYPE) ? MAILGUN_SECTYPE : $this->get_option('sectype');
154 $password = (defined('MAILGUN_PASSWORD') && MAILGUN_PASSWORD) ? MAILGUN_PASSWORD : $this->get_option('password');
155 $region = (defined('MAILGUN_REGION') && MAILGUN_REGION) ? MAILGUN_REGION : $this->get_option('region');
156
157 $smtp_endpoint = mg_smtp_get_region($region);
158 $smtp_endpoint = (bool) $smtp_endpoint ? $smtp_endpoint : 'smtp.mailgun.org';
159
160 $phpmailer->Mailer = 'smtp';
161 $phpmailer->Host = $smtp_endpoint;
162
163 if ('ssl' === $sectype) {
164 // For SSL-only connections, use 465
165 $phpmailer->Port = 465;
166 } else {
167 // Otherwise, use 587.
168 $phpmailer->Port = 587;
169 }
170
171 $phpmailer->SMTPAuth = true;
172 $phpmailer->Username = $username;
173 $phpmailer->Password = $password;
174
175 $phpmailer->SMTPSecure = (bool) $secure ? $sectype : '';
176 // Without this line... wp_mail for SMTP-only will always return false. But why? :(
177 $phpmailer->Debugoutput = 'mg_smtp_debug_output';
178 $phpmailer->SMTPDebug = 2;
179
180 // Emit some logging for SMTP connection
181 mg_smtp_debug_output(sprintf("PHPMailer configured to send via %s:%s", $phpmailer->Host, $phpmailer->Port),
182 'DEBUG');
183 }
184
185 /**
186 * Deactivate this plugin and die.
187 * Deactivate the plugin when files critical to it's operation cannot be loaded
188 *
189 * @param $file Files critical to plugin functionality
190 *
191 * @return void
192 */
193 public function deactivate_and_die($file)
194 {
195 load_plugin_textdomain('mailgun', false, 'mailgun/languages');
196 $message = sprintf(__('Mailgun has been automatically deactivated because the file <strong>%s</strong> is missing. Please reinstall the plugin and reactivate.'),
197 $file);
198 if (!function_exists('deactivate_plugins')) {
199 include ABSPATH . 'wp-admin/includes/plugin.php';
200 }
201 deactivate_plugins(__FILE__);
202 wp_die($message);
203 }
204
205 /**
206 * Make a Mailgun api call.
207 *
208 * @param string $uri The endpoint for the Mailgun API
209 * @param array $params Array of parameters passed to the API
210 * @param string $method The form request type
211 *
212 * @return string
213 *
214 */
215 public function api_call($uri, $params = [], $method = 'POST'): string
216 {
217 $options = get_option('mailgun');
218 $getRegion = (defined('MAILGUN_REGION') && MAILGUN_REGION) ? MAILGUN_REGION : $options[ 'region' ];
219 $apiKey = (defined('MAILGUN_APIKEY') && MAILGUN_APIKEY) ? MAILGUN_APIKEY : $options[ 'apiKey' ];
220 $domain = (defined('MAILGUN_DOMAIN') && MAILGUN_DOMAIN) ? MAILGUN_DOMAIN : $options[ 'domain' ];
221
222 $region = mg_api_get_region($getRegion);
223 $this->api_endpoint = ($region) ?: 'https://api.mailgun.net/v3/';
224
225 $time = time();
226 $url = $this->api_endpoint . $uri;
227 $headers = [
228 'Authorization' => 'Basic ' . base64_encode("api:{$apiKey}"),
229 ];
230
231 switch ($method) {
232 case 'GET':
233 $params[ 'sess' ] = '';
234 $querystring = http_build_query($params);
235 $url = $url . '?' . $querystring;
236 $params = '';
237 break;
238 case 'POST':
239 case 'PUT':
240 case 'DELETE':
241 $params[ 'sess' ] = '';
242 $params[ 'time' ] = $time;
243 $params[ 'hash' ] = sha1(date('U'));
244 break;
245 }
246
247 // make the request
248 $args = [
249 'method' => $method,
250 'body' => $params,
251 'headers' => $headers,
252 'sslverify' => true,
253 ];
254
255 // make the remote request
256 $result = wp_remote_request($url, $args);
257 if (!is_wp_error($result)) {
258 return $result['body'];
259 }
260
261 if (is_callable($result)) {
262 return $result->get_error_message();
263 }
264
265 if (is_array($result)) {
266 if (isset($result['response'])) {
267 return $result['response']['message'] ?? '';
268 }
269 }
270
271 return '';
272
273 }
274
275 /**
276 * Get account associated lists.
277 *
278 * @return array
279 *
280 * @throws JsonException
281 */
282 public function get_lists(): array
283 {
284 $results = [];
285
286 $lists_json = $this->api_call('lists', [], 'GET');
287
288 $lists_arr = json_decode($lists_json, true, 512, JSON_THROW_ON_ERROR);
289 if (isset($lists_arr[ 'items' ]) && !empty($lists_arr[ 'items' ])) {
290 $results = $lists_arr['items'];
291 }
292
293 return $results;
294 }
295
296 /**
297 * Handle add list ajax post.
298 *
299 * @return void json
300 *
301 * @throws JsonException
302 */
303 public function add_list()
304 {
305 $name = sanitize_text_field($_POST['name'] ?? null);
306 $email = sanitize_text_field($_POST['email'] ?? null);
307 $list_addresses = [];
308 foreach ($_POST['addresses'] as $address => $val) {
309 $list_addresses[sanitize_text_field($address)] = sanitize_text_field($val);
310 }
311
312 if (!empty($list_addresses)) {
313 $result = [];
314 foreach ($list_addresses as $address => $val) {
315 $result[] = $this->api_call(
316 "lists/{$address}/members",
317 [
318 'address' => $email,
319 'name' => $name,
320 ]
321 );
322 }
323 $message = 'Thank you!';
324 if ($result) {
325 $message = 'Something went wrong';
326 $response = json_decode($result[0], true);
327 if (is_array($response) && isset($response['message'])) {
328 $message = $response['message'];
329 }
330
331 }
332 echo json_encode([
333 'status' => 200,
334 'message' => $message
335 ], JSON_THROW_ON_ERROR);
336 } else {
337 echo json_encode([
338 'status' => 500,
339 'message' => 'Uh oh. We weren\'t able to add you to the list' . count($list_addresses) ? 's.' : '. Please try again.'
340 ], JSON_THROW_ON_ERROR);
341 }
342 wp_die();
343 }
344
345 /**
346 * Frontend List Form.
347 *
348 * @param string $list_address Mailgun address list id
349 * @param array $args widget arguments
350 * @param array $instance widget instance params
351 *
352 * @throws JsonException
353 */
354 public function list_form(string $list_address, array $args = [], array $instance = [])
355 {
356 $widgetId = $args['widget_id'] ?? 0;
357 $widget_class_id = "mailgun-list-widget-{$widgetId}";
358 $form_class_id = "list-form-{$widgetId}";
359
360 // List addresses from the plugin config
361 $list_addresses = array_map('trim', explode(',', $list_address));
362
363 // All list info from the API; used for list info when more than one list is available to subscribe to
364 $all_list_addresses = $this->get_lists();
365 ?>
366 <div class="mailgun-list-widget-front <?php echo esc_attr($widget_class_id); ?> widget">
367 <form class="list-form <?php echo esc_attr($form_class_id); ?>">
368 <div class="mailgun-list-widget-inputs">
369 <?php if (isset($args[ 'list_title' ])): ?>
370 <div class="mailgun-list-title">
371 <h4 class="widget-title">
372 <span><?php echo wp_kses_data($args[ 'list_title' ]); ?></span>
373 </h4>
374 </div>
375 <?php endif; ?>
376 <?php if (isset($args[ 'list_description' ])): ?>
377 <div class="mailgun-list-description">
378 <p class="widget-description">
379 <span><?php echo wp_kses_data($args[ 'list_description' ]); ?></span>
380 </p>
381 </div>
382 <?php endif; ?>
383 <?php if (isset($args[ 'collect_name' ]) && (int)$args['collect_name'] === 1): ?>
384 <p class="mailgun-list-widget-name">
385 <strong>Name:</strong>
386 <input type="text" name="name"/>
387 </p>
388 <?php endif; ?>
389 <p class="mailgun-list-widget-email">
390 <strong>Email:</strong>
391 <input type="text" name="email"/>
392 </p>
393 </div>
394
395 <?php if (count($list_addresses) > '1'): ?>
396 <ul class="mailgun-lists" style="list-style: none;">
397 <?php
398 foreach ($all_list_addresses as $la):
399 if (!in_array($la[ 'address' ], $list_addresses)):
400 continue;
401 endif;
402 ?>
403 <li>
404 <input type="checkbox" class="mailgun-list-name"
405 name="addresses[<?php echo esc_attr($la[ 'address' ]); ?>]"/> <?php echo esc_attr($la[ 'name' ] ?: $la[ 'address' ]); ?>
406 </li>
407 <?php endforeach; ?>
408 </ul>
409 <?php else: ?>
410 <input type="hidden" name="addresses[<?php echo esc_attr($list_addresses[ 0 ]); ?>]" value="on"/>
411 <?php endif; ?>
412
413 <input class="mailgun-list-submit-button" data-form-id="<?php echo esc_attr($form_class_id); ?>" type="button"
414 value="Subscribe"/>
415 <input type="hidden" name="mailgun-submission" value="1"/>
416
417 </form>
418 <div class="widget-list-panel result-panel" style="display:none;">
419 <span>Thank you for subscribing!</span>
420 </div>
421 </div>
422
423 <script>
424 jQuery(document).ready(function () {
425
426 jQuery('.mailgun-list-submit-button').on('click', function () {
427
428 var form_id = jQuery(this).data('form-id')
429
430 if (jQuery('.mailgun-list-name').length > 0 && jQuery('.' + form_id + ' .mailgun-list-name:checked').length < 1) {
431 alert('Please select a list to subscribe to.')
432 return
433 }
434
435 if (jQuery('.' + form_id + ' .mailgun-list-widget-name input') && jQuery('.' + form_id + ' .mailgun-list-widget-name input').val() === '') {
436 alert('Please enter your subscription name.')
437 return
438 }
439
440 if (jQuery('.' + form_id + ' .mailgun-list-widget-email input').val() === '') {
441 alert('Please enter your subscription email.')
442 return
443 }
444
445 jQuery.ajax({
446 url: '<?php echo admin_url('admin-ajax.php?action=add_list'); ?>',
447 action: 'add_list',
448 type: 'post',
449 dataType: 'json',
450 data: jQuery('.' + form_id + '').serialize(),
451 success: function (data) {
452 data_msg = data.message
453 already_exists = false
454 if (data_msg !== undefined) {
455 already_exists = data_msg.indexOf('Address already exists') > -1
456 }
457
458 // success
459 if ((data.status === 200)) {
460 jQuery('.<?php echo esc_attr($widget_class_id); ?> .widget-list-panel').css('display', 'none')
461 jQuery('.<?php echo esc_attr($widget_class_id); ?> .list-form').css('display', 'none')
462 jQuery('.<?php echo esc_attr($widget_class_id); ?> .result-panel').css('display', 'block')
463 // error
464 } else {
465 alert(data_msg)
466 }
467 }
468 })
469 })
470 })
471 </script>
472
473 <?php
474 }
475
476 /**
477 * Initialize List Form.
478 *
479 * @param array $atts Form attributes
480 *
481 * @return string
482 *
483 * @throws JsonException
484 */
485 public function build_list_form(array $atts): string
486 {
487 if (isset($atts['id']) && $atts['id'] != '') {
488 $args['widget_id'] = md5(rand(10000, 99999) . $atts['id']);
489
490 if (isset($atts['collect_name'])) {
491 $args['collect_name'] = true;
492 }
493
494 if (isset($atts['title'])) {
495 $args['list_title'] = $atts['title'];
496 }
497
498 if (isset($atts['description'])) {
499 $args['list_description'] = $atts['description'];
500 }
501
502 ob_start();
503 $this->list_form($atts['id'], $args);
504 return ob_get_clean();
505 }
506
507 return '<span>Mailgun list ID needed to render form!</span>
508 <br/>
509 <strong>Example :</strong> [mailgun id="[your list id]"]';
510 }
511
512 /**
513 * Initialize List Widget.
514 */
515 public function load_list_widget()
516 {
517 register_widget('list_widget');
518 add_shortcode('mailgun', [&$this, 'build_list_form']);
519 }
520
521 /**
522 * @return string
523 */
524 public function getAssetsPath(): string
525 {
526 return $this->assetsDir;
527 }
528 }
529
530 $mailgun = Mailgun::getInstance();
531
532 if (@include __DIR__ . '/includes/widget.php') {
533 add_action('widgets_init', [&$mailgun, 'load_list_widget']);
534 add_action('wp_ajax_nopriv_add_list', [&$mailgun, 'add_list']);
535 add_action('wp_ajax_add_list', [&$mailgun, 'add_list']);
536 }
537
538 if (is_admin()) {
539 if (@include __DIR__ . '/includes/admin.php') {
540 $mailgunAdmin = new MailgunAdmin();
541 } else {
542 $mailgun->deactivate_and_die(__DIR__ . '/includes/admin.php');
543 }
544 }
545