diff --git a/.github/workflows/wpcs.yml b/.github/workflows/wpcs.yml new file mode 100644 index 0000000..299ec1b --- /dev/null +++ b/.github/workflows/wpcs.yml @@ -0,0 +1,28 @@ +name: Wordpress Basic Checks + +on: + push: + branches: + - '**' # matches every branch + - '!master' + +jobs: + phpcs: + name: WPCS + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: WPCS check + uses: 10up/wpcs-action@stable + with: + enable_warnings: false # Enable checking for warnings (-w) + paths: '.' # Paths to check, space separated + excludes: '' # Paths to excludes, space separated + standard: 'WordPress' # Standard to use. Accepts WordPress|WordPress-Core|WordPress-Docs|WordPress-Extra|WordPress-VIP-Go|WordPressVIPMinimum|10up-Default. + standard_repo: '' # Public (git) repository URL of the coding standard + repo_branch: 'master' # Branch of Standard repository + phpcs_bin_path: 'phpcs' # Custom PHPCS bin path + use_local_config: 'true' # Use local config if available + extra_args: '' # Extra arguments passing to the command + only_changed_files: '' # Run the linter only on the changed files. Accepts true|false + only_changed_lines: '' # Run the linter only on the changed lines. Accepts true|false \ No newline at end of file diff --git a/includes/admin.php b/includes/admin.php index 7b8ede6..8bb1f1b 100755 --- a/includes/admin.php +++ b/includes/admin.php @@ -1,6 +1,5 @@ init(); @@ -49,25 +50,25 @@ public function __construct() load_plugin_textdomain('mailgun', false, 'mailgun/languages'); // Activation hook - register_activation_hook($this->plugin_file, [&$this, 'activation']); + register_activation_hook($this->plugin_file, array( &$this, 'activation' )); // Hook into admin_init and register settings and potentially register an admin_notice - add_action('admin_init', [&$this, 'admin_init']); + add_action('admin_init', array( &$this, 'admin_init' )); // Activate the options page - add_action('admin_menu', [&$this, 'admin_menu']); + add_action('admin_menu', array( &$this, 'admin_menu' )); // Register an AJAX action for testing mail sending capabilities - add_action('wp_ajax_mailgun-test', [&$this, 'ajax_send_test']); + add_action('wp_ajax_mailgun-test', array( &$this, 'ajax_send_test' )); } /** * Adds the default options during plugin activation. + * * @return void */ - public function activation(): void - { - if (!$this->options) { + public function activation(): void { + if ( ! $this->options) { $this->options = $this->defaults; add_option('mailgun', $this->options); } @@ -78,52 +79,57 @@ public function activation(): void * Initialize the default property. * * @return void - * */ - public function init(): void - { - $sitename = sanitize_text_field(strtolower($_SERVER['SERVER_NAME'])); + public function init(): void { + $sitename = sanitize_text_field(strtolower($_SERVER['SERVER_NAME'] ?? site_url())); if (substr($sitename, 0, 4) === 'www.') { $sitename = substr($sitename, 4); } - $region = (defined('MAILGUN_REGION') && MAILGUN_REGION) ? MAILGUN_REGION : $this->get_option('region'); + $region = ( defined('MAILGUN_REGION') && MAILGUN_REGION ) ? MAILGUN_REGION : $this->get_option('region'); $regionDefault = $region ?: 'us'; $this->defaults = array( - 'region' => $regionDefault, - 'useAPI' => '1', - 'apiKey' => '', - 'domain' => '', - 'username' => '', - 'password' => '', - 'secure' => '1', - 'sectype' => 'tls', - 'track-clicks' => '', - 'track-opens' => '', - 'campaign-id' => '', + 'region' => $regionDefault, + 'useAPI' => '1', + 'apiKey' => '', + 'domain' => '', + 'username' => '', + 'password' => '', + 'secure' => '1', + 'sectype' => 'tls', + 'track-clicks' => '', + 'track-opens' => '', + 'campaign-id' => '', 'override-from' => '0', - 'tag' => $sitename, + 'tag' => $sitename, ); - } /** * Add the options page. * * @return void - * */ - public function admin_menu(): void - { + public function admin_menu(): void { if (current_user_can('manage_options')) { - $this->hook_suffix = add_options_page(__('Mailgun', 'mailgun'), __('Mailgun', 'mailgun'), - 'manage_options', 'mailgun', [&$this, 'options_page']); - add_options_page(__('Mailgun Lists', 'mailgun'), __('Mailgun Lists', 'mailgun'), 'manage_options', - 'mailgun-lists', [&$this, 'lists_page']); - add_action("admin_print_scripts-{$this->hook_suffix}", [&$this, 'admin_js']); - add_filter("plugin_action_links_{$this->plugin_basename}", [&$this, 'filter_plugin_actions']); - add_action("admin_footer-{$this->hook_suffix}", [&$this, 'admin_footer_js']); + $this->hook_suffix = add_options_page( + __('Mailgun', 'mailgun'), + __('Mailgun', 'mailgun'), + 'manage_options', + 'mailgun', + array( &$this, 'options_page' ) + ); + add_options_page( + __('Mailgun Lists', 'mailgun'), + __('Mailgun Lists', 'mailgun'), + 'manage_options', + 'mailgun-lists', + array( &$this, 'lists_page' ) + ); + add_action("admin_print_scripts-{$this->hook_suffix}", array( &$this, 'admin_js' )); + add_filter("plugin_action_links_{$this->plugin_basename}", array( &$this, 'filter_plugin_actions' )); + add_action("admin_footer-{$this->hook_suffix}", array( &$this, 'admin_footer_js' )); } } @@ -131,19 +137,15 @@ public function admin_menu(): void * Enqueue javascript required for the admin settings page. * * @return void - * */ - public function admin_js(): void - { + public function admin_js(): void { wp_enqueue_script('jquery'); } /** * Output JS to footer for enhanced admin page functionality. - * */ - public function admin_footer_js(): void - { + public function admin_footer_js(): void { ?> @@ -169,8 +171,14 @@ public function admin_footer_js(): void jQuery('#mailgun-test').click(function (e) { e.preventDefault() if (formModified) { - var doTest = confirm('') + var doTest = confirm(' + + ') if (!doTest) { return false } @@ -213,13 +221,16 @@ public function admin_footer_js(): void * Output the options page. * * @return void - * */ - public function options_page(): void - { - if (!@include 'options-page.php') { - printf(__('

The options page for the Mailgun plugin cannot be displayed. The file %s is missing. Please reinstall the plugin.

', - 'mailgun'), __DIR__ . '/options-page.php'); + public function options_page(): void { + if ( ! @include 'options-page.php') { + printf( + __( + '

The options page for the Mailgun plugin cannot be displayed. The file %s is missing. Please reinstall the plugin.

', + 'mailgun' + ), + __DIR__ . '/options-page.php' + ); } } @@ -227,13 +238,16 @@ public function options_page(): void * Output the lists page. * * @return void - * */ - public function lists_page(): void - { - if (!@include 'lists-page.php') { - printf(__('

The lists page for the Mailgun plugin cannot be displayed. The file %s is missing. Please reinstall the plugin.

', - 'mailgun'), __DIR__ . '/lists-page.php'); + public function lists_page(): void { + if ( ! @include 'lists-page.php') { + printf( + __( + '

The lists page for the Mailgun plugin cannot be displayed. The file %s is missing. Please reinstall the plugin.

', + 'mailgun' + ), + __DIR__ . '/lists-page.php' + ); } } @@ -243,24 +257,20 @@ public function lists_page(): void * been configured yet. * * @return void - * */ - public function admin_init(): void - { + public function admin_init(): void { $this->register_settings(); - add_action('admin_notices', [&$this, 'admin_notices']); + add_action('admin_notices', array( &$this, 'admin_notices' )); } /** * Whitelist the mailgun options. * * @return void - * */ - public function register_settings(): void - { - register_setting('mailgun', 'mailgun', [&$this, 'validation']); + public function register_settings(): void { + register_setting('mailgun', 'mailgun', array( &$this, 'validation' )); } /** @@ -269,13 +279,11 @@ public function register_settings(): void * @param array $options An array of options posted from the options page * * @return array - * */ - public function validation(array $options): array - { - $apiKey = trim($options['apiKey']); + public function validation( array $options ): array { + $apiKey = trim($options['apiKey']); $username = trim($options['username']); - if (!empty($apiKey)) { + if ( ! empty($apiKey)) { $pos = strpos($apiKey, 'api:'); if ($pos !== false && $pos == 0) { $apiKey = substr($apiKey, 4); @@ -292,13 +300,13 @@ public function validation(array $options): array } } - if (!empty($username)) { - $username = preg_replace('/@.+$/', '', $username); + if ( ! empty($username)) { + $username = preg_replace('/@.+$/', '', $username); $options['username'] = $username; } foreach ($options as $key => $value) { - $options[$key] = trim($value); + $options[ $key ] = trim($value); } if (empty($options['override-from'])) { @@ -319,31 +327,32 @@ public function validation(array $options): array * when plugin settings or constants need to be configured * * @return void - * */ - public function admin_notices(): void - { + public function admin_notices(): void { $screen = get_current_screen(); - if (!isset($screen)) { + if ( ! isset($screen)) { return; } - if (!current_user_can('manage_options') || $screen->id === $this->hook_suffix) { + if ( ! current_user_can('manage_options') || $screen->id === $this->hook_suffix) { return; } - $smtpPasswordUndefined = (!$this->get_option('password') && (!defined('MAILGUN_PASSWORD') || !MAILGUN_PASSWORD)); - $smtpActiveNotConfigured = ($this->get_option('useAPI') === '0' && $smtpPasswordUndefined); - $apiRegionUndefined = (!$this->get_option('region') && (!defined('MAILGUN_REGION') || !MAILGUN_REGION)); - $apiKeyUndefined = (!$this->get_option('apiKey') && (!defined('MAILGUN_APIKEY') || !MAILGUN_APIKEY)); - $apiActiveNotConfigured = ($this->get_option('useAPI') === '1' && ($apiRegionUndefined || $apiKeyUndefined)); + $smtpPasswordUndefined = ( ! $this->get_option('password') && ( ! defined('MAILGUN_PASSWORD') || ! MAILGUN_PASSWORD ) ); + $smtpActiveNotConfigured = ( $this->get_option('useAPI') === '0' && $smtpPasswordUndefined ); + $apiRegionUndefined = ( ! $this->get_option('region') && ( ! defined('MAILGUN_REGION') || ! MAILGUN_REGION ) ); + $apiKeyUndefined = ( ! $this->get_option('apiKey') && ( ! defined('MAILGUN_APIKEY') || ! MAILGUN_APIKEY ) ); + $apiActiveNotConfigured = ( $this->get_option('useAPI') === '1' && ( $apiRegionUndefined || $apiKeyUndefined ) ); - if (isset($_SESSION) && (!isset($_SESSION['settings_turned_of']) || $_SESSION['settings_turned_of'] === false) && ($apiActiveNotConfigured || $smtpActiveNotConfigured)) { ?> + if (isset($_SESSION) && ( ! isset($_SESSION['settings_turned_of']) || $_SESSION['settings_turned_of'] === false ) && ( $apiActiveNotConfigured || $smtpActiveNotConfigured )) { + ?>

here', - 'mailgun'), + __( + 'Use HTTP API is turned off or you do not have SMTP credentials. You can configure your Mailgun settings in your wp-config.php file or here', + 'mailgun' + ), menu_page_url('mailgun', false) ); ?> @@ -354,8 +363,9 @@ public function admin_notices(): void get_option('override-from') === '1' && - (!$this->get_option('from-name') || !$this->get_option('from-address')) - ) { ?> + ( ! $this->get_option('from-name') || ! $this->get_option('from-address') ) + ) { + ?>

@@ -363,14 +373,17 @@ public function admin_notices(): void Configure Mailgun now.', - 'mailgun'), + __( + '"Override From" option requires that "From Name" and "From Address" be set to work properly! Configure Mailgun now.', + 'mailgun' + ), menu_page_url('mailgun', false) ); ?>

- ' . __('Settings', 'mailgun') . ''; array_unshift($links, $settings_link); @@ -392,89 +403,99 @@ public function filter_plugin_actions(array $links): array /** * AJAX callback function to test mail sending functionality. * - * @return string - * + * @return void * @throws JsonException */ - public function ajax_send_test() - { + public function ajax_send_test(): void { nocache_headers(); header('Content-Type: application/json'); - if (!current_user_can('manage_options') || !wp_verify_nonce(sanitize_text_field($_GET['_wpnonce']))) { + if ( ! current_user_can('manage_options') || ! wp_verify_nonce(sanitize_text_field($_GET['_wpnonce']))) { die( - json_encode([ - 'message' => __('Unauthorized', 'mailgun'), - 'method' => null, - 'error' => __('Unauthorized', 'mailgun'), - ], JSON_THROW_ON_ERROR) + json_encode( + array( + 'message' => __('Unauthorized', 'mailgun'), + 'method' => null, + 'error' => __('Unauthorized', 'mailgun'), + ), + JSON_THROW_ON_ERROR + ) ); } - $getRegion = (defined('MAILGUN_REGION') && MAILGUN_REGION) ? MAILGUN_REGION : $this->get_option('region'); - $useAPI = (defined('MAILGUN_USEAPI') && MAILGUN_USEAPI) ? MAILGUN_USEAPI : $this->get_option('useAPI'); - $secure = (defined('MAILGUN_SECURE') && MAILGUN_SECURE) ? MAILGUN_SECURE : $this->get_option('secure'); - $sectype = (defined('MAILGUN_SECTYPE') && MAILGUN_SECTYPE) ? MAILGUN_SECTYPE : $this->get_option('sectype'); - $replyTo = (defined('MAILGUN_REPLY_TO_ADDRESS') && MAILGUN_REPLY_TO_ADDRESS) ? MAILGUN_REPLY_TO_ADDRESS : $this->get_option('reply_to'); + $getRegion = ( defined('MAILGUN_REGION') && MAILGUN_REGION ) ? MAILGUN_REGION : $this->get_option('region'); + $useAPI = ( defined('MAILGUN_USEAPI') && MAILGUN_USEAPI ) ? MAILGUN_USEAPI : $this->get_option('useAPI'); + $secure = ( defined('MAILGUN_SECURE') && MAILGUN_SECURE ) ? MAILGUN_SECURE : $this->get_option('secure'); + $sectype = ( defined('MAILGUN_SECTYPE') && MAILGUN_SECTYPE ) ? MAILGUN_SECTYPE : $this->get_option('sectype'); + $replyTo = ( defined('MAILGUN_REPLY_TO_ADDRESS') && MAILGUN_REPLY_TO_ADDRESS ) ? MAILGUN_REPLY_TO_ADDRESS : $this->get_option('reply_to'); - if (!$getRegion) { - mg_api_last_error(__("Region has not been selected", "mailgun")); + if ( ! $getRegion) { + mg_api_last_error(__('Region has not been selected', 'mailgun')); } else { if ($getRegion === 'us') { - $region = __("U.S./North America", "mailgun"); + $region = __('U.S./North America', 'mailgun'); } - if ($getRegion === "eu") { - $region = __("Europe", "mailgun"); + if ($getRegion === 'eu') { + $region = __('Europe', 'mailgun'); } } if ($useAPI) { $method = __('HTTP API', 'mailgun'); } else { - $method = ($secure) ? __('Secure SMTP', 'mailgun') : __('Insecure SMTP', 'mailgun'); + $method = ( $secure ) ? __('Secure SMTP', 'mailgun') : __('Insecure SMTP', 'mailgun'); if ($secure) { $method .= sprintf(__(' via %s', 'mailgun'), $sectype); } } $admin_email = get_option('admin_email'); - if (!$admin_email) { + if ( ! $admin_email) { die( - json_encode([ - 'message' => __('Admin Email is empty', 'mailgun'), - 'method' => $method, - 'error' => __('Admin Email is empty', 'mailgun'), - ], JSON_THROW_ON_ERROR) + json_encode( + array( + 'message' => __('Admin Email is empty', 'mailgun'), + 'method' => $method, + 'error' => __('Admin Email is empty', 'mailgun'), + ), + JSON_THROW_ON_ERROR + ) ); } try { - $headers = [ + $headers = array( 'Content-Type: text/plain', 'Reply-To: ' . $replyTo, - ]; + ); $result = wp_mail( $admin_email, __('Mailgun WordPress Plugin Test', 'mailgun'), - sprintf(__("This is a test email generated by the Mailgun WordPress plugin.\n\nIf you have received this message, the requested test has succeeded.\n\nThe sending region is set to %s.\n\nThe method used to send this email was: %s.", - 'mailgun'), $region, $method), + sprintf( + __( + "This is a test email generated by the Mailgun WordPress plugin.\n\nIf you have received this message, the requested test has succeeded.\n\nThe sending region is set to %s.\n\nThe method used to send this email was: %s.", + 'mailgun' + ), + $region, + $method + ), $headers ); } catch (Throwable $throwable) { - //Log purpose + // Log purpose } if ($useAPI) { - if (!function_exists('mg_api_last_error')) { - if (!include __DIR__ . '/wp-mail-api.php') { + if ( ! function_exists('mg_api_last_error')) { + if ( ! include __DIR__ . '/wp-mail-api.php') { $this->deactivate_and_die(__DIR__ . '/wp-mail-api.php'); } } $error_msg = mg_api_last_error(); } else { - if (!function_exists('mg_smtp_last_error')) { - if (!include __DIR__ . '/wp-mail-smtp.php') { + if ( ! function_exists('mg_smtp_last_error')) { + if ( ! include __DIR__ . '/wp-mail-smtp.php') { $this->deactivate_and_die(__DIR__ . '/wp-mail-smtp.php'); } } @@ -491,22 +512,28 @@ public function ajax_send_test() if ($result) { die( - json_encode([ - 'message' => __('Success', 'mailgun'), - 'method' => $method, - 'error' => __('Success', 'mailgun'), - ], JSON_THROW_ON_ERROR) + json_encode( + array( + 'message' => __('Success', 'mailgun'), + 'method' => $method, + 'error' => __('Success', 'mailgun'), + ), + JSON_THROW_ON_ERROR + ) ); } // Error message will always be returned in case of failure, if not - connection wasn't successful $error_msg = $error_msg ?: "Can't connect to Mailgun"; die( - json_encode([ - 'message' => __('Failure', 'mailgun'), - 'method' => $method, - 'error' => $error_msg, - ], JSON_THROW_ON_ERROR) + json_encode( + array( + 'message' => __('Failure', 'mailgun'), + 'method' => $method, + 'error' => $error_msg, + ), + JSON_THROW_ON_ERROR + ) ); } } diff --git a/includes/lists-page.php b/includes/lists-page.php index de3025d..85e2c1d 100644 --- a/includes/lists-page.php +++ b/includes/lists-page.php @@ -1,7 +1,6 @@ get_option('apiKey'); -$mailgun_domain = (defined('MAILGUN_DOMAIN') && MAILGUN_DOMAIN) ? MAILGUN_DOMAIN : $this->get_option('domain'); +$missing_error = ''; +$api_key = ( defined('MAILGUN_APIKEY') && MAILGUN_APIKEY ) ? MAILGUN_APIKEY : $this->get_option('apiKey'); +$mailgun_domain = ( defined('MAILGUN_DOMAIN') && MAILGUN_DOMAIN ) ? MAILGUN_DOMAIN : $this->get_option('domain'); if ($api_key !== '') { if ($mailgun_domain === '') { @@ -36,7 +37,7 @@ // import available lists $lists_arr = $mailgun->get_lists(); -$icon = $mailgun->getAssetsPath() . 'icon-128x128.png'; +$icon = $mailgun->getAssetsPath() . 'icon-128x128.png'; ?> @@ -46,7 +47,7 @@ - Mailgun + Mailgun @@ -60,7 +61,7 @@
- + diff --git a/includes/mg-filter.php b/includes/mg-filter.php index 5f47321..fdf216b 100755 --- a/includes/mg-filter.php +++ b/includes/mg-filter.php @@ -1,6 +1,5 @@ site_name; } else { @@ -92,12 +91,12 @@ function mg_detect_from_name($from_name_header = null) $filter_from_name = null; - if ((!isset($mg_override_from) || $mg_override_from === '0') && has_filter('wp_mail_from_name')) { + if (( ! isset($mg_override_from) || $mg_override_from === '0' ) && has_filter('wp_mail_from_name')) { $filter_from_name = apply_filters( 'wp_mail_from_name', $from_name ); - if (!empty($filter_from_name)) { + if ( ! empty($filter_from_name)) { $from_name = $filter_from_name; } } @@ -110,7 +109,7 @@ function mg_detect_from_name($from_name_header = null) * This operates as a filter for the from address. If the override is set, * a given address will except in ONE case. * If the override is not enabled this is the from address resolution order: - * 1. From address given by headers - {@param $from_addr_header} + * 1. From address given by headers - {$from_addr_header} * 2. From address set in Mailgun settings * 3. From `MAILGUN_FROM_ADDRESS` constant * 4. From address constructed as `wordpress@` @@ -125,30 +124,28 @@ function mg_detect_from_name($from_name_header = null) * might appear to be another option but some hosts may refuse to * relay mail from an unknown domain. * - * @link http://trac.wordpress.org/ticket/5007. - * + * @param null $from_addr_header * @return string * * @since 1.5.8 */ -function mg_detect_from_address($from_addr_header = null): string -{ +function mg_detect_from_address( $from_addr_header = null ): string { // Get options to avoid strict mode problems - $mg_opts = get_option('mailgun'); + $mg_opts = get_option('mailgun'); $mg_override_from = $mg_opts['override-from'] ?? null; - $mg_from_addr = $mg_opts['from-address'] ?? null; + $mg_from_addr = $mg_opts['from-address'] ?? null; - if ($mg_override_from && !is_null($mg_from_addr)) { + if ($mg_override_from && ! is_null($mg_from_addr)) { $from_addr = $mg_from_addr; - } elseif (!is_null($from_addr_header)) { + } elseif ( ! is_null($from_addr_header)) { $from_addr = $from_addr_header; } elseif (defined('MAILGUN_FROM_ADDRESS') && MAILGUN_FROM_ADDRESS) { $from_addr = MAILGUN_FROM_ADDRESS; - } else if (empty($mg_from_addr)) { + } elseif (empty($mg_from_addr)) { if (function_exists('get_current_site')) { $sitedomain = get_current_site()->domain; } else { - $sitedomain = strtolower(sanitize_text_field($_SERVER['SERVER_NAME'])); + $sitedomain = strtolower(sanitize_text_field($_SERVER['SERVER_NAME'] ?? site_url())); if (substr($sitedomain, 0, 4) === 'www.') { $sitedomain = substr($sitedomain, 4); } @@ -160,12 +157,12 @@ function mg_detect_from_address($from_addr_header = null): string } $filter_from_addr = null; - if ((!isset($mg_override_from) || $mg_override_from === '0') && has_filter('wp_mail_from')) { + if (( ! isset($mg_override_from) || $mg_override_from === '0' ) && has_filter('wp_mail_from')) { $filter_from_addr = apply_filters( 'wp_mail_from', $from_addr ); - if (!is_null($filter_from_addr) || !empty($filter_from_addr)) { + if ( ! is_null($filter_from_addr) || ! empty($filter_from_addr)) { $from_addr = $filter_from_addr; } } @@ -196,32 +193,31 @@ function mg_detect_from_address($from_addr_header = null): string * * @since 1.5.8 */ -function mg_parse_headers($headers = []): array -{ +function mg_parse_headers( $headers = array() ): array { if (empty($headers)) { - return []; + return array(); } - if (!is_array($headers)) { + if ( ! is_array($headers)) { $tmp = explode("\n", str_replace("\r\n", "\n", $headers)); } else { $tmp = $headers; } - $new_headers = []; - if (!empty($tmp)) { - $name = null; - $value = null; + $new_headers = array(); + if ( ! empty($tmp)) { + $name = null; + $value = null; $boundary = null; - $parts = null; + $parts = null; - foreach ((array)$tmp as $header) { + foreach ( (array) $tmp as $header) { // If this header does not contain a ':', is it a fold? if (false === strpos($header, ':')) { // Does this header have a boundary? if (false !== stripos($header, 'boundary=')) { - $parts = preg_split('/boundary=/i', trim($header)); - $boundary = trim(str_replace(['"', '\''], '', $parts[1])); + $parts = preg_split('/boundary=/i', trim($header)); + $boundary = trim(str_replace(array( '"', '\'' ), '', $parts[1])); } $value .= $header; @@ -232,18 +228,18 @@ function mg_parse_headers($headers = []): array [$name, $value] = explode(':', trim($header), 2); // Clean up the values - $name = trim($name); + $name = trim($name); $value = trim($value); - if (!isset($new_headers[$name])) { - $new_headers[$name] = []; + if ( ! isset($new_headers[ $name ])) { + $new_headers[ $name ] = array(); } - $new_headers[$name][] = [ - 'value' => $value, + $new_headers[ $name ][] = array( + 'value' => $value, 'boundary' => $boundary, - 'parts' => $parts, - ]; + 'parts' => $parts, + ); } } @@ -254,29 +250,28 @@ function mg_parse_headers($headers = []): array * Takes a header array in the format produced by mg_parse_headers and * dumps them down in to a submittable header format. * - * @param array $headers Headers to dump + * @param array|null $headers Headers to dump * * @return string String of \r\n separated headers * * @since 1.5.8 */ -function mg_dump_headers($headers = null): string -{ - if (!is_array($headers)) { +function mg_dump_headers( array $headers = null ): string { + if ( ! is_array($headers)) { return ''; } $header_string = ''; foreach ($headers as $name => $values) { - $header_string .= sprintf("%s: ", $name); - $header_values = []; + $header_string .= sprintf('%s: ', $name); + $header_values = array(); foreach ($values as $content) { // XXX - Is it actually okay to discard `parts` and `boundary`? $header_values[] = $content['value']; } - $header_string .= sprintf("%s\r\n", implode(", ", $header_values)); + $header_string .= sprintf("%s\r\n", implode(', ', $header_values)); } return $header_string; @@ -292,8 +287,7 @@ function mg_dump_headers($headers = null): string * * @since 1.5.12 */ -function mg_api_get_region($getRegion) -{ +function mg_api_get_region( $getRegion ) { switch ($getRegion) { case 'us': return 'https://api.mailgun.net/v3/'; @@ -314,8 +308,7 @@ function mg_api_get_region($getRegion) * * @since 1.5.12 */ -function mg_smtp_get_region($getRegion) -{ +function mg_smtp_get_region( $getRegion ) { switch ($getRegion) { case 'us': return 'smtp.mailgun.org'; @@ -330,16 +323,15 @@ function mg_smtp_get_region($getRegion) * Override WP VIP GO filter * It sets default email address to `donotreply@wordpress.com` */ -if ((defined('WPCOM_IS_VIP_ENV') && WPCOM_IS_VIP_ENV) || (defined('VIP_GO_ENV') && VIP_GO_ENV)) { +if (( defined('WPCOM_IS_VIP_ENV') && WPCOM_IS_VIP_ENV ) || ( defined('VIP_GO_ENV') && VIP_GO_ENV )) { global $mg_from_mail; /** * @param string $from_mail - * @return mixed + * @return string */ - function mg_wp_mail_from_standard(string $from_mail) - { + function mg_wp_mail_from_standard( string $from_mail ): string { global $mg_from_mail; $mg_from_mail = $from_mail; @@ -351,13 +343,12 @@ function mg_wp_mail_from_standard(string $from_mail) /** * @param string $from_mail - * @return mixed + * @return string */ - function mg_wp_mail_from_new(string $from_mail) - { + function mg_wp_mail_from_new( string $from_mail ): string { global $mg_from_mail; - if (!empty($mg_from_mail) && is_email($mg_from_mail)) { + if ( ! empty($mg_from_mail) && is_email($mg_from_mail)) { return $mg_from_mail; } diff --git a/includes/options-page.php b/includes/options-page.php index 8143d71..e7e0604 100755 --- a/includes/options-page.php +++ b/includes/options-page.php @@ -1,6 +1,5 @@ get_option('domain'); +$mailgun_domain_const = ( ( defined('MAILGUN_DOMAIN') && MAILGUN_DOMAIN ) ? MAILGUN_DOMAIN : null ); +$mailgun_domain = $mailgun_domain_const ?: $this->get_option('domain'); -$mailgun_region_const = ((defined('MAILGUN_REGION') && MAILGUN_REGION) ? MAILGUN_REGION : null); -$mailgun_region = $mailgun_region_const ?: $this->get_option('region'); +$mailgun_region_const = ( ( defined('MAILGUN_REGION') && MAILGUN_REGION ) ? MAILGUN_REGION : null ); +$mailgun_region = $mailgun_region_const ?: $this->get_option('region'); -$mailgun_api_key_const = ((defined('MAILGUN_APIKEY') && MAILGUN_APIKEY) ? MAILGUN_APIKEY : null); -$mailgun_api_key = $mailgun_api_key_const ?: $this->get_option('apiKey'); +$mailgun_api_key_const = ( ( defined('MAILGUN_APIKEY') && MAILGUN_APIKEY ) ? MAILGUN_APIKEY : null ); +$mailgun_api_key = $mailgun_api_key_const ?: $this->get_option('apiKey'); -$mailgun_username_const = ((defined('MAILGUN_USERNAME') && MAILGUN_USERNAME) ? MAILGUN_USERNAME : null); -$mailgun_username = $mailgun_username_const ?: $this->get_option('username'); +$mailgun_username_const = ( ( defined('MAILGUN_USERNAME') && MAILGUN_USERNAME ) ? MAILGUN_USERNAME : null ); +$mailgun_username = $mailgun_username_const ?: $this->get_option('username'); -$mailgun_password_const = ((defined('MAILGUN_PASSWORD') && MAILGUN_PASSWORD) ? MAILGUN_PASSWORD : null); -$mailgun_password = $mailgun_password_const ?: $this->get_option('password'); +$mailgun_password_const = ( ( defined('MAILGUN_PASSWORD') && MAILGUN_PASSWORD ) ? MAILGUN_PASSWORD : null ); +$mailgun_password = $mailgun_password_const ?: $this->get_option('password'); -$mailgun_sectype_const = ((defined('MAILGUN_SECTYPE') && MAILGUN_SECTYPE) ? MAILGUN_SECTYPE : null); -$mailgun_sectype = $mailgun_sectype_const ?: $this->get_option('sectype'); +$mailgun_sectype_const = ( ( defined('MAILGUN_SECTYPE') && MAILGUN_SECTYPE ) ? MAILGUN_SECTYPE : null ); +$mailgun_sectype = $mailgun_sectype_const ?: $this->get_option('sectype'); -$mailgun_from_name_const = ((defined('MAILGUN_FROM_NAME') && MAILGUN_FROM_NAME) ? MAILGUN_FROM_NAME : null); -$mailgun_from_name = $mailgun_from_name_const ?: $this->get_option('from-name'); +$mailgun_from_name_const = ( ( defined('MAILGUN_FROM_NAME') && MAILGUN_FROM_NAME ) ? MAILGUN_FROM_NAME : null ); +$mailgun_from_name = $mailgun_from_name_const ?: $this->get_option('from-name'); -$mailgun_from_address_const = ((defined('MAILGUN_FROM_ADDRESS') && MAILGUN_FROM_ADDRESS) ? MAILGUN_FROM_ADDRESS : null); -$mailgun_from_address = $mailgun_from_address_const ?: $this->get_option('from-address'); +$mailgun_from_address_const = ( ( defined('MAILGUN_FROM_ADDRESS') && MAILGUN_FROM_ADDRESS ) ? MAILGUN_FROM_ADDRESS : null ); +$mailgun_from_address = $mailgun_from_address_const ?: $this->get_option('from-address'); -$mailgunReplyToAddressConst = ((defined('MAILGUN_REPLY_TO_ADDRESS') && MAILGUN_REPLY_TO_ADDRESS) ? MAILGUN_REPLY_TO_ADDRESS : null); -$mailgunReplyTo = $mailgunReplyToAddressConst ?: $this->get_option('reply_to'); +$mailgunReplyToAddressConst = ( ( defined('MAILGUN_REPLY_TO_ADDRESS') && MAILGUN_REPLY_TO_ADDRESS ) ? MAILGUN_REPLY_TO_ADDRESS : null ); +$mailgunReplyTo = $mailgunReplyToAddressConst ?: $this->get_option('reply_to'); -$mailgun_secure_const = (defined('MAILGUN_SECURE') ? MAILGUN_SECURE : null); -$mailgun_secure = !is_null($mailgun_secure_const) ? ((string)(1 * $mailgun_secure_const)) : $this->get_option('secure'); +$mailgun_secure_const = ( defined('MAILGUN_SECURE') ? MAILGUN_SECURE : null ); +$mailgun_secure = ! is_null($mailgun_secure_const) ? ( (string) ( 1 * $mailgun_secure_const ) ) : $this->get_option('secure'); -$mailgun_use_api_const = (defined('MAILGUN_USEAPI') ? MAILGUN_USEAPI : null); -$mailgun_use_api = !is_null($mailgun_use_api_const) ? ((string)(1 * $mailgun_use_api_const)) : $this->get_option('useAPI'); -$icon = $mailgun->getAssetsPath() . 'icon-128x128.png'; +$mailgun_use_api_const = ( defined('MAILGUN_USEAPI') ? MAILGUN_USEAPI : null ); +$mailgun_use_api = ! is_null($mailgun_use_api_const) ? ( (string) ( 1 * $mailgun_use_api_const ) ) : $this->get_option('useAPI'); +$icon = $mailgun->getAssetsPath() . 'icon-128x128.png'; -$trackClicks = (defined('MAILGUN_TRACK_CLICKS') ? MAILGUN_TRACK_CLICKS : null); -$trackOpens = (defined('MAILGUN_TRACK_OPENS') ? MAILGUN_TRACK_OPENS : null); +$trackClicks = ( defined('MAILGUN_TRACK_CLICKS') ? MAILGUN_TRACK_CLICKS : null ); +$trackOpens = ( defined('MAILGUN_TRACK_OPENS') ? MAILGUN_TRACK_OPENS : null ); $suppressClicks = $this->get_option('suppress_clicks') ?: 'no'; @@ -65,23 +66,26 @@

- Mailgun + Mailgun

Mailgun account is required to use this plugin and the Mailgun service.', 'mailgun'), - ['a' => [ - 'href' => [], - 'target' => [] - ] - ] - ), esc_url($url), '_blank' + array( + 'a' => array( + 'href' => array(), + 'target' => array(), + ), + ) + ), + esc_url($url), + '_blank' ); echo wp_kses_data($link); ?> @@ -89,16 +93,19 @@

Mailgun.com.', 'mailgun'), - ['a' => [ - 'href' => [], - 'target' => [] - ] - ] - ), esc_url($url), '_blank' + array( + 'a' => array( + 'href' => array(), + 'target' => array(), + ), + ) + ), + esc_url($url), + '_blank' ); echo wp_kses_data($link); ?> @@ -114,14 +121,14 @@

@@ -288,20 +298,20 @@
- - + +

- - + + @@ -157,10 +164,10 @@ + name="mailgun[domain]" + value="" + placeholder="samples.mailgun.org" + />

@@ -173,9 +180,9 @@

+ value="" + placeholder="key-3ax6xnjp29jd6fds4gc373sgvjxteol0" + />

+ name="mailgun[username]" + value="" + placeholder="postmaster" + />

+ name="mailgun[password]" + value="" + placeholder="my-password" + />

- - + + - > @@ -245,11 +252,11 @@ - - + + - > @@ -265,7 +272,7 @@ - > @@ -273,12 +280,15 @@

Open Tracking Documentation.', 'mailgun'); - echo wp_kses($link, [ - 'a' => [ - 'href' => [], - 'target' => [] - ] - ]); + echo wp_kses( + $link, + array( + 'a' => array( + 'href' => array(), + 'target' => array(), + ), + ) + ); ?>

- >

Open Tracking Documentation.', 'mailgun'), - [ - 'a' => [ - 'href' => [], - 'target' => [] - ] - ] + __('If enabled, HTML messages will include an open tracking beacon. Open Tracking Documentation.', 'mailgun'), + array( + 'a' => array( + 'href' => array(), + 'target' => array(), + ), + ) ); ?>

@@ -313,11 +323,11 @@
+ class="regular-text" + name="mailgun[from-address]" + value="" + placeholder="wordpress@mydomain.com" + />

+ name="mailgun[from-name]" + value="" + placeholder="WordPress" + />

Tracking and Tagging', 'mailgun'), - ['a' => [ - 'href' => [], - 'target' => [] - ] - ] + __('Tracking and Tagging', 'mailgun'), + array( + 'a' => array( + 'href' => array(), + 'target' => array(), + ), + ) ); ?>

@@ -451,11 +462,13 @@ class="regular-text" $link = sprintf( wp_kses( __('View available lists.', 'mailgun'), - ['a' => [ - 'href' => [], - ] - ] - ), esc_url($url) + array( + 'a' => array( + 'href' => array(), + ), + ) + ), + esc_url($url) ); echo wp_kses_data($link); ?> @@ -469,13 +482,13 @@ class="regular-text"

diff --git a/includes/widget.php b/includes/widget.php index d1f2502..5d06901 100644 --- a/includes/widget.php +++ b/includes/widget.php @@ -1,7 +1,7 @@ __('Mailgun list widget', 'wpb_widget_domain')] + array( 'description' => __('Mailgun list widget', 'wpb_widget_domain') ) ); } /** - * @param $args - * @param $instance + * @param mixed $args + * @param mixed $instance * @return void * @throws JsonException */ - public function widget($args, $instance) - { + public function widget( $args, $instance ) { $mailgun = Mailgun::getInstance(); - if (!isset($instance['list_address']) || !$instance['list_address']) { + if ( ! isset($instance['list_address']) || ! $instance['list_address']) { return; } // vars @@ -61,17 +63,16 @@ public function widget($args, $instance) $args['list_description'] = $instance['list_description']; } - $mailgun->list_form($list_address, $args, $instance); + $mailgun->list_form($list_address, $args); } // Widget Backend /** - * @param $instance + * @param mixed $instance * @return string|void */ - public function form($instance) - { + public function form( $instance ) { if (isset($instance['list_address'])) { $list_address = $instance['list_address']; } else { @@ -84,7 +85,7 @@ public function form($instance) $collect_name = ''; } - $list_title = $instance['list_title'] ?? null; + $list_title = $instance['list_title'] ?? null; $list_description = $instance['list_description'] ?? null; // Widget admin form @@ -107,18 +108,15 @@ public function form($instance) />

- deactivate_and_die(__DIR__ . '/mg-filter.php'); +if ( ! include __DIR__ . '/mg-filter.php') { + ( new Mailgun() )->deactivate_and_die(__DIR__ . '/mg-filter.php'); } /** - * mg_api_last_error is a compound getter/setter for the last error that was + * g_api_last_error is a compound getter/setter for the last error that was * encountered during a Mailgun API call. + * * @param string|null $error OPTIONAL * @return string|null Last error that occurred. * @since 1.5.0 */ -function mg_api_last_error(string $error = null): ?string -{ +function mg_api_last_error( string $error = null ): ?string { static $last_error; if (null === $error) { @@ -40,7 +41,7 @@ function mg_api_last_error(string $error = null): ?string } do_action('mailgun_error_track', $error); - $tmp = $last_error; + $tmp = $last_error; $last_error = $error; return $tmp; @@ -60,37 +61,37 @@ function mg_api_last_error(string $error = null): ?string add_filter('mg_mutate_to_rcpt_vars', 'mg_mutate_to_rcpt_vars_cb'); /** - * @param $to_addrs + * @param string|array $to_addrs Array or comma-separated list of email addresses to mutate. * @return array * @throws JsonException */ -function mg_mutate_to_rcpt_vars_cb($to_addrs): array -{ +function mg_mutate_to_rcpt_vars_cb( $to_addrs ): array { if (is_string($to_addrs)) { $to_addrs = explode(',', $to_addrs); } if (has_filter('mg_use_recipient_vars_syntax')) { + $rcpt_vars = array(); $use_rcpt_vars = apply_filters('mg_use_recipient_vars_syntax', null); if ($use_rcpt_vars) { $idx = 0; foreach ($to_addrs as $addr) { - $rcpt_vars[$addr] = ['batch_msg_id' => $idx]; - $idx++; + $rcpt_vars[ $addr ] = array( 'batch_msg_id' => $idx ); + ++$idx; } - return [ - 'to' => '%recipient%', + return array( + 'to' => '%recipient%', 'rcpt_vars' => json_encode($rcpt_vars, JSON_THROW_ON_ERROR), - ]; + ); } } - return [ - 'to' => $to_addrs, + return array( + 'to' => $to_addrs, 'rcpt_vars' => null, - ]; + ); } /** @@ -109,29 +110,34 @@ function mg_mutate_to_rcpt_vars_cb($to_addrs): array * @return bool Whether the email contents were sent successfully. * * @global PHPMailer\PHPMailer\PHPMailer $phpmailer - * */ -if (!function_exists('wp_mail')) { +if ( ! function_exists('wp_mail')) { + /** + * @param string $to + * @param string $subject + * @param mixed $message + * @param array $headers + * @param array $attachments + * @return bool * @throws \PHPMailer\PHPMailer\Exception */ - function wp_mail($to, $subject, $message, $headers = '', $attachments = []) - { + function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) { $mailgun = get_option('mailgun'); - $region = (defined('MAILGUN_REGION') && MAILGUN_REGION) ? MAILGUN_REGION : $mailgun['region']; - $apiKey = (defined('MAILGUN_APIKEY') && MAILGUN_APIKEY) ? MAILGUN_APIKEY : $mailgun['apiKey']; - $domain = (defined('MAILGUN_DOMAIN') && MAILGUN_DOMAIN) ? MAILGUN_DOMAIN : $mailgun['domain']; + $region = ( defined('MAILGUN_REGION') && MAILGUN_REGION ) ? MAILGUN_REGION : $mailgun['region']; + $apiKey = ( defined('MAILGUN_APIKEY') && MAILGUN_APIKEY ) ? MAILGUN_APIKEY : $mailgun['apiKey']; + $domain = ( defined('MAILGUN_DOMAIN') && MAILGUN_DOMAIN ) ? MAILGUN_DOMAIN : $mailgun['domain']; if (empty($apiKey) || empty($domain)) { return false; } // If a region is not set via defines or through the options page, default to US region. - if (!($region)) { + if ( ! ( $region )) { error_log('[Mailgun] No region configuration was found! Defaulting to US region.'); $region = 'us'; } - + // Respect WordPress core filters $atts = apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ); @@ -139,7 +145,7 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) $to = $atts['to']; } - if (!is_array($to)) { + if ( ! is_array($to)) { $to = explode(',', $to); } @@ -159,36 +165,36 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) $attachments = $atts['attachments']; } - if (!is_array($attachments)) { + if ( ! is_array($attachments)) { $attachments = explode("\n", str_replace("\r\n", "\n", $attachments)); } - $cc = []; - $bcc = []; + $cc = array(); + $bcc = array(); // Headers if (empty($headers)) { - $headers = []; + $headers = array(); } else { - if (!is_array($headers)) { + if ( ! is_array($headers)) { // Explode the headers out, so this function can take both // string headers and an array of headers. $tempheaders = explode("\n", str_replace("\r\n", "\n", $headers)); } else { $tempheaders = $headers; } - $headers = []; - $cc = []; - $bcc = []; + $headers = array(); + $cc = array(); + $bcc = array(); // If it's actually got contents - if (!empty($tempheaders)) { + if ( ! empty($tempheaders)) { // Iterate through the raw headers - foreach ((array)$tempheaders as $header) { + foreach ( (array) $tempheaders as $header) { if (strpos($header, ':') === false) { if (false !== stripos($header, 'boundary=')) { - $parts = preg_split('/boundary=/i', trim($header)); - $boundary = trim(str_replace(["'", '"'], '', $parts[1])); + $parts = preg_split('/boundary=/i', trim($header)); + $boundary = trim(str_replace(array( "'", '"' ), '', $parts[1])); } continue; } @@ -196,7 +202,7 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) [$name, $content] = explode(':', trim($header), 2); // Cleanup crew - $name = trim($name); + $name = trim($name); $content = trim($content); switch (strtolower($name)) { @@ -217,61 +223,61 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) case 'content-type': if (strpos($content, ';') !== false) { [$type, $charset] = explode(';', $content); - $content_type = trim($type); + $content_type = trim($type); if (false !== stripos($charset, 'charset=')) { - $charset = trim(str_replace(['charset=', '"'], '', $charset)); + $charset = trim(str_replace(array( 'charset=', '"' ), '', $charset)); } elseif (false !== stripos($charset, 'boundary=')) { - $boundary = trim(str_replace(['BOUNDARY=', 'boundary=', '"'], '', $charset)); - $charset = ''; + $boundary = trim(str_replace(array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset)); + $charset = ''; } } else { $content_type = trim($content); } break; case 'cc': - $cc = array_merge((array)$cc, explode(',', $content)); + $cc = array_merge( (array) $cc, explode(',', $content)); break; case 'bcc': - $bcc = array_merge((array)$bcc, explode(',', $content)); + $bcc = array_merge( (array) $bcc, explode(',', $content)); break; default: // Add it to our grand headers array - $headers[trim($name)] = trim($content); + $headers[ trim($name) ] = trim($content); break; } } } } - if (!isset($from_name)) { + if ( ! isset($from_name)) { $from_name = null; } - if (!isset($from_email)) { + if ( ! isset($from_email)) { $from_email = null; } - $from_name = mg_detect_from_name($from_name); + $from_name = mg_detect_from_name($from_name); $from_email = mg_detect_from_address($from_email); $fromString = "{$from_name} <{$from_email}>"; - $body = [ - 'from' => $fromString, + $body = array( + 'from' => $fromString, 'h:Sender' => $from_email, - 'to' => $to, - 'subject' => $subject, - ]; + 'to' => $to, + 'subject' => $subject, + ); $rcpt_data = apply_filters('mg_mutate_to_rcpt_vars', $to); - if (!is_null($rcpt_data['rcpt_vars'])) { + if ( ! is_null($rcpt_data['rcpt_vars'])) { $body['recipient-variables'] = $rcpt_data['rcpt_vars']; } - $body['o:tag'] = []; + $body['o:tag'] = array(); if (defined('MAILGUN_TRACK_CLICKS')) { $trackClicks = MAILGUN_TRACK_CLICKS; } else { - $trackClicks = !empty($mailgun['track-clicks']) ? $mailgun['track-clicks'] : 'no'; + $trackClicks = ! empty($mailgun['track-clicks']) ? $mailgun['track-clicks'] : 'no'; } if (defined('MAILGUN_TRACK_OPENS')) { $trackOpens = MAILGUN_TRACK_OPENS; @@ -281,22 +287,22 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) if (isset($mailgun['suppress_clicks']) && $mailgun['suppress_clicks'] === 'yes') { $passwordResetSubject = __('Password Reset Request', 'mailgun') ?: __( 'Password Reset Request', 'woocommerce' ); - if (!empty($passwordResetSubject) && stripos($subject, $passwordResetSubject) !== false) { + if ( ! empty($passwordResetSubject) && stripos($subject, $passwordResetSubject) !== false) { $trackClicks = 'no'; } } $body['o:tracking-clicks'] = $trackClicks; - $body['o:tracking-opens'] = $trackOpens; + $body['o:tracking-opens'] = $trackOpens; // this is the wordpress site tag if (isset($mailgun['tag'])) { - $tags = explode(',', str_replace(' ', '', $mailgun['tag'])); + $tags = explode(',', str_replace(' ', '', $mailgun['tag'])); $body['o:tag'] = $tags; } // campaign-id now refers to a list of tags which will be appended to the site tag - if (!empty($mailgun['campaign-id'])) { + if ( ! empty($mailgun['campaign-id'])) { $tags = explode(',', str_replace(' ', '', $mailgun['campaign-id'])); if (empty($body['o:tag'])) { $body['o:tag'] = $tags; @@ -323,20 +329,20 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) */ $body['o:tag'] = apply_filters('mailgun_tags', $body['o:tag'], $to, $subject, $message, $headers, $attachments, $region, $domain); - if (!empty($cc) && is_array($cc)) { + if ( ! empty($cc) && is_array($cc)) { $body['cc'] = implode(', ', $cc); } - if (!empty($bcc) && is_array($bcc)) { + if ( ! empty($bcc) && is_array($bcc)) { $body['bcc'] = implode(', ', $bcc); } // If we are not given a Content-Type in the supplied headers, // write the message body to a file and try to determine the mimetype // using get_mime_content_type. - if (!isset($content_type)) { + if ( ! isset($content_type)) { $tmppath = tempnam(get_temp_dir(), 'mg'); - $tmp = fopen($tmppath, 'w+'); + $tmp = fopen($tmppath, 'w+'); fwrite($tmp, $message); fclose($tmp); @@ -356,7 +362,7 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) if ('text/plain' === $content_type) { $body['text'] = $message; - } else if ('text/html' === $content_type) { + } elseif ('text/html' === $content_type) { $body['html'] = $message; } else { $body['text'] = $message; @@ -371,14 +377,14 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) global $phpmailer; // (Re)create it, if it's gone missing. - if (!($phpmailer instanceof PHPMailer\PHPMailer\PHPMailer)) { + if ( ! ( $phpmailer instanceof PHPMailer\PHPMailer\PHPMailer )) { require_once ABSPATH . WPINC . '/PHPMailer/PHPMailer.php'; require_once ABSPATH . WPINC . '/PHPMailer/SMTP.php'; require_once ABSPATH . WPINC . '/PHPMailer/Exception.php'; $phpmailer = new PHPMailer\PHPMailer\PHPMailer(true); - $phpmailer::$validator = static function ($email) { - return (bool)is_email($email); + $phpmailer::$validator = static function ( $email ) { + return (bool) is_email($email); }; } @@ -387,7 +393,7 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) * * @param PHPMailer $phpmailer The PHPMailer instance (passed by reference). */ - do_action_ref_array('phpmailer_init', [&$phpmailer]); + do_action_ref_array('phpmailer_init', array( &$phpmailer )); $plainTextMessage = $phpmailer->AltBody; @@ -397,27 +403,27 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) } // If we don't have a charset from the input headers - if (!isset($charset)) { + if ( ! isset($charset)) { $charset = get_bloginfo('charset'); } // Set the content-type and charset $charset = apply_filters('wp_mail_charset', $charset); if (isset($headers['Content-Type'])) { - if (!strstr($headers['Content-Type'], 'charset')) { + if ( ! strstr($headers['Content-Type'], 'charset')) { $headers['Content-Type'] = rtrim($headers['Content-Type'], '; ') . "; charset={$charset}"; } } - $replyTo = (defined('MAILGUN_REPLY_TO_ADDRESS') && MAILGUN_REPLY_TO_ADDRESS) ? MAILGUN_REPLY_TO_ADDRESS : get_option('reply_to'); - if (!empty($replyTo)) { + $replyTo = ( defined('MAILGUN_REPLY_TO_ADDRESS') && MAILGUN_REPLY_TO_ADDRESS ) ? MAILGUN_REPLY_TO_ADDRESS : get_option('reply_to'); + if ( ! empty($replyTo)) { $headers['Reply-To'] = $replyTo; } // Set custom headers - if (!empty($headers)) { - foreach ((array)$headers as $name => $content) { - $body["h:{$name}"] = $content; + if ( ! empty($headers)) { + foreach ( (array) $headers as $name => $content) { + $body[ "h:{$name}" ] = $content; } } @@ -446,17 +452,17 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) $payload .= '--' . $boundary . '--'; - $data = [ - 'body' => $payload, - 'headers' => [ + $data = array( + 'body' => $payload, + 'headers' => array( 'Authorization' => 'Basic ' . base64_encode("api:{$apiKey}"), - 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, - ], - ]; + 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, + ), + ); $endpoint = mg_api_get_region($region); - $endpoint = ($endpoint) ?: 'https://api.mailgun.net/v3/'; - $url = $endpoint . "{$domain}/messages"; + $endpoint = ( $endpoint ) ?: 'https://api.mailgun.net/v3/'; + $url = $endpoint . "{$domain}/messages"; $isFallbackNeeded = false; try { @@ -471,10 +477,10 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) $response_code = wp_remote_retrieve_response_code($response); $response_body = json_decode(wp_remote_retrieve_body($response)); - if ((int)$response_code !== 200 || !isset($response_body->message)) { + if ( (int) $response_code !== 200 || ! isset($response_body->message)) { // Store response code and HTTP response message in last error. $response_message = wp_remote_retrieve_response_message($response); - $errmsg = "$response_code - $response_message"; + $errmsg = "$response_code - $response_message"; mg_api_last_error($errmsg); $isFallbackNeeded = true; @@ -488,20 +494,20 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) $isFallbackNeeded = true; } - //Email Fallback + // Email Fallback if ($isFallbackNeeded) { global $phpmailer; // (Re)create it, if it's gone missing. - if (!($phpmailer instanceof PHPMailer\PHPMailer\PHPMailer)) { + if ( ! ( $phpmailer instanceof PHPMailer\PHPMailer\PHPMailer )) { require_once ABSPATH . WPINC . '/PHPMailer/PHPMailer.php'; require_once ABSPATH . WPINC . '/PHPMailer/SMTP.php'; require_once ABSPATH . WPINC . '/PHPMailer/Exception.php'; $phpmailer = new PHPMailer\PHPMailer\PHPMailer(true); - $phpmailer::$validator = static function ($email) { - return (bool)is_email($email); + $phpmailer::$validator = static function ( $email ) { + return (bool) is_email($email); }; } @@ -510,13 +516,13 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) $phpmailer->clearAttachments(); $phpmailer->clearCustomHeaders(); $phpmailer->clearReplyTos(); - $phpmailer->Body = ''; + $phpmailer->Body = ''; $phpmailer->AltBody = ''; // Set "From" name and email. // If we don't have a name from the input headers. - if (!isset($from_name)) { + if ( ! isset($from_name)) { $from_name = 'WordPress'; } @@ -527,9 +533,9 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) * another option, but some hosts may refuse to relay mail from an unknown domain. * See https://core.trac.wordpress.org/ticket/5007. */ - if (!isset($from_email)) { + if ( ! isset($from_email)) { // Get the site domain and get rid of www. - $sitename = wp_parse_url(network_home_url(), PHP_URL_HOST); + $sitename = wp_parse_url(network_home_url(), PHP_URL_HOST); $from_email = 'wordpress@'; if (null !== $sitename) { @@ -543,6 +549,7 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) /** * Filters the email address to send from. + * * @param string $from_email Email address to send from. * @since 2.2.0 */ @@ -550,6 +557,7 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) /** * Filters the name to associate with the "from" email address. + * * @param string $from_name Name associated with the "from" email address. * @since 2.3.0 */ @@ -558,7 +566,7 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) try { $phpmailer->setFrom($from_email, $from_name, false); } catch (PHPMailer\PHPMailer\Exception $e) { - $mail_error_data = compact('to', 'subject', 'message', 'headers', 'attachments'); + $mail_error_data = compact('to', 'subject', 'message', 'headers', 'attachments'); $mail_error_data['phpmailer_exception_code'] = $e->getCode(); /** This filter is documented in wp-includes/pluggable.php */ @@ -569,7 +577,7 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) // Set mail's subject and body. $phpmailer->Subject = $subject; - $phpmailer->Body = $message; + $phpmailer->Body = $message; // Set destination addresses, using appropriate methods for handling addresses. $address_headers = compact('to', 'cc', 'bcc', 'replyTo'); @@ -579,7 +587,7 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) continue; } - foreach ((array)$addresses as $address) { + foreach ( (array) $addresses as $address) { try { // Break $recipient into name and address parts if in the format "Foo ". $recipient_name = ''; @@ -587,7 +595,7 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) if (preg_match('/(.*)<(.+)>/', $address, $matches)) { if (count($matches) === 3) { $recipient_name = $matches[1]; - $address = $matches[2]; + $address = $matches[2]; } } @@ -617,12 +625,13 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) // Set Content-Type and charset. // If we don't have a Content-Type from the input headers. - if (!isset($content_type)) { + if ( ! isset($content_type)) { $content_type = 'text/plain'; } /** * Filters the wp_mail() content type. + * * @param string $content_type Default wp_mail() content type. * @since 2.3.0 */ @@ -636,22 +645,23 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) } // If we don't have a charset from the input headers. - if (!isset($charset)) { + if ( ! isset($charset)) { $charset = get_bloginfo('charset'); } /** * Filters the default wp_mail() charset. + * * @param string $charset Default email charset. * @since 2.3.0 */ $phpmailer->CharSet = apply_filters('wp_mail_charset', $charset); // Set custom headers. - if (!empty($headers)) { - foreach ((array)$headers as $name => $content) { + if ( ! empty($headers)) { + foreach ( (array) $headers as $name => $content) { // Only add custom headers not added automatically by PHPMailer. - if (!in_array($name, ['MIME-Version', 'X-Mailer'], true)) { + if ( ! in_array($name, array( 'MIME-Version', 'X-Mailer' ), true)) { try { $phpmailer->addCustomHeader(sprintf('%1$s: %2$s', $name, $content)); } catch (PHPMailer\PHPMailer\Exception $e) { @@ -660,12 +670,12 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) } } - if (false !== stripos($content_type, 'multipart') && !empty($boundary)) { + if (false !== stripos($content_type, 'multipart') && ! empty($boundary)) { $phpmailer->addCustomHeader(sprintf('Content-Type: %s; boundary="%s"', $content_type, $boundary)); } } - if (!empty($attachments)) { + if ( ! empty($attachments)) { foreach ($attachments as $filename => $attachment) { $filename = is_string($filename) ? $filename : ''; @@ -679,10 +689,11 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) /** * Fires after PHPMailer is initialized. + * * @param PHPMailer $phpmailer The PHPMailer instance (passed by reference). * @since 2.2.0 */ - do_action_ref_array('phpmailer_init', [&$phpmailer]); + do_action_ref_array('phpmailer_init', array( &$phpmailer )); $mail_data = compact('to', 'subject', 'message', 'headers', 'attachments'); @@ -695,6 +706,7 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) * The firing of this action does not necessarily mean that the recipient(s) received the * email successfully. It only means that the `send` method above was able to * process the request without any errors. + * * @param array $mail_data { * An array containing the email recipient(s), subject, message, headers, and attachments. * @type string[] $to Email addresses to send message. @@ -713,6 +725,7 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) /** * Fires after a PHPMailer\PHPMailer\Exception is caught. + * * @param WP_Error $error A WP_Error object with the PHPMailer\PHPMailer\Exception message, and an array * containing the mail recipient, subject, message, headers, and attachments. * @since 4.4.0 @@ -728,12 +741,11 @@ function wp_mail($to, $subject, $message, $headers = '', $attachments = []) } /** - * @param $body - * @param $boundary + * @param array $body + * @param mixed $boundary * @return string */ -function mg_build_payload_from_body($body, $boundary): string -{ +function mg_build_payload_from_body( $body, $boundary ): string { $payload = ''; // Iterate through pre-built params and build payload: @@ -760,12 +772,11 @@ function mg_build_payload_from_body($body, $boundary): string } /** - * @param $attachments - * @param $boundary + * @param array $attachments + * @param mixed $boundary * @return string|null */ -function mg_build_attachments_payload($attachments, $boundary): ?string -{ +function mg_build_attachments_payload( $attachments, $boundary ): ?string { $payload = ''; if (empty($attachments)) { @@ -774,13 +785,13 @@ function mg_build_attachments_payload($attachments, $boundary): ?string // If we have attachments, add them to the payload. $i = 0; foreach ($attachments as $attachment) { - if (!empty($attachment)) { + if ( ! empty($attachment)) { $payload .= '--' . $boundary; $payload .= "\r\n"; $payload .= 'Content-Disposition: form-data; name="attachment[' . $i . ']"; filename="' . basename($attachment) . '"' . "\r\n\r\n"; $payload .= file_get_contents($attachment); $payload .= "\r\n"; - $i++; + ++$i; } } diff --git a/includes/wp-mail-smtp.php b/includes/wp-mail-smtp.php index d9c1877..cee0db8 100644 --- a/includes/wp-mail-smtp.php +++ b/includes/wp-mail-smtp.php @@ -1,7 +1,6 @@ deactivate_and_die(__DIR__ .'/mg-filter.php'); +if ( ! include __DIR__ . '/mg-filter.php') { + ( new Mailgun() )->deactivate_and_die(__DIR__ . '/mg-filter.php'); } /** @@ -34,15 +35,14 @@ * * @since 1.5.0 */ -function mg_smtp_last_error($error = null) -{ +function mg_smtp_last_error( $error = null ) { static $last_error; if (null === $error) { return $last_error; } - $tmp = $last_error; + $tmp = $last_error; $last_error = $error; return $tmp; @@ -58,8 +58,7 @@ function mg_smtp_last_error($error = null) * * @since 1.5.7 */ -function mg_smtp_debug_output(string $str, $level) -{ +function mg_smtp_debug_output( string $str, $level ) { if (defined('MG_DEBUG_SMTP') && MG_DEBUG_SMTP) { error_log("PHPMailer [$level] $str"); } @@ -75,14 +74,11 @@ function mg_smtp_debug_output(string $str, $level) * * @since 1.5.7 */ -function wp_mail_failed($error) -{ +function wp_mail_failed( $error ) { if (is_wp_error($error)) { mg_smtp_last_error($error->get_error_message()); - } else { - if (method_exists($error, '__toString')) { + } elseif (method_exists($error, '__toString')) { mg_smtp_last_error($error->__toString()); - } } } @@ -96,26 +92,25 @@ function wp_mail_failed($error) * * @since 1.5.8 */ -function mg_smtp_mail_filter(array $args) -{ +function mg_smtp_mail_filter( array $args ) { // Extract the arguments from array to ($to, $subject, $message, $headers, $attachments) extract($args, EXTR_OVERWRITE); // $headers and $attachments are optional - make sure they exist - $headers = (!isset($headers)) ? '' : $headers; - $attachments = (!isset($attachments)) ? [] : $attachments; + $headers = ( ! isset($headers) ) ? '' : $headers; + $attachments = ( ! isset($attachments) ) ? array() : $attachments; - $mg_opts = get_option('mailgun'); + $mg_opts = get_option('mailgun'); $mg_headers = mg_parse_headers($headers); // Filter the `From:` header - $from_header = (isset($mg_headers['From'])) ? $mg_headers['From'][0] : null; + $from_header = ( isset($mg_headers['From']) ) ? $mg_headers['From'][0] : null; - list($from_name, $from_addr) = [null, null]; - if (!is_null($from_header)) { - $content = $from_header['value']; + list($from_name, $from_addr) = array( null, null ); + if ( ! is_null($from_header)) { + $content = $from_header['value']; $boundary = $from_header['boundary']; - $parts = $from_header['parts']; + $parts = $from_header['parts']; if (strpos($content, '<') !== false) { $from_name = substr($content, 0, strpos($content, '<') - 1); @@ -130,11 +125,11 @@ function mg_smtp_mail_filter(array $args) } } - if (!isset($from_name)) { + if ( ! isset($from_name)) { $from_name = null; } - if (!isset($from_addr)) { + if ( ! isset($from_addr)) { $from_addr = null; } @@ -142,11 +137,10 @@ function mg_smtp_mail_filter(array $args) $from_addr = mg_detect_from_address($from_addr); $from_header['value'] = sprintf('%s <%s>', $from_name, $from_addr); - $mg_headers['From'] = [$from_header]; + $mg_headers['From'] = array( $from_header ); // Header compaction $headers = mg_dump_headers($mg_headers); return compact('to', 'subject', 'message', 'headers', 'attachments'); } - diff --git a/mailgun.php b/mailgun.php index 1182ae2..8422de9 100755 --- a/mailgun.php +++ b/mailgun.php @@ -11,6 +11,8 @@ * License: GPLv2 or later * Text Domain: mailgun * Domain Path: /languages/. + * + * @package Mailgun */ /* @@ -39,12 +41,12 @@ * Registers handlers for later actions and sets up config variables with * WordPress. */ -class Mailgun -{ +class Mailgun { + /** * @var Mailgun $instance */ - private static $instance; + private static Mailgun $instance; /** * @var false|mixed|null @@ -54,63 +56,60 @@ class Mailgun /** * @var string */ - protected $plugin_file; + protected string $plugin_file; /** * @var string */ - protected $plugin_basename; + protected string $plugin_basename; /** * @var string */ - protected $assetsDir; + protected string $assetsDir; /** * @var string */ - private $api_endpoint; + private string $api_endpoint; /** * Setup shared functionality for Admin and Front End. - * */ - public function __construct() - { - $this->options = get_option('mailgun'); - $this->plugin_file = __FILE__; - $this->plugin_basename = plugin_basename($this->plugin_file); - $this->assetsDir = plugin_dir_url($this->plugin_file) . 'assets/'; + public function __construct() { + $this->options = get_option( 'mailgun' ); + $this->plugin_file = __FILE__; + $this->plugin_basename = plugin_basename( $this->plugin_file ); + $this->assetsDir = plugin_dir_url( $this->plugin_file ) . 'assets/'; // Either override the wp_mail function or configure PHPMailer to use the // Mailgun SMTP servers // When using SMTP, we also need to inject a `wp_mail` filter to make "from" settings // work properly. Fixed issues with 1.5.7+ - if ($this->get_option('useAPI') || (defined('MAILGUN_USEAPI') && MAILGUN_USEAPI)) { - if (!function_exists('wp_mail')) { - if (!include_once(__DIR__ . '/includes/wp-mail-api.php')) { - $this->deactivate_and_die(__DIR__ . '/includes/wp-mail-api.php'); + if ( $this->get_option( 'useAPI' ) || ( defined( 'MAILGUN_USEAPI' ) && MAILGUN_USEAPI ) ) { + if ( ! function_exists( 'wp_mail' ) ) { + if ( ! include_once __DIR__ . '/includes/wp-mail-api.php' ) { + $this->deactivate_and_die( __DIR__ . '/includes/wp-mail-api.php' ); } } } else { // Using SMTP, include the SMTP filter - if (!function_exists('mg_smtp_mail_filter')) { - if (!include __DIR__ . '/includes/wp-mail-smtp.php') { - $this->deactivate_and_die(__DIR__ . '/includes/wp-mail-smtp.php'); + if ( ! function_exists( 'mg_smtp_mail_filter' ) ) { + if ( ! include __DIR__ . '/includes/wp-mail-smtp.php' ) { + $this->deactivate_and_die( __DIR__ . '/includes/wp-mail-smtp.php' ); } } - add_filter('wp_mail', 'mg_smtp_mail_filter'); - add_action('phpmailer_init', [&$this, 'phpmailer_init']); - add_action('wp_mail_failed', 'wp_mail_failed'); + add_filter( 'wp_mail', 'mg_smtp_mail_filter' ); + add_action( 'phpmailer_init', array( &$this, 'phpmailer_init' ) ); + add_action( 'wp_mail_failed', 'wp_mail_failed' ); } } /** * @return static */ - public static function getInstance() - { - if (!isset(self::$instance)) { + public static function getInstance(): Mailgun { + if ( ! isset( self::$instance ) ) { self::$instance = new self(); } @@ -120,24 +119,21 @@ public static function getInstance() /** * Get specific option from the options table. * - * @param string $option Name of option to be used as array key for retrieving the specific value + * @param string $option Name of option to be used as array key for retrieving the specific value * @param array|null $options Array to iterate over for specific values - * @param bool $default False if no options are set - * + * @param bool $defaultValue Default value to return if option is not found * @return mixed - * */ - public function get_option(string $option, ?array $options = null, bool $default = false) - { - if (is_null($options)) { + public function get_option( string $option, ?array $options = null, bool $defaultValue = false ) { + if ( is_null( $options ) ) { $options = &$this->options; } - if (isset($options[$option])) { - return $options[$option]; + if ( isset( $options[ $option ] ) ) { + return $options[ $option ]; } - return $default; + return $defaultValue; } /** @@ -147,25 +143,23 @@ public function get_option(string $option, ?array $options = null, bool $default * @param object $phpmailer The PHPMailer object to modify by reference * * @return void - * */ - public function phpmailer_init(&$phpmailer) - { - $username = (defined('MAILGUN_USERNAME') && MAILGUN_USERNAME) ? MAILGUN_USERNAME : $this->get_option('username'); - $domain = (defined('MAILGUN_DOMAIN') && MAILGUN_DOMAIN) ? MAILGUN_DOMAIN : $this->get_option('domain'); - $username = preg_replace('/@.+$/', '', $username) . "@{$domain}"; - $secure = (defined('MAILGUN_SECURE') && MAILGUN_SECURE) ? MAILGUN_SECURE : $this->get_option('secure'); - $sectype = (defined('MAILGUN_SECTYPE') && MAILGUN_SECTYPE) ? MAILGUN_SECTYPE : $this->get_option('sectype'); - $password = (defined('MAILGUN_PASSWORD') && MAILGUN_PASSWORD) ? MAILGUN_PASSWORD : $this->get_option('password'); - $region = (defined('MAILGUN_REGION') && MAILGUN_REGION) ? MAILGUN_REGION : $this->get_option('region'); - - $smtp_endpoint = mg_smtp_get_region($region); + public function phpmailer_init( &$phpmailer ): void { + $username = ( defined( 'MAILGUN_USERNAME' ) && MAILGUN_USERNAME ) ? MAILGUN_USERNAME : $this->get_option( 'username' ); + $domain = ( defined( 'MAILGUN_DOMAIN' ) && MAILGUN_DOMAIN ) ? MAILGUN_DOMAIN : $this->get_option( 'domain' ); + $username = preg_replace( '/@.+$/', '', $username ) . "@{$domain}"; + $secure = ( defined( 'MAILGUN_SECURE' ) && MAILGUN_SECURE ) ? MAILGUN_SECURE : $this->get_option( 'secure' ); + $sectype = ( defined( 'MAILGUN_SECTYPE' ) && MAILGUN_SECTYPE ) ? MAILGUN_SECTYPE : $this->get_option( 'sectype' ); + $password = ( defined( 'MAILGUN_PASSWORD' ) && MAILGUN_PASSWORD ) ? MAILGUN_PASSWORD : $this->get_option( 'password' ); + $region = ( defined( 'MAILGUN_REGION' ) && MAILGUN_REGION ) ? MAILGUN_REGION : $this->get_option( 'region' ); + + $smtp_endpoint = mg_smtp_get_region( $region ); $smtp_endpoint = (bool) $smtp_endpoint ? $smtp_endpoint : 'smtp.mailgun.org'; $phpmailer->Mailer = 'smtp'; - $phpmailer->Host = $smtp_endpoint; + $phpmailer->Host = $smtp_endpoint; - if ('ssl' === $sectype) { + if ( 'ssl' === $sectype ) { // For SSL-only connections, use 465 $phpmailer->Port = 465; } else { @@ -180,11 +174,13 @@ public function phpmailer_init(&$phpmailer) $phpmailer->SMTPSecure = (bool) $secure ? $sectype : ''; // Without this line... wp_mail for SMTP-only will always return false. But why? :( $phpmailer->Debugoutput = 'mg_smtp_debug_output'; - $phpmailer->SMTPDebug = 2; + $phpmailer->SMTPDebug = 2; // Emit some logging for SMTP connection - mg_smtp_debug_output(sprintf("PHPMailer configured to send via %s:%s", $phpmailer->Host, $phpmailer->Port), - 'DEBUG'); + mg_smtp_debug_output( + sprintf( 'PHPMailer configured to send via %s:%s', $phpmailer->Host, $phpmailer->Port ), + 'DEBUG' + ); } /** @@ -195,89 +191,87 @@ public function phpmailer_init(&$phpmailer) * * @return void */ - public function deactivate_and_die($file) - { - load_plugin_textdomain('mailgun', false, 'mailgun/languages'); - $message = sprintf(__('Mailgun has been automatically deactivated because the file %s is missing. Please reinstall the plugin and reactivate.'), - $file); - if (!function_exists('deactivate_plugins')) { + public function deactivate_and_die( $file ): void { + load_plugin_textdomain( 'mailgun', false, 'mailgun/languages' ); + $message = sprintf( + __( 'Mailgun has been automatically deactivated because the file %s is missing. Please reinstall the plugin and reactivate.' ), + $file + ); + if ( ! function_exists( 'deactivate_plugins' ) ) { include ABSPATH . 'wp-admin/includes/plugin.php'; } - deactivate_plugins(__FILE__); - wp_die($message); + deactivate_plugins( __FILE__ ); + wp_die( $message ); } /** * Make a Mailgun api call. * - * @param string $uri The endpoint for the Mailgun API - * @param array $params Array of parameters passed to the API - * @param string $method The form request type + * @param string $uri The endpoint for the Mailgun API + * @param array $params Array of parameters passed to the API + * @param string $method The form request type * * @return string - * */ - public function api_call($uri, $params = [], $method = 'POST'): string - { - $options = get_option('mailgun'); - $getRegion = (defined('MAILGUN_REGION') && MAILGUN_REGION) ? MAILGUN_REGION : $options[ 'region' ]; - $apiKey = (defined('MAILGUN_APIKEY') && MAILGUN_APIKEY) ? MAILGUN_APIKEY : $options[ 'apiKey' ]; - $domain = (defined('MAILGUN_DOMAIN') && MAILGUN_DOMAIN) ? MAILGUN_DOMAIN : $options[ 'domain' ]; - - if (!function_exists('mg_api_get_region')) { + public function api_call( string $uri, array $params = array(), string $method = 'POST' ): string { + $options = get_option( 'mailgun' ); + $getRegion = ( defined( 'MAILGUN_REGION' ) && MAILGUN_REGION ) ? MAILGUN_REGION : $options['region']; + $apiKey = ( defined( 'MAILGUN_APIKEY' ) && MAILGUN_APIKEY ) ? MAILGUN_APIKEY : $options['apiKey']; + $domain = ( defined( 'MAILGUN_DOMAIN' ) && MAILGUN_DOMAIN ) ? MAILGUN_DOMAIN : $options['domain']; + + if ( ! function_exists( 'mg_api_get_region' ) ) { include __DIR__ . '/includes/mg-filter.php'; } - $region = mg_api_get_region($getRegion); - $this->api_endpoint = ($region) ?: 'https://api.mailgun.net/v3/'; + $region = mg_api_get_region( $getRegion ); + $this->api_endpoint = ( $region ) ?: 'https://api.mailgun.net/v3/'; - $time = time(); - $url = $this->api_endpoint . $uri; - $headers = [ - 'Authorization' => 'Basic ' . base64_encode("api:{$apiKey}"), - ]; + $time = time(); + $url = $this->api_endpoint . $uri; + $headers = array( + 'Authorization' => 'Basic ' . base64_encode( "api:{$apiKey}" ), + ); - switch ($method) { + switch ( $method ) { case 'GET': - $params[ 'sess' ] = ''; - $querystring = http_build_query($params); - $url = $url . '?' . $querystring; - $params = ''; + $params['sess'] = ''; + $querystring = http_build_query( $params ); + $url = $url . '?' . $querystring; + $params = ''; break; case 'POST': case 'PUT': case 'DELETE': - $params[ 'sess' ] = ''; - $params[ 'time' ] = $time; - $params[ 'hash' ] = sha1(date('U')); + $params['sess'] = ''; + $params['time'] = $time; + $params['hash'] = sha1( date( 'U' ) ); break; } // make the request - $args = [ - 'method' => $method, - 'body' => $params, - 'headers' => $headers, + $args = array( + 'method' => $method, + 'body' => $params, + 'headers' => $headers, 'sslverify' => true, - ]; + ); // make the remote request - $result = wp_remote_request($url, $args); - if (!is_wp_error($result)) { + $result = wp_remote_request( $url, $args ); + if ( ! is_wp_error( $result ) ) { return $result['body']; } - if (is_callable($result)) { + if ( is_callable( $result ) ) { return $result->get_error_message(); } - if (is_array($result)) { - if (isset($result['response'])) { + if ( is_array( $result ) ) { + if ( isset( $result['response'] ) ) { return $result['response']['message'] ?? ''; } } return ''; - } /** @@ -287,14 +281,13 @@ public function api_call($uri, $params = [], $method = 'POST'): string * * @throws JsonException */ - public function get_lists(): array - { - $results = []; + public function get_lists(): array { + $results = array(); - $lists_json = $this->api_call('lists', [], 'GET'); + $lists_json = $this->api_call( 'lists', array(), 'GET' ); - $lists_arr = json_decode($lists_json, true, 512, JSON_THROW_ON_ERROR); - if (isset($lists_arr[ 'items' ]) && !empty($lists_arr[ 'items' ])) { + $lists_arr = json_decode( $lists_json, true, 512, JSON_THROW_ON_ERROR ); + if ( isset( $lists_arr['items'] ) && ! empty( $lists_arr['items'] ) ) { $results = $lists_arr['items']; } @@ -308,44 +301,48 @@ public function get_lists(): array * * @throws JsonException */ - public function add_list() - { - $name = sanitize_text_field($_POST['name'] ?? null); - $email = sanitize_text_field($_POST['email'] ?? null); - $list_addresses = []; - foreach ($_POST['addresses'] as $address => $val) { - $list_addresses[sanitize_text_field($address)] = sanitize_text_field($val); + public function add_list(): void { + $name = sanitize_text_field( $_POST['name'] ?? null ); + $email = sanitize_text_field( $_POST['email'] ?? null ); + $list_addresses = array(); + foreach ( $_POST['addresses'] as $address => $val ) { + $list_addresses[ sanitize_text_field( $address ) ] = sanitize_text_field( $val ); } - if (!empty($list_addresses)) { - $result = []; - foreach ($list_addresses as $address => $val) { + if ( ! empty( $list_addresses ) ) { + $result = array(); + foreach ( $list_addresses as $address => $val ) { $result[] = $this->api_call( "lists/{$address}/members", - [ + array( 'address' => $email, - 'name' => $name, - ] + 'name' => $name, + ) ); } $message = 'Thank you!'; - if ($result) { - $message = 'Something went wrong'; - $response = json_decode($result[0], true); - if (is_array($response) && isset($response['message'])) { + if ( $result ) { + $message = 'Something went wrong'; + $response = json_decode( $result[0], true ); + if ( is_array( $response ) && isset( $response['message'] ) ) { $message = $response['message']; } - - } - echo json_encode([ - 'status' => 200, - 'message' => $message - ], JSON_THROW_ON_ERROR); + } + echo json_encode( + array( + 'status' => 200, + 'message' => $message, + ), + JSON_THROW_ON_ERROR + ); } else { - echo json_encode([ - 'status' => 500, - 'message' => 'Uh oh. We weren\'t able to add you to the list' . count($list_addresses) ? 's.' : '. Please try again.' - ], JSON_THROW_ON_ERROR); + echo json_encode( + array( + 'status' => 500, + 'message' => 'Uh oh. We weren\'t able to add you to the list' . count( $list_addresses ) ? 's.' : '. Please try again.', + ), + JSON_THROW_ON_ERROR + ); } wp_die(); } @@ -354,41 +351,38 @@ public function add_list() * Frontend List Form. * * @param string $list_address Mailgun address list id - * @param array $args widget arguments - * @param array $instance widget instance params - * + * @param array $args widget arguments * @throws JsonException */ - public function list_form(string $list_address, array $args = [], array $instance = []) - { - $widgetId = $args['widget_id'] ?? 0; + public function list_form( string $list_address, array $args = array() ): void { + $widgetId = $args['widget_id'] ?? 0; $widget_class_id = "mailgun-list-widget-{$widgetId}"; - $form_class_id = "list-form-{$widgetId}"; + $form_class_id = "list-form-{$widgetId}"; // List addresses from the plugin config - $list_addresses = array_map('trim', explode(',', $list_address)); + $list_addresses = array_map( 'trim', explode( ',', $list_address ) ); // All list info from the API; used for list info when more than one list is available to subscribe to $all_list_addresses = $this->get_lists(); - ?> -
-
+ ?> +
+
- +

- +

- +

- +

- +

Name: @@ -400,26 +394,26 @@ public function list_form(string $list_address, array $args = [], array $instanc

- '1'): ?> + '1' ) : ?>
    + ?>
  • + name="addresses[]"/>
- - + + - + @@ -429,53 +423,53 @@ public function list_form(string $list_address, array $args = [], array $instanc
list_form($atts['id'], $args); + $this->list_form( $atts['id'], $args ); return ob_get_clean(); } @@ -520,31 +513,29 @@ public function build_list_form(array $atts): string /** * Initialize List Widget. */ - public function load_list_widget() - { - register_widget('list_widget'); - add_shortcode('mailgun', [&$this, 'build_list_form']); + public function load_list_widget() { + register_widget( 'List_Widget' ); + add_shortcode( 'mailgun', array( &$this, 'build_list_form' ) ); } /** * @return string */ - public function getAssetsPath(): string - { + public function getAssetsPath(): string { return $this->assetsDir; } } $mailgun = Mailgun::getInstance(); -if (@include __DIR__ . '/includes/widget.php') { - add_action('widgets_init', [&$mailgun, 'load_list_widget']); - add_action('wp_ajax_nopriv_add_list', [&$mailgun, 'add_list']); - add_action('wp_ajax_add_list', [&$mailgun, 'add_list']); +if (include __DIR__ . '/includes/widget.php' ) { + add_action('widgets_init', array( &$mailgun, 'load_list_widget' )); + add_action('wp_ajax_nopriv_add_list', array( &$mailgun, 'add_list' )); + add_action('wp_ajax_add_list', array( &$mailgun, 'add_list' )); } if (is_admin()) { - if (@include __DIR__ . '/includes/admin.php') { + if (include __DIR__ . '/includes/admin.php') { $mailgunAdmin = new MailgunAdmin(); } else { $mailgun->deactivate_and_die(__DIR__ . '/includes/admin.php'); diff --git a/phpcs.xml.dist b/phpcs.xml.dist new file mode 100644 index 0000000..c9c6acb --- /dev/null +++ b/phpcs.xml.dist @@ -0,0 +1,113 @@ + + + + The Coding standard for the WordPress Coding Standards itself. + + + . + + + */vendor/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file