diff options
author | yehudah <yehudah@b8457f37-d9ea-0310-8a92-e5e31aec5664> | 2017-10-17 19:09:18 +0000 |
---|---|---|
committer | yehudah <yehudah@b8457f37-d9ea-0310-8a92-e5e31aec5664> | 2017-10-17 19:09:18 +0000 |
commit | 0e5055bf5b513df03b0f9ac8bd2810ffe72ed744 (patch) | |
tree | bd07c648e0940a26b9e2b74c55cdc6fe959ead8d | |
parent | 263bc7987e090b0b25d241fa6951f32b8eb2552f (diff) | |
download | Post-SMTP-0e5055bf5b513df03b0f9ac8bd2810ffe72ed744.zip |
= 1.7.6 - 2017-10-17
* Missing sendgrid files
* Fixed: Localization slug
* Fixed: Error sending files with sendgrid
17 files changed, 3120 insertions, 3236 deletions
diff --git a/Postman/Postman-Configuration/PostmanConfigurationController.php b/Postman/Postman-Configuration/PostmanConfigurationController.php index 58d26d7..db63f6b 100644 --- a/Postman/Postman-Configuration/PostmanConfigurationController.php +++ b/Postman/Postman-Configuration/PostmanConfigurationController.php @@ -1,48 +1,48 @@ <?php -require_once ('PostmanRegisterConfigurationSettings.php'); +require_once( 'PostmanRegisterConfigurationSettings.php' ); class PostmanConfigurationController { const CONFIGURATION_SLUG = 'postman/configuration'; const CONFIGURATION_WIZARD_SLUG = 'postman/configuration_wizard'; - + // logging private $logger; private $options; private $settingsRegistry; - + // Holds the values to be used in the fields callbacks private $rootPluginFilenameAndPath; - + /** * Constructor * - * @param unknown $rootPluginFilenameAndPath + * @param unknown $rootPluginFilenameAndPath */ - public function __construct($rootPluginFilenameAndPath) { - assert ( ! empty ( $rootPluginFilenameAndPath ) ); - assert ( PostmanUtils::isAdmin () ); - assert ( is_admin () ); - - $this->logger = new PostmanLogger ( get_class ( $this ) ); + public function __construct( $rootPluginFilenameAndPath ) { + assert( ! empty( $rootPluginFilenameAndPath ) ); + assert( PostmanUtils::isAdmin() ); + assert( is_admin() ); + + $this->logger = new PostmanLogger( get_class( $this ) ); $this->rootPluginFilenameAndPath = $rootPluginFilenameAndPath; - $this->options = PostmanOptions::getInstance (); - $this->settingsRegistry = new PostmanSettingsRegistry (); - - PostmanUtils::registerAdminMenu ( $this, 'addConfigurationSubmenu' ); - PostmanUtils::registerAdminMenu ( $this, 'addSetupWizardSubmenu' ); - + $this->options = PostmanOptions::getInstance(); + $this->settingsRegistry = new PostmanSettingsRegistry(); + + PostmanUtils::registerAdminMenu( $this, 'addConfigurationSubmenu' ); + PostmanUtils::registerAdminMenu( $this, 'addSetupWizardSubmenu' ); + // hook on the init event - add_action ( 'init', array ( + add_action( 'init', array( $this, - 'on_init' + 'on_init', ) ); - + // initialize the scripts, stylesheets and form fields - add_action ( 'admin_init', array ( + add_action( 'admin_init', array( $this, - 'on_admin_init' + 'on_admin_init', ) ); } - + /** * Functions to execute on the init event * @@ -51,189 +51,187 @@ class PostmanConfigurationController { */ public function on_init() { // register Ajax handlers - new PostmanGetHostnameByEmailAjaxController (); - new PostmanManageConfigurationAjaxHandler (); - new PostmanImportConfigurationAjaxController ( $this->options ); + new PostmanGetHostnameByEmailAjaxController(); + new PostmanManageConfigurationAjaxHandler(); + new PostmanImportConfigurationAjaxController( $this->options ); } - + /** * Fires on the admin_init method */ public function on_admin_init() { - // - $this->registerStylesAndScripts (); - $this->settingsRegistry->on_admin_init (); + $this->registerStylesAndScripts(); + $this->settingsRegistry->on_admin_init(); } - + /** * Register and add settings */ private function registerStylesAndScripts() { - if ($this->logger->isTrace ()) { - $this->logger->trace ( 'registerStylesAndScripts()' ); + if ( $this->logger->isTrace() ) { + $this->logger->trace( 'registerStylesAndScripts()' ); } // register the stylesheet and javascript external resources - $pluginData = apply_filters ( 'postman_get_plugin_metadata', null ); - wp_register_script ( 'postman_manual_config_script', plugins_url ( 'Postman/Postman-Configuration/postman_manual_config.js', $this->rootPluginFilenameAndPath ), array ( + $pluginData = apply_filters( 'postman_get_plugin_metadata', null ); + wp_register_script( 'postman_manual_config_script', plugins_url( 'Postman/Postman-Configuration/postman_manual_config.js', $this->rootPluginFilenameAndPath ), array( PostmanViewController::JQUERY_SCRIPT, 'jquery_validation', - PostmanViewController::POSTMAN_SCRIPT + PostmanViewController::POSTMAN_SCRIPT, ), $pluginData ['version'] ); - wp_register_script ( 'postman_wizard_script', plugins_url ( 'Postman/Postman-Configuration/postman_wizard.js', $this->rootPluginFilenameAndPath ), array ( + wp_register_script( 'postman_wizard_script', plugins_url( 'Postman/Postman-Configuration/postman_wizard.js', $this->rootPluginFilenameAndPath ), array( PostmanViewController::JQUERY_SCRIPT, 'jquery_validation', 'jquery_steps_script', PostmanViewController::POSTMAN_SCRIPT, - 'sprintf' + 'sprintf', ), $pluginData ['version'] ); } - + /** */ private function addLocalizeScriptsToPage() { - $warning = __ ( 'Warning', Postman::TEXT_DOMAIN ); + $warning = __( 'Warning', Postman::TEXT_DOMAIN ); /* translators: where %s is the name of the SMTP server */ - wp_localize_script ( 'postman_wizard_script', 'postman_smtp_mitm', sprintf ( '%s: %s', $warning, __ ( 'connected to %1$s instead of %2$s.', Postman::TEXT_DOMAIN ) ) ); + wp_localize_script( 'postman_wizard_script', 'postman_smtp_mitm', sprintf( '%s: %s', $warning, __( 'connected to %1$s instead of %2$s.', Postman::TEXT_DOMAIN ) ) ); /* translators: where %d is a port number */ - wp_localize_script ( 'postman_wizard_script', 'postman_wizard_bad_redirect_url', __ ( 'You are about to configure OAuth 2.0 with an IP address instead of a domain name. This is not permitted. Either assign a real domain name to your site or add a fake one in your local host file.', Postman::TEXT_DOMAIN ) ); - + wp_localize_script( 'postman_wizard_script', 'postman_wizard_bad_redirect_url', __( 'You are about to configure OAuth 2.0 with an IP address instead of a domain name. This is not permitted. Either assign a real domain name to your site or add a fake one in your local host file.', Postman::TEXT_DOMAIN ) ); + // user input - wp_localize_script ( PostmanViewController::POSTMAN_SCRIPT, 'postman_input_sender_email', '#input_' . PostmanOptions::MESSAGE_SENDER_EMAIL ); - wp_localize_script ( PostmanViewController::POSTMAN_SCRIPT, 'postman_input_sender_name', '#input_' . PostmanOptions::MESSAGE_SENDER_NAME ); - wp_localize_script ( PostmanViewController::POSTMAN_SCRIPT, 'postman_port_element_name', '#input_' . PostmanOptions::PORT ); - wp_localize_script ( PostmanViewController::POSTMAN_SCRIPT, 'postman_hostname_element_name', '#input_' . PostmanOptions::HOSTNAME ); - + wp_localize_script( PostmanViewController::POSTMAN_SCRIPT, 'postman_input_sender_email', '#input_' . PostmanOptions::MESSAGE_SENDER_EMAIL ); + wp_localize_script( PostmanViewController::POSTMAN_SCRIPT, 'postman_input_sender_name', '#input_' . PostmanOptions::MESSAGE_SENDER_NAME ); + wp_localize_script( PostmanViewController::POSTMAN_SCRIPT, 'postman_port_element_name', '#input_' . PostmanOptions::PORT ); + wp_localize_script( PostmanViewController::POSTMAN_SCRIPT, 'postman_hostname_element_name', '#input_' . PostmanOptions::HOSTNAME ); + // the enc input - wp_localize_script ( PostmanViewController::POSTMAN_SCRIPT, 'postman_enc_for_password_el', '#input_enc_type_password' ); + wp_localize_script( PostmanViewController::POSTMAN_SCRIPT, 'postman_enc_for_password_el', '#input_enc_type_password' ); // these are the ids for the <option>s in the encryption <select> - // the password inputs - wp_localize_script ( PostmanViewController::POSTMAN_SCRIPT, 'postman_input_basic_username', '#input_' . PostmanOptions::BASIC_AUTH_USERNAME ); - wp_localize_script ( PostmanViewController::POSTMAN_SCRIPT, 'postman_input_basic_password', '#input_' . PostmanOptions::BASIC_AUTH_PASSWORD ); - + wp_localize_script( PostmanViewController::POSTMAN_SCRIPT, 'postman_input_basic_username', '#input_' . PostmanOptions::BASIC_AUTH_USERNAME ); + wp_localize_script( PostmanViewController::POSTMAN_SCRIPT, 'postman_input_basic_password', '#input_' . PostmanOptions::BASIC_AUTH_PASSWORD ); + // the auth input - wp_localize_script ( PostmanViewController::POSTMAN_SCRIPT, 'postman_redirect_url_el', '#input_oauth_redirect_url' ); - wp_localize_script ( PostmanViewController::POSTMAN_SCRIPT, 'postman_input_auth_type', '#input_' . PostmanOptions::AUTHENTICATION_TYPE ); - + wp_localize_script( PostmanViewController::POSTMAN_SCRIPT, 'postman_redirect_url_el', '#input_oauth_redirect_url' ); + wp_localize_script( PostmanViewController::POSTMAN_SCRIPT, 'postman_input_auth_type', '#input_' . PostmanOptions::AUTHENTICATION_TYPE ); + // the transport modules scripts - foreach ( PostmanTransportRegistry::getInstance ()->getTransports () as $transport ) { - $transport->enqueueScript (); + foreach ( PostmanTransportRegistry::getInstance()->getTransports() as $transport ) { + $transport->enqueueScript(); } // we need data from port test - PostmanConnectivityTestController::addLocalizeScriptForPortTest (); - + PostmanConnectivityTestController::addLocalizeScriptForPortTest(); + } - + /** * Register the Configuration screen */ public function addConfigurationSubmenu() { - $page = add_submenu_page ( null, sprintf ( __ ( '%s Setup', Postman::TEXT_DOMAIN ), __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ) ), __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ), Postman::MANAGE_POSTMAN_CAPABILITY_NAME, PostmanConfigurationController::CONFIGURATION_SLUG, array ( + $page = add_submenu_page( null, sprintf( __( '%s Setup', Postman::TEXT_DOMAIN ), __( 'Postman SMTP', Postman::TEXT_DOMAIN ) ), __( 'Postman SMTP', Postman::TEXT_DOMAIN ), Postman::MANAGE_POSTMAN_CAPABILITY_NAME, PostmanConfigurationController::CONFIGURATION_SLUG, array( $this, - 'outputManualConfigurationContent' + 'outputManualConfigurationContent', ) ); // When the plugin options page is loaded, also load the stylesheet - add_action ( 'admin_print_styles-' . $page, array ( + add_action( 'admin_print_styles-' . $page, array( $this, - 'enqueueConfigurationResources' + 'enqueueConfigurationResources', ) ); } - + /** */ function enqueueConfigurationResources() { - $this->addLocalizeScriptsToPage (); - wp_enqueue_style ( PostmanViewController::POSTMAN_STYLE ); - wp_enqueue_style ( 'jquery_ui_style' ); - wp_enqueue_script ( 'postman_manual_config_script' ); - wp_enqueue_script ( 'jquery-ui-tabs' ); + $this->addLocalizeScriptsToPage(); + wp_enqueue_style( PostmanViewController::POSTMAN_STYLE ); + wp_enqueue_style( 'jquery_ui_style' ); + wp_enqueue_script( 'postman_manual_config_script' ); + wp_enqueue_script( 'jquery-ui-tabs' ); } - + /** * Register the Setup Wizard screen */ public function addSetupWizardSubmenu() { - $page = add_submenu_page ( null, sprintf ( __ ( '%s Setup', Postman::TEXT_DOMAIN ), __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ) ), __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ), Postman::MANAGE_POSTMAN_CAPABILITY_NAME, PostmanConfigurationController::CONFIGURATION_WIZARD_SLUG, array ( + $page = add_submenu_page( null, sprintf( __( '%s Setup', Postman::TEXT_DOMAIN ), __( 'Postman SMTP', Postman::TEXT_DOMAIN ) ), __( 'Postman SMTP', Postman::TEXT_DOMAIN ), Postman::MANAGE_POSTMAN_CAPABILITY_NAME, PostmanConfigurationController::CONFIGURATION_WIZARD_SLUG, array( $this, - 'outputWizardContent' + 'outputWizardContent', ) ); // When the plugin options page is loaded, also load the stylesheet - add_action ( 'admin_print_styles-' . $page, array ( + add_action( 'admin_print_styles-' . $page, array( $this, - 'enqueueWizardResources' + 'enqueueWizardResources', ) ); } - + /** */ function enqueueWizardResources() { - $this->addLocalizeScriptsToPage (); - $this->importableConfiguration = new PostmanImportableConfiguration (); + $this->addLocalizeScriptsToPage(); + $this->importableConfiguration = new PostmanImportableConfiguration(); $startPage = 1; - if ($this->importableConfiguration->isImportAvailable ()) { + if ( $this->importableConfiguration->isImportAvailable() ) { $startPage = 0; } - wp_localize_script ( PostmanViewController::POSTMAN_SCRIPT, 'postman_setup_wizard', array ( - 'start_page' => $startPage + wp_localize_script( PostmanViewController::POSTMAN_SCRIPT, 'postman_setup_wizard', array( + 'start_page' => $startPage, ) ); - wp_enqueue_style ( 'jquery_steps_style' ); - wp_enqueue_style ( PostmanViewController::POSTMAN_STYLE ); - wp_enqueue_script ( 'postman_wizard_script' ); - wp_localize_script ( PostmanViewController::POSTMAN_SCRIPT, '$jq', 'jQuery.noConflict(true)' ); - $shortLocale = substr ( get_locale (), 0, 2 ); - if ($shortLocale != 'en') { - $url = plugins_url ( sprintf ( 'script/jquery-validate/localization/messages_%s.js', $shortLocale ), $this->rootPluginFilenameAndPath ); - wp_enqueue_script ( sprintf ( 'jquery-validation-locale-%s', $shortLocale ), $url ); + wp_enqueue_style( 'jquery_steps_style' ); + wp_enqueue_style( PostmanViewController::POSTMAN_STYLE ); + wp_enqueue_script( 'postman_wizard_script' ); + wp_localize_script( PostmanViewController::POSTMAN_SCRIPT, '$jq', 'jQuery.noConflict(true)' ); + $shortLocale = substr( get_locale(), 0, 2 ); + if ( $shortLocale != 'en' ) { + $url = plugins_url( sprintf( 'script/jquery-validate/localization/messages_%s.js', $shortLocale ), $this->rootPluginFilenameAndPath ); + wp_enqueue_script( sprintf( 'jquery-validation-locale-%s', $shortLocale ), $url ); } } - + /** */ public function outputManualConfigurationContent() { print '<div class="wrap">'; - - PostmanViewController::outputChildPageHeader ( __ ( 'Settings', Postman::TEXT_DOMAIN ), 'advanced_config' ); + + PostmanViewController::outputChildPageHeader( __( 'Settings', Postman::TEXT_DOMAIN ), 'advanced_config' ); print '<div id="config_tabs"><ul>'; - print sprintf ( '<li><a href="#account_config">%s</a></li>', __ ( 'Account', Postman::TEXT_DOMAIN ) ); - print sprintf ( '<li><a href="#message_config">%s</a></li>', __ ( 'Message', Postman::TEXT_DOMAIN ) ); - print sprintf ( '<li><a href="#logging_config">%s</a></li>', __ ( 'Logging', Postman::TEXT_DOMAIN ) ); - print sprintf ( '<li><a href="#advanced_options_config">%s</a></li>', __ ( 'Advanced', Postman::TEXT_DOMAIN ) ); + print sprintf( '<li><a href="#account_config">%s</a></li>', __( 'Account', Postman::TEXT_DOMAIN ) ); + print sprintf( '<li><a href="#message_config">%s</a></li>', __( 'Message', Postman::TEXT_DOMAIN ) ); + print sprintf( '<li><a href="#logging_config">%s</a></li>', __( 'Logging', Postman::TEXT_DOMAIN ) ); + print sprintf( '<li><a href="#advanced_options_config">%s</a></li>', __( 'Advanced', Postman::TEXT_DOMAIN ) ); print '</ul>'; print '<form method="post" action="options.php">'; // This prints out all hidden setting fields - settings_fields ( PostmanAdminController::SETTINGS_GROUP_NAME ); + settings_fields( PostmanAdminController::SETTINGS_GROUP_NAME ); print '<section id="account_config">'; - if (sizeof ( PostmanTransportRegistry::getInstance ()->getTransports () ) > 1) { - do_settings_sections ( 'transport_options' ); + if ( sizeof( PostmanTransportRegistry::getInstance()->getTransports() ) > 1 ) { + do_settings_sections( 'transport_options' ); } else { - printf ( '<input id="input_%2$s" type="hidden" name="%1$s[%2$s]" value="%3$s"/>', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::TRANSPORT_TYPE, PostmanSmtpModuleTransport::SLUG ); + printf( '<input id="input_%2$s" type="hidden" name="%1$s[%2$s]" value="%3$s"/>', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::TRANSPORT_TYPE, PostmanSmtpModuleTransport::SLUG ); } print '<div id="smtp_config" class="transport_setting">'; - do_settings_sections ( PostmanAdminController::SMTP_OPTIONS ); + do_settings_sections( PostmanAdminController::SMTP_OPTIONS ); print '</div>'; print '<div id="password_settings" class="authentication_setting non-oauth2">'; - do_settings_sections ( PostmanAdminController::BASIC_AUTH_OPTIONS ); + do_settings_sections( PostmanAdminController::BASIC_AUTH_OPTIONS ); print '</div>'; print '<div id="oauth_settings" class="authentication_setting non-basic">'; - do_settings_sections ( PostmanAdminController::OAUTH_AUTH_OPTIONS ); + do_settings_sections( PostmanAdminController::OAUTH_AUTH_OPTIONS ); print '</div>'; print '<div id="mandrill_settings" class="authentication_setting non-basic non-oauth2">'; - do_settings_sections ( PostmanMandrillTransport::MANDRILL_AUTH_OPTIONS ); + do_settings_sections( PostmanMandrillTransport::MANDRILL_AUTH_OPTIONS ); print '</div>'; print '<div id="sendgrid_settings" class="authentication_setting non-basic non-oauth2">'; - do_settings_sections ( PostmanSendGridTransport::SENDGRID_AUTH_OPTIONS ); + do_settings_sections( PostmanSendGridTransport::SENDGRID_AUTH_OPTIONS ); print '</div>'; print '</section>'; print '<section id="message_config">'; - do_settings_sections ( PostmanAdminController::MESSAGE_SENDER_OPTIONS ); - do_settings_sections ( PostmanAdminController::MESSAGE_FROM_OPTIONS ); - do_settings_sections ( PostmanAdminController::EMAIL_VALIDATION_OPTIONS ); - do_settings_sections ( PostmanAdminController::MESSAGE_OPTIONS ); - do_settings_sections ( PostmanAdminController::MESSAGE_HEADERS_OPTIONS ); + do_settings_sections( PostmanAdminController::MESSAGE_SENDER_OPTIONS ); + do_settings_sections( PostmanAdminController::MESSAGE_FROM_OPTIONS ); + do_settings_sections( PostmanAdminController::EMAIL_VALIDATION_OPTIONS ); + do_settings_sections( PostmanAdminController::MESSAGE_OPTIONS ); + do_settings_sections( PostmanAdminController::MESSAGE_HEADERS_OPTIONS ); print '</section>'; print '<section id="logging_config">'; - do_settings_sections ( PostmanAdminController::LOGGING_OPTIONS ); + do_settings_sections( PostmanAdminController::LOGGING_OPTIONS ); print '</section>'; /* * print '<section id="logging_config">'; @@ -241,133 +239,132 @@ class PostmanConfigurationController { * print '</section>'; */ print '<section id="advanced_options_config">'; - do_settings_sections ( PostmanAdminController::NETWORK_OPTIONS ); - do_settings_sections ( PostmanAdminController::ADVANCED_OPTIONS ); + do_settings_sections( PostmanAdminController::NETWORK_OPTIONS ); + do_settings_sections( PostmanAdminController::ADVANCED_OPTIONS ); print '</section>'; - submit_button (); + submit_button(); print '</form>'; print '</div>'; print '</div>'; } - + /** */ public function outputWizardContent() { // Set default values for input fields - $this->options->setMessageSenderEmailIfEmpty ( wp_get_current_user ()->user_email ); - $this->options->setMessageSenderNameIfEmpty ( wp_get_current_user ()->display_name ); - + $this->options->setMessageSenderEmailIfEmpty( wp_get_current_user()->user_email ); + $this->options->setMessageSenderNameIfEmpty( wp_get_current_user()->display_name ); + // construct Wizard print '<div class="wrap">'; - - PostmanViewController::outputChildPageHeader ( __ ( 'Setup Wizard', Postman::TEXT_DOMAIN ) ); - + + PostmanViewController::outputChildPageHeader( __( 'Setup Wizard', Postman::TEXT_DOMAIN ) ); + print '<form id="postman_wizard" method="post" action="options.php">'; - + // account tab - // message tab - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::PREVENT_MESSAGE_SENDER_EMAIL_OVERRIDE, $this->options->isPluginSenderEmailEnforced () ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::PREVENT_MESSAGE_SENDER_NAME_OVERRIDE, $this->options->isPluginSenderNameEnforced () ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::REPLY_TO, $this->options->getReplyTo () ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::FORCED_TO_RECIPIENTS, $this->options->getForcedToRecipients () ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::FORCED_CC_RECIPIENTS, $this->options->getForcedCcRecipients () ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::FORCED_BCC_RECIPIENTS, $this->options->getForcedBccRecipients () ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::ADDITIONAL_HEADERS, $this->options->getAdditionalHeaders () ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::DISABLE_EMAIL_VALIDAITON, $this->options->isEmailValidationDisabled () ); - + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::PREVENT_MESSAGE_SENDER_EMAIL_OVERRIDE, $this->options->isPluginSenderEmailEnforced() ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::PREVENT_MESSAGE_SENDER_NAME_OVERRIDE, $this->options->isPluginSenderNameEnforced() ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::REPLY_TO, $this->options->getReplyTo() ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::FORCED_TO_RECIPIENTS, $this->options->getForcedToRecipients() ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::FORCED_CC_RECIPIENTS, $this->options->getForcedCcRecipients() ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::FORCED_BCC_RECIPIENTS, $this->options->getForcedBccRecipients() ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::ADDITIONAL_HEADERS, $this->options->getAdditionalHeaders() ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::DISABLE_EMAIL_VALIDAITON, $this->options->isEmailValidationDisabled() ); + // logging tab - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::MAIL_LOG_ENABLED_OPTION, $this->options->getMailLoggingEnabled () ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::MAIL_LOG_MAX_ENTRIES, $this->options->getMailLoggingMaxEntries () ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::TRANSCRIPT_SIZE, $this->options->getTranscriptSize () ); - + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::MAIL_LOG_ENABLED_OPTION, $this->options->getMailLoggingEnabled() ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::MAIL_LOG_MAX_ENTRIES, $this->options->getMailLoggingMaxEntries() ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::TRANSCRIPT_SIZE, $this->options->getTranscriptSize() ); + // advanced tab - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::CONNECTION_TIMEOUT, $this->options->getConnectionTimeout () ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::READ_TIMEOUT, $this->options->getReadTimeout () ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::LOG_LEVEL, $this->options->getLogLevel () ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::RUN_MODE, $this->options->getRunMode () ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::STEALTH_MODE, $this->options->isStealthModeEnabled () ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::TEMPORARY_DIRECTORY, $this->options->getTempDirectory () ); - + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::CONNECTION_TIMEOUT, $this->options->getConnectionTimeout() ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::READ_TIMEOUT, $this->options->getReadTimeout() ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::LOG_LEVEL, $this->options->getLogLevel() ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::RUN_MODE, $this->options->getRunMode() ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::STEALTH_MODE, $this->options->isStealthModeEnabled() ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]" value="%3$s" />', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::TEMPORARY_DIRECTORY, $this->options->getTempDirectory() ); + // display the setting text - settings_fields ( PostmanAdminController::SETTINGS_GROUP_NAME ); - + settings_fields( PostmanAdminController::SETTINGS_GROUP_NAME ); + // Wizard Step 0 - printf ( '<h5>%s</h5>', _x ( 'Import Configuration', 'Wizard Step Title', Postman::TEXT_DOMAIN ) ); + printf( '<h5>%s</h5>', _x( 'Import Configuration', 'Wizard Step Title', Postman::TEXT_DOMAIN ) ); print '<fieldset>'; - printf ( '<legend>%s</legend>', _x ( 'Import configuration from another plugin?', 'Wizard Step Title', Postman::TEXT_DOMAIN ) ); - printf ( '<p>%s</p>', __ ( 'If you had a working configuration with another Plugin, the Setup Wizard can begin with those settings.', Postman::TEXT_DOMAIN ) ); + printf( '<legend>%s</legend>', _x( 'Import configuration from another plugin?', 'Wizard Step Title', Postman::TEXT_DOMAIN ) ); + printf( '<p>%s</p>', __( 'If you had a working configuration with another Plugin, the Setup Wizard can begin with those settings.', Postman::TEXT_DOMAIN ) ); print '<table class="input_auth_type">'; - printf ( '<tr><td><input type="radio" id="import_none" name="input_plugin" value="%s" checked="checked"></input></td><td><label> %s</label></td></tr>', 'none', __ ( 'None', Postman::TEXT_DOMAIN ) ); - - if ($this->importableConfiguration->isImportAvailable ()) { - foreach ( $this->importableConfiguration->getAvailableOptions () as $options ) { - printf ( '<tr><td><input type="radio" name="input_plugin" value="%s"/></td><td><label> %s</label></td></tr>', $options->getPluginSlug (), $options->getPluginName () ); + printf( '<tr><td><input type="radio" id="import_none" name="input_plugin" value="%s" checked="checked"></input></td><td><label> %s</label></td></tr>', 'none', __( 'None', Postman::TEXT_DOMAIN ) ); + + if ( $this->importableConfiguration->isImportAvailable() ) { + foreach ( $this->importableConfiguration->getAvailableOptions() as $options ) { + printf( '<tr><td><input type="radio" name="input_plugin" value="%s"/></td><td><label> %s</label></td></tr>', $options->getPluginSlug(), $options->getPluginName() ); } } print '</table>'; print '</fieldset>'; - + // Wizard Step 1 - printf ( '<h5>%s</h5>', _x ( 'Sender Details', 'Wizard Step Title', Postman::TEXT_DOMAIN ) ); + printf( '<h5>%s</h5>', _x( 'Sender Details', 'Wizard Step Title', Postman::TEXT_DOMAIN ) ); print '<fieldset>'; - printf ( '<legend>%s</legend>', _x ( 'Who is the mail coming from?', 'Wizard Step Title', Postman::TEXT_DOMAIN ) ); - printf ( '<p>%s</p>', __ ( 'Enter the email address and name you\'d like to send mail as.', Postman::TEXT_DOMAIN ) ); - printf ( '<p>%s</p>', __ ( 'Please note that to prevent abuse, many email services will <em>not</em> let you send from an email address other than the one you authenticate with.', Postman::TEXT_DOMAIN ) ); - printf ( '<label for="postman_options[sender_email]">%s</label>', __ ( 'Email Address', Postman::TEXT_DOMAIN ) ); - print $this->settingsRegistry->from_email_callback (); + printf( '<legend>%s</legend>', _x( 'Who is the mail coming from?', 'Wizard Step Title', Postman::TEXT_DOMAIN ) ); + printf( '<p>%s</p>', __( 'Enter the email address and name you\'d like to send mail as.', Postman::TEXT_DOMAIN ) ); + printf( '<p>%s</p>', __( 'Please note that to prevent abuse, many email services will <em>not</em> let you send from an email address other than the one you authenticate with.', Postman::TEXT_DOMAIN ) ); + printf( '<label for="postman_options[sender_email]">%s</label>', __( 'Email Address', Postman::TEXT_DOMAIN ) ); + print $this->settingsRegistry->from_email_callback(); print '<br/>'; - printf ( '<label for="postman_options[sender_name]">%s</label>', __ ( 'Name', Postman::TEXT_DOMAIN ) ); - print $this->settingsRegistry->sender_name_callback (); + printf( '<label for="postman_options[sender_name]">%s</label>', __( 'Name', Postman::TEXT_DOMAIN ) ); + print $this->settingsRegistry->sender_name_callback(); print '</fieldset>'; - + // Wizard Step 2 - printf ( '<h5>%s</h5>', __ ( 'Outgoing Mail Server Hostname', Postman::TEXT_DOMAIN ) ); + printf( '<h5>%s</h5>', __( 'Outgoing Mail Server Hostname', Postman::TEXT_DOMAIN ) ); print '<fieldset>'; - foreach ( PostmanTransportRegistry::getInstance ()->getTransports () as $transport ) { - $transport->printWizardMailServerHostnameStep (); + foreach ( PostmanTransportRegistry::getInstance()->getTransports() as $transport ) { + $transport->printWizardMailServerHostnameStep(); } print '</fieldset>'; - + // Wizard Step 3 - printf ( '<h5>%s</h5>', __ ( 'Connectivity Test', Postman::TEXT_DOMAIN ) ); + printf( '<h5>%s</h5>', __( 'Connectivity Test', Postman::TEXT_DOMAIN ) ); print '<fieldset>'; - printf ( '<legend>%s</legend>', __ ( 'How will the connection to the mail server be established?', Postman::TEXT_DOMAIN ) ); - printf ( '<p>%s</p>', __ ( 'Your connection settings depend on what your email service provider offers, and what your WordPress host allows.', Postman::TEXT_DOMAIN ) ); - printf ( '<p id="connectivity_test_status">%s: <span id="port_test_status">%s</span></p>', __ ( 'Connectivity Test', Postman::TEXT_DOMAIN ), _x ( 'Ready', 'TCP Port Test Status', Postman::TEXT_DOMAIN ) ); - printf ( '<p class="ajax-loader" style="display:none"><img src="%s"/></p>', plugins_url ( 'postman-smtp/style/ajax-loader.gif' ) ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]">', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::TRANSPORT_TYPE ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]">', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::PORT ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]">', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::SECURITY_TYPE ); - printf ( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]">', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::AUTHENTICATION_TYPE ); + printf( '<legend>%s</legend>', __( 'How will the connection to the mail server be established?', Postman::TEXT_DOMAIN ) ); + printf( '<p>%s</p>', __( 'Your connection settings depend on what your email service provider offers, and what your WordPress host allows.', Postman::TEXT_DOMAIN ) ); + printf( '<p id="connectivity_test_status">%s: <span id="port_test_status">%s</span></p>', __( 'Connectivity Test', Postman::TEXT_DOMAIN ), _x( 'Ready', 'TCP Port Test Status', Postman::TEXT_DOMAIN ) ); + printf( '<p class="ajax-loader" style="display:none"><img src="%s"/></p>', plugins_url( 'post-smtp/style/ajax-loader.gif' ) ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]">', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::TRANSPORT_TYPE ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]">', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::PORT ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]">', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::SECURITY_TYPE ); + printf( '<input type="hidden" id="input_%2$s" name="%1$s[%2$s]">', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::AUTHENTICATION_TYPE ); print '<p id="wizard_recommendation"></p>'; /* Translators: Where %1$s is the socket identifier and %2$s is the authentication type */ - printf ( '<p class="user_override" style="display:none"><label><span>%s:</span></label> <table id="user_socket_override" class="user_override"></table></p>', _x ( 'Socket', 'A socket is the network term for host and port together', Postman::TEXT_DOMAIN ) ); - printf ( '<p class="user_override" style="display:none"><label><span>%s:</span></label> <table id="user_auth_override" class="user_override"></table></p>', __ ( 'Authentication', Postman::TEXT_DOMAIN ) ); + printf( '<p class="user_override" style="display:none"><label><span>%s:</span></label> <table id="user_socket_override" class="user_override"></table></p>', _x( 'Socket', 'A socket is the network term for host and port together', Postman::TEXT_DOMAIN ) ); + printf( '<p class="user_override" style="display:none"><label><span>%s:</span></label> <table id="user_auth_override" class="user_override"></table></p>', __( 'Authentication', Postman::TEXT_DOMAIN ) ); print ('<p><span id="smtp_mitm" style="display:none; background-color:yellow"></span></p>') ; - $warning = __ ( 'Warning', Postman::TEXT_DOMAIN ); - $clearCredentialsWarning = __ ( 'This configuration option will send your authorization credentials in the clear.', Postman::TEXT_DOMAIN ); - printf ( '<p id="smtp_not_secure" style="display:none"><span style="background-color:yellow">%s: %s</span></p>', $warning, $clearCredentialsWarning ); + $warning = __( 'Warning', Postman::TEXT_DOMAIN ); + $clearCredentialsWarning = __( 'This configuration option will send your authorization credentials in the clear.', Postman::TEXT_DOMAIN ); + printf( '<p id="smtp_not_secure" style="display:none"><span style="background-color:yellow">%s: %s</span></p>', $warning, $clearCredentialsWarning ); print '</fieldset>'; - + // Wizard Step 4 - printf ( '<h5>%s</h5>', __ ( 'Authentication', Postman::TEXT_DOMAIN ) ); + printf( '<h5>%s</h5>', __( 'Authentication', Postman::TEXT_DOMAIN ) ); print '<fieldset>'; - printf ( '<legend>%s</legend>', __ ( 'How will you prove your identity to the mail server?', Postman::TEXT_DOMAIN ) ); - foreach ( PostmanTransportRegistry::getInstance ()->getTransports () as $transport ) { - $transport->printWizardAuthenticationStep (); + printf( '<legend>%s</legend>', __( 'How will you prove your identity to the mail server?', Postman::TEXT_DOMAIN ) ); + foreach ( PostmanTransportRegistry::getInstance()->getTransports() as $transport ) { + $transport->printWizardAuthenticationStep(); } print '</fieldset>'; - + // Wizard Step 5 - printf ( '<h5>%s</h5>', _x ( 'Finish', 'The final step of the Wizard', Postman::TEXT_DOMAIN ) ); + printf( '<h5>%s</h5>', _x( 'Finish', 'The final step of the Wizard', Postman::TEXT_DOMAIN ) ); print '<fieldset>'; - printf ( '<legend>%s</legend>', _x ( 'You\'re Done!', 'Wizard Step Title', Postman::TEXT_DOMAIN ) ); + printf( '<legend>%s</legend>', _x( 'You\'re Done!', 'Wizard Step Title', Postman::TEXT_DOMAIN ) ); print '<section>'; - printf ( '<p>%s</p>', __ ( 'Click Finish to save these settings, then:', Postman::TEXT_DOMAIN ) ); + printf( '<p>%s</p>', __( 'Click Finish to save these settings, then:', Postman::TEXT_DOMAIN ) ); print '<ul style="margin-left: 20px">'; - printf ( '<li class="wizard-auth-oauth2">%s</li>', __ ( 'Grant permission with the Email Provider for Postman to send email and', Postman::TEXT_DOMAIN ) ); - printf ( '<li>%s</li>', __ ( 'Send yourself a Test Email to make sure everything is working!', Postman::TEXT_DOMAIN ) ); + printf( '<li class="wizard-auth-oauth2">%s</li>', __( 'Grant permission with the Email Provider for Postman to send email and', Postman::TEXT_DOMAIN ) ); + printf( '<li>%s</li>', __( 'Send yourself a Test Email to make sure everything is working!', Postman::TEXT_DOMAIN ) ); print '</ul>'; print '</section>'; print '</fieldset>'; @@ -379,188 +376,187 @@ class PostmanConfigurationController { /** * * @author jasonhendriks - * */ class PostmanGetHostnameByEmailAjaxController extends PostmanAbstractAjaxHandler { const IS_GOOGLE_PARAMETER = 'is_google'; function __construct() { - parent::__construct (); - PostmanUtils::registerAjaxHandler ( 'postman_check_email', $this, 'getAjaxHostnameByEmail' ); + parent::__construct(); + PostmanUtils::registerAjaxHandler( 'postman_check_email', $this, 'getAjaxHostnameByEmail' ); } /** * This Ajax function retrieves the smtp hostname for a give e-mail address */ function getAjaxHostnameByEmail() { - $goDaddyHostDetected = $this->getBooleanRequestParameter ( 'go_daddy' ); - $email = $this->getRequestParameter ( 'email' ); - $d = new PostmanSmtpDiscovery ( $email ); - $smtp = $d->getSmtpServer (); - $this->logger->debug ( 'given email ' . $email . ', smtp server is ' . $smtp ); - $this->logger->trace ( $d ); - if ($goDaddyHostDetected && ! $d->isGoogle) { + $goDaddyHostDetected = $this->getBooleanRequestParameter( 'go_daddy' ); + $email = $this->getRequestParameter( 'email' ); + $d = new PostmanSmtpDiscovery( $email ); + $smtp = $d->getSmtpServer(); + $this->logger->debug( 'given email ' . $email . ', smtp server is ' . $smtp ); + $this->logger->trace( $d ); + if ( $goDaddyHostDetected && ! $d->isGoogle ) { // override with the GoDaddy SMTP server $smtp = 'relay-hosting.secureserver.net'; - $this->logger->debug ( 'detected GoDaddy SMTP server, smtp server is ' . $smtp ); + $this->logger->debug( 'detected GoDaddy SMTP server, smtp server is ' . $smtp ); } - $response = array ( + $response = array( 'hostname' => $smtp, self::IS_GOOGLE_PARAMETER => $d->isGoogle, 'is_go_daddy' => $d->isGoDaddy, - 'is_well_known' => $d->isWellKnownDomain + 'is_well_known' => $d->isWellKnownDomain, ); - $this->logger->trace ( $response ); - wp_send_json_success ( $response ); + $this->logger->trace( $response ); + wp_send_json_success( $response ); } } class PostmanManageConfigurationAjaxHandler extends PostmanAbstractAjaxHandler { function __construct() { - parent::__construct (); - PostmanUtils::registerAjaxHandler ( 'manual_config', $this, 'getManualConfigurationViaAjax' ); - PostmanUtils::registerAjaxHandler ( 'get_wizard_configuration_options', $this, 'getWizardConfigurationViaAjax' ); + parent::__construct(); + PostmanUtils::registerAjaxHandler( 'manual_config', $this, 'getManualConfigurationViaAjax' ); + PostmanUtils::registerAjaxHandler( 'get_wizard_configuration_options', $this, 'getWizardConfigurationViaAjax' ); } - + /** * Handle a Advanced Configuration request with Ajax * * @throws Exception */ function getManualConfigurationViaAjax() { - $queryTransportType = $this->getTransportTypeFromRequest (); - $queryAuthType = $this->getAuthenticationTypeFromRequest (); - $queryHostname = $this->getHostnameFromRequest (); - + $queryTransportType = $this->getTransportTypeFromRequest(); + $queryAuthType = $this->getAuthenticationTypeFromRequest(); + $queryHostname = $this->getHostnameFromRequest(); + // the outgoing server hostname is only required for the SMTP Transport // the Gmail API transport doesn't use an SMTP server - $transport = PostmanTransportRegistry::getInstance ()->getTransport ( $queryTransportType ); - if (! $transport) { - throw new Exception ( 'Unable to find transport ' . $queryTransportType ); + $transport = PostmanTransportRegistry::getInstance()->getTransport( $queryTransportType ); + if ( ! $transport ) { + throw new Exception( 'Unable to find transport ' . $queryTransportType ); } - + // create the response - $response = $transport->populateConfiguration ( $queryHostname ); + $response = $transport->populateConfiguration( $queryHostname ); $response ['referer'] = 'manual_config'; - + // set the display_auth to oauth2 if the transport needs it - if ($transport->isOAuthUsed ( $queryAuthType )) { + if ( $transport->isOAuthUsed( $queryAuthType ) ) { $response ['display_auth'] = 'oauth2'; - $this->logger->debug ( 'ajaxRedirectUrl answer display_auth:' . $response ['display_auth'] ); + $this->logger->debug( 'ajaxRedirectUrl answer display_auth:' . $response ['display_auth'] ); } - $this->logger->trace ( $response ); - wp_send_json_success ( $response ); + $this->logger->trace( $response ); + wp_send_json_success( $response ); } - + /** * Once the Port Tests have run, the results are analyzed. * The Transport place bids on the sockets and highest bid becomes the recommended * The UI response is built so the user may choose a different socket with different options. */ function getWizardConfigurationViaAjax() { - $this->logger->debug ( 'in getWizardConfiguration' ); - $originalSmtpServer = $this->getRequestParameter ( 'original_smtp_server' ); - $queryHostData = $this->getHostDataFromRequest (); - $sockets = array (); + $this->logger->debug( 'in getWizardConfiguration' ); + $originalSmtpServer = $this->getRequestParameter( 'original_smtp_server' ); + $queryHostData = $this->getHostDataFromRequest(); + $sockets = array(); foreach ( $queryHostData as $id => $datum ) { - array_push ( $sockets, new PostmanWizardSocket ( $datum ) ); + array_push( $sockets, new PostmanWizardSocket( $datum ) ); } - $this->logger->error ( $sockets ); - $userPortOverride = $this->getUserPortOverride (); - $userAuthOverride = $this->getUserAuthOverride (); - + $this->logger->error( $sockets ); + $userPortOverride = $this->getUserPortOverride(); + $userAuthOverride = $this->getUserAuthOverride(); + // determine a configuration recommendation - $winningRecommendation = $this->getWinningRecommendation ( $sockets, $userPortOverride, $userAuthOverride, $originalSmtpServer ); - if ($this->logger->isTrace ()) { - $this->logger->trace ( 'winning recommendation:' ); - $this->logger->trace ( $winningRecommendation ); + $winningRecommendation = $this->getWinningRecommendation( $sockets, $userPortOverride, $userAuthOverride, $originalSmtpServer ); + if ( $this->logger->isTrace() ) { + $this->logger->trace( 'winning recommendation:' ); + $this->logger->trace( $winningRecommendation ); } - + // create the reponse - $response = array (); - $configuration = array (); + $response = array(); + $configuration = array(); $response ['referer'] = 'wizard'; - if (isset ( $userPortOverride ) || isset ( $userAuthOverride )) { + if ( isset( $userPortOverride ) || isset( $userAuthOverride ) ) { $configuration ['user_override'] = true; } - - if (isset ( $winningRecommendation )) { - + + if ( isset( $winningRecommendation ) ) { + // create an appropriate (theoretical) transport - $transport = PostmanTransportRegistry::getInstance ()->getTransport ( $winningRecommendation ['transport'] ); - + $transport = PostmanTransportRegistry::getInstance()->getTransport( $winningRecommendation ['transport'] ); + // create user override menu - $overrideMenu = $this->createOverrideMenus ( $sockets, $winningRecommendation, $userPortOverride, $userAuthOverride ); - if ($this->logger->isTrace ()) { - $this->logger->trace ( 'override menu:' ); - $this->logger->trace ( $overrideMenu ); + $overrideMenu = $this->createOverrideMenus( $sockets, $winningRecommendation, $userPortOverride, $userAuthOverride ); + if ( $this->logger->isTrace() ) { + $this->logger->trace( 'override menu:' ); + $this->logger->trace( $overrideMenu ); } - + $queryHostName = $winningRecommendation ['hostname']; - if ($this->logger->isDebug ()) { - $this->logger->debug ( 'Getting scribe for ' . $queryHostName ); + if ( $this->logger->isDebug() ) { + $this->logger->debug( 'Getting scribe for ' . $queryHostName ); } - $generalConfig1 = $transport->populateConfiguration ( $queryHostName ); - $generalConfig2 = $transport->populateConfigurationFromRecommendation ( $winningRecommendation ); - $configuration = array_merge ( $configuration, $generalConfig1, $generalConfig2 ); + $generalConfig1 = $transport->populateConfiguration( $queryHostName ); + $generalConfig2 = $transport->populateConfigurationFromRecommendation( $winningRecommendation ); + $configuration = array_merge( $configuration, $generalConfig1, $generalConfig2 ); $response ['override_menu'] = $overrideMenu; $response ['configuration'] = $configuration; - if ($this->logger->isTrace ()) { - $this->logger->trace ( 'configuration:' ); - $this->logger->trace ( $configuration ); - $this->logger->trace ( 'response:' ); - $this->logger->trace ( $response ); + if ( $this->logger->isTrace() ) { + $this->logger->trace( 'configuration:' ); + $this->logger->trace( $configuration ); + $this->logger->trace( 'response:' ); + $this->logger->trace( $response ); } - wp_send_json_success ( $response ); + wp_send_json_success( $response ); } else { /* translators: where %s is the URL to the Connectivity Test page */ - $configuration ['message'] = sprintf ( __ ( 'Postman can\'t find any way to send mail on your system. Run a <a href="%s">connectivity test</a>.', Postman::TEXT_DOMAIN ), PostmanViewController::getPageUrl ( PostmanViewController::PORT_TEST_SLUG ) ); + $configuration ['message'] = sprintf( __( 'Postman can\'t find any way to send mail on your system. Run a <a href="%s">connectivity test</a>.', Postman::TEXT_DOMAIN ), PostmanViewController::getPageUrl( PostmanViewController::PORT_TEST_SLUG ) ); $response ['configuration'] = $configuration; - if ($this->logger->isTrace ()) { - $this->logger->trace ( 'configuration:' ); - $this->logger->trace ( $configuration ); + if ( $this->logger->isTrace() ) { + $this->logger->trace( 'configuration:' ); + $this->logger->trace( $configuration ); } - wp_send_json_error ( $response ); + wp_send_json_error( $response ); } } - + /** * // for each successful host/port combination * // ask a transport if they support it, and if they do at what priority is it * // configure for the highest priority you find * - * @param unknown $queryHostData + * @param unknown $queryHostData * @return unknown */ - private function getWinningRecommendation($sockets, $userSocketOverride, $userAuthOverride, $originalSmtpServer) { + private function getWinningRecommendation( $sockets, $userSocketOverride, $userAuthOverride, $originalSmtpServer ) { foreach ( $sockets as $socket ) { - $winningRecommendation = $this->getWin ( $socket, $userSocketOverride, $userAuthOverride, $originalSmtpServer ); - $this->logger->error ( $socket->label ); + $winningRecommendation = $this->getWin( $socket, $userSocketOverride, $userAuthOverride, $originalSmtpServer ); + $this->logger->error( $socket->label ); } return $winningRecommendation; } - + /** * - * @param PostmanSocket $socket - * @param unknown $userSocketOverride - * @param unknown $userAuthOverride - * @param unknown $originalSmtpServer + * @param PostmanSocket $socket + * @param unknown $userSocketOverride + * @param unknown $userAuthOverride + * @param unknown $originalSmtpServer * @return Ambigous <NULL, unknown, string> */ - private function getWin(PostmanWizardSocket $socket, $userSocketOverride, $userAuthOverride, $originalSmtpServer) { + private function getWin( PostmanWizardSocket $socket, $userSocketOverride, $userAuthOverride, $originalSmtpServer ) { static $recommendationPriority = - 1; static $winningRecommendation = null; $available = $socket->success; - if ($available) { - $this->logger->debug ( sprintf ( 'Asking for judgement on %s:%s', $socket->hostname, $socket->port ) ); - $recommendation = PostmanTransportRegistry::getInstance ()->getRecommendation ( $socket, $userAuthOverride, $originalSmtpServer ); - $recommendationId = sprintf ( '%s_%s', $socket->hostname, $socket->port ); + if ( $available ) { + $this->logger->debug( sprintf( 'Asking for judgement on %s:%s', $socket->hostname, $socket->port ) ); + $recommendation = PostmanTransportRegistry::getInstance()->getRecommendation( $socket, $userAuthOverride, $originalSmtpServer ); + $recommendationId = sprintf( '%s_%s', $socket->hostname, $socket->port ); $recommendation ['id'] = $recommendationId; - $this->logger->debug ( sprintf ( 'Got a recommendation: [%d] %s', $recommendation ['priority'], $recommendationId ) ); - if (isset ( $userSocketOverride )) { - if ($recommendationId == $userSocketOverride) { + $this->logger->debug( sprintf( 'Got a recommendation: [%d] %s', $recommendation ['priority'], $recommendationId ) ); + if ( isset( $userSocketOverride ) ) { + if ( $recommendationId == $userSocketOverride ) { $winningRecommendation = $recommendation; - $this->logger->debug ( sprintf ( 'User chosen socket %s is the winner', $recommendationId ) ); + $this->logger->debug( sprintf( 'User chosen socket %s is the winner', $recommendationId ) ); } - } elseif ($recommendation && $recommendation ['priority'] > $recommendationPriority) { + } elseif ( $recommendation && $recommendation ['priority'] > $recommendationPriority ) { $recommendationPriority = $recommendation ['priority']; $winningRecommendation = $recommendation; } @@ -568,82 +564,82 @@ class PostmanManageConfigurationAjaxHandler extends PostmanAbstractAjaxHandler { } return $winningRecommendation; } - + /** * - * @param unknown $queryHostData + * @param unknown $queryHostData * @return multitype: */ - private function createOverrideMenus($sockets, $winningRecommendation, $userSocketOverride, $userAuthOverride) { - $overrideMenu = array (); + private function createOverrideMenus( $sockets, $winningRecommendation, $userSocketOverride, $userAuthOverride ) { + $overrideMenu = array(); foreach ( $sockets as $socket ) { - $overrideItem = $this->createOverrideMenu ( $socket, $winningRecommendation, $userSocketOverride, $userAuthOverride ); - if ($overrideItem != null) { - $overrideMenu [$socket->id] = $overrideItem; + $overrideItem = $this->createOverrideMenu( $socket, $winningRecommendation, $userSocketOverride, $userAuthOverride ); + if ( $overrideItem != null ) { + $overrideMenu [ $socket->id ] = $overrideItem; } } - + // sort - krsort ( $overrideMenu ); - $sortedMenu = array (); + krsort( $overrideMenu ); + $sortedMenu = array(); foreach ( $overrideMenu as $menu ) { - array_push ( $sortedMenu, $menu ); + array_push( $sortedMenu, $menu ); } - + return $sortedMenu; } - + /** * - * @param PostmanWizardSocket $socket - * @param unknown $winningRecommendation - * @param unknown $userSocketOverride - * @param unknown $userAuthOverride + * @param PostmanWizardSocket $socket + * @param unknown $winningRecommendation + * @param unknown $userSocketOverride + * @param unknown $userAuthOverride */ - private function createOverrideMenu(PostmanWizardSocket $socket, $winningRecommendation, $userSocketOverride, $userAuthOverride) { - if ($socket->success) { - $transport = PostmanTransportRegistry::getInstance ()->getTransport ( $socket->transport ); - $this->logger->debug ( sprintf ( 'Transport %s is building the override menu for socket', $transport->getSlug () ) ); - $overrideItem = $transport->createOverrideMenu ( $socket, $winningRecommendation, $userSocketOverride, $userAuthOverride ); + private function createOverrideMenu( PostmanWizardSocket $socket, $winningRecommendation, $userSocketOverride, $userAuthOverride ) { + if ( $socket->success ) { + $transport = PostmanTransportRegistry::getInstance()->getTransport( $socket->transport ); + $this->logger->debug( sprintf( 'Transport %s is building the override menu for socket', $transport->getSlug() ) ); + $overrideItem = $transport->createOverrideMenu( $socket, $winningRecommendation, $userSocketOverride, $userAuthOverride ); return $overrideItem; } return null; } - + /** */ private function getTransportTypeFromRequest() { - return $this->getRequestParameter ( 'transport' ); + return $this->getRequestParameter( 'transport' ); } - + /** */ private function getHostnameFromRequest() { - return $this->getRequestParameter ( 'hostname' ); + return $this->getRequestParameter( 'hostname' ); } - + /** */ private function getAuthenticationTypeFromRequest() { - return $this->getRequestParameter ( 'auth_type' ); + return $this->getRequestParameter( 'auth_type' ); } - + /** */ private function getHostDataFromRequest() { - return $this->getRequestParameter ( 'host_data' ); + return $this->getRequestParameter( 'host_data' ); } - + /** */ private function getUserPortOverride() { - return $this->getRequestParameter ( 'user_port_override' ); + return $this->getRequestParameter( 'user_port_override' ); } - + /** */ private function getUserAuthOverride() { - return $this->getRequestParameter ( 'user_auth_override' ); + return $this->getRequestParameter( 'user_auth_override' ); } } class PostmanImportConfigurationAjaxController extends PostmanAbstractAjaxHandler { @@ -651,44 +647,44 @@ class PostmanImportConfigurationAjaxController extends PostmanAbstractAjaxHandle /** * Constructor * - * @param PostmanOptions $options + * @param PostmanOptions $options */ - function __construct(PostmanOptions $options) { - parent::__construct (); + function __construct( PostmanOptions $options ) { + parent::__construct(); $this->options = $options; - PostmanUtils::registerAjaxHandler ( 'import_configuration', $this, 'getConfigurationFromExternalPluginViaAjax' ); + PostmanUtils::registerAjaxHandler( 'import_configuration', $this, 'getConfigurationFromExternalPluginViaAjax' ); } - + /** * This function extracts configuration details form a competing SMTP plugin * and pushes them into the Postman configuration screen. */ function getConfigurationFromExternalPluginViaAjax() { - $importableConfiguration = new PostmanImportableConfiguration (); - $plugin = $this->getRequestParameter ( 'plugin' ); - $this->logger->debug ( 'Looking for config=' . $plugin ); - foreach ( $importableConfiguration->getAvailableOptions () as $this->options ) { - if ($this->options->getPluginSlug () == $plugin) { - $this->logger->debug ( 'Sending configuration response' ); - $response = array ( - PostmanOptions::MESSAGE_SENDER_EMAIL => $this->options->getMessageSenderEmail (), - PostmanOptions::MESSAGE_SENDER_NAME => $this->options->getMessageSenderName (), - PostmanOptions::HOSTNAME => $this->options->getHostname (), - PostmanOptions::PORT => $this->options->getPort (), - PostmanOptions::AUTHENTICATION_TYPE => $this->options->getAuthenticationType (), - PostmanOptions::SECURITY_TYPE => $this->options->getEncryptionType (), - PostmanOptions::BASIC_AUTH_USERNAME => $this->options->getUsername (), - PostmanOptions::BASIC_AUTH_PASSWORD => $this->options->getPassword (), - 'success' => true + $importableConfiguration = new PostmanImportableConfiguration(); + $plugin = $this->getRequestParameter( 'plugin' ); + $this->logger->debug( 'Looking for config=' . $plugin ); + foreach ( $importableConfiguration->getAvailableOptions() as $this->options ) { + if ( $this->options->getPluginSlug() == $plugin ) { + $this->logger->debug( 'Sending configuration response' ); + $response = array( + PostmanOptions::MESSAGE_SENDER_EMAIL => $this->options->getMessageSenderEmail(), + PostmanOptions::MESSAGE_SENDER_NAME => $this->options->getMessageSenderName(), + PostmanOptions::HOSTNAME => $this->options->getHostname(), + PostmanOptions::PORT => $this->options->getPort(), + PostmanOptions::AUTHENTICATION_TYPE => $this->options->getAuthenticationType(), + PostmanOptions::SECURITY_TYPE => $this->options->getEncryptionType(), + PostmanOptions::BASIC_AUTH_USERNAME => $this->options->getUsername(), + PostmanOptions::BASIC_AUTH_PASSWORD => $this->options->getPassword(), + 'success' => true, ); break; } } - if (! isset ( $response )) { - $response = array ( - 'success' => false + if ( ! isset( $response ) ) { + $response = array( + 'success' => false, ); } - wp_send_json ( $response ); + wp_send_json( $response ); } } diff --git a/Postman/Postman-Connectivity-Test/PostmanConnectivityTestController.php b/Postman/Postman-Connectivity-Test/PostmanConnectivityTestController.php index 3c1a23f..069c414 100644 --- a/Postman/Postman-Connectivity-Test/PostmanConnectivityTestController.php +++ b/Postman/Postman-Connectivity-Test/PostmanConnectivityTestController.php @@ -1,45 +1,43 @@ <?php -// class PostmanConnectivityTestController { - - // - const PORT_TEST_SLUG = 'postman/port_test'; - + + const PORT_TEST_SLUG = 'postman/port_test'; + // logging private $logger; - + // Holds the values to be used in the fields callbacks private $rootPluginFilenameAndPath; - + /** * Constructor * - * @param unknown $rootPluginFilenameAndPath + * @param unknown $rootPluginFilenameAndPath */ - public function __construct($rootPluginFilenameAndPath) { - assert ( ! empty ( $rootPluginFilenameAndPath ) ); - assert ( PostmanUtils::isAdmin () ); - assert ( is_admin () ); - - $this->logger = new PostmanLogger ( get_class ( $this ) ); + public function __construct( $rootPluginFilenameAndPath ) { + assert( ! empty( $rootPluginFilenameAndPath ) ); + assert( PostmanUtils::isAdmin() ); + assert( is_admin() ); + + $this->logger = new PostmanLogger( get_class( $this ) ); $this->rootPluginFilenameAndPath = $rootPluginFilenameAndPath; - - PostmanUtils::registerAdminMenu ( $this, 'addPortTestSubmenu' ); - + + PostmanUtils::registerAdminMenu( $this, 'addPortTestSubmenu' ); + // hook on the init event - add_action ( 'init', array ( + add_action( 'init', array( $this, - 'on_init' + 'on_init', ) ); - + // initialize the scripts, stylesheets and form fields - add_action ( 'admin_init', array ( + add_action( 'admin_init', array( $this, - 'on_admin_init' + 'on_admin_init', ) ); } - + /** * Functions to execute on the init event * @@ -48,133 +46,132 @@ class PostmanConnectivityTestController { */ public function on_init() { // register Ajax handlers - new PostmanPortTestAjaxController (); + new PostmanPortTestAjaxController(); } - + /** * Fires on the admin_init method */ public function on_admin_init() { - // - $this->registerStylesAndScripts (); + $this->registerStylesAndScripts(); } - + /** * Register and add settings */ private function registerStylesAndScripts() { - if ($this->logger->isTrace ()) { - $this->logger->trace ( 'registerStylesAndScripts()' ); + if ( $this->logger->isTrace() ) { + $this->logger->trace( 'registerStylesAndScripts()' ); } // register the stylesheet and javascript external resources - $pluginData = apply_filters ( 'postman_get_plugin_metadata', null ); - wp_register_script ( 'postman_port_test_script', plugins_url ( 'Postman/Postman-Connectivity-Test/postman_port_test.js', $this->rootPluginFilenameAndPath ), array ( + $pluginData = apply_filters( 'postman_get_plugin_metadata', null ); + wp_register_script( 'postman_port_test_script', plugins_url( 'Postman/Postman-Connectivity-Test/postman_port_test.js', $this->rootPluginFilenameAndPath ), array( PostmanViewController::JQUERY_SCRIPT, 'jquery_validation', PostmanViewController::POSTMAN_SCRIPT, - 'sprintf' + 'sprintf', ), $pluginData ['version'] ); } - + /** * Register the Email Test screen */ public function addPortTestSubmenu() { - $page = add_submenu_page ( null, sprintf ( __ ( '%s Setup', Postman::TEXT_DOMAIN ), __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ) ), __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ), Postman::MANAGE_POSTMAN_CAPABILITY_NAME, PostmanConnectivityTestController::PORT_TEST_SLUG, array ( + $page = add_submenu_page( null, sprintf( __( '%s Setup', Postman::TEXT_DOMAIN ), __( 'Postman SMTP', Postman::TEXT_DOMAIN ) ), __( 'Postman SMTP', Postman::TEXT_DOMAIN ), Postman::MANAGE_POSTMAN_CAPABILITY_NAME, PostmanConnectivityTestController::PORT_TEST_SLUG, array( $this, - 'outputPortTestContent' + 'outputPortTestContent', ) ); // When the plugin options page is loaded, also load the stylesheet - add_action ( 'admin_print_styles-' . $page, array ( + add_action( 'admin_print_styles-' . $page, array( $this, - 'enqueuePortTestResources' + 'enqueuePortTestResources', ) ); } - + /** */ function enqueuePortTestResources() { - wp_enqueue_style ( PostmanViewController::POSTMAN_STYLE ); - wp_enqueue_script ( 'postman_port_test_script' ); - $warning = __ ( 'Warning', Postman::TEXT_DOMAIN ); - wp_localize_script ( PostmanViewController::POSTMAN_SCRIPT, 'postman_hostname_element_name', '#input_' . PostmanOptions::HOSTNAME ); - PostmanConnectivityTestController::addLocalizeScriptForPortTest (); + wp_enqueue_style( PostmanViewController::POSTMAN_STYLE ); + wp_enqueue_script( 'postman_port_test_script' ); + $warning = __( 'Warning', Postman::TEXT_DOMAIN ); + wp_localize_script( PostmanViewController::POSTMAN_SCRIPT, 'postman_hostname_element_name', '#input_' . PostmanOptions::HOSTNAME ); + PostmanConnectivityTestController::addLocalizeScriptForPortTest(); } static function addLocalizeScriptForPortTest() { - wp_localize_script ( PostmanViewController::POSTMAN_SCRIPT, 'postman_port_test', array ( - 'in_progress' => _x ( 'Checking..', 'The "please wait" message', Postman::TEXT_DOMAIN ), - 'open' => _x ( 'Open', 'The port is open', Postman::TEXT_DOMAIN ), - 'closed' => _x ( 'Closed', 'The port is closed', Postman::TEXT_DOMAIN ), - 'yes' => __ ( 'Yes', Postman::TEXT_DOMAIN ), - 'no' => __ ( 'No', Postman::TEXT_DOMAIN ), - /* translators: where %d is a port number */ - 'blocked' => __ ( 'No outbound route between this site and the Internet on Port %d.', Postman::TEXT_DOMAIN ), - /* translators: where %d is a port number and %s is a hostname */ - 'try_dif_smtp' => __ ( 'Port %d is open, but not to %s.', Postman::TEXT_DOMAIN ), - /* translators: where %d is the port number and %s is the hostname */ - 'success' => __ ( 'Port %d can be used for SMTP to %s.', Postman::TEXT_DOMAIN ), - 'mitm' => sprintf ( '%s: %s', __ ( 'Warning', Postman::TEXT_DOMAIN ), __ ( 'connected to %1$s instead of %2$s.', Postman::TEXT_DOMAIN ) ), - /* translators: where %d is a port number and %s is the URL for the Postman Gmail Extension */ - 'https_success' => __ ( 'Port %d can be used with the %s.', Postman::TEXT_DOMAIN ) + wp_localize_script( PostmanViewController::POSTMAN_SCRIPT, 'postman_port_test', array( + 'in_progress' => _x( 'Checking..', 'The "please wait" message', Postman::TEXT_DOMAIN ), + 'open' => _x( 'Open', 'The port is open', Postman::TEXT_DOMAIN ), + 'closed' => _x( 'Closed', 'The port is closed', Postman::TEXT_DOMAIN ), + 'yes' => __( 'Yes', Postman::TEXT_DOMAIN ), + 'no' => __( 'No', Postman::TEXT_DOMAIN ), + /* translators: where %d is a port number */ + 'blocked' => __( 'No outbound route between this site and the Internet on Port %d.', Postman::TEXT_DOMAIN ), + /* translators: where %d is a port number and %s is a hostname */ + 'try_dif_smtp' => __( 'Port %d is open, but not to %s.', Postman::TEXT_DOMAIN ), + /* translators: where %d is the port number and %s is the hostname */ + 'success' => __( 'Port %d can be used for SMTP to %s.', Postman::TEXT_DOMAIN ), + 'mitm' => sprintf( '%s: %s', __( 'Warning', Postman::TEXT_DOMAIN ), __( 'connected to %1$s instead of %2$s.', Postman::TEXT_DOMAIN ) ), + /* translators: where %d is a port number and %s is the URL for the Postman Gmail Extension */ + 'https_success' => __( 'Port %d can be used with the %s.', Postman::TEXT_DOMAIN ), ) ); } - + /** * Get the settings option array and print one of its values */ public function port_test_hostname_callback() { - $hostname = PostmanTransportRegistry::getInstance ()->getSelectedTransport ()->getHostname (); - if (empty ( $hostname )) { - $hostname = PostmanTransportRegistry::getInstance ()->getActiveTransport ()->getHostname (); + $hostname = PostmanTransportRegistry::getInstance()->getSelectedTransport()->getHostname(); + if ( empty( $hostname ) ) { + $hostname = PostmanTransportRegistry::getInstance()->getActiveTransport()->getHostname(); } - printf ( '<input type="text" id="input_hostname" name="postman_options[hostname]" value="%s" size="40" class="required"/>', $hostname ); + printf( '<input type="text" id="input_hostname" name="postman_options[hostname]" value="%s" size="40" class="required"/>', $hostname ); } - + /** */ public function outputPortTestContent() { print '<div class="wrap">'; - - PostmanViewController::outputChildPageHeader ( __ ( 'Connectivity Test', Postman::TEXT_DOMAIN ) ); - + + PostmanViewController::outputChildPageHeader( __( 'Connectivity Test', Postman::TEXT_DOMAIN ) ); + print '<p>'; - print __ ( 'This test determines which well-known ports are available for Postman to use.', Postman::TEXT_DOMAIN ); + print __( 'This test determines which well-known ports are available for Postman to use.', Postman::TEXT_DOMAIN ); print '<form id="port_test_form_id" method="post">'; - printf ( '<label for="hostname">%s</label>', __ ( 'Outgoing Mail Server Hostname', Postman::TEXT_DOMAIN ) ); - $this->port_test_hostname_callback (); - submit_button ( _x ( 'Begin Test', 'Button Label', Postman::TEXT_DOMAIN ), 'primary', 'begin-port-test', true ); + printf( '<label for="hostname">%s</label>', __( 'Outgoing Mail Server Hostname', Postman::TEXT_DOMAIN ) ); + $this->port_test_hostname_callback(); + submit_button( _x( 'Begin Test', 'Button Label', Postman::TEXT_DOMAIN ), 'primary', 'begin-port-test', true ); print '</form>'; print '<table id="connectivity_test_table">'; - print sprintf ( '<tr><th rowspan="2">%s</th><th rowspan="2">%s</th><th rowspan="2">%s</th><th rowspan="2">%s</th><th rowspan="2">%s</th><th colspan="5">%s</th></tr>', __ ( 'Transport', Postman::TEXT_DOMAIN ), _x ( 'Socket', 'A socket is the network term for host and port together', Postman::TEXT_DOMAIN ), __ ( 'Status', Postman::TEXT_DOMAIN ) . '<sup>*</sup>', __ ( 'Service Available', Postman::TEXT_DOMAIN ), __ ( 'Server ID', Postman::TEXT_DOMAIN ), __ ( 'Authentication', Postman::TEXT_DOMAIN ) ); - print sprintf ( '<tr><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th></tr>', 'None', 'Login', 'Plain', 'CRAM-MD5', 'OAuth 2.0' ); - $sockets = PostmanTransportRegistry::getInstance ()->getSocketsForSetupWizardToProbe (); + print sprintf( '<tr><th rowspan="2">%s</th><th rowspan="2">%s</th><th rowspan="2">%s</th><th rowspan="2">%s</th><th rowspan="2">%s</th><th colspan="5">%s</th></tr>', __( 'Transport', Postman::TEXT_DOMAIN ), _x( 'Socket', 'A socket is the network term for host and port together', Postman::TEXT_DOMAIN ), __( 'Status', Postman::TEXT_DOMAIN ) . '<sup>*</sup>', __( 'Service Available', Postman::TEXT_DOMAIN ), __( 'Server ID', Postman::TEXT_DOMAIN ), __( 'Authentication', Postman::TEXT_DOMAIN ) ); + print sprintf( '<tr><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th></tr>', 'None', 'Login', 'Plain', 'CRAM-MD5', 'OAuth 2.0' ); + $sockets = PostmanTransportRegistry::getInstance()->getSocketsForSetupWizardToProbe(); foreach ( $sockets as $socket ) { - if ($socket ['smtp']) { - print sprintf ( '<tr id="%s"><th class="name">%s</th><td class="socket">%s:%s</td><td class="firewall resettable">-</td><td class="service resettable">-</td><td class="reported_id resettable">-</td><td class="auth_none resettable">-</td><td class="auth_login resettable">-</td><td class="auth_plain resettable">-</td><td class="auth_crammd5 resettable">-</td><td class="auth_xoauth2 resettable">-</td></tr>', $socket ['id'], $socket ['transport_name'], $socket ['host'], $socket ['port'] ); + if ( $socket ['smtp'] ) { + print sprintf( '<tr id="%s"><th class="name">%s</th><td class="socket">%s:%s</td><td class="firewall resettable">-</td><td class="service resettable">-</td><td class="reported_id resettable">-</td><td class="auth_none resettable">-</td><td class="auth_login resettable">-</td><td class="auth_plain resettable">-</td><td class="auth_crammd5 resettable">-</td><td class="auth_xoauth2 resettable">-</td></tr>', $socket ['id'], $socket ['transport_name'], $socket ['host'], $socket ['port'] ); } else { - print sprintf ( '<tr id="%s"><th class="name">%s</th><td class="socket">%s:%s</td><td class="firewall resettable">-</td><td class="service resettable">-</td><td class="reported_id resettable">-</td><td colspan="5">%s</td></tr>', $socket ['id'], $socket ['transport_name'], $socket ['host'], $socket ['port'], __ ( 'n/a', Postman::TEXT_DOMAIN ) ); + print sprintf( '<tr id="%s"><th class="name">%s</th><td class="socket">%s:%s</td><td class="firewall resettable">-</td><td class="service resettable">-</td><td class="reported_id resettable">-</td><td colspan="5">%s</td></tr>', $socket ['id'], $socket ['transport_name'], $socket ['host'], $socket ['port'], __( 'n/a', Postman::TEXT_DOMAIN ) ); } } print '</table>'; /* Translators: Where %s is the name of the service providing Internet connectivity test */ - printf ( '<p class="portquiz" style="display:none; font-size:0.8em">* %s</p>', sprintf ( __ ( 'According to %s', Postman::TEXT_DOMAIN ), '<a target="_new" href="http://ww.downor.me/portquiz.net">portquiz.net</a>' ) ); - printf ( '<p class="ajax-loader" style="display:none"><img src="%s"/></p>', plugins_url ( 'postman-smtp/style/ajax-loader.gif' ) ); + printf( '<p class="portquiz" style="display:none; font-size:0.8em">* %s</p>', sprintf( __( 'According to %s', Postman::TEXT_DOMAIN ), '<a target="_new" href="http://ww.downor.me/portquiz.net">portquiz.net</a>' ) ); + printf( '<p class="ajax-loader" style="display:none"><img src="%s"/></p>', plugins_url( 'post-smtp/style/ajax-loader.gif' ) ); print '<section id="conclusion" style="display:none">'; - print sprintf ( '<h3>%s:</h3>', __ ( 'Summary', Postman::TEXT_DOMAIN ) ); + print sprintf( '<h3>%s:</h3>', __( 'Summary', Postman::TEXT_DOMAIN ) ); print '<ol class="conclusion">'; print '</ol>'; print '</section>'; print '<section id="blocked-port-help" style="display:none">'; - print sprintf ( '<p><b>%s</b></p>', __ ( 'A test with <span style="color:red">"No"</span> Service Available indicates one or more of these issues:', Postman::TEXT_DOMAIN ) ); + print sprintf( '<p><b>%s</b></p>', __( 'A test with <span style="color:red">"No"</span> Service Available indicates one or more of these issues:', Postman::TEXT_DOMAIN ) ); print '<ol>'; - printf ( '<li>%s</li>', __ ( 'Your web host has placed a firewall between this site and the Internet', Postman::TEXT_DOMAIN ) ); - printf ( '<li>%s</li>', __ ( 'The SMTP hostname is wrong or the mail server does not provide service on this port', Postman::TEXT_DOMAIN ) ); + printf( '<li>%s</li>', __( 'Your web host has placed a firewall between this site and the Internet', Postman::TEXT_DOMAIN ) ); + printf( '<li>%s</li>', __( 'The SMTP hostname is wrong or the mail server does not provide service on this port', Postman::TEXT_DOMAIN ) ); /* translators: where (1) is the URL and (2) is the system */ - $systemBlockMessage = __ ( 'Your <a href="%1$s">%2$s configuration</a> is preventing outbound connections', Postman::TEXT_DOMAIN ); - printf ( '<li>%s</li>', sprintf ( $systemBlockMessage, 'http://php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen', 'PHP' ) ); - printf ( '<li>%s</li>', sprintf ( $systemBlockMessage, 'http://wp-mix.com/disable-external-url-requests/', 'WordPress' ) ); + $systemBlockMessage = __( 'Your <a href="%1$s">%2$s configuration</a> is preventing outbound connections', Postman::TEXT_DOMAIN ); + printf( '<li>%s</li>', sprintf( $systemBlockMessage, 'http://php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen', 'PHP' ) ); + printf( '<li>%s</li>', sprintf( $systemBlockMessage, 'http://wp-mix.com/disable-external-url-requests/', 'WordPress' ) ); print '</ol></p>'; - print sprintf ( '<p><b>%s</b></p>', __ ( 'If the issues above can not be resolved, your last option is to configure Postman to use an email account managed by your web host with an SMTP server managed by your web host.', Postman::TEXT_DOMAIN ) ); + print sprintf( '<p><b>%s</b></p>', __( 'If the issues above can not be resolved, your last option is to configure Postman to use an email account managed by your web host with an SMTP server managed by your web host.', Postman::TEXT_DOMAIN ) ); print '</section>'; print '</div>'; } @@ -183,25 +180,24 @@ class PostmanConnectivityTestController { /** * * @author jasonhendriks - * */ class PostmanPortTestAjaxController { private $logger; /** * Constructor * - * @param PostmanOptions $options + * @param PostmanOptions $options */ function __construct() { - $this->logger = new PostmanLogger ( get_class ( $this ) ); - PostmanUtils::registerAjaxHandler ( 'postman_get_hosts_to_test', $this, 'getPortsToTestViaAjax' ); - PostmanUtils::registerAjaxHandler ( 'postman_wizard_port_test', $this, 'runSmtpTest' ); - PostmanUtils::registerAjaxHandler ( 'postman_wizard_port_test_smtps', $this, 'runSmtpsTest' ); - PostmanUtils::registerAjaxHandler ( 'postman_port_quiz_test', $this, 'runPortQuizTest' ); - PostmanUtils::registerAjaxHandler ( 'postman_test_port', $this, 'runSmtpTest' ); - PostmanUtils::registerAjaxHandler ( 'postman_test_smtps', $this, 'runSmtpsTest' ); + $this->logger = new PostmanLogger( get_class( $this ) ); + PostmanUtils::registerAjaxHandler( 'postman_get_hosts_to_test', $this, 'getPortsToTestViaAjax' ); + PostmanUtils::registerAjaxHandler( 'postman_wizard_port_test', $this, 'runSmtpTest' ); + PostmanUtils::registerAjaxHandler( 'postman_wizard_port_test_smtps', $this, 'runSmtpsTest' ); + PostmanUtils::registerAjaxHandler( 'postman_port_quiz_test', $this, 'runPortQuizTest' ); + PostmanUtils::registerAjaxHandler( 'postman_test_port', $this, 'runSmtpTest' ); + PostmanUtils::registerAjaxHandler( 'postman_test_smtps', $this, 'runSmtpsTest' ); } - + /** * This Ajax function determines which hosts/ports to test in both the Wizard Connectivity Test and direct Connectivity Test * @@ -209,79 +205,79 @@ class PostmanPortTestAjaxController { * combinations to run the connectivity test on */ function getPortsToTestViaAjax() { - $queryHostname = PostmanUtils::getRequestParameter ( 'hostname' ); + $queryHostname = PostmanUtils::getRequestParameter( 'hostname' ); // originalSmtpServer is what SmtpDiscovery thinks the SMTP server should be, given an email address - $originalSmtpServer = PostmanUtils::getRequestParameter ( 'original_smtp_server' ); - if ($this->logger->isDebug ()) { - $this->logger->debug ( 'Probing available transports for sockets against hostname ' . $queryHostname ); + $originalSmtpServer = PostmanUtils::getRequestParameter( 'original_smtp_server' ); + if ( $this->logger->isDebug() ) { + $this->logger->debug( 'Probing available transports for sockets against hostname ' . $queryHostname ); } - $sockets = PostmanTransportRegistry::getInstance ()->getSocketsForSetupWizardToProbe ( $queryHostname, $originalSmtpServer ); - $response = array ( - 'hosts' => $sockets + $sockets = PostmanTransportRegistry::getInstance()->getSocketsForSetupWizardToProbe( $queryHostname, $originalSmtpServer ); + $response = array( + 'hosts' => $sockets, ); - wp_send_json_success ( $response ); + wp_send_json_success( $response ); } - + /** * This Ajax function retrieves whether a TCP port is open or not */ function runPortQuizTest() { $hostname = 'portquiz.net'; - $port = intval ( PostmanUtils::getRequestParameter ( 'port' ) ); - $this->logger->debug ( 'testing TCP port: hostname ' . $hostname . ' port ' . $port ); - $portTest = new PostmanPortTest ( $hostname, $port ); - $success = $portTest->genericConnectionTest (); - $this->buildResponse ( $hostname, $port, $portTest, $success ); + $port = intval( PostmanUtils::getRequestParameter( 'port' ) ); + $this->logger->debug( 'testing TCP port: hostname ' . $hostname . ' port ' . $port ); + $portTest = new PostmanPortTest( $hostname, $port ); + $success = $portTest->genericConnectionTest(); + $this->buildResponse( $hostname, $port, $portTest, $success ); } - + /** * This Ajax function retrieves whether a TCP port is open or not. * This is called by both the Wizard and Port Test */ function runSmtpTest() { - $hostname = trim ( PostmanUtils::getRequestParameter ( 'hostname' ) ); - $port = intval ( PostmanUtils::getRequestParameter ( 'port' ) ); - $transport = trim ( PostmanUtils::getRequestParameter ( 'transport' ) ); - $timeout = PostmanUtils::getRequestParameter ( 'timeout' ); - $this->logger->trace ( $timeout ); - $portTest = new PostmanPortTest ( $hostname, $port ); - if (isset ( $timeout )) { - $portTest->setConnectionTimeout ( intval ( $timeout ) ); - $portTest->setReadTimeout ( intval ( $timeout ) ); + $hostname = trim( PostmanUtils::getRequestParameter( 'hostname' ) ); + $port = intval( PostmanUtils::getRequestParameter( 'port' ) ); + $transport = trim( PostmanUtils::getRequestParameter( 'transport' ) ); + $timeout = PostmanUtils::getRequestParameter( 'timeout' ); + $this->logger->trace( $timeout ); + $portTest = new PostmanPortTest( $hostname, $port ); + if ( isset( $timeout ) ) { + $portTest->setConnectionTimeout( intval( $timeout ) ); + $portTest->setReadTimeout( intval( $timeout ) ); } - if ($port != 443) { - $this->logger->debug ( sprintf ( 'testing SMTP socket %s:%s (%s)', $hostname, $port, $transport ) ); - $success = $portTest->testSmtpPorts (); + if ( $port != 443 ) { + $this->logger->debug( sprintf( 'testing SMTP socket %s:%s (%s)', $hostname, $port, $transport ) ); + $success = $portTest->testSmtpPorts(); } else { - $this->logger->debug ( sprintf ( 'testing HTTPS socket %s:%s (%s)', $hostname, $port, $transport ) ); - $success = $portTest->testHttpPorts (); + $this->logger->debug( sprintf( 'testing HTTPS socket %s:%s (%s)', $hostname, $port, $transport ) ); + $success = $portTest->testHttpPorts(); } - $this->buildResponse ( $hostname, $port, $portTest, $success, $transport ); + $this->buildResponse( $hostname, $port, $portTest, $success, $transport ); } /** * This Ajax function retrieves whether a TCP port is open or not */ function runSmtpsTest() { - $hostname = trim ( PostmanUtils::getRequestParameter ( 'hostname' ) ); - $port = intval ( PostmanUtils::getRequestParameter ( 'port' ) ); - $transport = trim ( PostmanUtils::getRequestParameter ( 'transport' ) ); - $transportName = trim ( PostmanUtils::getRequestParameter ( 'transport_name' ) ); - $this->logger->debug ( sprintf ( 'testing SMTPS socket %s:%s (%s)', $hostname, $port, $transport ) ); - $portTest = new PostmanPortTest ( $hostname, $port ); + $hostname = trim( PostmanUtils::getRequestParameter( 'hostname' ) ); + $port = intval( PostmanUtils::getRequestParameter( 'port' ) ); + $transport = trim( PostmanUtils::getRequestParameter( 'transport' ) ); + $transportName = trim( PostmanUtils::getRequestParameter( 'transport_name' ) ); + $this->logger->debug( sprintf( 'testing SMTPS socket %s:%s (%s)', $hostname, $port, $transport ) ); + $portTest = new PostmanPortTest( $hostname, $port ); $portTest->transportName = $transportName; - $success = $portTest->testSmtpsPorts (); - $this->buildResponse ( $hostname, $port, $portTest, $success, $transport ); + $success = $portTest->testSmtpsPorts(); + $this->buildResponse( $hostname, $port, $portTest, $success, $transport ); } - + /** * - * @param unknown $hostname - * @param unknown $port - * @param unknown $success + * @param unknown $hostname + * @param unknown $port + * @param unknown $success */ - private function buildResponse($hostname, $port, PostmanPortTest $portTest, $success, $transport = '') { - $this->logger->debug ( sprintf ( 'testing port result for %s:%s success=%s', $hostname, $port, $success ) ); - $response = array ( + private function buildResponse( $hostname, $port, PostmanPortTest $portTest, $success, $transport = '' ) { + $this->logger->debug( sprintf( 'testing port result for %s:%s success=%s', $hostname, $port, $success ) ); + $response = array( 'hostname' => $hostname, 'hostname_domain_only' => $portTest->hostnameDomainOnly, 'port' => $port, @@ -290,7 +286,7 @@ class PostmanPortTestAjaxController { 'mitm' => ($portTest->mitm), 'reported_hostname' => $portTest->reportedHostname, 'reported_hostname_domain_only' => $portTest->reportedHostnameDomainOnly, - 'message' => $portTest->getErrorMessage (), + 'message' => $portTest->getErrorMessage(), 'start_tls' => $portTest->startTls, 'auth_plain' => $portTest->authPlain, 'auth_login' => $portTest->authLogin, @@ -299,14 +295,14 @@ class PostmanPortTestAjaxController { 'auth_none' => $portTest->authNone, 'try_smtps' => $portTest->trySmtps, 'success' => $success, - 'transport' => $transport + 'transport' => $transport, ); - $this->logger->trace ( 'Ajax response:' ); - $this->logger->trace ( $response ); - if ($success) { - wp_send_json_success ( $response ); + $this->logger->trace( 'Ajax response:' ); + $this->logger->trace( $response ); + if ( $success ) { + wp_send_json_success( $response ); } else { - wp_send_json_error ( $response ); + wp_send_json_error( $response ); } } } diff --git a/Postman/Postman-Diagnostic-Test/PostmanDiagnosticTestController.php b/Postman/Postman-Diagnostic-Test/PostmanDiagnosticTestController.php index 46fbd19..c820c97 100644 --- a/Postman/Postman-Diagnostic-Test/PostmanDiagnosticTestController.php +++ b/Postman/Postman-Diagnostic-Test/PostmanDiagnosticTestController.php @@ -1,44 +1,44 @@ <?php class PostmanDiagnosticTestController { const DIAGNOSTICS_SLUG = 'postman/diagnostics'; - + // logging private $logger; private $options; - + // Holds the values to be used in the fields callbacks private $rootPluginFilenameAndPath; - + /** * Constructor * - * @param unknown $rootPluginFilenameAndPath + * @param unknown $rootPluginFilenameAndPath */ - public function __construct($rootPluginFilenameAndPath) { - assert ( ! empty ( $rootPluginFilenameAndPath ) ); - assert ( PostmanUtils::isAdmin () ); - assert ( is_admin () ); - - $this->logger = new PostmanLogger ( get_class ( $this ) ); + public function __construct( $rootPluginFilenameAndPath ) { + assert( ! empty( $rootPluginFilenameAndPath ) ); + assert( PostmanUtils::isAdmin() ); + assert( is_admin() ); + + $this->logger = new PostmanLogger( get_class( $this ) ); $this->rootPluginFilenameAndPath = $rootPluginFilenameAndPath; - $this->options = PostmanOptions::getInstance (); - + $this->options = PostmanOptions::getInstance(); + // register the admin menu - PostmanUtils::registerAdminMenu ( $this, 'addDiagnosticsSubmenu' ); - + PostmanUtils::registerAdminMenu( $this, 'addDiagnosticsSubmenu' ); + // hook on the init event - add_action ( 'init', array ( + add_action( 'init', array( $this, - 'on_init' + 'on_init', ) ); - + // initialize the scripts, stylesheets and form fields - add_action ( 'admin_init', array ( + add_action( 'admin_init', array( $this, - 'on_admin_init' + 'on_admin_init', ) ); } - + /** * Functions to execute on the init event * @@ -47,66 +47,65 @@ class PostmanDiagnosticTestController { */ public function on_init() { // register Ajax handlers - new PostmanGetDiagnosticsViaAjax (); + new PostmanGetDiagnosticsViaAjax(); } - + /** * Fires on the admin_init method */ public function on_admin_init() { - // - $this->registerStylesAndScripts (); + $this->registerStylesAndScripts(); } - + /** * Register and add settings */ private function registerStylesAndScripts() { - if ($this->logger->isTrace ()) { - $this->logger->trace ( 'registerStylesAndScripts()' ); + if ( $this->logger->isTrace() ) { + $this->logger->trace( 'registerStylesAndScripts()' ); } - + // register the javascript resource - $pluginData = apply_filters ( 'postman_get_plugin_metadata', null ); - wp_register_script ( 'postman_diagnostics_script', plugins_url ( 'Postman/Postman-Diagnostic-Test/postman_diagnostics.js', $this->rootPluginFilenameAndPath ), array ( + $pluginData = apply_filters( 'postman_get_plugin_metadata', null ); + wp_register_script( 'postman_diagnostics_script', plugins_url( 'Postman/Postman-Diagnostic-Test/postman_diagnostics.js', $this->rootPluginFilenameAndPath ), array( PostmanViewController::JQUERY_SCRIPT, - PostmanViewController::POSTMAN_SCRIPT + PostmanViewController::POSTMAN_SCRIPT, ), $pluginData ['version'] ); } - + /** * Register the Diagnostics screen */ public function addDiagnosticsSubmenu() { - $page = add_submenu_page ( null, sprintf ( __ ( '%s Setup', Postman::TEXT_DOMAIN ), __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ) ), __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ), Postman::MANAGE_POSTMAN_CAPABILITY_NAME, PostmanDiagnosticTestController::DIAGNOSTICS_SLUG, array ( + $page = add_submenu_page( null, sprintf( __( '%s Setup', Postman::TEXT_DOMAIN ), __( 'Postman SMTP', Postman::TEXT_DOMAIN ) ), __( 'Postman SMTP', Postman::TEXT_DOMAIN ), Postman::MANAGE_POSTMAN_CAPABILITY_NAME, PostmanDiagnosticTestController::DIAGNOSTICS_SLUG, array( $this, - 'outputDiagnosticsContent' + 'outputDiagnosticsContent', ) ); // When the plugin options page is loaded, also load the stylesheet - add_action ( 'admin_print_styles-' . $page, array ( + add_action( 'admin_print_styles-' . $page, array( $this, - 'enqueueDiagnosticsScreenStylesheet' + 'enqueueDiagnosticsScreenStylesheet', ) ); } function enqueueDiagnosticsScreenStylesheet() { - wp_enqueue_style ( PostmanViewController::POSTMAN_STYLE ); - wp_enqueue_script ( 'postman_diagnostics_script' ); + wp_enqueue_style( PostmanViewController::POSTMAN_STYLE ); + wp_enqueue_script( 'postman_diagnostics_script' ); } - + /** */ public function outputDiagnosticsContent() { // test features print '<div class="wrap">'; - - PostmanViewController::outputChildPageHeader ( __ ( 'Diagnostic Test', Postman::TEXT_DOMAIN ) ); - - printf ( '<h4>%s</h4>', __ ( 'Are you having issues with Postman?', Postman::TEXT_DOMAIN ) ); + + PostmanViewController::outputChildPageHeader( __( 'Diagnostic Test', Postman::TEXT_DOMAIN ) ); + + printf( '<h4>%s</h4>', __( 'Are you having issues with Postman?', Postman::TEXT_DOMAIN ) ); /* translators: where %1$s and %2$s are the URLs to the Troubleshooting and Support Forums on WordPress.org */ - printf ( '<p style="margin:0 10px">%s</p>', sprintf ( __ ( 'Please check the <a href="%1$s">troubleshooting and error messages</a> page and the <a href="%2$s">support forum</a>.', Postman::TEXT_DOMAIN ), 'https://wordpress.org/plugins/postman-smtp/other_notes/', 'https://wordpress.org/support/plugin/postman-smtp' ) ); - printf ( '<h4>%s</h4>', __ ( 'Diagnostic Test', Postman::TEXT_DOMAIN ) ); - printf ( '<p style="margin:0 10px">%s</p><br/>', sprintf ( __ ( 'If you write for help, please include the following:', Postman::TEXT_DOMAIN ), 'https://wordpress.org/plugins/postman-smtp/other_notes/', 'https://wordpress.org/support/plugin/postman-smtp' ) ); - printf ( '<textarea readonly="readonly" id="diagnostic-text" cols="80" rows="15">%s</textarea>', _x ( 'Checking..', 'The "please wait" message', Postman::TEXT_DOMAIN ) ); + printf( '<p style="margin:0 10px">%s</p>', sprintf( __( 'Please check the <a href="%1$s">troubleshooting and error messages</a> page and the <a href="%2$s">support forum</a>.', Postman::TEXT_DOMAIN ), 'https://wordpress.org/plugins/post-smtp/other_notes/', 'https://wordpress.org/support/plugin/postman-smtp' ) ); + printf( '<h4>%s</h4>', __( 'Diagnostic Test', Postman::TEXT_DOMAIN ) ); + printf( '<p style="margin:0 10px">%s</p><br/>', sprintf( __( 'If you write for help, please include the following:', Postman::TEXT_DOMAIN ), 'https://wordpress.org/plugins/post-smtp/other_notes/', 'https://wordpress.org/support/plugin/postman-smtp' ) ); + printf( '<textarea readonly="readonly" id="diagnostic-text" cols="80" rows="15">%s</textarea>', _x( 'Checking..', 'The "please wait" message', Postman::TEXT_DOMAIN ) ); print '</div>'; } } @@ -114,7 +113,6 @@ class PostmanDiagnosticTestController { /** * * @author jasonhendriks - * */ class PostmanGetDiagnosticsViaAjax { private $diagnostics; @@ -123,59 +121,59 @@ class PostmanGetDiagnosticsViaAjax { /** * Constructor * - * @param PostmanOptions $options + * @param PostmanOptions $options */ function __construct() { - $this->options = PostmanOptions::getInstance (); - $this->authorizationToken = PostmanOAuthToken::getInstance (); + $this->options = PostmanOptions::getInstance(); + $this->authorizationToken = PostmanOAuthToken::getInstance(); $this->diagnostics = ''; - PostmanUtils::registerAjaxHandler ( 'postman_diagnostics', $this, 'getDiagnostics' ); + PostmanUtils::registerAjaxHandler( 'postman_diagnostics', $this, 'getDiagnostics' ); } - private function addToDiagnostics($header, $data) { - if (isset ( $data )) { - $this->diagnostics .= sprintf ( '%s: %s%s', $header, $data, PHP_EOL ); + private function addToDiagnostics( $header, $data ) { + if ( isset( $data ) ) { + $this->diagnostics .= sprintf( '%s: %s%s', $header, $data, PHP_EOL ); } } private function getActivePlugins() { // from http://stackoverflow.com/questions/20488264/how-do-i-get-activated-plugin-list-in-wordpress-plugin-development - $apl = get_option ( 'active_plugins' ); - $plugins = get_plugins (); - $pluginText = array (); + $apl = get_option( 'active_plugins' ); + $plugins = get_plugins(); + $pluginText = array(); foreach ( $apl as $p ) { - if (isset ( $plugins [$p] )) { - array_push ( $pluginText, $plugins [$p] ['Name'] ); + if ( isset( $plugins [ $p ] ) ) { + array_push( $pluginText, $plugins [ $p ] ['Name'] ); } } - return implode ( ', ', $pluginText ); + return implode( ', ', $pluginText ); } private function getPhpDependencies() { - $apl = PostmanPreRequisitesCheck::getState (); - $pluginText = array (); + $apl = PostmanPreRequisitesCheck::getState(); + $pluginText = array(); foreach ( $apl as $p ) { - array_push ( $pluginText, $p ['name'] . '=' . ($p ['ready'] ? 'Yes' : 'No') ); + array_push( $pluginText, $p ['name'] . '=' . ($p ['ready'] ? 'Yes' : 'No') ); } - return implode ( ', ', $pluginText ); + return implode( ', ', $pluginText ); } private function getTransports() { $transports = ''; - foreach ( PostmanTransportRegistry::getInstance ()->getTransports () as $transport ) { - $transports .= ' : ' . $transport->getName (); + foreach ( PostmanTransportRegistry::getInstance()->getTransports() as $transport ) { + $transports .= ' : ' . $transport->getName(); } return $transports; } - + /** * Diagnostic Data test to current SMTP server * * @return string */ - private function testConnectivity(PostmanModuleTransport $transport) { - $hostname = $transport->getHostname ( $this->options ); - $port = $transport->getPort ( $this->options ); - if (! empty ( $hostname ) && ! empty ( $port )) { - $portTest = new PostmanPortTest ( $transport->getHostname ( $this->options ), $transport->getPort ( $this->options ) ); - $result = $portTest->genericConnectionTest ( $this->options->getConnectionTimeout () ); - if ($result) { + private function testConnectivity( PostmanModuleTransport $transport ) { + $hostname = $transport->getHostname( $this->options ); + $port = $transport->getPort( $this->options ); + if ( ! empty( $hostname ) && ! empty( $port ) ) { + $portTest = new PostmanPortTest( $transport->getHostname( $this->options ), $transport->getPort( $this->options ) ); + $result = $portTest->genericConnectionTest( $this->options->getConnectionTimeout() ); + if ( $result ) { return 'Yes'; } else { return 'No'; @@ -183,93 +181,93 @@ class PostmanGetDiagnosticsViaAjax { } return 'n/a'; } - + /** * Inspects the $wp_filter variable and returns the plugins attached to it * From: http://stackoverflow.com/questions/5224209/wordpress-how-do-i-get-all-the-registered-functions-for-the-content-filter */ - private function getFilters($hook = '') { + private function getFilters( $hook = '' ) { global $wp_filter; - if (empty ( $hook ) || ! isset ( $wp_filter [$hook] )) - return null; - $functionArray = array (); - foreach ( $wp_filter [$hook] as $functions ) { + if ( empty( $hook ) || ! isset( $wp_filter [ $hook ] ) ) { + return null; } + $functionArray = array(); + foreach ( $wp_filter [ $hook ] as $functions ) { foreach ( $functions as $function ) { $thing = $function ['function']; - if (is_array ( $thing )) { - $name = get_class ( $thing [0] ) . '->' . $thing [1]; - array_push ( $functionArray, $name ); + if ( is_array( $thing ) ) { + $name = get_class( $thing [0] ) . '->' . $thing [1]; + array_push( $functionArray, $name ); } else { - array_push ( $functionArray, $thing ); + array_push( $functionArray, $thing ); } } } - return implode ( ', ', $functionArray ); + return implode( ', ', $functionArray ); } - + /** */ public function getDiagnostics() { - $transportRegistry = PostmanTransportRegistry::getInstance (); - $this->addToDiagnostics ( 'OS', php_uname () ); - $this->addToDiagnostics ( 'PHP', PHP_OS . ' ' . PHP_VERSION . ' ' . setlocale ( LC_CTYPE, 0 ) ); - $this->addToDiagnostics ( 'PHP Dependencies', $this->getPhpDependencies () ); - $this->addToDiagnostics ( 'WordPress', (is_multisite () ? 'Multisite ' : '') . get_bloginfo ( 'version' ) . ' ' . get_locale () . ' ' . get_bloginfo( 'charset', 'display' ) ); - $this->addToDiagnostics ( 'WordPress Theme', wp_get_theme () ); - $this->addToDiagnostics ( 'WordPress Plugins', $this->getActivePlugins () ); + $transportRegistry = PostmanTransportRegistry::getInstance(); + $this->addToDiagnostics( 'OS', php_uname() ); + $this->addToDiagnostics( 'PHP', PHP_OS . ' ' . PHP_VERSION . ' ' . setlocale( LC_CTYPE, 0 ) ); + $this->addToDiagnostics( 'PHP Dependencies', $this->getPhpDependencies() ); + $this->addToDiagnostics( 'WordPress', (is_multisite() ? 'Multisite ' : '') . get_bloginfo( 'version' ) . ' ' . get_locale() . ' ' . get_bloginfo( 'charset', 'display' ) ); + $this->addToDiagnostics( 'WordPress Theme', wp_get_theme() ); + $this->addToDiagnostics( 'WordPress Plugins', $this->getActivePlugins() ); { - $bindResult = apply_filters ( 'postman_wp_mail_bind_status', null ); + $bindResult = apply_filters( 'postman_wp_mail_bind_status', null ); $wp_mail_file_name = 'n/a'; - if (class_exists ( 'ReflectionFunction' )) { - $wp_mail = new ReflectionFunction ( 'wp_mail' ); - $wp_mail_file_name = realpath ( $wp_mail->getFileName () ); - } - if (! $bindResult ['bound']) { - $this->addToDiagnostics ( 'WordPress wp_mail Owner', $wp_mail_file_name ); - } + if ( class_exists( 'ReflectionFunction' ) ) { + $wp_mail = new ReflectionFunction( 'wp_mail' ); + $wp_mail_file_name = realpath( $wp_mail->getFileName() ); + } + if ( ! $bindResult ['bound'] ) { + $this->addToDiagnostics( 'WordPress wp_mail Owner', $wp_mail_file_name ); } - $this->addToDiagnostics ( 'WordPress wp_mail Filter(s)', $this->getFilters ( 'wp_mail' ) ); - $this->addToDiagnostics ( 'WordPress wp_mail_from Filter(s)', $this->getFilters ( 'wp_mail_from' ) ); - $this->addToDiagnostics ( 'WordPress wp_mail_from_name Filter(s)', $this->getFilters ( 'wp_mail_from_name' ) ); - $this->addToDiagnostics ( 'WordPress wp_mail_content_type Filter(s)', $this->getFilters ( 'wp_mail_content_type' ) ); - $this->addToDiagnostics ( 'WordPress wp_mail_charset Filter(s)', $this->getFilters ( 'wp_mail_charset' ) ); - $this->addToDiagnostics ( 'WordPress phpmailer_init Action(s)', $this->getFilters ( 'phpmailer_init' ) ); - $pluginData = apply_filters ( 'postman_get_plugin_metadata', null ); - $this->addToDiagnostics ( 'Postman', $pluginData ['version'] ); + } + $this->addToDiagnostics( 'WordPress wp_mail Filter(s)', $this->getFilters( 'wp_mail' ) ); + $this->addToDiagnostics( 'WordPress wp_mail_from Filter(s)', $this->getFilters( 'wp_mail_from' ) ); + $this->addToDiagnostics( 'WordPress wp_mail_from_name Filter(s)', $this->getFilters( 'wp_mail_from_name' ) ); + $this->addToDiagnostics( 'WordPress wp_mail_content_type Filter(s)', $this->getFilters( 'wp_mail_content_type' ) ); + $this->addToDiagnostics( 'WordPress wp_mail_charset Filter(s)', $this->getFilters( 'wp_mail_charset' ) ); + $this->addToDiagnostics( 'WordPress phpmailer_init Action(s)', $this->getFilters( 'phpmailer_init' ) ); + $pluginData = apply_filters( 'postman_get_plugin_metadata', null ); + $this->addToDiagnostics( 'Postman', $pluginData ['version'] ); { - $s1 = $this->options->getEnvelopeSender (); - $s2 = $this->options->getMessageSenderEmail (); - if (! empty ( $s1 ) || ! empty ( $s2 )) { - $this->addToDiagnostics ( 'Postman Sender Domain (Envelope|Message)', ($hostname = substr ( strrchr ( $this->options->getEnvelopeSender (), "@" ), 1 )) . ' | ' . ($hostname = substr ( strrchr ( $this->options->getMessageSenderEmail (), "@" ), 1 )) ); - } + $s1 = $this->options->getEnvelopeSender(); + $s2 = $this->options->getMessageSenderEmail(); + if ( ! empty( $s1 ) || ! empty( $s2 ) ) { + $this->addToDiagnostics( 'Postman Sender Domain (Envelope|Message)', ($hostname = substr( strrchr( $this->options->getEnvelopeSender(), '@' ), 1 )) . ' | ' . ($hostname = substr( strrchr( $this->options->getMessageSenderEmail(), '@' ), 1 )) ); + } } - $this->addToDiagnostics ( 'Postman Prevent Message Sender Override (Email|Name)', ($this->options->isSenderEmailOverridePrevented () ? 'Yes' : 'No') . ' | ' . ($this->options->isSenderNameOverridePrevented () ? 'Yes' : 'No') ); + $this->addToDiagnostics( 'Postman Prevent Message Sender Override (Email|Name)', ($this->options->isSenderEmailOverridePrevented() ? 'Yes' : 'No') . ' | ' . ($this->options->isSenderNameOverridePrevented() ? 'Yes' : 'No') ); { // status of the active transport - $transport = $transportRegistry->getActiveTransport (); - $this->addToDiagnostics ( 'Postman Active Transport', sprintf ( '%s (%s)', $transport->getName (), $transportRegistry->getPublicTransportUri ( $transport ) ) ); - $this->addToDiagnostics ( 'Postman Active Transport Status (Ready|Connected)', ($transport->isConfiguredAndReady () ? 'Yes' : 'No') . ' | ' . ($this->testConnectivity ( $transport )) ); + $transport = $transportRegistry->getActiveTransport(); + $this->addToDiagnostics( 'Postman Active Transport', sprintf( '%s (%s)', $transport->getName(), $transportRegistry->getPublicTransportUri( $transport ) ) ); + $this->addToDiagnostics( 'Postman Active Transport Status (Ready|Connected)', ($transport->isConfiguredAndReady() ? 'Yes' : 'No') . ' | ' . ($this->testConnectivity( $transport )) ); } - if ($transportRegistry->getActiveTransport () != $transportRegistry->getSelectedTransport () && $transportRegistry->getSelectedTransport () != null) { + if ( $transportRegistry->getActiveTransport() != $transportRegistry->getSelectedTransport() && $transportRegistry->getSelectedTransport() != null ) { // status of the selected transport - $transport = $transportRegistry->getSelectedTransport (); - $this->addToDiagnostics ( 'Postman Selected Transport', sprintf ( '%s (%s)', $transport->getName (), $transportRegistry->getPublicTransportUri ( $transport ) ) ); - $this->addToDiagnostics ( 'Postman Selected Transport Status (Ready|Connected)', ($transport->isConfiguredAndReady () ? 'Yes' : 'No') . ' | ' . ($this->testConnectivity ( $transport )) ); + $transport = $transportRegistry->getSelectedTransport(); + $this->addToDiagnostics( 'Postman Selected Transport', sprintf( '%s (%s)', $transport->getName(), $transportRegistry->getPublicTransportUri( $transport ) ) ); + $this->addToDiagnostics( 'Postman Selected Transport Status (Ready|Connected)', ($transport->isConfiguredAndReady() ? 'Yes' : 'No') . ' | ' . ($this->testConnectivity( $transport )) ); } - $this->addToDiagnostics ( 'Postman Deliveries (Success|Fail)', (PostmanState::getInstance ()->getSuccessfulDeliveries ()) . ' | ' . (PostmanState::getInstance ()->getFailedDeliveries ()) ); - if ($this->options->getConnectionTimeout () != PostmanOptions::DEFAULT_TCP_CONNECTION_TIMEOUT || $this->options->getReadTimeout () != PostmanOptions::DEFAULT_TCP_READ_TIMEOUT) { - $this->addToDiagnostics ( 'Postman TCP Timeout (Connection|Read)', $this->options->getConnectionTimeout () . ' | ' . $this->options->getReadTimeout () ); + $this->addToDiagnostics( 'Postman Deliveries (Success|Fail)', (PostmanState::getInstance()->getSuccessfulDeliveries()) . ' | ' . (PostmanState::getInstance()->getFailedDeliveries()) ); + if ( $this->options->getConnectionTimeout() != PostmanOptions::DEFAULT_TCP_CONNECTION_TIMEOUT || $this->options->getReadTimeout() != PostmanOptions::DEFAULT_TCP_READ_TIMEOUT ) { + $this->addToDiagnostics( 'Postman TCP Timeout (Connection|Read)', $this->options->getConnectionTimeout() . ' | ' . $this->options->getReadTimeout() ); } - if ($this->options->isMailLoggingEnabled () != PostmanOptions::DEFAULT_MAIL_LOG_ENABLED || $this->options->getMailLoggingMaxEntries () != PostmanOptions::DEFAULT_MAIL_LOG_ENTRIES || $this->options->getTranscriptSize () != PostmanOptions::DEFAULT_TRANSCRIPT_SIZE) { - $this->addToDiagnostics ( 'Postman Email Log (Enabled|Limit|Transcript Size)', ($this->options->isMailLoggingEnabled () ? 'Yes' : 'No') . ' | ' . $this->options->getMailLoggingMaxEntries () . ' | ' . $this->options->getTranscriptSize () ); + if ( $this->options->isMailLoggingEnabled() != PostmanOptions::DEFAULT_MAIL_LOG_ENABLED || $this->options->getMailLoggingMaxEntries() != PostmanOptions::DEFAULT_MAIL_LOG_ENTRIES || $this->options->getTranscriptSize() != PostmanOptions::DEFAULT_TRANSCRIPT_SIZE ) { + $this->addToDiagnostics( 'Postman Email Log (Enabled|Limit|Transcript Size)', ($this->options->isMailLoggingEnabled() ? 'Yes' : 'No') . ' | ' . $this->options->getMailLoggingMaxEntries() . ' | ' . $this->options->getTranscriptSize() ); } - $this->addToDiagnostics ( 'Postman Run Mode', $this->options->getRunMode () == PostmanOptions::RUN_MODE_PRODUCTION ? null : $this->options->getRunMode () ); - $this->addToDiagnostics ( 'Postman PHP LogLevel', $this->options->getLogLevel () == PostmanLogger::ERROR_INT ? null : $this->options->getLogLevel () ); - $this->addToDiagnostics ( 'Postman Stealth Mode', $this->options->isStealthModeEnabled () ? 'Yes' : null ); - $this->addToDiagnostics ( 'Postman File Locking (Enabled|Temp Dir)', PostmanState::getInstance ()->isFileLockingEnabled () ? null : 'No' . ' | ' . $this->options->getTempDirectory () ); - $response = array ( - 'message' => $this->diagnostics + $this->addToDiagnostics( 'Postman Run Mode', $this->options->getRunMode() == PostmanOptions::RUN_MODE_PRODUCTION ? null : $this->options->getRunMode() ); + $this->addToDiagnostics( 'Postman PHP LogLevel', $this->options->getLogLevel() == PostmanLogger::ERROR_INT ? null : $this->options->getLogLevel() ); + $this->addToDiagnostics( 'Postman Stealth Mode', $this->options->isStealthModeEnabled() ? 'Yes' : null ); + $this->addToDiagnostics( 'Postman File Locking (Enabled|Temp Dir)', PostmanState::getInstance()->isFileLockingEnabled() ? null : 'No' . ' | ' . $this->options->getTempDirectory() ); + $response = array( + 'message' => $this->diagnostics, ); - wp_send_json_success ( $response ); + wp_send_json_success( $response ); } } diff --git a/Postman/Postman-Mail/PostmanMandrillMailEngine.php b/Postman/Postman-Mail/PostmanMandrillMailEngine.php index 4f68807..bd26e07 100644 --- a/Postman/Postman-Mail/PostmanMandrillMailEngine.php +++ b/Postman/Postman-Mail/PostmanMandrillMailEngine.php @@ -1,8 +1,8 @@ <?php -if (! class_exists ( "PostmanMandrillMailEngine" )) { - +if ( ! class_exists( 'PostmanMandrillMailEngine' ) ) { + require_once 'mailchimp-mandrill-api-php-da3adc10042e/src/Mandrill.php'; - + /** * Sends mail with Mandrill API * https://mandrillapp.com/api/docs/messages.php.html @@ -10,222 +10,221 @@ if (! class_exists ( "PostmanMandrillMailEngine" )) { * @author jasonhendriks */ class PostmanMandrillMailEngine implements PostmanMailEngine { - + // logger for all concrete classes - populate with setLogger($logger) protected $logger; - + // the result private $transcript; - - // + private $apiKey; private $mandrillMessage; - + /** * - * @param unknown $senderEmail - * @param unknown $accessToken + * @param unknown $senderEmail + * @param unknown $accessToken */ - function __construct($apiKey) { - assert ( ! empty ( $apiKey ) ); + function __construct( $apiKey ) { + assert( ! empty( $apiKey ) ); $this->apiKey = $apiKey; - + // create the logger - $this->logger = new PostmanLogger ( get_class ( $this ) ); - + $this->logger = new PostmanLogger( get_class( $this ) ); + // create the Message - $this->mandrillMessage = array ( - 'to' => array (), - 'headers' => array () + $this->mandrillMessage = array( + 'to' => array(), + 'headers' => array(), ); } - + /** * (non-PHPdoc) * * @see PostmanSmtpEngine::send() */ - public function send(PostmanMessage $message) { - $options = PostmanOptions::getInstance (); - + public function send( PostmanMessage $message ) { + $options = PostmanOptions::getInstance(); + // add the Postman signature - append it to whatever the user may have set - if (! $options->isStealthModeEnabled ()) { - $pluginData = apply_filters ( 'postman_get_plugin_metadata', null ); - $this->addHeader ( 'X-Mailer', sprintf ( 'Postman SMTP %s for WordPress (%s)', $pluginData ['version'], 'https://wordpress.org/plugins/postman-smtp/' ) ); + if ( ! $options->isStealthModeEnabled() ) { + $pluginData = apply_filters( 'postman_get_plugin_metadata', null ); + $this->addHeader( 'X-Mailer', sprintf( 'Postman SMTP %s for WordPress (%s)', $pluginData ['version'], 'https://wordpress.org/plugins/post-smtp/' ) ); } - + // add the headers - see http://framework.zend.com/manual/1.12/en/zend.mail.additional-headers.html - foreach ( ( array ) $message->getHeaders () as $header ) { - $this->logger->debug ( sprintf ( 'Adding user header %s=%s', $header ['name'], $header ['content'] ) ); - $this->addHeader ( $header ['name'], $header ['content'], true ); + foreach ( ( array ) $message->getHeaders() as $header ) { + $this->logger->debug( sprintf( 'Adding user header %s=%s', $header ['name'], $header ['content'] ) ); + $this->addHeader( $header ['name'], $header ['content'], true ); } - + // if the caller set a Content-Type header, use it - $contentType = $message->getContentType (); - if (! empty ( $contentType )) { - $this->logger->debug ( 'Adding content-type ' . $contentType ); - $this->addHeader ( 'Content-Type', $contentType ); + $contentType = $message->getContentType(); + if ( ! empty( $contentType ) ) { + $this->logger->debug( 'Adding content-type ' . $contentType ); + $this->addHeader( 'Content-Type', $contentType ); } - + // add the From Header - $sender = $message->getFromAddress (); + $sender = $message->getFromAddress(); { - $senderEmail = $sender->getEmail (); - $senderName = $sender->getName (); - assert ( ! empty ( $senderEmail ) ); + $senderEmail = $sender->getEmail(); + $senderName = $sender->getName(); + assert( ! empty( $senderEmail ) ); $this->mandrillMessage ['from_email'] = $senderEmail; - if (! empty ( $senderName )) { - $this->mandrillMessage ['from_name'] = $senderName; - } + if ( ! empty( $senderName ) ) { + $this->mandrillMessage ['from_name'] = $senderName; + } // now log it - $sender->log ( $this->logger, 'From' ); + $sender->log( $this->logger, 'From' ); } - + // add the Sender Header, overriding what the user may have set - $this->addHeader ( 'Sender', $options->getEnvelopeSender () ); - + $this->addHeader( 'Sender', $options->getEnvelopeSender() ); + // add the to recipients - foreach ( ( array ) $message->getToRecipients () as $recipient ) { - $recipient->log ( $this->logger, 'To' ); - $recipient = array ( - 'email' => $recipient->getEmail (), - 'name' => $recipient->getName (), - 'type' => 'to' + foreach ( ( array ) $message->getToRecipients() as $recipient ) { + $recipient->log( $this->logger, 'To' ); + $recipient = array( + 'email' => $recipient->getEmail(), + 'name' => $recipient->getName(), + 'type' => 'to', ); - array_push ( $this->mandrillMessage ['to'], $recipient ); + array_push( $this->mandrillMessage ['to'], $recipient ); } - + // add the cc recipients - foreach ( ( array ) $message->getCcRecipients () as $recipient ) { - $recipient->log ( $this->logger, 'Cc' ); - $recipient = array ( - 'email' => $recipient->getEmail (), - 'name' => $recipient->getName (), - 'type' => 'cc' + foreach ( ( array ) $message->getCcRecipients() as $recipient ) { + $recipient->log( $this->logger, 'Cc' ); + $recipient = array( + 'email' => $recipient->getEmail(), + 'name' => $recipient->getName(), + 'type' => 'cc', ); - array_push ( $this->mandrillMessage ['to'], $recipient ); + array_push( $this->mandrillMessage ['to'], $recipient ); } - + // add the bcc recipients - foreach ( ( array ) $message->getBccRecipients () as $recipient ) { - $recipient->log ( $this->logger, 'Bcc' ); - $recipient = array ( - 'email' => $recipient->getEmail (), - 'name' => $recipient->getName (), - 'type' => 'bcc' + foreach ( ( array ) $message->getBccRecipients() as $recipient ) { + $recipient->log( $this->logger, 'Bcc' ); + $recipient = array( + 'email' => $recipient->getEmail(), + 'name' => $recipient->getName(), + 'type' => 'bcc', ); - array_push ( $this->mandrillMessage ['to'], $recipient ); + array_push( $this->mandrillMessage ['to'], $recipient ); } - + // add the reply-to - $replyTo = $message->getReplyTo (); + $replyTo = $message->getReplyTo(); // $replyTo is null or a PostmanEmailAddress object - if (isset ( $replyTo )) { - $this->addHeader ( 'reply-to', $replyTo->format () ); + if ( isset( $replyTo ) ) { + $this->addHeader( 'reply-to', $replyTo->format() ); } - + // add the date - $date = $message->getDate (); - if (! empty ( $date )) { - $this->addHeader ( 'date', $message->getDate () ); + $date = $message->getDate(); + if ( ! empty( $date ) ) { + $this->addHeader( 'date', $message->getDate() ); } - + // add the messageId - $messageId = $message->getMessageId (); - if (! empty ( $messageId )) { - $this->addHeader ( 'message-id', $messageId ); + $messageId = $message->getMessageId(); + if ( ! empty( $messageId ) ) { + $this->addHeader( 'message-id', $messageId ); } - + // add the subject - if (null !== $message->getSubject ()) { - $this->mandrillMessage ['subject'] = $message->getSubject (); + if ( null !== $message->getSubject() ) { + $this->mandrillMessage ['subject'] = $message->getSubject(); } - + // add the message content { - $textPart = $message->getBodyTextPart (); - if (! empty ( $textPart )) { - $this->logger->debug ( 'Adding body as text' ); - $this->mandrillMessage ['text'] = $textPart; - } - $htmlPart = $message->getBodyHtmlPart (); - if (! empty ( $htmlPart )) { - $this->logger->debug ( 'Adding body as html' ); - $this->mandrillMessage ['html'] = $htmlPart; - } + $textPart = $message->getBodyTextPart(); + if ( ! empty( $textPart ) ) { + $this->logger->debug( 'Adding body as text' ); + $this->mandrillMessage ['text'] = $textPart; + } + $htmlPart = $message->getBodyHtmlPart(); + if ( ! empty( $htmlPart ) ) { + $this->logger->debug( 'Adding body as html' ); + $this->mandrillMessage ['html'] = $htmlPart; } - + } + // add attachments - $this->logger->debug ( "Adding attachments" ); - $this->addAttachmentsToMail ( $message ); - - $result = array (); + $this->logger->debug( 'Adding attachments' ); + $this->addAttachmentsToMail( $message ); + + $result = array(); try { - if ($this->logger->isDebug ()) { - $this->logger->debug ( "Creating Mandrill service with apiKey=" . $this->apiKey ); + if ( $this->logger->isDebug() ) { + $this->logger->debug( 'Creating Mandrill service with apiKey=' . $this->apiKey ); } - $mandrill = new Postman_Mandrill ( $this->apiKey ); - + $mandrill = new Postman_Mandrill( $this->apiKey ); + // send the message - if ($this->logger->isDebug ()) { - $this->logger->debug ( "Sending mail" ); + if ( $this->logger->isDebug() ) { + $this->logger->debug( 'Sending mail' ); } - - $result = $mandrill->messages->send ( $this->mandrillMessage ); - if ($this->logger->isInfo ()) { - $this->logger->info ( sprintf ( 'Message %d accepted for delivery', PostmanState::getInstance ()->getSuccessfulDeliveries () + 1 ) ); + + $result = $mandrill->messages->send( $this->mandrillMessage ); + if ( $this->logger->isInfo() ) { + $this->logger->info( sprintf( 'Message %d accepted for delivery', PostmanState::getInstance()->getSuccessfulDeliveries() + 1 ) ); } - - $this->transcript = print_r ( $result, true ); + + $this->transcript = print_r( $result, true ); $this->transcript .= PostmanModuleTransport::RAW_MESSAGE_FOLLOWS; - $this->transcript .= print_r ( $this->mandrillMessage, true ); + $this->transcript .= print_r( $this->mandrillMessage, true ); } catch ( Exception $e ) { - $this->transcript = $e->getMessage (); + $this->transcript = $e->getMessage(); $this->transcript .= PostmanModuleTransport::RAW_MESSAGE_FOLLOWS; - $this->transcript .= print_r ( $this->mandrillMessage, true ); + $this->transcript .= print_r( $this->mandrillMessage, true ); throw $e; } } - private function addHeader($key, $value, $append = false) { - $this->logger->debug ( 'Adding header: ' . $key . ' = ' . $value ); + private function addHeader( $key, $value, $append = false ) { + $this->logger->debug( 'Adding header: ' . $key . ' = ' . $value ); $header = &$this->mandrillMessage ['headers']; - if ($append && ! empty ( $header [$key] )) { - $header [$key] = $header [$key] . ', ' . $value; + if ( $append && ! empty( $header [ $key ] ) ) { + $header [ $key ] = $header [ $key ] . ', ' . $value; } else { - $header [$key] = $value; + $header [ $key ] = $value; } } - + /** * Add attachments to the message * - * @param Postman_Zend_Mail $mail + * @param Postman_Zend_Mail $mail */ - private function addAttachmentsToMail(PostmanMessage $message) { - $attachments = $message->getAttachments (); - if (isset ( $attachments )) { - $this->mandrillMessage ['attachments'] = array (); - if (! is_array ( $attachments )) { + private function addAttachmentsToMail( PostmanMessage $message ) { + $attachments = $message->getAttachments(); + if ( isset( $attachments ) ) { + $this->mandrillMessage ['attachments'] = array(); + if ( ! is_array( $attachments ) ) { // WordPress may a single filename or a newline-delimited string list of multiple filenames - $attArray = explode ( PHP_EOL, $attachments ); + $attArray = explode( PHP_EOL, $attachments ); } else { $attArray = $attachments; } // otherwise WordPress sends an array foreach ( $attArray as $file ) { - if (! empty ( $file )) { - $this->logger->debug ( "Adding attachment: " . $file ); - $attachment = array ( + if ( ! empty( $file ) ) { + $this->logger->debug( 'Adding attachment: ' . $file ); + $attachment = array( 'type' => 'attachment', - 'name' => basename ( $file ), - 'content' => file_get_contents ( $file ) + 'name' => basename( $file ), + 'content' => file_get_contents( $file ), ); - array_push ( $this->mandrillMessage ['attachments'], $attachment ); + array_push( $this->mandrillMessage ['attachments'], $attachment ); } } } } - + // return the SMTP session transcript public function getTranscript() { return $this->transcript; diff --git a/Postman/Postman-Mail/PostmanMessage.php b/Postman/Postman-Mail/PostmanMessage.php index bd852c4..f9b7dd3 100644 --- a/Postman/Postman-Mail/PostmanMessage.php +++ b/Postman/Postman-Mail/PostmanMessage.php @@ -1,8 +1,8 @@ <?php -if (! class_exists ( "PostmanMessage" )) { - +if ( ! class_exists( 'PostmanMessage' ) ) { + require_once 'PostmanEmailAddress.php'; - + /** * This class knows how to interface with Wordpress * including loading/saving to the database. @@ -11,14 +11,13 @@ if (! class_exists ( "PostmanMessage" )) { * http://framework.zend.com/manual/current/en/modules/zend.mail.smtp.options.html * * @author jasonhendriks - * */ class PostmanMessage { const EOL = "\r\n"; - + // logger for all concrete classes - populate with setLogger($logger) protected $logger; - + // set by the caller private $from; private $replyTo; @@ -33,44 +32,43 @@ if (! class_exists ( "PostmanMessage" )) { private $attachments; private $date; private $messageId; - + // determined by the send() method private $isTextHtml; private $contentType; private $charset; - - // + private $boundary; - + /** * No-argument constructor */ function __construct() { - $this->logger = new PostmanLogger ( get_class ( $this ) ); - $this->headers = array (); - $this->toRecipients = array (); - $this->ccRecipients = array (); - $this->bccRecipients = array (); + $this->logger = new PostmanLogger( get_class( $this ) ); + $this->headers = array(); + $this->toRecipients = array(); + $this->ccRecipients = array(); + $this->bccRecipients = array(); } - + /** * * @return boolean */ public function isBodyPartsEmpty() { - return empty ( $this->bodyTextPart ) && empty ( $this->bodyHtmlPart ); + return empty( $this->bodyTextPart ) && empty( $this->bodyHtmlPart ); } - + /** * - * @param PostmanModuleTransport $transport + * @param PostmanModuleTransport $transport */ - public function validate(PostmanModuleTransport $transport) { - if ($transport->isEmailValidationSupported ()) { - $this->internalValidate (); + public function validate( PostmanModuleTransport $transport ) { + if ( $transport->isEmailValidationSupported() ) { + $this->internalValidate(); } } - + /** * Create body parts based on content type * MyMail creates its own body parts @@ -78,176 +76,175 @@ if (! class_exists ( "PostmanMessage" )) { public function createBodyParts() { // modify the content-type to include the boundary - if (false !== stripos ( $this->contentType, 'multipart' ) && ! empty ( $this->boundary )) { + if ( false !== stripos( $this->contentType, 'multipart' ) && ! empty( $this->boundary ) ) { // Lines in email are terminated by CRLF ("\r\n") according to RFC2821 - $this->contentType = sprintf ( "%s;\r\n\t boundary=\"%s\"", $this->contentType, $this->getBoundary () ); + $this->contentType = sprintf( "%s;\r\n\t boundary=\"%s\"", $this->contentType, $this->getBoundary() ); } - - // - $body = $this->getBody (); - $contentType = $this->getContentType (); + + $body = $this->getBody(); + $contentType = $this->getContentType(); // add the message content as either text or html - if (empty ( $contentType ) || substr ( $contentType, 0, 10 ) === 'text/plain') { - $this->logger->debug ( 'Creating text body part' ); - $this->setBodyTextPart ( $body ); - } else if (substr ( $contentType, 0, 9 ) === 'text/html') { - $this->logger->debug ( 'Creating html body part' ); - $this->setBodyHtmlPart ( $body ); - } else if (substr ( $contentType, 0, 21 ) === 'multipart/alternative') { - $this->logger->debug ( 'Adding body as multipart/alternative' ); - $arr = explode ( PHP_EOL, $body ); + if ( empty( $contentType ) || substr( $contentType, 0, 10 ) === 'text/plain' ) { + $this->logger->debug( 'Creating text body part' ); + $this->setBodyTextPart( $body ); + } else if ( substr( $contentType, 0, 9 ) === 'text/html' ) { + $this->logger->debug( 'Creating html body part' ); + $this->setBodyHtmlPart( $body ); + } else if ( substr( $contentType, 0, 21 ) === 'multipart/alternative' ) { + $this->logger->debug( 'Adding body as multipart/alternative' ); + $arr = explode( PHP_EOL, $body ); $textBody = ''; $htmlBody = ''; $mode = ''; foreach ( $arr as $s ) { - $this->logger->trace ( 'mode: ' . $mode . ' bodyline: ' . $s ); - if (substr ( $s, 0, 25 ) === "Content-Type: text/plain;") { + $this->logger->trace( 'mode: ' . $mode . ' bodyline: ' . $s ); + if ( substr( $s, 0, 25 ) === 'Content-Type: text/plain;' ) { $mode = 'foundText'; - } else if (substr ( $s, 0, 24 ) === "Content-Type: text/html;") { + } else if ( substr( $s, 0, 24 ) === 'Content-Type: text/html;' ) { $mode = 'foundHtml'; - } else if ($mode == 'textReading') { + } else if ( $mode == 'textReading' ) { $textBody .= $s; - } else if ($mode == 'htmlReading') { + } else if ( $mode == 'htmlReading' ) { $htmlBody .= $s; - } else if ($mode == 'foundText') { - $trim = trim ( $s ); - if (empty ( $trim )) { + } else if ( $mode == 'foundText' ) { + $trim = trim( $s ); + if ( empty( $trim ) ) { $mode = 'textReading'; } - } else if ($mode == 'foundHtml') { - $trim = trim ( $s ); - if (empty ( $trim )) { + } else if ( $mode == 'foundHtml' ) { + $trim = trim( $s ); + if ( empty( $trim ) ) { $mode = 'htmlReading'; } } } - $this->setBodyHtmlPart ( $htmlBody ); - $this->setBodyTextPart ( $textBody ); + $this->setBodyHtmlPart( $htmlBody ); + $this->setBodyTextPart( $textBody ); } else { - $this->logger->error ( 'Unknown content-type: ' . $contentType ); - $this->setBodyTextPart ( $body ); + $this->logger->error( 'Unknown content-type: ' . $contentType ); + $this->setBodyTextPart( $body ); } } - + /** * Apply the WordPress filters to the email */ public function applyFilters() { - if ($this->logger->isDebug ()) { - $this->logger->debug ( 'Applying WordPress filters' ); + if ( $this->logger->isDebug() ) { + $this->logger->debug( 'Applying WordPress filters' ); } - + /** * Filter the email address to send from. * * @since 2.2.0 - * + * * @param string $from_email * Email address to send from. */ - $filteredEmail = apply_filters ( 'wp_mail_from', $this->getFromAddress ()->getEmail () ); - if ($this->logger->isTrace ()) { - $this->logger->trace ( 'wp_mail_from: ' . $filteredEmail ); + $filteredEmail = apply_filters( 'wp_mail_from', $this->getFromAddress()->getEmail() ); + if ( $this->logger->isTrace() ) { + $this->logger->trace( 'wp_mail_from: ' . $filteredEmail ); } - if ($this->getFromAddress ()->getEmail () !== $filteredEmail) { - $this->logger->debug ( sprintf ( 'Filtering From email address: before=%s after=%s', $this->getFromAddress ()->getEmail (), $filteredEmail ) ); - $this->getFromAddress ()->setEmail ( $filteredEmail ); + if ( $this->getFromAddress()->getEmail() !== $filteredEmail ) { + $this->logger->debug( sprintf( 'Filtering From email address: before=%s after=%s', $this->getFromAddress()->getEmail(), $filteredEmail ) ); + $this->getFromAddress()->setEmail( $filteredEmail ); } - + /** * Filter the name to associate with the "from" email address. * * @since 2.3.0 - * + * * @param string $from_name * Name associated with the "from" email address. */ - $filteredName = apply_filters ( 'wp_mail_from_name', $this->getFromAddress ()->getName () ); - if ($this->logger->isTrace ()) { - $this->logger->trace ( 'wp_mail_from_name: ' . $filteredName ); + $filteredName = apply_filters( 'wp_mail_from_name', $this->getFromAddress()->getName() ); + if ( $this->logger->isTrace() ) { + $this->logger->trace( 'wp_mail_from_name: ' . $filteredName ); } - if ($this->getFromAddress ()->getName () !== $filteredName) { - $this->logger->debug ( sprintf ( 'Filtering From email name: before=%s after=%s', $this->getFromAddress ()->getName (), $filteredName ) ); - $this->getFromAddress ()->setName ( $filteredName ); + if ( $this->getFromAddress()->getName() !== $filteredName ) { + $this->logger->debug( sprintf( 'Filtering From email name: before=%s after=%s', $this->getFromAddress()->getName(), $filteredName ) ); + $this->getFromAddress()->setName( $filteredName ); } - + /** * Filter the default wp_mail() charset. * * @since 2.3.0 - * + * * @param string $charset * Default email charset. */ - $filteredCharset = apply_filters ( 'wp_mail_charset', $this->getCharset () ); - if ($this->logger->isTrace ()) { - $this->logger->trace ( 'wp_mail_charset: ' . $filteredCharset ); + $filteredCharset = apply_filters( 'wp_mail_charset', $this->getCharset() ); + if ( $this->logger->isTrace() ) { + $this->logger->trace( 'wp_mail_charset: ' . $filteredCharset ); } - if ($this->getCharset () !== $filteredCharset) { - $this->logger->debug ( sprintf ( 'Filtering Charset: before=%s after=%s', $this->getCharset (), $filteredCharset ) ); - $this->setCharset ( $filteredCharset ); + if ( $this->getCharset() !== $filteredCharset ) { + $this->logger->debug( sprintf( 'Filtering Charset: before=%s after=%s', $this->getCharset(), $filteredCharset ) ); + $this->setCharset( $filteredCharset ); } - + /** * Filter the wp_mail() content type. * * @since 2.3.0 - * + * * @param string $content_type * Default wp_mail() content type. */ - $filteredContentType = apply_filters ( 'wp_mail_content_type', $this->getContentType () ); - if ($this->logger->isTrace ()) { - $this->logger->trace ( sprintf ( 'wp_mail_content_type: "%s"', $filteredContentType ) ); + $filteredContentType = apply_filters( 'wp_mail_content_type', $this->getContentType() ); + if ( $this->logger->isTrace() ) { + $this->logger->trace( sprintf( 'wp_mail_content_type: "%s"', $filteredContentType ) ); } - if ($this->getContentType () != $filteredContentType) { - $this->logger->debug ( sprintf ( 'Filtering Content-Type: before=%s after=%s', $this->getContentType (), $filteredContentType ) ); - $this->setContentType ( $filteredContentType ); + if ( $this->getContentType() != $filteredContentType ) { + $this->logger->debug( sprintf( 'Filtering Content-Type: before=%s after=%s', $this->getContentType(), $filteredContentType ) ); + $this->setContentType( $filteredContentType ); } - + // Postman has it's own 'user override' filter - $options = PostmanOptions::getInstance (); - $forcedEmailAddress = $options->getMessageSenderEmail (); - if ($options->isSenderEmailOverridePrevented () && $this->getFromAddress ()->getEmail () !== $forcedEmailAddress) { - $this->logger->debug ( sprintf ( 'Forced From email address: before=%s after=%s', $this->getFromAddress ()->getEmail (), $forcedEmailAddress ) ); - $this->getFromAddress ()->setEmail ( $forcedEmailAddress ); + $options = PostmanOptions::getInstance(); + $forcedEmailAddress = $options->getMessageSenderEmail(); + if ( $options->isSenderEmailOverridePrevented() && $this->getFromAddress()->getEmail() !== $forcedEmailAddress ) { + $this->logger->debug( sprintf( 'Forced From email address: before=%s after=%s', $this->getFromAddress()->getEmail(), $forcedEmailAddress ) ); + $this->getFromAddress()->setEmail( $forcedEmailAddress ); } - $forcedEmailName = $options->getMessageSenderName (); - if ($options->isSenderNameOverridePrevented () && $this->getFromAddress ()->getName () !== $forcedEmailName) { - $this->logger->debug ( sprintf ( 'Forced From email name: before=%s after=%s', $this->getFromAddress ()->getName (), $forcedEmailName ) ); - $this->getFromAddress ()->setName ( $forcedEmailName ); + $forcedEmailName = $options->getMessageSenderName(); + if ( $options->isSenderNameOverridePrevented() && $this->getFromAddress()->getName() !== $forcedEmailName ) { + $this->logger->debug( sprintf( 'Forced From email name: before=%s after=%s', $this->getFromAddress()->getName(), $forcedEmailName ) ); + $this->getFromAddress()->setName( $forcedEmailName ); } } - + /** * Check all email headers for errors * Throw an exception if an error is found */ private function internalValidate() { // check the reply-to address for errors - if (isset ( $this->replyTo )) { - $this->getReplyTo ()->validate ( 'Reply-To' ); + if ( isset( $this->replyTo ) ) { + $this->getReplyTo()->validate( 'Reply-To' ); } - + // check the from address for errors - $this->getFromAddress ()->validate ( 'From' ); - + $this->getFromAddress()->validate( 'From' ); + // validate the To recipients - foreach ( ( array ) $this->getToRecipients () as $toRecipient ) { - $toRecipient->validate ( 'To' ); + foreach ( ( array ) $this->getToRecipients() as $toRecipient ) { + $toRecipient->validate( 'To' ); } - + // validate the Cc recipients - foreach ( ( array ) $this->getCcRecipients () as $ccRecipient ) { - $ccRecipient->validate ( 'Cc' ); + foreach ( ( array ) $this->getCcRecipients() as $ccRecipient ) { + $ccRecipient->validate( 'Cc' ); } - + // validate the Bcc recipients - foreach ( ( array ) $this->getBccRecipients () as $bccRecipient ) { - $bccRecipient->validate ( 'Bcc' ); + foreach ( ( array ) $this->getBccRecipients() as $bccRecipient ) { + $bccRecipient->validate( 'Bcc' ); } } - + /** * * @return PostmanEmailAddress @@ -255,7 +252,7 @@ if (! class_exists ( "PostmanMessage" )) { public function getFromAddress() { return $this->from; } - + /** * Get the charset, checking first the WordPress bloginfo, then the header, then the wp_mail_charset filter. * @@ -264,16 +261,16 @@ if (! class_exists ( "PostmanMessage" )) { public function getCharset() { return $this->charset; } - + /** * Set the charset * - * @param unknown $charset + * @param unknown $charset */ - public function setCharset($charset) { + public function setCharset( $charset ) { $this->charset = $charset; } - + /** * Get the content type, checking first the header, then the wp_mail_content_type filter * @@ -282,7 +279,7 @@ if (! class_exists ( "PostmanMessage" )) { public function getContentType() { return $this->contentType; } - public function setContentType($contentType) { + public function setContentType( $contentType ) { $this->contentType = $contentType; } /** @@ -291,8 +288,8 @@ if (! class_exists ( "PostmanMessage" )) { * Array or comma-separated list of email addresses to send message. * @throws Exception */ - public function addTo($to) { - $this->addRecipients ( $this->toRecipients, $to ); + public function addTo( $to ) { + $this->addRecipients( $this->toRecipients, $to ); } /** * @@ -300,8 +297,8 @@ if (! class_exists ( "PostmanMessage" )) { * Array or comma-separated list of email addresses to send message. * @throws Exception */ - public function addCc($cc) { - $this->addRecipients ( $this->ccRecipients, $cc ); + public function addCc( $cc ) { + $this->addRecipients( $this->ccRecipients, $cc ); } /** * @@ -309,8 +306,8 @@ if (! class_exists ( "PostmanMessage" )) { * Array or comma-separated list of email addresses to send message. * @throws Exception */ - public function addBcc($bcc) { - $this->addRecipients ( $this->bccRecipients, $bcc ); + public function addBcc( $bcc ) { + $this->addRecipients( $this->bccRecipients, $bcc ); } /** * @@ -318,208 +315,208 @@ if (! class_exists ( "PostmanMessage" )) { * Array or comma-separated list of email addresses to send message. * @throws Exception */ - private function addRecipients(&$recipientList, $recipients) { - if (! empty ( $recipients )) { - $recipients = PostmanEmailAddress::convertToArray ( $recipients ); + private function addRecipients( &$recipientList, $recipients ) { + if ( ! empty( $recipients ) ) { + $recipients = PostmanEmailAddress::convertToArray( $recipients ); foreach ( $recipients as $recipient ) { - if (! empty ( $recipient )) { - $this->logger->debug ( sprintf ( 'User added recipient: "%s"', $recipient ) ); - array_push ( $recipientList, new PostmanEmailAddress ( $recipient ) ); + if ( ! empty( $recipient ) ) { + $this->logger->debug( sprintf( 'User added recipient: "%s"', $recipient ) ); + array_push( $recipientList, new PostmanEmailAddress( $recipient ) ); } } } } - + /** * For the string version, each header line (beginning with From:, Cc:, etc.) is delimited with a newline ("\r\n") */ - public function addHeaders($headers) { - if (! is_array ( $headers )) { + public function addHeaders( $headers ) { + if ( ! is_array( $headers ) ) { // WordPress may send a string where "each header line (beginning with From:, Cc:, etc.) is delimited with a newline ("\r\n") (advanced)" // this converts that string to an array - $headers = explode ( "\n", str_replace ( "\r\n", "\n", $headers ) ); + $headers = explode( "\n", str_replace( "\r\n", "\n", $headers ) ); // $headers = explode ( PHP_EOL, $headers ); } // otherwise WordPress sends an array foreach ( $headers as $header ) { - if (! empty ( $header )) { + if ( ! empty( $header ) ) { // boundary may be in a header line, but it's not a header // eg. boundary="----=_NextPart_DC7E1BB5... - if (strpos ( $header, ':' ) === false) { - if (false !== stripos ( $header, 'boundary=' )) { - $parts = preg_split ( '/boundary=/i', trim ( $header ) ); - $this->boundary = trim ( str_replace ( array ( + if ( strpos( $header, ':' ) === false ) { + if ( false !== stripos( $header, 'boundary=' ) ) { + $parts = preg_split( '/boundary=/i', trim( $header ) ); + $this->boundary = trim( str_replace( array( "'", - '"' + '"', ), '', $parts [1] ) ); - $this->logger->debug ( sprintf ( 'Processing special boundary header \'%s\'', $this->getBoundary () ) ); + $this->logger->debug( sprintf( 'Processing special boundary header \'%s\'', $this->getBoundary() ) ); } else { - $this->logger->debug ( sprintf ( 'Ignoring broken header \'%s\'', $header ) ); + $this->logger->debug( sprintf( 'Ignoring broken header \'%s\'', $header ) ); } continue; } - list ( $name, $content ) = explode ( ':', trim ( $header ), 2 ); - $this->processHeader ( $name, $content ); + list ( $name, $content ) = explode( ':', trim( $header ), 2 ); + $this->processHeader( $name, $content ); } } } - + /** * Add the headers that were processed in processHeaders() * Zend requires that several headers are specially handled. * - * @param unknown $name - * @param unknown $value - * @param Postman_Zend_Mail $mail + * @param unknown $name + * @param unknown $value + * @param Postman_Zend_Mail $mail */ - private function processHeader($name, $content) { - $name = trim ( $name ); - $content = trim ( $content ); - switch (strtolower ( $name )) { + private function processHeader( $name, $content ) { + $name = trim( $name ); + $content = trim( $content ); + switch ( strtolower( $name ) ) { case 'content-type' : - $this->logProcessHeader ( 'Content-Type', $name, $content ); - if (strpos ( $content, ';' ) !== false) { - list ( $type, $charset ) = explode ( ';', $content ); - $this->setContentType ( trim ( $type ) ); - if (false !== stripos ( $charset, 'charset=' )) { - $charset = trim ( str_replace ( array ( + $this->logProcessHeader( 'Content-Type', $name, $content ); + if ( strpos( $content, ';' ) !== false ) { + list ( $type, $charset ) = explode( ';', $content ); + $this->setContentType( trim( $type ) ); + if ( false !== stripos( $charset, 'charset=' ) ) { + $charset = trim( str_replace( array( 'charset=', - '"' + '"', ), '', $charset ) ); - } elseif (false !== stripos ( $charset, 'boundary=' )) { - $this->boundary = trim ( str_replace ( array ( + } elseif ( false !== stripos( $charset, 'boundary=' ) ) { + $this->boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', - '"' + '"', ), '', $charset ) ); $charset = ''; } - if (! empty ( $charset )) { - $this->setCharset ( $charset ); + if ( ! empty( $charset ) ) { + $this->setCharset( $charset ); } } else { - $this->setContentType ( trim ( $content ) ); + $this->setContentType( trim( $content ) ); } break; case 'to' : - $this->logProcessHeader ( 'To', $name, $content ); - $this->addTo ( $content ); + $this->logProcessHeader( 'To', $name, $content ); + $this->addTo( $content ); break; case 'cc' : - $this->logProcessHeader ( 'Cc', $name, $content ); - $this->addCc ( $content ); + $this->logProcessHeader( 'Cc', $name, $content ); + $this->addCc( $content ); break; case 'bcc' : - $this->logProcessHeader ( 'Bcc', $name, $content ); - $this->addBcc ( $content ); + $this->logProcessHeader( 'Bcc', $name, $content ); + $this->addBcc( $content ); break; case 'from' : - $this->logProcessHeader ( 'From', $name, $content ); - $this->setFrom ( $content ); + $this->logProcessHeader( 'From', $name, $content ); + $this->setFrom( $content ); break; case 'subject' : - $this->logProcessHeader ( 'Subject', $name, $content ); - $this->setSubject ( $content ); + $this->logProcessHeader( 'Subject', $name, $content ); + $this->setSubject( $content ); break; case 'reply-to' : - $this->logProcessHeader ( 'Reply-To', $name, $content ); - $this->setReplyTo ( $content ); + $this->logProcessHeader( 'Reply-To', $name, $content ); + $this->setReplyTo( $content ); break; case 'sender' : - $this->logProcessHeader ( 'Sender', $name, $content ); - $this->logger->warn ( sprintf ( 'Ignoring Sender header \'%s\'', $content ) ); + $this->logProcessHeader( 'Sender', $name, $content ); + $this->logger->warn( sprintf( 'Ignoring Sender header \'%s\'', $content ) ); break; case 'return-path' : - $this->logProcessHeader ( 'Return-Path', $name, $content ); - $this->logger->warn ( sprintf ( 'Ignoring Return-Path header \'%s\'', $content ) ); + $this->logProcessHeader( 'Return-Path', $name, $content ); + $this->logger->warn( sprintf( 'Ignoring Return-Path header \'%s\'', $content ) ); break; case 'date' : - $this->logProcessHeader ( 'Date', $name, $content ); - $this->setDate ( $content ); + $this->logProcessHeader( 'Date', $name, $content ); + $this->setDate( $content ); break; case 'message-id' : - $this->logProcessHeader ( 'Message-Id', $name, $content ); - $this->setMessageId ( $content ); + $this->logProcessHeader( 'Message-Id', $name, $content ); + $this->setMessageId( $content ); break; default : // Add it to our grand headers array - $this->logProcessHeader ( 'other', $name, $content ); - array_push ( $this->headers, array ( + $this->logProcessHeader( 'other', $name, $content ); + array_push( $this->headers, array( 'name' => $name, - 'content' => $content + 'content' => $content, ) ); break; } } - + /** * - * @param unknown $desc - * @param unknown $name - * @param unknown $content + * @param unknown $desc + * @param unknown $name + * @param unknown $content */ - private function logProcessHeader($desc, $name, $content) { - $this->logger->debug ( 'Processing ' . $desc . ' Header - ' . $name . ': ' . $content ); + private function logProcessHeader( $desc, $name, $content ) { + $this->logger->debug( 'Processing ' . $desc . ' Header - ' . $name . ': ' . $content ); } - + /** * Add attachments to the message * - * @param Postman_Zend_Mail $mail + * @param Postman_Zend_Mail $mail */ - public function addAttachmentsToMail(Postman_Zend_Mail $mail) { + public function addAttachmentsToMail( Postman_Zend_Mail $mail ) { $attachments = $this->attachments; - if (! is_array ( $attachments )) { + if ( ! is_array( $attachments ) ) { // WordPress may a single filename or a newline-delimited string list of multiple filenames - $attArray = explode ( PHP_EOL, $attachments ); + $attArray = explode( PHP_EOL, $attachments ); } else { $attArray = $attachments; } // otherwise WordPress sends an array foreach ( $attArray as $file ) { - if (! empty ( $file )) { - $this->logger->debug ( "Adding attachment: " . $file ); - $at = new Postman_Zend_Mime_Part ( file_get_contents ( $file ) ); + if ( ! empty( $file ) ) { + $this->logger->debug( 'Adding attachment: ' . $file ); + $at = new Postman_Zend_Mime_Part( file_get_contents( $file ) ); // $at->type = 'image/gif'; $at->disposition = Postman_Zend_Mime::DISPOSITION_ATTACHMENT; $at->encoding = Postman_Zend_Mime::ENCODING_BASE64; - $at->filename = basename ( $file ); - $mail->addAttachment ( $at ); + $at->filename = basename( $file ); + $mail->addAttachment( $at ); } } } - function setBody($body) { + function setBody( $body ) { $this->body = $body; } - function setBodyTextPart($bodyTextPart) { + function setBodyTextPart( $bodyTextPart ) { $this->bodyTextPart = $bodyTextPart; } - function setBodyHtmlPart($bodyHtmlPart) { + function setBodyHtmlPart( $bodyHtmlPart ) { $this->bodyHtmlPart = $bodyHtmlPart; } - function setSubject($subject) { + function setSubject( $subject ) { $this->subject = $subject; } - function setAttachments($attachments) { + function setAttachments( $attachments ) { $this->attachments = $attachments; } - function setFrom($email, $name = null) { - if (! empty ( $email )) { - $this->from = new PostmanEmailAddress ( $email, $name ); + function setFrom( $email, $name = null ) { + if ( ! empty( $email ) ) { + $this->from = new PostmanEmailAddress( $email, $name ); } } - function setReplyTo($replyTo) { - if (! empty ( $replyTo )) { - $this->replyTo = new PostmanEmailAddress ( $replyTo ); + function setReplyTo( $replyTo ) { + if ( ! empty( $replyTo ) ) { + $this->replyTo = new PostmanEmailAddress( $replyTo ); } } - function setMessageId($messageId) { + function setMessageId( $messageId ) { $this->messageId = $messageId; } - function setDate($date) { + function setDate( $date ) { $this->date = $date; } - + // return the headers public function getHeaders() { return $this->headers; diff --git a/Postman/Postman-Mail/PostmanSendGridMailEngine.php b/Postman/Postman-Mail/PostmanSendGridMailEngine.php index 0798428..524955a 100644 --- a/Postman/Postman-Mail/PostmanSendGridMailEngine.php +++ b/Postman/Postman-Mail/PostmanSendGridMailEngine.php @@ -1,196 +1,194 @@ <?php -if (! class_exists ( "PostmanSendGridMailEngine" )) { - +if ( ! class_exists( 'PostmanSendGridMailEngine' ) ) { + require_once 'sendgrid-php-3.2.0/sendgrid-php.php'; - + /** * Sends mail with the SendGrid API * https://sendgrid.com/docs/API_Reference/Web_API/mail.html * * @author jasonhendriks - * */ class PostmanSendGridMailEngine implements PostmanMailEngine { - + // logger for all concrete classes - populate with setLogger($logger) protected $logger; - + // the result private $transcript; - - // + private $email; private $apiKey; - + /** * - * @param unknown $senderEmail - * @param unknown $accessToken + * @param unknown $senderEmail + * @param unknown $accessToken */ - function __construct($apiKey) { - assert ( ! empty ( $apiKey ) ); + function __construct( $apiKey ) { + assert( ! empty( $apiKey ) ); $this->apiKey = $apiKey; - + // create the logger - $this->logger = new PostmanLogger ( get_class ( $this ) ); - + $this->logger = new PostmanLogger( get_class( $this ) ); + // create the Message - $this->email = new SendGrid\Email (); + $this->email = new SendGrid\Email(); } - + /** * (non-PHPdoc) * * @see PostmanSmtpEngine::send() */ - public function send(PostmanMessage $message) { - $options = PostmanOptions::getInstance (); - + public function send( PostmanMessage $message ) { + $options = PostmanOptions::getInstance(); + // add the Postman signature - append it to whatever the user may have set - if (! $options->isStealthModeEnabled ()) { - $pluginData = apply_filters ( 'postman_get_plugin_metadata', null ); - $this->email->addHeader ( 'X-Mailer', sprintf ( 'Postman SMTP %s for WordPress (%s)', $pluginData ['version'], 'https://wordpress.org/plugins/postman-smtp/' ) ); + if ( ! $options->isStealthModeEnabled() ) { + $pluginData = apply_filters( 'postman_get_plugin_metadata', null ); + $this->email->addHeader( 'X-Mailer', sprintf( 'Postman SMTP %s for WordPress (%s)', $pluginData ['version'], 'https://wordpress.org/plugins/post-smtp/' ) ); } - + // add the headers - see http://framework.zend.com/manual/1.12/en/zend.mail.additional-headers.html - foreach ( ( array ) $message->getHeaders () as $header ) { - $this->logger->debug ( sprintf ( 'Adding user header %s=%s', $header ['name'], $header ['content'] ) ); - $this->email->addHeader ( $header ['name'], $header ['content'] ); + foreach ( ( array ) $message->getHeaders() as $header ) { + $this->logger->debug( sprintf( 'Adding user header %s=%s', $header ['name'], $header ['content'] ) ); + $this->email->addHeader( $header ['name'], $header ['content'] ); } - + // if the caller set a Content-Type header, use it - $contentType = $message->getContentType (); - if (! empty ( $contentType )) { - $this->logger->debug ( 'Adding content-type ' . $contentType ); - $this->email->addHeader ( 'Content-Type', $contentType ); + $contentType = $message->getContentType(); + if ( ! empty( $contentType ) ) { + $this->logger->debug( 'Adding content-type ' . $contentType ); + $this->email->addHeader( 'Content-Type', $contentType ); } - + // add the From Header - $sender = $message->getFromAddress (); + $sender = $message->getFromAddress(); { - $senderEmail = $sender->getEmail (); - $senderName = $sender->getName (); - assert ( ! empty ( $senderEmail ) ); - $this->email->setFrom ( $senderEmail ); - if (! empty ( $senderName )) { - $this->email->setFromName ( $senderName ); - } + $senderEmail = $sender->getEmail(); + $senderName = $sender->getName(); + assert( ! empty( $senderEmail ) ); + $this->email->setFrom( $senderEmail ); + if ( ! empty( $senderName ) ) { + $this->email->setFromName( $senderName ); + } // now log it - $sender->log ( $this->logger, 'From' ); + $sender->log( $this->logger, 'From' ); } - + // add the Sender Header, overriding what the user may have set - $this->email->addHeader ( 'Sender', $options->getEnvelopeSender () ); - + $this->email->addHeader( 'Sender', $options->getEnvelopeSender() ); + // add the to recipients - foreach ( ( array ) $message->getToRecipients () as $recipient ) { - $recipient->log ( $this->logger, 'To' ); - $this->email->addTo ( $recipient->getEmail (), $recipient->getName () ); + foreach ( ( array ) $message->getToRecipients() as $recipient ) { + $recipient->log( $this->logger, 'To' ); + $this->email->addTo( $recipient->getEmail(), $recipient->getName() ); } - + // add the cc recipients - foreach ( ( array ) $message->getCcRecipients () as $recipient ) { - $recipient->log ( $this->logger, 'Cc' ); - $this->email->addCc ( $recipient->getEmail (), $recipient->getName () ); + foreach ( ( array ) $message->getCcRecipients() as $recipient ) { + $recipient->log( $this->logger, 'Cc' ); + $this->email->addCc( $recipient->getEmail(), $recipient->getName() ); } - + // add the bcc recipients - foreach ( ( array ) $message->getBccRecipients () as $recipient ) { - $recipient->log ( $this->logger, 'Bcc' ); - $this->email->addBcc ( $recipient->getEmail (), $recipient->getName () ); + foreach ( ( array ) $message->getBccRecipients() as $recipient ) { + $recipient->log( $this->logger, 'Bcc' ); + $this->email->addBcc( $recipient->getEmail(), $recipient->getName() ); } - + // add the reply-to - $replyTo = $message->getReplyTo (); + $replyTo = $message->getReplyTo(); // $replyTo is null or a PostmanEmailAddress object - if (isset ( $replyTo )) { - $this->email->setReplyTo ( $replyTo->format () ); + if ( isset( $replyTo ) ) { + $this->email->setReplyTo( $replyTo->format() ); } - + // add the date - $date = $message->getDate (); - if (! empty ( $date )) { - $this->email->setDate ( $message->getDate () ); + $date = $message->getDate(); + if ( ! empty( $date ) ) { + $this->email->setDate( $message->getDate() ); } - + // add the messageId - $messageId = $message->getMessageId (); - if (! empty ( $messageId )) { - $this->email->addHeader ( 'message-id', $messageId ); + $messageId = $message->getMessageId(); + if ( ! empty( $messageId ) ) { + $this->email->addHeader( 'message-id', $messageId ); } - + // add the subject - if (null !== $message->getSubject ()) { - $this->email->setSubject ( $message->getSubject () ); + if ( null !== $message->getSubject() ) { + $this->email->setSubject( $message->getSubject() ); } - + // add the message content { - $textPart = $message->getBodyTextPart (); - if (! empty ( $textPart )) { - $this->logger->debug ( 'Adding body as text' ); - $this->email->setText ( $textPart ); - } - $htmlPart = $message->getBodyHtmlPart (); - if (! empty ( $htmlPart )) { - $this->logger->debug ( 'Adding body as html' ); - $this->email->setHtml ( $htmlPart ); - } + $textPart = $message->getBodyTextPart(); + if ( ! empty( $textPart ) ) { + $this->logger->debug( 'Adding body as text' ); + $this->email->setText( $textPart ); } - + $htmlPart = $message->getBodyHtmlPart(); + if ( ! empty( $htmlPart ) ) { + $this->logger->debug( 'Adding body as html' ); + $this->email->setHtml( $htmlPart ); + } + } + // add attachments - $this->logger->debug ( "Adding attachments" ); - $this->addAttachmentsToMail ( $message ); - - $result = array (); + $this->logger->debug( 'Adding attachments' ); + $this->addAttachmentsToMail( $message ); + + $result = array(); try { - - if ($this->logger->isDebug ()) { - $this->logger->debug ( "Creating SendGrid service with apiKey=" . $this->apiKey ); + + if ( $this->logger->isDebug() ) { + $this->logger->debug( 'Creating SendGrid service with apiKey=' . $this->apiKey ); } - $sendgrid = new SendGrid ( $this->apiKey ); - + $sendgrid = new SendGrid( $this->apiKey ); + // send the message - if ($this->logger->isDebug ()) { - $this->logger->debug ( "Sending mail" ); + if ( $this->logger->isDebug() ) { + $this->logger->debug( 'Sending mail' ); } - $result = $sendgrid->send ( $this->email ); - if ($this->logger->isInfo ()) { - $this->logger->info ( ); + $result = $sendgrid->send( $this->email ); + if ( $this->logger->isInfo() ) { + $this->logger->info( ); } - $this->transcript = print_r ( $result, true ); + $this->transcript = print_r( $result, true ); $this->transcript .= PostmanModuleTransport::RAW_MESSAGE_FOLLOWS; - $this->transcript .= print_r ( $this->email, true ); + $this->transcript .= print_r( $this->email, true ); } catch ( SendGrid\Exception $e ) { - $this->transcript = $e->getMessage (); + $this->transcript = $e->getMessage(); $this->transcript .= PostmanModuleTransport::RAW_MESSAGE_FOLLOWS; - $this->transcript .= print_r ( $this->email, true ); + $this->transcript .= print_r( $this->email, true ); throw $e; } } - + /** * Add attachments to the message * - * @param Postman_Zend_Mail $mail + * @param Postman_Zend_Mail $mail */ - private function addAttachmentsToMail(PostmanMessage $message) { - $attachments = $message->getAttachments (); - if (! is_array ( $attachments )) { + private function addAttachmentsToMail( PostmanMessage $message ) { + $attachments = $message->getAttachments(); + if ( ! is_array( $attachments ) ) { // WordPress may a single filename or a newline-delimited string list of multiple filenames - $attArray = explode ( PHP_EOL, $attachments ); + $attArray = explode( PHP_EOL, $attachments ); } else { $attArray = $attachments; } // otherwise WordPress sends an array foreach ( $attArray as $file ) { - if (! empty ( $file )) { - $this->logger->debug ( "Adding attachment: " . $file ); - $this->email->addAttachment ( basename ( $file ) ); + if ( ! empty( $file ) ) { + $this->logger->debug( 'Adding attachment: ' . $file ); + $this->email->addAttachment( $file ); } } } - + // return the SMTP session transcript public function getTranscript() { return $this->transcript; diff --git a/Postman/Postman-Mail/PostmanSmtpModuleTransport.php b/Postman/Postman-Mail/PostmanSmtpModuleTransport.php index 5c45ded..2526d92 100644 --- a/Postman/Postman-Mail/PostmanSmtpModuleTransport.php +++ b/Postman/Postman-Mail/PostmanSmtpModuleTransport.php @@ -4,20 +4,19 @@ require_once 'PostmanModuleTransport.php'; /** * * @author jasonhendriks - * */ class PostmanSmtpModuleTransport extends PostmanAbstractZendModuleTransport implements PostmanZendModuleTransport { const SLUG = 'smtp'; - public function __construct($rootPluginFilenameAndPath) { - parent::__construct ( $rootPluginFilenameAndPath ); - + public function __construct( $rootPluginFilenameAndPath ) { + parent::__construct( $rootPluginFilenameAndPath ); + // add a hook on the plugins_loaded event - add_action ( 'admin_init', array ( + add_action( 'admin_init', array( $this, - 'on_admin_init' + 'on_admin_init', ) ); } - + /** * (non-PHPdoc) * @@ -25,30 +24,30 @@ class PostmanSmtpModuleTransport extends PostmanAbstractZendModuleTransport impl */ public function createMailEngine() { require_once 'PostmanZendMailEngine.php'; - return new PostmanZendMailEngine ( $this ); + return new PostmanZendMailEngine( $this ); } - + /** * (non-PHPdoc) * * @see PostmanZendModuleTransport::createZendMailTransport() */ - public function createZendMailTransport($fakeHostname, $fakeConfig) { - if (PostmanOptions::AUTHENTICATION_TYPE_OAUTH2 == $this->getAuthenticationType ()) { - $config = PostmanOAuth2ConfigurationFactory::createConfig ( $this ); + public function createZendMailTransport( $fakeHostname, $fakeConfig ) { + if ( PostmanOptions::AUTHENTICATION_TYPE_OAUTH2 == $this->getAuthenticationType() ) { + $config = PostmanOAuth2ConfigurationFactory::createConfig( $this ); } else { - $config = PostmanBasicAuthConfigurationFactory::createConfig ( $this ); + $config = PostmanBasicAuthConfigurationFactory::createConfig( $this ); } - return new Postman_Zend_Mail_Transport_Smtp ( $this->getHostname (), $config ); + return new Postman_Zend_Mail_Transport_Smtp( $this->getHostname(), $config ); } - + /** * Determines whether Mail Engine locking is needed * * @see PostmanModuleTransport::requiresLocking() */ public function isLockingRequired() { - return PostmanOptions::AUTHENTICATION_TYPE_OAUTH2 == $this->getAuthenticationType (); + return PostmanOptions::AUTHENTICATION_TYPE_OAUTH2 == $this->getAuthenticationType(); } public function getSlug() { return self::SLUG; @@ -58,193 +57,193 @@ class PostmanSmtpModuleTransport extends PostmanAbstractZendModuleTransport impl } public function getHostname() { $this->options = $this->options; - return $this->options->getHostname (); + return $this->options->getHostname(); } public function getPort() { $this->options = $this->options; - return $this->options->getPort (); + return $this->options->getPort(); } public function getAuthenticationType() { - return $this->options->getAuthenticationType (); + return $this->options->getAuthenticationType(); } public function getCredentialsId() { $this->options = $this->options; - if ($this->options->isAuthTypeOAuth2 ()) { - return $this->options->getClientId (); + if ( $this->options->isAuthTypeOAuth2() ) { + return $this->options->getClientId(); } else { - return $this->options->getUsername (); + return $this->options->getUsername(); } } public function getCredentialsSecret() { $this->options = $this->options; - if ($this->options->isAuthTypeOAuth2 ()) { - return $this->options->getClientSecret (); + if ( $this->options->isAuthTypeOAuth2() ) { + return $this->options->getClientSecret(); } else { - return $this->options->getPassword (); + return $this->options->getPassword(); } } - + /** * (non-PHPdoc) * * @see PostmanTransport::getMisconfigurationMessage() */ protected function validateTransportConfiguration() { - $messages = parent::validateTransportConfiguration (); - if (! $this->isHostConfigured ( $this->options )) { - array_push ( $messages, __ ( 'Outgoing Mail Server Hostname and Port can not be empty.', Postman::TEXT_DOMAIN ) ); - $this->setNotConfiguredAndReady (); + $messages = parent::validateTransportConfiguration(); + if ( ! $this->isHostConfigured( $this->options ) ) { + array_push( $messages, __( 'Outgoing Mail Server Hostname and Port can not be empty.', Postman::TEXT_DOMAIN ) ); + $this->setNotConfiguredAndReady(); } - if (! $this->isEnvelopeFromConfigured ()) { - array_push ( $messages, __ ( 'Envelope-From Email Address can not be empty', Postman::TEXT_DOMAIN ) . '.' ); - $this->setNotConfiguredAndReady (); + if ( ! $this->isEnvelopeFromConfigured() ) { + array_push( $messages, __( 'Envelope-From Email Address can not be empty', Postman::TEXT_DOMAIN ) . '.' ); + $this->setNotConfiguredAndReady(); } - if ($this->options->isAuthTypePassword () && ! $this->isPasswordAuthenticationConfigured ( $this->options )) { - array_push ( $messages, __ ( 'Username and password can not be empty.', Postman::TEXT_DOMAIN ) ); - $this->setNotConfiguredAndReady (); + if ( $this->options->isAuthTypePassword() && ! $this->isPasswordAuthenticationConfigured( $this->options ) ) { + array_push( $messages, __( 'Username and password can not be empty.', Postman::TEXT_DOMAIN ) ); + $this->setNotConfiguredAndReady(); } - if ($this->getAuthenticationType () == PostmanOptions::AUTHENTICATION_TYPE_OAUTH2) { - if (! $this->isOAuth2SupportedHostConfigured ()) { + if ( $this->getAuthenticationType() == PostmanOptions::AUTHENTICATION_TYPE_OAUTH2 ) { + if ( ! $this->isOAuth2SupportedHostConfigured() ) { /* translators: %1$s is the Client ID label, and %2$s is the Client Secret label (e.g. Warning: OAuth 2.0 authentication requires an OAuth 2.0-capable Outgoing Mail Server, Sender Email Address, Client ID, and Client Secret.) */ - array_push ( $messages, sprintf ( __ ( 'OAuth 2.0 authentication requires a supported OAuth 2.0-capable Outgoing Mail Server.', Postman::TEXT_DOMAIN ) ) ); - $this->setNotConfiguredAndReady (); + array_push( $messages, sprintf( __( 'OAuth 2.0 authentication requires a supported OAuth 2.0-capable Outgoing Mail Server.', Postman::TEXT_DOMAIN ) ) ); + $this->setNotConfiguredAndReady(); } } - if (empty ( $messages )) { - $this->setReadyForOAuthGrant (); - if ($this->isPermissionNeeded ( $this->options, $this->getOAuthToken () )) { + if ( empty( $messages ) ) { + $this->setReadyForOAuthGrant(); + if ( $this->isPermissionNeeded( $this->options, $this->getOAuthToken() ) ) { /* translators: %1$s is the Client ID label, and %2$s is the Client Secret label */ - $message = sprintf ( __ ( 'You have configured OAuth 2.0 authentication, but have not received permission to use it.', Postman::TEXT_DOMAIN ), $this->getScribe ()->getClientIdLabel (), $this->getScribe ()->getClientSecretLabel () ); - $message .= sprintf ( ' <a href="%s">%s</a>.', PostmanUtils::getGrantOAuthPermissionUrl (), $this->getScribe ()->getRequestPermissionLinkText () ); - array_push ( $messages, $message ); - $this->setNotConfiguredAndReady (); + $message = sprintf( __( 'You have configured OAuth 2.0 authentication, but have not received permission to use it.', Postman::TEXT_DOMAIN ), $this->getScribe()->getClientIdLabel(), $this->getScribe()->getClientSecretLabel() ); + $message .= sprintf( ' <a href="%s">%s</a>.', PostmanUtils::getGrantOAuthPermissionUrl(), $this->getScribe()->getRequestPermissionLinkText() ); + array_push( $messages, $message ); + $this->setNotConfiguredAndReady(); } } return $messages; } - + /** * * @return boolean */ private function isOAuth2SupportedHostConfigured() { - $options = PostmanOptions::getInstance (); - $hostname = $options->getHostname (); - $supportedOAuthProvider = $this->isServiceProviderGoogle ( $hostname ) || $this->isServiceProviderMicrosoft ( $hostname ) || $this->isServiceProviderYahoo ( $hostname ); + $options = PostmanOptions::getInstance(); + $hostname = $options->getHostname(); + $supportedOAuthProvider = $this->isServiceProviderGoogle( $hostname ) || $this->isServiceProviderMicrosoft( $hostname ) || $this->isServiceProviderYahoo( $hostname ); return $supportedOAuthProvider; } - + /** * Given a hostname, what ports should we test? * * May return an array of several combinations. */ - public function getSocketsForSetupWizardToProbe($hostname, $smtpServerGuess) { - $hosts = array ( - $this->createSocketDefinition ( $hostname, 25 ), - $this->createSocketDefinition ( $hostname, 465 ), - $this->createSocketDefinition ( $hostname, 587 ) + public function getSocketsForSetupWizardToProbe( $hostname, $smtpServerGuess ) { + $hosts = array( + $this->createSocketDefinition( $hostname, 25 ), + $this->createSocketDefinition( $hostname, 465 ), + $this->createSocketDefinition( $hostname, 587 ), ); - + return $hosts; } - + /** * Creates a single socket for the Wizard to test */ - protected function createSocketDefinition($hostname, $port) { - $socket = parent::createSocketDefinition ( $hostname, $port ); + protected function createSocketDefinition( $hostname, $port ) { + $socket = parent::createSocketDefinition( $hostname, $port ); $socket ['smtp'] = true; return $socket; } - + /** * SendGrid will never recommend it's configuration * - * @param unknown $hostData + * @param unknown $hostData */ - public function getConfigurationBid(PostmanWizardSocket $hostData, $userAuthOverride, $originalSmtpServer) { + public function getConfigurationBid( PostmanWizardSocket $hostData, $userAuthOverride, $originalSmtpServer ) { $port = $hostData->port; $hostname = $hostData->hostname; // because some servers, like smtp.broadband.rogers.com, report XOAUTH2 but have no OAuth2 front-end - $supportedOAuth2Provider = $this->isServiceProviderGoogle ( $hostname ) || $this->isServiceProviderMicrosoft ( $hostname ) || $this->isServiceProviderYahoo ( $hostname ); + $supportedOAuth2Provider = $this->isServiceProviderGoogle( $hostname ) || $this->isServiceProviderMicrosoft( $hostname ) || $this->isServiceProviderYahoo( $hostname ); $score = 1; - $recommendation = array (); + $recommendation = array(); // increment score for auth type - if ($hostData->mitm) { - $this->logger->debug ( 'Losing points for MITM' ); + if ( $hostData->mitm ) { + $this->logger->debug( 'Losing points for MITM' ); $score -= 10000; $recommendation ['mitm'] = true; } - if (! empty ( $originalSmtpServer ) && $hostname != $originalSmtpServer) { - $this->logger->debug ( 'Losing points for Not The Original SMTP server' ); + if ( ! empty( $originalSmtpServer ) && $hostname != $originalSmtpServer ) { + $this->logger->debug( 'Losing points for Not The Original SMTP server' ); $score -= 10000; } $secure = true; - if ($hostData->startTls) { + if ( $hostData->startTls ) { // STARTTLS was formalized in 2002 // http://www.rfc-editor.org/rfc/rfc3207.txt $recommendation ['enc'] = PostmanOptions::SECURITY_TYPE_STARTTLS; $score += 30000; - } elseif ($hostData->protocol == 'SMTPS') { + } elseif ( $hostData->protocol == 'SMTPS' ) { // "The hopelessly confusing and imprecise term, SSL, // has often been used to indicate the SMTPS wrapper and // TLS to indicate the STARTTLS protocol extension." // http://stackoverflow.com/a/19942206/4368109 $recommendation ['enc'] = PostmanOptions::SECURITY_TYPE_SMTPS; $score += 28000; - } elseif ($hostData->protocol == 'SMTP') { + } elseif ( $hostData->protocol == 'SMTP' ) { $recommendation ['enc'] = PostmanOptions::SECURITY_TYPE_NONE; $score += 26000; $secure = false; } - + // if there is a way to send mail.... - if ($score > 10) { - + if ( $score > 10 ) { + // determine the authentication type - if ($hostData->auth_xoauth && $supportedOAuth2Provider && (empty ( $userAuthOverride ) || $userAuthOverride == 'oauth2')) { + if ( $hostData->auth_xoauth && $supportedOAuth2Provider && (empty( $userAuthOverride ) || $userAuthOverride == 'oauth2') ) { $recommendation ['auth'] = PostmanOptions::AUTHENTICATION_TYPE_OAUTH2; $recommendation ['display_auth'] = 'oauth2'; $score += 500; - if (! $secure) { - $this->logger->debug ( 'Losing points for sending credentials in the clear' ); + if ( ! $secure ) { + $this->logger->debug( 'Losing points for sending credentials in the clear' ); $score -= 10000; } - } elseif ($hostData->auth_crammd5 && (empty ( $userAuthOverride ) || $userAuthOverride == 'password')) { + } elseif ( $hostData->auth_crammd5 && (empty( $userAuthOverride ) || $userAuthOverride == 'password') ) { $recommendation ['auth'] = PostmanOptions::AUTHENTICATION_TYPE_CRAMMD5; $recommendation ['display_auth'] = 'password'; $score += 400; - if (! $secure) { - $this->logger->debug ( 'Losing points for sending credentials in the clear' ); + if ( ! $secure ) { + $this->logger->debug( 'Losing points for sending credentials in the clear' ); $score -= 10000; } - } elseif ($hostData->authPlain && (empty ( $userAuthOverride ) || $userAuthOverride == 'password')) { + } elseif ( $hostData->authPlain && (empty( $userAuthOverride ) || $userAuthOverride == 'password') ) { $recommendation ['auth'] = PostmanOptions::AUTHENTICATION_TYPE_PLAIN; $recommendation ['display_auth'] = 'password'; $score += 300; - if (! $secure) { - $this->logger->debug ( 'Losing points for sending credentials in the clear' ); + if ( ! $secure ) { + $this->logger->debug( 'Losing points for sending credentials in the clear' ); $score -= 10000; } - } elseif ($hostData->auth_login && (empty ( $userAuthOverride ) || $userAuthOverride == 'password')) { + } elseif ( $hostData->auth_login && (empty( $userAuthOverride ) || $userAuthOverride == 'password') ) { $recommendation ['auth'] = PostmanOptions::AUTHENTICATION_TYPE_LOGIN; $recommendation ['display_auth'] = 'password'; $score += 200; - if (! $secure) { - $this->logger->debug ( 'Losing points for sending credentials in the clear' ); + if ( ! $secure ) { + $this->logger->debug( 'Losing points for sending credentials in the clear' ); $score -= 10000; } - } else if (empty ( $userAuthOverride ) || $userAuthOverride == 'none') { + } else if ( empty( $userAuthOverride ) || $userAuthOverride == 'none' ) { $recommendation ['auth'] = PostmanOptions::AUTHENTICATION_TYPE_NONE; $recommendation ['display_auth'] = 'none'; $score += 100; } - + // tiny weighting to prejudice the port selection, all things being equal - if ($port == 587) { + if ( $port == 587 ) { $score += 4; - } elseif ($port == 25) { + } elseif ( $port == 25 ) { // "due to the prevalence of machines that have worms, // viruses, or other malicious software that generate large amounts of // spam, many sites now prohibit outbound traffic on the standard SMTP @@ -252,33 +251,33 @@ class PostmanSmtpModuleTransport extends PostmanAbstractZendModuleTransport impl // servers." // http://www.rfc-editor.org/rfc/rfc6409.txt $score += 3; - } elseif ($port == 465) { + } elseif ( $port == 465 ) { // use of port 465 for SMTP was deprecated in 1998 // http://www.imc.org/ietf-apps-tls/mail-archive/msg00204.html $score += 2; } else { $score += 1; } - + // create the recommendation message for the user // this can only be set if there is a valid ['auth'] and ['enc'] - $transportDescription = $this->getTransportDescription ( $recommendation ['enc'] ); - $authDesc = $this->getAuthenticationDescription ( $recommendation ['auth'] ); - $recommendation ['label'] = sprintf ( 'SMTP - %2$s:%3$d', $transportDescription, $hostData->hostnameDomainOnly, $port ); + $transportDescription = $this->getTransportDescription( $recommendation ['enc'] ); + $authDesc = $this->getAuthenticationDescription( $recommendation ['auth'] ); + $recommendation ['label'] = sprintf( 'SMTP - %2$s:%3$d', $transportDescription, $hostData->hostnameDomainOnly, $port ); /* translators: where %1$s is a description of the transport (eg. SMTPS-SSL), %2$s is a description of the authentication (eg. Password-CRAMMD5), %3$d is the TCP port (eg. 465), %4$d is the hostname */ - $recommendation ['message'] = sprintf ( __ ( 'Postman recommends %1$s with %2$s authentication to host %4$s on port %3$d.', Postman::TEXT_DOMAIN ), $transportDescription, $authDesc, $port, $hostname ); + $recommendation ['message'] = sprintf( __( 'Postman recommends %1$s with %2$s authentication to host %4$s on port %3$d.', Postman::TEXT_DOMAIN ), $transportDescription, $authDesc, $port, $hostname ); } - + // fill-in the rest of the recommendation $recommendation ['transport'] = PostmanSmtpModuleTransport::SLUG; $recommendation ['priority'] = $score; $recommendation ['port'] = $port; $recommendation ['hostname'] = $hostname; $recommendation ['transport'] = self::SLUG; - + return $recommendation; } - + /** * Functions to execute on the admin_init event * @@ -287,303 +286,303 @@ class PostmanSmtpModuleTransport extends PostmanAbstractZendModuleTransport impl */ public function on_admin_init() { // only administrators should be able to trigger this - if (PostmanUtils::isAdmin ()) { - $this->addSettings (); - $this->registerStylesAndScripts (); + if ( PostmanUtils::isAdmin() ) { + $this->addSettings(); + $this->registerStylesAndScripts(); } } - + /** */ public function registerStylesAndScripts() { // register the stylesheet and javascript external resources - $pluginData = apply_filters ( 'postman_get_plugin_metadata', null ); - wp_register_script ( 'postman_smtp_script', plugins_url ( 'Postman/Postman-Mail/postman_smtp.js', $this->rootPluginFilenameAndPath ), array ( + $pluginData = apply_filters( 'postman_get_plugin_metadata', null ); + wp_register_script( 'postman_smtp_script', plugins_url( 'Postman/Postman-Mail/postman_smtp.js', $this->rootPluginFilenameAndPath ), array( PostmanViewController::JQUERY_SCRIPT, 'jquery_validation', - PostmanViewController::POSTMAN_SCRIPT + PostmanViewController::POSTMAN_SCRIPT, ), $pluginData ['version'] ); } - + /* * What follows in the code responsible for creating the Admin Settings page */ - + /** */ public function enqueueScript() { - wp_enqueue_script ( 'postman_smtp_script' ); + wp_enqueue_script( 'postman_smtp_script' ); } - + /** */ public function addSettings() { $transport = $this; $this->options = $this->options; - $oauthScribe = $transport->getScribe (); - + $oauthScribe = $transport->getScribe(); + // Sanitize - add_settings_section ( PostmanAdminController::SMTP_SECTION, __ ( 'Transport Settings', Postman::TEXT_DOMAIN ), array ( + add_settings_section( PostmanAdminController::SMTP_SECTION, __( 'Transport Settings', Postman::TEXT_DOMAIN ), array( $this, - 'printSmtpSectionInfo' + 'printSmtpSectionInfo', ), PostmanAdminController::SMTP_OPTIONS ); - - add_settings_field ( PostmanOptions::HOSTNAME, __ ( 'Outgoing Mail Server Hostname', Postman::TEXT_DOMAIN ), array ( + + add_settings_field( PostmanOptions::HOSTNAME, __( 'Outgoing Mail Server Hostname', Postman::TEXT_DOMAIN ), array( $this, - 'hostname_callback' + 'hostname_callback', ), PostmanAdminController::SMTP_OPTIONS, PostmanAdminController::SMTP_SECTION ); - - add_settings_field ( PostmanOptions::PORT, __ ( 'Outgoing Mail Server Port', Postman::TEXT_DOMAIN ), array ( + + add_settings_field( PostmanOptions::PORT, __( 'Outgoing Mail Server Port', Postman::TEXT_DOMAIN ), array( $this, - 'port_callback' + 'port_callback', ), PostmanAdminController::SMTP_OPTIONS, PostmanAdminController::SMTP_SECTION ); - - add_settings_field ( PostmanOptions::ENVELOPE_SENDER, __ ( 'Envelope-From Email Address', Postman::TEXT_DOMAIN ), array ( + + add_settings_field( PostmanOptions::ENVELOPE_SENDER, __( 'Envelope-From Email Address', Postman::TEXT_DOMAIN ), array( $this, - 'sender_email_callback' + 'sender_email_callback', ), PostmanAdminController::SMTP_OPTIONS, PostmanAdminController::SMTP_SECTION ); - - add_settings_field ( PostmanOptions::SECURITY_TYPE, _x ( 'Security', 'Configuration Input Field', Postman::TEXT_DOMAIN ), array ( + + add_settings_field( PostmanOptions::SECURITY_TYPE, _x( 'Security', 'Configuration Input Field', Postman::TEXT_DOMAIN ), array( $this, - 'encryption_type_callback' + 'encryption_type_callback', ), PostmanAdminController::SMTP_OPTIONS, PostmanAdminController::SMTP_SECTION ); - - add_settings_field ( PostmanOptions::AUTHENTICATION_TYPE, __ ( 'Authentication', Postman::TEXT_DOMAIN ), array ( + + add_settings_field( PostmanOptions::AUTHENTICATION_TYPE, __( 'Authentication', Postman::TEXT_DOMAIN ), array( $this, - 'authentication_type_callback' + 'authentication_type_callback', ), PostmanAdminController::SMTP_OPTIONS, PostmanAdminController::SMTP_SECTION ); - - add_settings_section ( PostmanAdminController::BASIC_AUTH_SECTION, __ ( 'Authentication', Postman::TEXT_DOMAIN ), array ( + + add_settings_section( PostmanAdminController::BASIC_AUTH_SECTION, __( 'Authentication', Postman::TEXT_DOMAIN ), array( $this, - 'printBasicAuthSectionInfo' + 'printBasicAuthSectionInfo', ), PostmanAdminController::BASIC_AUTH_OPTIONS ); - - add_settings_field ( PostmanOptions::BASIC_AUTH_USERNAME, __ ( 'Username', Postman::TEXT_DOMAIN ), array ( + + add_settings_field( PostmanOptions::BASIC_AUTH_USERNAME, __( 'Username', Postman::TEXT_DOMAIN ), array( $this, - 'basic_auth_username_callback' + 'basic_auth_username_callback', ), PostmanAdminController::BASIC_AUTH_OPTIONS, PostmanAdminController::BASIC_AUTH_SECTION ); - - add_settings_field ( PostmanOptions::BASIC_AUTH_PASSWORD, __ ( 'Password', Postman::TEXT_DOMAIN ), array ( + + add_settings_field( PostmanOptions::BASIC_AUTH_PASSWORD, __( 'Password', Postman::TEXT_DOMAIN ), array( $this, - 'basic_auth_password_callback' + 'basic_auth_password_callback', ), PostmanAdminController::BASIC_AUTH_OPTIONS, PostmanAdminController::BASIC_AUTH_SECTION ); - + // the OAuth section - add_settings_section ( PostmanAdminController::OAUTH_SECTION, __ ( 'Authentication', Postman::TEXT_DOMAIN ), array ( + add_settings_section( PostmanAdminController::OAUTH_SECTION, __( 'Authentication', Postman::TEXT_DOMAIN ), array( $this, - 'printOAuthSectionInfo' + 'printOAuthSectionInfo', ), PostmanAdminController::OAUTH_AUTH_OPTIONS ); - - add_settings_field ( 'callback_domain', sprintf ( '<span id="callback_domain">%s</span>', $oauthScribe->getCallbackDomainLabel () ), array ( + + add_settings_field( 'callback_domain', sprintf( '<span id="callback_domain">%s</span>', $oauthScribe->getCallbackDomainLabel() ), array( $this, - 'callback_domain_callback' + 'callback_domain_callback', ), PostmanAdminController::OAUTH_AUTH_OPTIONS, PostmanAdminController::OAUTH_SECTION ); - - add_settings_field ( 'redirect_url', sprintf ( '<span id="redirect_url">%s</span>', $oauthScribe->getCallbackUrlLabel () ), array ( + + add_settings_field( 'redirect_url', sprintf( '<span id="redirect_url">%s</span>', $oauthScribe->getCallbackUrlLabel() ), array( $this, - 'redirect_url_callback' + 'redirect_url_callback', ), PostmanAdminController::OAUTH_AUTH_OPTIONS, PostmanAdminController::OAUTH_SECTION ); - - add_settings_field ( PostmanOptions::CLIENT_ID, $oauthScribe->getClientIdLabel (), array ( + + add_settings_field( PostmanOptions::CLIENT_ID, $oauthScribe->getClientIdLabel(), array( $this, - 'oauth_client_id_callback' + 'oauth_client_id_callback', ), PostmanAdminController::OAUTH_AUTH_OPTIONS, PostmanAdminController::OAUTH_SECTION ); - - add_settings_field ( PostmanOptions::CLIENT_SECRET, $oauthScribe->getClientSecretLabel (), array ( + + add_settings_field( PostmanOptions::CLIENT_SECRET, $oauthScribe->getClientSecretLabel(), array( $this, - 'oauth_client_secret_callback' + 'oauth_client_secret_callback', ), PostmanAdminController::OAUTH_AUTH_OPTIONS, PostmanAdminController::OAUTH_SECTION ); } - + /** * Print the Section text */ public function printSmtpSectionInfo() { - print __ ( 'Configure the communication with the mail server.', Postman::TEXT_DOMAIN ); + print __( 'Configure the communication with the mail server.', Postman::TEXT_DOMAIN ); } - + /** * Get the settings option array and print one of its values */ public function hostname_callback() { - printf ( '<input type="text" id="input_hostname" name="postman_options[hostname]" value="%s" size="40" class="required" placeholder="%s"/>', null !== $this->options->getHostname () ? esc_attr ( $this->options->getHostname () ) : '', __ ( 'Required', Postman::TEXT_DOMAIN ) ); + printf( '<input type="text" id="input_hostname" name="postman_options[hostname]" value="%s" size="40" class="required" placeholder="%s"/>', null !== $this->options->getHostname() ? esc_attr( $this->options->getHostname() ) : '', __( 'Required', Postman::TEXT_DOMAIN ) ); } - + /** * Get the settings option array and print one of its values */ - public function port_callback($args) { - printf ( '<input type="text" id="input_port" name="postman_options[port]" value="%s" %s placeholder="%s"/>', null !== $this->options->getPort () ? esc_attr ( $this->options->getPort () ) : '', isset ( $args ['style'] ) ? $args ['style'] : '', __ ( 'Required', Postman::TEXT_DOMAIN ) ); + public function port_callback( $args ) { + printf( '<input type="text" id="input_port" name="postman_options[port]" value="%s" %s placeholder="%s"/>', null !== $this->options->getPort() ? esc_attr( $this->options->getPort() ) : '', isset( $args ['style'] ) ? $args ['style'] : '', __( 'Required', Postman::TEXT_DOMAIN ) ); } - + /** * Get the settings option array and print one of its values */ public function encryption_type_callback() { - $encType = $this->options->getEncryptionType (); + $encType = $this->options->getEncryptionType(); print '<select id="input_enc_type" class="input_encryption_type" name="postman_options[enc_type]">'; - printf ( '<option class="input_enc_type_none" value="%s" %s>%s</option>', PostmanOptions::SECURITY_TYPE_NONE, $encType == PostmanOptions::SECURITY_TYPE_NONE ? 'selected="selected"' : '', __ ( 'None', Postman::TEXT_DOMAIN ) ); - printf ( '<option class="input_enc_type_ssl" value="%s" %s>%s</option>', PostmanOptions::SECURITY_TYPE_SMTPS, $encType == PostmanOptions::SECURITY_TYPE_SMTPS ? 'selected="selected"' : '', 'SMTPS' ); - printf ( '<option class="input_enc_type_tls" value="%s" %s>%s</option>', PostmanOptions::SECURITY_TYPE_STARTTLS, $encType == PostmanOptions::SECURITY_TYPE_STARTTLS ? 'selected="selected"' : '', 'STARTTLS' ); + printf( '<option class="input_enc_type_none" value="%s" %s>%s</option>', PostmanOptions::SECURITY_TYPE_NONE, $encType == PostmanOptions::SECURITY_TYPE_NONE ? 'selected="selected"' : '', __( 'None', Postman::TEXT_DOMAIN ) ); + printf( '<option class="input_enc_type_ssl" value="%s" %s>%s</option>', PostmanOptions::SECURITY_TYPE_SMTPS, $encType == PostmanOptions::SECURITY_TYPE_SMTPS ? 'selected="selected"' : '', 'SMTPS' ); + printf( '<option class="input_enc_type_tls" value="%s" %s>%s</option>', PostmanOptions::SECURITY_TYPE_STARTTLS, $encType == PostmanOptions::SECURITY_TYPE_STARTTLS ? 'selected="selected"' : '', 'STARTTLS' ); print '</select>'; } - + /** * Get the settings option array and print one of its values */ public function authentication_type_callback() { - $authType = $this->options->getAuthenticationType (); - printf ( '<select id="input_%2$s" class="input_%2$s" name="%1$s[%2$s]">', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::AUTHENTICATION_TYPE ); - printf ( '<option class="input_auth_type_none" value="%s" %s>%s</option>', PostmanOptions::AUTHENTICATION_TYPE_NONE, $authType == PostmanOptions::AUTHENTICATION_TYPE_NONE ? 'selected="selected"' : '', 'None' ); - printf ( '<option class="input_auth_type_plain" value="%s" %s>%s</option>', PostmanOptions::AUTHENTICATION_TYPE_PLAIN, $authType == PostmanOptions::AUTHENTICATION_TYPE_PLAIN ? 'selected="selected"' : '', 'Plain' ); - printf ( '<option class="input_auth_type_login" value="%s" %s>%s</option>', PostmanOptions::AUTHENTICATION_TYPE_LOGIN, $authType == PostmanOptions::AUTHENTICATION_TYPE_LOGIN ? 'selected="selected"' : '', 'Login' ); - printf ( '<option class="input_auth_type_crammd5" value="%s" %s>%s</option>', PostmanOptions::AUTHENTICATION_TYPE_CRAMMD5, $authType == PostmanOptions::AUTHENTICATION_TYPE_CRAMMD5 ? 'selected="selected"' : '', 'CRAM-MD5' ); - printf ( '<option class="input_auth_type_oauth2" value="%s" %s>%s</option>', PostmanOptions::AUTHENTICATION_TYPE_OAUTH2, $authType == PostmanOptions::AUTHENTICATION_TYPE_OAUTH2 ? 'selected="selected"' : '', 'OAuth 2.0' ); + $authType = $this->options->getAuthenticationType(); + printf( '<select id="input_%2$s" class="input_%2$s" name="%1$s[%2$s]">', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::AUTHENTICATION_TYPE ); + printf( '<option class="input_auth_type_none" value="%s" %s>%s</option>', PostmanOptions::AUTHENTICATION_TYPE_NONE, $authType == PostmanOptions::AUTHENTICATION_TYPE_NONE ? 'selected="selected"' : '', 'None' ); + printf( '<option class="input_auth_type_plain" value="%s" %s>%s</option>', PostmanOptions::AUTHENTICATION_TYPE_PLAIN, $authType == PostmanOptions::AUTHENTICATION_TYPE_PLAIN ? 'selected="selected"' : '', 'Plain' ); + printf( '<option class="input_auth_type_login" value="%s" %s>%s</option>', PostmanOptions::AUTHENTICATION_TYPE_LOGIN, $authType == PostmanOptions::AUTHENTICATION_TYPE_LOGIN ? 'selected="selected"' : '', 'Login' ); + printf( '<option class="input_auth_type_crammd5" value="%s" %s>%s</option>', PostmanOptions::AUTHENTICATION_TYPE_CRAMMD5, $authType == PostmanOptions::AUTHENTICATION_TYPE_CRAMMD5 ? 'selected="selected"' : '', 'CRAM-MD5' ); + printf( '<option class="input_auth_type_oauth2" value="%s" %s>%s</option>', PostmanOptions::AUTHENTICATION_TYPE_OAUTH2, $authType == PostmanOptions::AUTHENTICATION_TYPE_OAUTH2 ? 'selected="selected"' : '', 'OAuth 2.0' ); print '</select>'; } - + /** * Print the Section text */ public function printBasicAuthSectionInfo() { - print __ ( 'Enter the account credentials.', Postman::TEXT_DOMAIN ); + print __( 'Enter the account credentials.', Postman::TEXT_DOMAIN ); } - + /** * Get the settings option array and print one of its values */ public function basic_auth_username_callback() { - $inputValue = (null !== $this->options->getUsername () ? esc_attr ( $this->options->getUsername () ) : ''); - $inputDescription = __ ( 'The Username is usually the same as the Envelope-From Email Address.', Postman::TEXT_DOMAIN ); + $inputValue = (null !== $this->options->getUsername() ? esc_attr( $this->options->getUsername() ) : ''); + $inputDescription = __( 'The Username is usually the same as the Envelope-From Email Address.', Postman::TEXT_DOMAIN ); print ('<input tabindex="99" id="fake_user_name" name="fake_user[name]" style="position:absolute; top:-500px;" type="text" value="Safari Autofill Me">') ; - printf ( '<input type="text" id="input_basic_auth_username" name="postman_options[basic_auth_username]" value="%s" size="40" class="required" placeholder="%s"/><br/><span class="postman_input_description">%s</span>', $inputValue, __ ( 'Required', Postman::TEXT_DOMAIN ), $inputDescription ); + printf( '<input type="text" id="input_basic_auth_username" name="postman_options[basic_auth_username]" value="%s" size="40" class="required" placeholder="%s"/><br/><span class="postman_input_description">%s</span>', $inputValue, __( 'Required', Postman::TEXT_DOMAIN ), $inputDescription ); } - + /** * Get the settings option array and print one of its values */ public function basic_auth_password_callback() { print ('<input tabindex="99" id="fake_password" name="fake[password]" style="position:absolute; top:-500px;" type="password" value="Safari Autofill Me">') ; - printf ( '<input type="password" id="input_basic_auth_password" name="postman_options[basic_auth_password]" value="%s" size="40" class="required" placeholder="%s"/>', null !== $this->options->getPassword () ? esc_attr ( PostmanUtils::obfuscatePassword ( $this->options->getPassword () ) ) : '', __ ( 'Required', Postman::TEXT_DOMAIN ) ); + printf( '<input type="password" id="input_basic_auth_password" name="postman_options[basic_auth_password]" value="%s" size="40" class="required" placeholder="%s"/>', null !== $this->options->getPassword() ? esc_attr( PostmanUtils::obfuscatePassword( $this->options->getPassword() ) ) : '', __( 'Required', Postman::TEXT_DOMAIN ) ); print ' <input type="button" id="togglePasswordField" value="Show Password" class="button button-secondary" style="visibility:hidden" />'; } - + /** * Get the settings option array and print one of its values */ public function oauth_client_id_callback() { - printf ( '<input type="text" onClick="this.setSelectionRange(0, this.value.length)" id="oauth_client_id" name="postman_options[oauth_client_id]" value="%s" size="60" class="required" placeholder="%s"/>', null !== $this->options->getClientId () ? esc_attr ( $this->options->getClientId () ) : '', __ ( 'Required', Postman::TEXT_DOMAIN ) ); + printf( '<input type="text" onClick="this.setSelectionRange(0, this.value.length)" id="oauth_client_id" name="postman_options[oauth_client_id]" value="%s" size="60" class="required" placeholder="%s"/>', null !== $this->options->getClientId() ? esc_attr( $this->options->getClientId() ) : '', __( 'Required', Postman::TEXT_DOMAIN ) ); } - + /** * Get the settings option array and print one of its values */ public function oauth_client_secret_callback() { - printf ( '<input type="text" onClick="this.setSelectionRange(0, this.value.length)" autocomplete="off" id="oauth_client_secret" name="postman_options[oauth_client_secret]" value="%s" size="60" class="required" placeholder="%s"/>', null !== $this->options->getClientSecret () ? esc_attr ( $this->options->getClientSecret () ) : '', __ ( 'Required', Postman::TEXT_DOMAIN ) ); + printf( '<input type="text" onClick="this.setSelectionRange(0, this.value.length)" autocomplete="off" id="oauth_client_secret" name="postman_options[oauth_client_secret]" value="%s" size="60" class="required" placeholder="%s"/>', null !== $this->options->getClientSecret() ? esc_attr( $this->options->getClientSecret() ) : '', __( 'Required', Postman::TEXT_DOMAIN ) ); } - + /** * Print the Section text */ public function printOAuthSectionInfo() { $this->options = $this->options; $transport = $this; - $oauthScribe = $transport->getScribe (); - printf ( '<p id="wizard_oauth2_help">%s</p>', $oauthScribe->getOAuthHelp () ); + $oauthScribe = $transport->getScribe(); + printf( '<p id="wizard_oauth2_help">%s</p>', $oauthScribe->getOAuthHelp() ); } - + /** * Get the settings option array and print one of its values */ public function callback_domain_callback() { - printf ( '<input type="text" onClick="this.setSelectionRange(0, this.value.length)" readonly="readonly" id="input_oauth_callback_domain" value="%s" size="60"/>', $this->getCallbackDomain () ); + printf( '<input type="text" onClick="this.setSelectionRange(0, this.value.length)" readonly="readonly" id="input_oauth_callback_domain" value="%s" size="60"/>', $this->getCallbackDomain() ); } - + /** */ private function getCallbackDomain() { try { $this->options = $this->options; $transport = $this; - $oauthScribe = $transport->getScribe (); - return $oauthScribe->getCallbackDomain (); + $oauthScribe = $transport->getScribe(); + return $oauthScribe->getCallbackDomain(); } catch ( Exception $e ) { - return __ ( 'Error computing your domain root - please enter it manually', Postman::TEXT_DOMAIN ); + return __( 'Error computing your domain root - please enter it manually', Postman::TEXT_DOMAIN ); } } - + /** * Get the settings option array and print one of its values */ public function redirect_url_callback() { $this->options = $this->options; $transport = $this; - $oauthScribe = $transport->getScribe (); - printf ( '<input type="text" onClick="this.setSelectionRange(0, this.value.length)" readonly="readonly" id="input_oauth_redirect_url" value="%s" size="60"/>', $oauthScribe->getCallbackUrl () ); + $oauthScribe = $transport->getScribe(); + printf( '<input type="text" onClick="this.setSelectionRange(0, this.value.length)" readonly="readonly" id="input_oauth_redirect_url" value="%s" size="60"/>', $oauthScribe->getCallbackUrl() ); } - + /** * Get the settings option array and print one of its values */ public function sender_email_callback() { - $inputValue = (null !== $this->options->getEnvelopeSender () ? esc_attr ( $this->options->getEnvelopeSender () ) : ''); - $requiredLabel = __ ( 'Required', Postman::TEXT_DOMAIN ); - $envelopeFromMessage = __ ( 'This address, like the <b>return address</b> printed on an envelope, identifies the account owner to the SMTP server.', Postman::TEXT_DOMAIN ); - $spfMessage = sprintf ( __ ( 'For reliable delivery, this domain must specify an <a target="_new" href="%s">SPF record</a> permitting the use of the SMTP server named above.', Postman::TEXT_DOMAIN ), 'https://www.mail-tester.com/spf/' ); - printf ( '<input type="email" id="input_envelope_sender_email" name="postman_options[envelope_sender]" value="%s" size="40" class="required" placeholder="%s"/> <br/><span class="postman_input_description">%s %s</span>', $inputValue, $requiredLabel, $envelopeFromMessage, $spfMessage ); + $inputValue = (null !== $this->options->getEnvelopeSender() ? esc_attr( $this->options->getEnvelopeSender() ) : ''); + $requiredLabel = __( 'Required', Postman::TEXT_DOMAIN ); + $envelopeFromMessage = __( 'This address, like the <b>return address</b> printed on an envelope, identifies the account owner to the SMTP server.', Postman::TEXT_DOMAIN ); + $spfMessage = sprintf( __( 'For reliable delivery, this domain must specify an <a target="_new" href="%s">SPF record</a> permitting the use of the SMTP server named above.', Postman::TEXT_DOMAIN ), 'https://www.mail-tester.com/spf/' ); + printf( '<input type="email" id="input_envelope_sender_email" name="postman_options[envelope_sender]" value="%s" size="40" class="required" placeholder="%s"/> <br/><span class="postman_input_description">%s %s</span>', $inputValue, $requiredLabel, $envelopeFromMessage, $spfMessage ); } - + /** */ public function printWizardMailServerHostnameStep() { - printf ( '<legend>%s</legend>', _x ( 'Which host will relay the mail?', 'Wizard Step Title', Postman::TEXT_DOMAIN ) ); - printf ( '<p>%s</p>', __ ( 'This is the Outgoing (SMTP) Mail Server, or Mail Submission Agent (MSA), which Postman delegates mail delivery to. This server is specific to your email account, and if you don\'t know what to use, ask your email service provider.', Postman::TEXT_DOMAIN ) ); - printf ( '<p>%s</p>', __ ( 'Note that many WordPress hosts, such as GoDaddy, Bluehost and Dreamhost, require that you use their mail accounts with their mail servers, and prevent you from using others.', Postman::TEXT_DOMAIN ) ); - printf ( '<label for="hostname">%s</label>', __ ( 'Outgoing Mail Server Hostname', Postman::TEXT_DOMAIN ) ); - print $this->hostname_callback (); - printf ( '<p class="ajax-loader" style="display:none"><img src="%s"/></p>', plugins_url ( 'postman-smtp/style/ajax-loader.gif' ) ); - $warning = __ ( 'Warning', Postman::TEXT_DOMAIN ); + printf( '<legend>%s</legend>', _x( 'Which host will relay the mail?', 'Wizard Step Title', Postman::TEXT_DOMAIN ) ); + printf( '<p>%s</p>', __( 'This is the Outgoing (SMTP) Mail Server, or Mail Submission Agent (MSA), which Postman delegates mail delivery to. This server is specific to your email account, and if you don\'t know what to use, ask your email service provider.', Postman::TEXT_DOMAIN ) ); + printf( '<p>%s</p>', __( 'Note that many WordPress hosts, such as GoDaddy, Bluehost and Dreamhost, require that you use their mail accounts with their mail servers, and prevent you from using others.', Postman::TEXT_DOMAIN ) ); + printf( '<label for="hostname">%s</label>', __( 'Outgoing Mail Server Hostname', Postman::TEXT_DOMAIN ) ); + print $this->hostname_callback(); + printf( '<p class="ajax-loader" style="display:none"><img src="%s"/></p>', plugins_url( 'post-smtp/style/ajax-loader.gif' ) ); + $warning = __( 'Warning', Postman::TEXT_DOMAIN ); /* Translators: Where (%s) is the name of the web host */ - $nonGodaddyDomainMessage = sprintf ( __ ( 'Your email address <b>requires</b> access to a remote SMTP server blocked by %s.', Postman::TEXT_DOMAIN ), 'GoDaddy' ); - $nonGodaddyDomainMessage .= sprintf ( ' %s', __ ( 'If you have access to cPanel, enable the Remote Mail Exchanger.', Postman::TEXT_DOMAIN ) ); - printf ( '<p id="godaddy_block"><span style="background-color:yellow"><b>%s</b>: %s</span></p>', $warning, $nonGodaddyDomainMessage ); + $nonGodaddyDomainMessage = sprintf( __( 'Your email address <b>requires</b> access to a remote SMTP server blocked by %s.', Postman::TEXT_DOMAIN ), 'GoDaddy' ); + $nonGodaddyDomainMessage .= sprintf( ' %s', __( 'If you have access to cPanel, enable the Remote Mail Exchanger.', Postman::TEXT_DOMAIN ) ); + printf( '<p id="godaddy_block"><span style="background-color:yellow"><b>%s</b>: %s</span></p>', $warning, $nonGodaddyDomainMessage ); /* Translators: Where (%1$s) is the SPF-info URL and (%2$s) is the name of the web host */ - $godaddyCustomDomainMessage = sprintf ( __ ( 'If you own this domain, make sure it has an <a href="%1$s">SPF record authorizing %2$s</a> as a relay, or you will have delivery problems.', Postman::TEXT_DOMAIN ), 'http://www.mail-tester.com/spf/godaddy', 'GoDaddy' ); - printf ( '<p id="godaddy_spf_required"><span style="background-color:yellow"><b>%s</b>: %s</span></p>', $warning, $godaddyCustomDomainMessage ); + $godaddyCustomDomainMessage = sprintf( __( 'If you own this domain, make sure it has an <a href="%1$s">SPF record authorizing %2$s</a> as a relay, or you will have delivery problems.', Postman::TEXT_DOMAIN ), 'http://www.mail-tester.com/spf/godaddy', 'GoDaddy' ); + printf( '<p id="godaddy_spf_required"><span style="background-color:yellow"><b>%s</b>: %s</span></p>', $warning, $godaddyCustomDomainMessage ); } - + /** */ public function printWizardAuthenticationStep() { print '<section class="wizard-auth-oauth2">'; print '<p id="wizard_oauth2_help"></p>'; - printf ( '<label id="callback_domain" for="callback_domain">%s</label>', $this->getScribe ()->getCallbackDomainLabel () ); + printf( '<label id="callback_domain" for="callback_domain">%s</label>', $this->getScribe()->getCallbackDomainLabel() ); print '<br />'; - print $this->callback_domain_callback (); + print $this->callback_domain_callback(); print '<br />'; - printf ( '<label id="redirect_url" for="redirect_uri">%s</label>', $this->getScribe ()->getCallbackUrlLabel () ); + printf( '<label id="redirect_url" for="redirect_uri">%s</label>', $this->getScribe()->getCallbackUrlLabel() ); print '<br />'; - print $this->redirect_url_callback (); + print $this->redirect_url_callback(); print '<br />'; - printf ( '<label id="client_id" for="client_id">%s</label>', $this->getScribe ()->getClientIdLabel () ); + printf( '<label id="client_id" for="client_id">%s</label>', $this->getScribe()->getClientIdLabel() ); print '<br />'; - print $this->oauth_client_id_callback (); + print $this->oauth_client_id_callback(); print '<br />'; - printf ( '<label id="client_secret" for="client_secret">%s</label>', $this->getScribe ()->getClientSecretLabel () ); + printf( '<label id="client_secret" for="client_secret">%s</label>', $this->getScribe()->getClientSecretLabel() ); print '<br />'; - print $this->oauth_client_secret_callback (); + print $this->oauth_client_secret_callback(); print '<br />'; print '</section>'; - + print '<section class="wizard-auth-basic">'; - printf ( '<p class="port-explanation-ssl">%s</p>', __ ( 'Enter the account credentials.', Postman::TEXT_DOMAIN ) ); - printf ( '<label for="username">%s</label>', __ ( 'Username', Postman::TEXT_DOMAIN ) ); + printf( '<p class="port-explanation-ssl">%s</p>', __( 'Enter the account credentials.', Postman::TEXT_DOMAIN ) ); + printf( '<label for="username">%s</label>', __( 'Username', Postman::TEXT_DOMAIN ) ); print '<br />'; - print $this->basic_auth_username_callback (); + print $this->basic_auth_username_callback(); print '<br />'; - printf ( '<label for="password">%s</label>', __ ( 'Password', Postman::TEXT_DOMAIN ) ); + printf( '<label for="password">%s</label>', __( 'Password', Postman::TEXT_DOMAIN ) ); print '<br />'; - print $this->basic_auth_password_callback (); + print $this->basic_auth_password_callback(); print '</section>'; } } diff --git a/Postman/Postman-Mail/PostmanZendMailEngine.php b/Postman/Postman-Mail/PostmanZendMailEngine.php index 943be50..8d69811 100644 --- a/Postman/Postman-Mail/PostmanZendMailEngine.php +++ b/Postman/Postman-Mail/PostmanZendMailEngine.php @@ -1,6 +1,6 @@ <?php -if (! class_exists ( "PostmanZendMailEngine" )) { - +if ( ! class_exists( 'PostmanZendMailEngine' ) ) { + require_once 'Zend-1.12.10/Loader.php'; require_once 'Zend-1.12.10/Registry.php'; require_once 'Zend-1.12.10/Mime/Message.php'; @@ -25,7 +25,7 @@ if (! class_exists ( "PostmanZendMailEngine" )) { require_once 'Zend-1.12.10/Mail/Protocol/Smtp/Auth/Login.php'; require_once 'Zend-1.12.10/Mail/Protocol/Smtp/Auth/Crammd5.php'; require_once 'Zend-1.12.10/Mail/Protocol/Smtp/Auth/Plain.php'; - + /** * This class knows how to interface with Wordpress * including loading/saving to the database. @@ -34,208 +34,206 @@ if (! class_exists ( "PostmanZendMailEngine" )) { * http://framework.zend.com/manual/current/en/modules/zend.mail.smtp.options.html * * @author jasonhendriks - * */ class PostmanZendMailEngine implements PostmanMailEngine { - + // logger for all concrete classes - populate with setLogger($logger) protected $logger; - + // the result private $transcript; - - // + private $transport; - + /** * - * @param unknown $senderEmail - * @param unknown $accessToken + * @param unknown $senderEmail + * @param unknown $accessToken */ - function __construct(PostmanZendModuleTransport $transport) { - assert ( isset ( $transport ) ); + function __construct( PostmanZendModuleTransport $transport ) { + assert( isset( $transport ) ); $this->transport = $transport; - + // create the logger - $this->logger = new PostmanLogger ( get_class ( $this ) ); + $this->logger = new PostmanLogger( get_class( $this ) ); } - + /** * (non-PHPdoc) * * @see PostmanSmtpEngine::send() */ - public function send(PostmanMessage $message) { - $this->logger->debug ( "Prepping Zend" ); - $envelopeFrom = new PostmanEmailAddress ( $this->transport->getEnvelopeFromEmailAddress () ); - if ($this->transport->isEnvelopeFromValidationSupported ()) { + public function send( PostmanMessage $message ) { + $this->logger->debug( 'Prepping Zend' ); + $envelopeFrom = new PostmanEmailAddress( $this->transport->getEnvelopeFromEmailAddress() ); + if ( $this->transport->isEnvelopeFromValidationSupported() ) { // validate the envelope from since we didn't do it in the Message - $envelopeFrom->validate ( 'Envelope From' ); + $envelopeFrom->validate( 'Envelope From' ); } - + // create the Message - $charset = $message->getCharset (); - $this->logger->debug ( 'Building Postman_Zend_Mail with charset=' . $charset ); - $mail = new Postman_Zend_Mail ( $charset ); - + $charset = $message->getCharset(); + $this->logger->debug( 'Building Postman_Zend_Mail with charset=' . $charset ); + $mail = new Postman_Zend_Mail( $charset ); + // add the Postman signature - append it to whatever the user may have set - if (! PostmanOptions::getInstance ()->isStealthModeEnabled ()) { - $pluginData = apply_filters ( 'postman_get_plugin_metadata', null ); - $mail->addHeader ( 'X-Mailer', sprintf ( 'Postman SMTP %s for WordPress (%s)', $pluginData ['version'], 'https://wordpress.org/plugins/postman-smtp/' ) ); + if ( ! PostmanOptions::getInstance()->isStealthModeEnabled() ) { + $pluginData = apply_filters( 'postman_get_plugin_metadata', null ); + $mail->addHeader( 'X-Mailer', sprintf( 'Postman SMTP %s for WordPress (%s)', $pluginData ['version'], 'https://wordpress.org/plugins/post-smtp/' ) ); } - + // add the headers - see http://framework.zend.com/manual/1.12/en/zend.mail.additional-headers.html - foreach ( ( array ) $message->getHeaders () as $header ) { - $this->logger->debug ( sprintf ( 'Adding user header %s=%s', $header ['name'], $header ['content'] ) ); - $mail->addHeader ( $header ['name'], $header ['content'], true ); + foreach ( ( array ) $message->getHeaders() as $header ) { + $this->logger->debug( sprintf( 'Adding user header %s=%s', $header ['name'], $header ['content'] ) ); + $mail->addHeader( $header ['name'], $header ['content'], true ); } - + // if the caller set a Content-Type header, use it - $contentType = $message->getContentType (); - if (! empty ( $contentType )) { - $mail->addHeader ( 'Content-Type', $contentType, false ); - $this->logger->debug ( 'Adding content-type ' . $contentType ); + $contentType = $message->getContentType(); + if ( ! empty( $contentType ) ) { + $mail->addHeader( 'Content-Type', $contentType, false ); + $this->logger->debug( 'Adding content-type ' . $contentType ); } - + // add the From Header - $fromHeader = $this->addFrom ( $message, $mail ); - $fromHeader->log ( $this->logger, 'From' ); - + $fromHeader = $this->addFrom( $message, $mail ); + $fromHeader->log( $this->logger, 'From' ); + // add the Sender Header, overriding what the user may have set - $mail->addHeader ( 'Sender', $this->transport->getFromEmailAddress (), false ); + $mail->addHeader( 'Sender', $this->transport->getFromEmailAddress(), false ); // from RFC 5321: http://tools.ietf.org/html/rfc5321#section-4.4 // A message-originating SMTP system SHOULD NOT send a message that // already contains a Return-path header field. // I changed Zend/Mail/Mail.php to fix this - $mail->setReturnPath ( $this->transport->getEnvelopeFromEmailAddress () ); - + $mail->setReturnPath( $this->transport->getEnvelopeFromEmailAddress() ); + // add the to recipients - foreach ( ( array ) $message->getToRecipients () as $recipient ) { - $recipient->log ( $this->logger, 'To' ); - $mail->addTo ( $recipient->getEmail (), $recipient->getName () ); + foreach ( ( array ) $message->getToRecipients() as $recipient ) { + $recipient->log( $this->logger, 'To' ); + $mail->addTo( $recipient->getEmail(), $recipient->getName() ); } - + // add the cc recipients - foreach ( ( array ) $message->getCcRecipients () as $recipient ) { - $recipient->log ( $this->logger, 'Cc' ); - $mail->addCc ( $recipient->getEmail (), $recipient->getName () ); + foreach ( ( array ) $message->getCcRecipients() as $recipient ) { + $recipient->log( $this->logger, 'Cc' ); + $mail->addCc( $recipient->getEmail(), $recipient->getName() ); } - + // add the to recipients - foreach ( ( array ) $message->getBccRecipients () as $recipient ) { - $recipient->log ( $this->logger, 'Bcc' ); - $mail->addBcc ( $recipient->getEmail (), $recipient->getName () ); + foreach ( ( array ) $message->getBccRecipients() as $recipient ) { + $recipient->log( $this->logger, 'Bcc' ); + $mail->addBcc( $recipient->getEmail(), $recipient->getName() ); } - + // add the reply-to - $replyTo = $message->getReplyTo (); + $replyTo = $message->getReplyTo(); // $replyTo is null or a PostmanEmailAddress object - if (isset ( $replyTo )) { - $mail->setReplyTo ( $replyTo->getEmail (), $replyTo->getName () ); + if ( isset( $replyTo ) ) { + $mail->setReplyTo( $replyTo->getEmail(), $replyTo->getName() ); } - + // add the date - $date = $message->getDate (); - if (! empty ( $date )) { - $mail->setDate ( $date ); + $date = $message->getDate(); + if ( ! empty( $date ) ) { + $mail->setDate( $date ); } - + // add the messageId - $messageId = $message->getMessageId (); - if (! empty ( $messageId )) { - $mail->setMessageId ( $messageId ); + $messageId = $message->getMessageId(); + if ( ! empty( $messageId ) ) { + $mail->setMessageId( $messageId ); } - + // add the subject - if (null !== $message->getSubject ()) { - $mail->setSubject ( $message->getSubject () ); + if ( null !== $message->getSubject() ) { + $mail->setSubject( $message->getSubject() ); } - + // add the message content { - $textPart = $message->getBodyTextPart (); - if (! empty ( $textPart )) { - $this->logger->debug ( 'Adding body as text' ); - $mail->setBodyText ( $textPart ); - } - $htmlPart = $message->getBodyHtmlPart (); - if (! empty ( $htmlPart )) { - $this->logger->debug ( 'Adding body as html' ); - $mail->setBodyHtml ( $htmlPart ); - } + $textPart = $message->getBodyTextPart(); + if ( ! empty( $textPart ) ) { + $this->logger->debug( 'Adding body as text' ); + $mail->setBodyText( $textPart ); } - + $htmlPart = $message->getBodyHtmlPart(); + if ( ! empty( $htmlPart ) ) { + $this->logger->debug( 'Adding body as html' ); + $mail->setBodyHtml( $htmlPart ); + } + } + // add attachments - $this->logger->debug ( "Adding attachments" ); - $message->addAttachmentsToMail ( $mail ); - + $this->logger->debug( 'Adding attachments' ); + $message->addAttachmentsToMail( $mail ); + // create the SMTP transport - $this->logger->debug ( "Create the Zend_Mail transport" ); - $zendTransport = $this->transport->createZendMailTransport ( $this->transport->getHostname (), array () ); - + $this->logger->debug( 'Create the Zend_Mail transport' ); + $zendTransport = $this->transport->createZendMailTransport( $this->transport->getHostname(), array() ); + try { // send the message - $this->logger->debug ( "Sending mail" ); - $mail->send ( $zendTransport ); - if ($this->logger->isInfo ()) { - $this->logger->info ( sprintf ( 'Message %d accepted for delivery', PostmanState::getInstance ()->getSuccessfulDeliveries () + 1 ) ); + $this->logger->debug( 'Sending mail' ); + $mail->send( $zendTransport ); + if ( $this->logger->isInfo() ) { + $this->logger->info( sprintf( 'Message %d accepted for delivery', PostmanState::getInstance()->getSuccessfulDeliveries() + 1 ) ); } // finally not supported?? - if ($zendTransport->getConnection () && ! PostmanUtils::isEmpty ( $zendTransport->getConnection ()->getLog () )) { - $this->transcript = $zendTransport->getConnection ()->getLog (); - } else if (method_exists ( $zendTransport, 'getTranscript' ) && ! PostmanUtils::isEmpty ( $zendTransport->getTranscript () )) { + if ( $zendTransport->getConnection() && ! PostmanUtils::isEmpty( $zendTransport->getConnection()->getLog() ) ) { + $this->transcript = $zendTransport->getConnection()->getLog(); + } else if ( method_exists( $zendTransport, 'getTranscript' ) && ! PostmanUtils::isEmpty( $zendTransport->getTranscript() ) ) { // then use the API response - $this->transcript = $zendTransport->getTranscript (); - } else if (method_exists ( $zendTransport, 'getMessage' ) && ! PostmanUtils::isEmpty ( $zendTransport->getMessage () )) { + $this->transcript = $zendTransport->getTranscript(); + } else if ( method_exists( $zendTransport, 'getMessage' ) && ! PostmanUtils::isEmpty( $zendTransport->getMessage() ) ) { // then use the Raw Message as the Transcript - $this->transcript = $zendTransport->getMessage (); + $this->transcript = $zendTransport->getMessage(); } } catch ( Exception $e ) { // finally not supported?? - if ($zendTransport->getConnection () && ! PostmanUtils::isEmpty ( $zendTransport->getConnection ()->getLog () )) { - $this->transcript = $zendTransport->getConnection ()->getLog (); - } else if (method_exists ( $zendTransport, 'getTranscript' ) && ! PostmanUtils::isEmpty ( $zendTransport->getTranscript () )) { + if ( $zendTransport->getConnection() && ! PostmanUtils::isEmpty( $zendTransport->getConnection()->getLog() ) ) { + $this->transcript = $zendTransport->getConnection()->getLog(); + } else if ( method_exists( $zendTransport, 'getTranscript' ) && ! PostmanUtils::isEmpty( $zendTransport->getTranscript() ) ) { // then use the API response - $this->transcript = $zendTransport->getTranscript (); - } else if (method_exists ( $zendTransport, 'getMessage' ) && ! PostmanUtils::isEmpty ( $zendTransport->getMessage () )) { + $this->transcript = $zendTransport->getTranscript(); + } else if ( method_exists( $zendTransport, 'getMessage' ) && ! PostmanUtils::isEmpty( $zendTransport->getMessage() ) ) { // then use the Raw Message as the Transcript - $this->transcript = $zendTransport->getMessage (); + $this->transcript = $zendTransport->getMessage(); } - + // get the current exception message - $message = $e->getMessage (); - if ($e->getCode () == 334) { + $message = $e->getMessage(); + if ( $e->getCode() == 334 ) { // replace the unusable Google message with a better one in the case of code 334 - $message = sprintf ( __ ( 'Communication Error [334] - make sure the Envelope From email is the same account used to create the Client ID.', Postman::TEXT_DOMAIN ) ); + $message = sprintf( __( 'Communication Error [334] - make sure the Envelope From email is the same account used to create the Client ID.', Postman::TEXT_DOMAIN ) ); } // create a new exception - $newException = new Exception ( $message, $e->getCode () ); + $newException = new Exception( $message, $e->getCode() ); // throw the new exception after handling throw $newException; } } - + /** * Get the sender from PostmanMessage and add it to the Postman_Zend_Mail object * - * @param PostmanMessage $message - * @param Postman_Zend_Mail $mail + * @param PostmanMessage $message + * @param Postman_Zend_Mail $mail * @return PostmanEmailAddress */ - public function addFrom(PostmanMessage $message, Postman_Zend_Mail $mail) { - $sender = $message->getFromAddress (); + public function addFrom( PostmanMessage $message, Postman_Zend_Mail $mail ) { + $sender = $message->getFromAddress(); // now log it and push it into the message - $senderEmail = $sender->getEmail (); - $senderName = $sender->getName (); - assert ( ! empty ( $senderEmail ) ); - if (! empty ( $senderName )) { - $mail->setFrom ( $senderEmail, $senderName ); + $senderEmail = $sender->getEmail(); + $senderName = $sender->getName(); + assert( ! empty( $senderEmail ) ); + if ( ! empty( $senderName ) ) { + $mail->setFrom( $senderEmail, $senderName ); } else { - $mail->setFrom ( $senderEmail ); + $mail->setFrom( $senderEmail ); } return $sender; } - + // return the SMTP session transcript public function getTranscript() { return $this->transcript; diff --git a/Postman/Postman-Mail/sendgrid-php-3.2.0/lib/SendGrid/Email.php b/Postman/Postman-Mail/sendgrid-php-3.2.0/lib/SendGrid/Email.php index 6c6451a..1557802 100644 --- a/Postman/Postman-Mail/sendgrid-php-3.2.0/lib/SendGrid/Email.php +++ b/Postman/Postman-Mail/sendgrid-php-3.2.0/lib/SendGrid/Email.php @@ -4,689 +4,634 @@ namespace SendGrid; class Email { - public - $to, - $toName, - $from, - $fromName, - $replyTo, - $cc, - $ccName, - $bcc, - $bccName, - $subject, - $text, - $html, - $date, - $content, - $headers, - $smtpapi, - $attachments; - - public function __construct() - { - $this->fromName = false; - $this->replyTo = false; - $this->smtpapi = new \Smtpapi\Header(); - } - - /** - * _removeFromList - * Given a list of key/value pairs, removes the associated keys - * where a value matches the given string ($item) - * - * @param Array $list - the list of key/value pairs - * @param String $item - the value to be removed - */ - private function _removeFromList(&$list, $item, $key_field = null) - { - foreach ($list as $key => $val) { - if ($key_field) { - if ($val[$key_field] == $item) { - unset($list[$key]); - } - } else { - if ($val == $item) { - unset($list[$key]); - } - } - } - //repack the indices - $list = array_values($list); - } - - public function addTo($email, $name = null) - { - if ($this->to == null) { - $this->to = array(); - } - - if (is_array($email)) { - foreach ($email as $e) { - $this->to[] = $e; - } - } else { - $this->to[] = $email; - } - - if (is_array($name)) { - foreach ($name as $n) { - $this->addToName($n); - } - } elseif ($name) { - $this->addToName($name); - } - - return $this; - } - - public function addSmtpapiTo($email, $name = null) - { - $this->smtpapi->addTo($email, $name); - - return $this; - } - - public function setTos(array $emails) - { - $this->to = $emails; - - return $this; - } - - public function setSmtpapiTos(array $emails) - { - $this->smtpapi->setTos($emails); - - return $this; - } - - public function addToName($name) - { - if ($this->toName == null) { - $this->toName = array(); - } - - $this->toName[] = $name; - - return $this; - } - - public function getToNames() - { - return $this->toName; - } - - public function setFrom($email) - { - $this->from = $email; - - return $this; - } - - public function getFrom($as_array = false) - { - if ($as_array && ($name = $this->getFromName())) { - return array("$this->from" => $name); - } else { - return $this->from; - } - } - - public function setFromName($name) - { - $this->fromName = $name; - - return $this; - } - - public function getFromName() - { - return $this->fromName; - } - - public function setReplyTo($email) - { - $this->replyTo = $email; - - return $this; - } - - public function getReplyTo() - { - return $this->replyTo; - } - - public function setCc($email) - { - $this->cc = array($email); - - return $this; - } - - public function setCcs(array $email_list) - { - $this->cc = $email_list; - - return $this; - } - - public function addCc($email, $name = null) - { - if ($this->cc == null) { - $this->cc = array(); - } - - if (is_array($email)) { - foreach ($email as $e) { - $this->cc[] = $e; - } - } else { - $this->cc[] = $email; - } - - if (is_array($name)) { - foreach ($name as $n) { - $this->addCcName($n); - } - } elseif ($name) { - $this->addCcName($name); - } - - return $this; - } - - public function addCcName($name) - { - if ($this->ccName == null) { - $this->ccName = array(); - } - - $this->ccName[] = $name; - - return $this; - } - - public function removeCc($email) - { - $this->_removeFromList($this->cc, $email); - - return $this; - } - - public function getCcs() - { - return $this->cc; - } - - public function getCcNames() - { - return $this->ccName; - } - - public function setBcc($email) - { - $this->bcc = array($email); - - return $this; - } - - public function setBccs($email_list) - { - $this->bcc = $email_list; - - return $this; - } - - public function addBcc($email, $name = null) - { - if ($this->bcc == null) { - $this->bcc = array(); - } - - if (is_array($email)) { - foreach ($email as $e) { - $this->bcc[] = $e; - } - } else { - $this->bcc[] = $email; - } - - if (is_array($name)) { - foreach ($name as $n) { - $this->addBccName($n); - } - } elseif ($name) { - $this->addBccName($name); - } - - return $this; - } - - public function addBccName($name) - { - if ($this->bccName == null) { - $this->bccName = array(); - } - - $this->bccName[] = $name; - - return $this; - } - - public function getBccNames() - { - return $this->bccName; - } - - public function removeBcc($email) - { - $this->_removeFromList($this->bcc, $email); - - return $this; - } - - public function getBccs() - { - return $this->bcc; - } - - public function setSubject($subject) - { - $this->subject = $subject; - - return $this; - } - - public function getSubject() - { - return $this->subject; - } - - public function setDate($date) - { - $this->date = $date; - - return $this; - } - - public function getDate() - { - return $this->date; - } - - public function setText($text) - { - $this->text = $text; - - return $this; - } - - public function getText() - { - return $this->text; - } - - public function setHtml($html) - { - $this->html = $html; - - return $this; - } - - public function getHtml() - { - return $this->html; - } - - public function setSendAt($timestamp) - { - $this->smtpapi->setSendAt($timestamp); - - return $this; - } - - public function setSendEachAt(array $timestamps) - { - $this->smtpapi->setSendEachAt($timestamps); - - return $this; - } - - public function addSendEachAt($timestamp) - { - $this->smtpapi->addSendEachAt($timestamp); - - return $this; - } - - /** - * Convenience method to add template - * - * @param string The id of the template - * - * @return $this - */ - public function setTemplateId($templateId) - { - $this->addFilter('templates', 'enabled', 1); - $this->addFilter('templates', 'template_id', $templateId); - - return $this; - } - - /** Convenience method to set asm group id - * - * @param string the group id - * - * @return $this - */ - public function setAsmGroupId($groupId) - { - $this->smtpapi->setASMGroupID($groupId); - - return $this; - } - - public function setAttachments(array $files) - { - $this->attachments = array(); - - foreach ($files as $filename => $file) { - if (is_string($filename)) { - $this->addAttachment($file, $filename); - } else { - $this->addAttachment($file); - } - } - - return $this; - } - - public function setAttachment($file, $custom_filename = null, $cid = null) - { - $this->attachments = array($this->getAttachmentInfo($file, $custom_filename, $cid)); - - return $this; - } - - public function addAttachment($file, $custom_filename = null, $cid = null) - { - $this->attachments[] = $this->getAttachmentInfo($file, $custom_filename, $cid); - - return $this; - } - - public function getAttachments() - { - return $this->attachments; - } - - public function removeAttachment($file) - { - $this->_removeFromList($this->attachments, $file, "file"); - - return $this; - } - - private function getAttachmentInfo($file, $custom_filename = null, $cid = null) - { - $info = pathinfo($file); - $info['file'] = $file; - if (!is_null($custom_filename)) { - $info['custom_filename'] = $custom_filename; - } - if ($cid !== null) { - $info['cid'] = $cid; - } - - return $info; - } - - public function setCategories($categories) - { - $this->smtpapi->setCategories($categories); - - return $this; - } - - public function setCategory($category) - { - $this->smtpapi->setCategory($category); - - return $this; - } - - public function addCategory($category) - { - $this->smtpapi->addCategory($category); - - return $this; - } - - public function removeCategory($category) - { - $this->smtpapi->removeCategory($category); - - return $this; - } + public + $to, + $toName, + $from, + $fromName, + $replyTo, + $cc, + $ccName, + $bcc, + $bccName, + $subject, + $text, + $html, + $date, + $content, + $headers, + $smtpapi, + $attachments; + + public function __construct() { + + $this->fromName = false; + $this->replyTo = false; + $this->smtpapi = new \Smtpapi\Header(); + } + + /** + * _removeFromList + * Given a list of key/value pairs, removes the associated keys + * where a value matches the given string ($item) + * + * @param Array $list - the list of key/value pairs + * @param String $item - the value to be removed + */ + private function _removeFromList( &$list, $item, $key_field = null ) { + foreach ( $list as $key => $val ) { + if ( $key_field ) { + if ( $val[ $key_field ] == $item ) { + unset( $list[ $key ] ); + } + } else { + if ( $val == $item ) { + unset( $list[ $key ] ); + } + } + } + // repack the indices + $list = array_values( $list ); + } + + public function addTo( $email, $name = null ) { + if ( $this->to == null ) { + $this->to = array(); + } + + if ( is_array( $email ) ) { + foreach ( $email as $e ) { + $this->to[] = $e; + } + } else { + $this->to[] = $email; + } + + if ( is_array( $name ) ) { + foreach ( $name as $n ) { + $this->addToName( $n ); + } + } elseif ( $name ) { + $this->addToName( $name ); + } + + return $this; + } + + public function addSmtpapiTo( $email, $name = null ) { + $this->smtpapi->addTo( $email, $name ); + + return $this; + } + + public function setTos( array $emails ) { + $this->to = $emails; + + return $this; + } + + public function setSmtpapiTos( array $emails ) { + $this->smtpapi->setTos( $emails ); + + return $this; + } + + public function addToName( $name ) { + if ( $this->toName == null ) { + $this->toName = array(); + } + + $this->toName[] = $name; + + return $this; + } + + public function getToNames() { + + return $this->toName; + } + + public function setFrom( $email ) { + $this->from = $email; + + return $this; + } + + public function getFrom( $as_array = false ) { + if ( $as_array && ($name = $this->getFromName()) ) { + return array( "$this->from" => $name ); + } else { + return $this->from; + } + } - public function setSubstitutions($key_value_pairs) - { - $this->smtpapi->setSubstitutions($key_value_pairs); + public function setFromName( $name ) { + $this->fromName = $name; - return $this; - } + return $this; + } + + public function getFromName() { + + return $this->fromName; + } - public function addSubstitution($from_value, array $to_values) - { - $this->smtpapi->addSubstitution($from_value, $to_values); + public function setReplyTo( $email ) { + $this->replyTo = $email; - return $this; - } + return $this; + } - public function setSections(array $key_value_pairs) - { - $this->smtpapi->setSections($key_value_pairs); + public function getReplyTo() { - return $this; - } + return $this->replyTo; + } - public function addSection($from_value, $to_value) - { - $this->smtpapi->addSection($from_value, $to_value); + public function setCc( $email ) { + $this->cc = array( $email ); - return $this; - } + return $this; + } - public function setUniqueArgs(array $key_value_pairs) - { - $this->smtpapi->setUniqueArgs($key_value_pairs); + public function setCcs( array $email_list ) { + $this->cc = $email_list; - return $this; - } + return $this; + } - ## synonym method - public function setUniqueArguments(array $key_value_pairs) - { - $this->smtpapi->setUniqueArgs($key_value_pairs); + public function addCc( $email, $name = null ) { + if ( $this->cc == null ) { + $this->cc = array(); + } - return $this; - } + if ( is_array( $email ) ) { + foreach ( $email as $e ) { + $this->cc[] = $e; + } + } else { + $this->cc[] = $email; + } - public function addUniqueArg($key, $value) - { - $this->smtpapi->addUniqueArg($key, $value); - - return $this; - } - - ## synonym method - public function addUniqueArgument($key, $value) - { - $this->smtpapi->addUniqueArg($key, $value); - - return $this; - } - - public function setFilters($filter_settings) - { - $this->smtpapi->setFilters($filter_settings); - - return $this; - } - - ## synonym method - public function setFilterSettings($filter_settings) - { - $this->smtpapi->setFilters($filter_settings); - - return $this; - } - - public function addFilter($filter_name, $parameter_name, $parameter_value) - { - $this->smtpapi->addFilter($filter_name, $parameter_name, $parameter_value); - - return $this; - } - - ## synonym method - public function addFilterSetting($filter_name, $parameter_name, $parameter_value) - { - $this->smtpapi->addFilter($filter_name, $parameter_name, $parameter_value); - - return $this; - } - - public function getHeaders() - { - return $this->headers; - } - - public function getHeadersJson() - { - if (count($this->getHeaders()) <= 0) { - return "{}"; - } - - return json_encode($this->getHeaders(), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); - } - - public function setHeaders($key_value_pairs) - { - $this->headers = $key_value_pairs; - - return $this; - } - - public function addHeader($key, $value) - { - $this->headers[$key] = $value; - - return $this; - } - - public function removeHeader($key) - { - unset($this->headers[$key]); - - return $this; - } - - public function getSmtpapi() - { - return $this->smtpapi; - } - - public function toWebFormat() - { - $web = array( - 'to' => $this->to, - 'from' => $this->getFrom(), - 'x-smtpapi' => $this->smtpapi->jsonString(), - 'subject' => $this->getSubject(), - 'text' => $this->getText(), - 'html' => $this->getHtml(), - 'headers' => $this->getHeadersJson(), - ); - - if ($this->getToNames()) { - $web['toname'] = $this->getToNames(); - } - if ($this->getCcs()) { - $web['cc'] = $this->getCcs(); - } - if ($this->getCcNames()) { - $web['ccname'] = $this->getCcNames(); - } - if ($this->getBccs()) { - $web['bcc'] = $this->getBccs(); - } - if ($this->getBccNames()) { - $web['bccname'] = $this->getBccNames(); - } - if ($this->getFromName()) { - $web['fromname'] = $this->getFromName(); - } - if ($this->getReplyTo()) { - $web['replyto'] = $this->getReplyTo(); - } - if ($this->getDate()) { - $web['date'] = $this->getDate(); - } - if ($this->smtpapi->to && (count($this->smtpapi->to) > 0)) { - $web['to'] = ""; - } - - $web = $this->updateMissingTo($web); - - if ($this->getAttachments()) { - foreach ($this->getAttachments() as $f) { - $file = $f['file']; - $extension = null; - if (array_key_exists('extension', $f)) { - $extension = $f['extension']; - }; - $filename = $f['filename']; - $full_filename = $filename; - - if (isset($extension)) { - $full_filename = $filename . '.' . $extension; - } - if (array_key_exists('custom_filename', $f)) { - $full_filename = $f['custom_filename']; - } - - if (array_key_exists('cid', $f)) { - $web['content[' . $full_filename . ']'] = $f['cid']; - } - - $contents = '@' . $file; - - // Guzzle handles this for us. - // http://guzzle3.readthedocs.org/en/latest/http-client/request.html#post-requests - // if (class_exists('CurlFile', false)) { // php >= 5.5 - // $contents = new \CurlFile($file, $extension, $filename); - // } - - $web['files[' . $full_filename . ']'] = $contents; - }; - } - - return $web; - } - - /** - * There needs to be at least 1 to address, or else the mail won't send. - * This method modifies the data that will be sent via either Rest - */ - public function updateMissingTo($data) - { - if ($this->smtpapi->to && (count($this->smtpapi->to) > 0)) { - $data['to'] = $this->getFrom(); - } - - return $data; - } + if ( is_array( $name ) ) { + foreach ( $name as $n ) { + $this->addCcName( $n ); + } + } elseif ( $name ) { + $this->addCcName( $name ); + } + + return $this; + } + + public function addCcName( $name ) { + if ( $this->ccName == null ) { + $this->ccName = array(); + } + + $this->ccName[] = $name; + + return $this; + } + + public function removeCc( $email ) { + $this->_removeFromList( $this->cc, $email ); + + return $this; + } + + public function getCcs() { + + return $this->cc; + } + + public function getCcNames() { + + return $this->ccName; + } + + public function setBcc( $email ) { + $this->bcc = array( $email ); + + return $this; + } + + public function setBccs( $email_list ) { + $this->bcc = $email_list; + + return $this; + } + + public function addBcc( $email, $name = null ) { + if ( $this->bcc == null ) { + $this->bcc = array(); + } + + if ( is_array( $email ) ) { + foreach ( $email as $e ) { + $this->bcc[] = $e; + } + } else { + $this->bcc[] = $email; + } + + if ( is_array( $name ) ) { + foreach ( $name as $n ) { + $this->addBccName( $n ); + } + } elseif ( $name ) { + $this->addBccName( $name ); + } + + return $this; + } + + public function addBccName( $name ) { + if ( $this->bccName == null ) { + $this->bccName = array(); + } + + $this->bccName[] = $name; + + return $this; + } + + public function getBccNames() { + + return $this->bccName; + } + + public function removeBcc( $email ) { + $this->_removeFromList( $this->bcc, $email ); + + return $this; + } + + public function getBccs() { + + return $this->bcc; + } + + public function setSubject( $subject ) { + $this->subject = $subject; + + return $this; + } + + public function getSubject() { + + return $this->subject; + } + + public function setDate( $date ) { + $this->date = $date; + + return $this; + } + + public function getDate() { + + return $this->date; + } + + public function setText( $text ) { + $this->text = $text; + + return $this; + } + + public function getText() { + + return $this->text; + } + + public function setHtml( $html ) { + $this->html = $html; + + return $this; + } + + public function getHtml() { + + return $this->html; + } + + public function setSendAt( $timestamp ) { + $this->smtpapi->setSendAt( $timestamp ); + + return $this; + } + + public function setSendEachAt( array $timestamps ) { + $this->smtpapi->setSendEachAt( $timestamps ); + + return $this; + } + + public function addSendEachAt( $timestamp ) { + $this->smtpapi->addSendEachAt( $timestamp ); + + return $this; + } + + /** + * Convenience method to add template + * + * @param string The id of the template + * + * @return $this + */ + public function setTemplateId( $templateId ) { + $this->addFilter( 'templates', 'enabled', 1 ); + $this->addFilter( 'templates', 'template_id', $templateId ); + + return $this; + } + + /** Convenience method to set asm group id + * + * @param string the group id + * + * @return $this + */ + public function setAsmGroupId( $groupId ) { + $this->smtpapi->setASMGroupID( $groupId ); + + return $this; + } + + public function setAttachments( array $files ) { + $this->attachments = array(); + + foreach ( $files as $filename => $file ) { + if ( is_string( $filename ) ) { + $this->addAttachment( $file, $filename ); + } else { + $this->addAttachment( $file ); + } + } + + return $this; + } + + public function setAttachment( $file, $custom_filename = null, $cid = null ) { + $this->attachments = array( $this->getAttachmentInfo( $file, $custom_filename, $cid ) ); + + return $this; + } + + public function addAttachment( $file, $custom_filename = null, $cid = null ) { + $this->attachments[] = $this->getAttachmentInfo( $file, $custom_filename, $cid ); + + return $this; + } + + public function getAttachments() { + + return $this->attachments; + } + + public function removeAttachment( $file ) { + $this->_removeFromList( $this->attachments, $file, 'file' ); + + return $this; + } + + private function getAttachmentInfo( $file, $custom_filename = null, $cid = null ) { + $info = pathinfo( $file ); + $info['file'] = $file; + if ( ! is_null( $custom_filename ) ) { + $info['custom_filename'] = $custom_filename; + } + if ( $cid !== null ) { + $info['cid'] = $cid; + } + + return $info; + } + + public function setCategories( $categories ) { + $this->smtpapi->setCategories( $categories ); + + return $this; + } + + public function setCategory( $category ) { + $this->smtpapi->setCategory( $category ); + + return $this; + } + + public function addCategory( $category ) { + $this->smtpapi->addCategory( $category ); + + return $this; + } + + public function removeCategory( $category ) { + $this->smtpapi->removeCategory( $category ); + + return $this; + } + + public function setSubstitutions( $key_value_pairs ) { + $this->smtpapi->setSubstitutions( $key_value_pairs ); + + return $this; + } + + public function addSubstitution( $from_value, array $to_values ) { + $this->smtpapi->addSubstitution( $from_value, $to_values ); + + return $this; + } + + public function setSections( array $key_value_pairs ) { + $this->smtpapi->setSections( $key_value_pairs ); + + return $this; + } + + public function addSection( $from_value, $to_value ) { + $this->smtpapi->addSection( $from_value, $to_value ); + + return $this; + } + + public function setUniqueArgs( array $key_value_pairs ) { + $this->smtpapi->setUniqueArgs( $key_value_pairs ); + + return $this; + } + + // synonym method + public function setUniqueArguments( array $key_value_pairs ) { + $this->smtpapi->setUniqueArgs( $key_value_pairs ); + + return $this; + } + + public function addUniqueArg( $key, $value ) { + $this->smtpapi->addUniqueArg( $key, $value ); + + return $this; + } + + // synonym method + public function addUniqueArgument( $key, $value ) { + $this->smtpapi->addUniqueArg( $key, $value ); + + return $this; + } + + public function setFilters( $filter_settings ) { + $this->smtpapi->setFilters( $filter_settings ); + + return $this; + } + + // synonym method + public function setFilterSettings( $filter_settings ) { + $this->smtpapi->setFilters( $filter_settings ); + + return $this; + } + + public function addFilter( $filter_name, $parameter_name, $parameter_value ) { + $this->smtpapi->addFilter( $filter_name, $parameter_name, $parameter_value ); + + return $this; + } + + // synonym method + public function addFilterSetting( $filter_name, $parameter_name, $parameter_value ) { + $this->smtpapi->addFilter( $filter_name, $parameter_name, $parameter_value ); + + return $this; + } + + public function getHeaders() { + + return $this->headers; + } + + public function getHeadersJson() { + + if ( count( $this->getHeaders() ) <= 0 ) { + return '{}'; + } + + return json_encode( $this->getHeaders(), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP ); + } + + public function setHeaders( $key_value_pairs ) { + $this->headers = $key_value_pairs; + + return $this; + } + + public function addHeader( $key, $value ) { + $this->headers[ $key ] = $value; + + return $this; + } + + public function removeHeader( $key ) { + unset( $this->headers[ $key ] ); + + return $this; + } + + public function getSmtpapi() { + + return $this->smtpapi; + } + + public function toWebFormat() { + + $web = array( + 'to' => $this->to, + 'from' => $this->getFrom(), + 'x-smtpapi' => $this->smtpapi->jsonString(), + 'subject' => $this->getSubject(), + 'text' => $this->getText(), + 'html' => $this->getHtml(), + 'headers' => $this->getHeadersJson(), + ); + + if ( $this->getToNames() ) { + $web['toname'] = $this->getToNames(); + } + if ( $this->getCcs() ) { + $web['cc'] = $this->getCcs(); + } + if ( $this->getCcNames() ) { + $web['ccname'] = $this->getCcNames(); + } + if ( $this->getBccs() ) { + $web['bcc'] = $this->getBccs(); + } + if ( $this->getBccNames() ) { + $web['bccname'] = $this->getBccNames(); + } + if ( $this->getFromName() ) { + $web['fromname'] = $this->getFromName(); + } + if ( $this->getReplyTo() ) { + $web['replyto'] = $this->getReplyTo(); + } + if ( $this->getDate() ) { + $web['date'] = $this->getDate(); + } + if ( $this->smtpapi->to && (count( $this->smtpapi->to ) > 0) ) { + $web['to'] = ''; + } + + $web = $this->updateMissingTo( $web ); + + if ( $this->getAttachments() ) { + foreach ( $this->getAttachments() as $f ) { + $file = $f['file']; + $extension = null; + if ( array_key_exists( 'extension', $f ) ) { + $extension = $f['extension']; + }; + $filename = $f['filename']; + $full_filename = $filename; + + if ( isset( $extension ) ) { + $full_filename = $filename . '.' . $extension; + } + if ( array_key_exists( 'custom_filename', $f ) ) { + $full_filename = $f['custom_filename']; + } + + if ( array_key_exists( 'cid', $f ) ) { + $web[ 'content[' . $full_filename . ']' ] = $f['cid']; + } + + $contents = '@' . $file; + + // Guzzle handles this for us. + // http://guzzle3.readthedocs.org/en/latest/http-client/request.html#post-requests + // if (class_exists('CurlFile', false)) { // php >= 5.5 + // $contents = new \CurlFile($file, $extension, $filename); + // } + $web[ 'files[' . $full_filename . ']' ] = $contents; + }; + } + + return $web; + } + + /** + * There needs to be at least 1 to address, or else the mail won't send. + * This method modifies the data that will be sent via either Rest + */ + public function updateMissingTo( $data ) { + if ( $this->smtpapi->to && (count( $this->smtpapi->to ) > 0) ) { + $data['to'] = $this->getFrom(); + } + + return $data; + } } diff --git a/Postman/Postman-Mail/sendgrid-php-3.2.0/vendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequest.php b/Postman/Postman-Mail/sendgrid-php-3.2.0/vendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequest.php index 212850a..774c982 100644 --- a/Postman/Postman-Mail/sendgrid-php-3.2.0/vendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequest.php +++ b/Postman/Postman-Mail/sendgrid-php-3.2.0/vendor/guzzle/guzzle/src/Guzzle/Http/Message/EntityEnclosingRequest.php @@ -13,235 +13,222 @@ use Guzzle\Http\Exception\RequestException; */ class EntityEnclosingRequest extends Request implements EntityEnclosingRequestInterface { - /** @var int When the size of the body is greater than 1MB, then send Expect: 100-Continue */ - protected $expectCutoff = 1048576; - - /** @var EntityBodyInterface $body Body of the request */ - protected $body; - - /** @var QueryString POST fields to use in the EntityBody */ - protected $postFields; - - /** @var array POST files to send with the request */ - protected $postFiles = array(); - - public function __construct($method, $url, $headers = array()) - { - $this->postFields = new QueryString(); - parent::__construct($method, $url, $headers); - } - - /** - * @return string - */ - public function __toString() - { - // Only attempt to include the POST data if it's only fields - if (count($this->postFields) && empty($this->postFiles)) { - return parent::__toString() . (string) $this->postFields; - } - - return parent::__toString() . $this->body; - } - - public function setState($state, array $context = array()) - { - parent::setState($state, $context); - if ($state == self::STATE_TRANSFER && !$this->body && !count($this->postFields) && !count($this->postFiles)) { - $this->setHeader('Content-Length', 0)->removeHeader('Transfer-Encoding'); - } - - return $this->state; - } - - public function setBody($body, $contentType = null) - { - $this->body = EntityBody::factory($body); - - // Auto detect the Content-Type from the path of the request if possible - if ($contentType === null && !$this->hasHeader('Content-Type')) { - $contentType = $this->body->getContentType(); - } - - if ($contentType) { - $this->setHeader('Content-Type', $contentType); - } - - // Always add the Expect 100-Continue header if the body cannot be rewound. This helps with redirects. - if (!$this->body->isSeekable() && $this->expectCutoff !== false) { - $this->setHeader('Expect', '100-Continue'); - } - - // Set the Content-Length header if it can be determined - $size = $this->body->getContentLength(); - if ($size !== null && $size !== false) { - $this->setHeader('Content-Length', $size); - if ($size > $this->expectCutoff) { - $this->setHeader('Expect', '100-Continue'); - } - } elseif (!$this->hasHeader('Content-Length')) { - if ('1.1' == $this->protocolVersion) { - $this->setHeader('Transfer-Encoding', 'chunked'); - } else { - throw new RequestException( - 'Cannot determine Content-Length and cannot use chunked Transfer-Encoding when using HTTP/1.0' - ); - } - } - - return $this; - } - - public function getBody() - { - return $this->body; - } - - /** - * Set the size that the entity body of the request must exceed before adding the Expect: 100-Continue header. - * - * @param int|bool $size Cutoff in bytes. Set to false to never send the expect header (even with non-seekable data) - * - * @return self - */ - public function setExpectHeaderCutoff($size) - { - $this->expectCutoff = $size; - if ($size === false || !$this->body) { - $this->removeHeader('Expect'); - } elseif ($this->body && $this->body->getSize() && $this->body->getSize() > $size) { - $this->setHeader('Expect', '100-Continue'); - } - - return $this; - } - - public function configureRedirects($strict = false, $maxRedirects = 5) - { - $this->getParams()->set(RedirectPlugin::STRICT_REDIRECTS, $strict); - if ($maxRedirects == 0) { - $this->getParams()->set(RedirectPlugin::DISABLE, true); - } else { - $this->getParams()->set(RedirectPlugin::MAX_REDIRECTS, $maxRedirects); - } - - return $this; - } - - public function getPostField($field) - { - return $this->postFields->get($field); - } - - public function getPostFields() - { - return $this->postFields; - } - - public function setPostField($key, $value) - { - $this->postFields->set($key, $value); - $this->processPostFields(); - - return $this; - } - - public function addPostFields($fields) - { - $this->postFields->merge($fields); - $this->processPostFields(); - - return $this; - } - - public function removePostField($field) - { - $this->postFields->remove($field); - $this->processPostFields(); - - return $this; - } - - public function getPostFiles() - { - return $this->postFiles; - } - - public function getPostFile($fieldName) - { - return isset($this->postFiles[$fieldName]) ? $this->postFiles[$fieldName] : null; - } - - public function removePostFile($fieldName) - { - unset($this->postFiles[$fieldName]); - $this->processPostFields(); - - return $this; - } - - public function addPostFile($field, $filename = null, $contentType = null, $postname = null) - { - $data = null; - - if ($field instanceof PostFileInterface) { - $data = $field; - } elseif (is_array($filename)) { - // Allow multiple values to be set in a single key - foreach ($filename as $file) { - $this->addPostFile($field, $file, $contentType); - } - return $this; - } elseif (!is_string($filename)) { - throw new RequestException('The path to a file must be a string'); - } elseif (!empty($filename)) { - // Adding an empty file will cause cURL to error out - $data = new PostFile($field, $filename, $contentType, $postname); - } - - if ($data) { - if (!isset($this->postFiles[$data->getFieldName()])) { - $this->postFiles[$data->getFieldName()] = array($data); - } else { - $this->postFiles[$data->getFieldName()][] = $data; - } - $this->processPostFields(); - } - - return $this; - } - - public function addPostFiles(array $files) - { - foreach ($files as $key => $file) { - if ($file instanceof PostFileInterface) { - $this->addPostFile($file, null, null, false); - } elseif (is_string($file)) { - // Convert non-associative array keys into 'file' - if (is_numeric($key)) { - $key = 'file'; - } - $this->addPostFile($key, $file, null, false); - } else { - throw new RequestException('File must be a string or instance of PostFileInterface'); - } - } - - return $this; - } - - /** - * Determine what type of request should be sent based on post fields - */ - protected function processPostFields() - { - if (!$this->postFiles) { - $this->removeHeader('Expect')->setHeader('Content-Type', self::URL_ENCODED); - } else { - $this->setHeader('Content-Type', self::MULTIPART); - if ($this->expectCutoff !== false) { - $this->setHeader('Expect', '100-Continue'); - } - } - } + /** @var int When the size of the body is greater than 1MB, then send Expect: 100-Continue */ + protected $expectCutoff = 1048576; + + /** @var EntityBodyInterface $body Body of the request */ + protected $body; + + /** @var QueryString POST fields to use in the EntityBody */ + protected $postFields; + + /** @var array POST files to send with the request */ + protected $postFiles = array(); + + public function __construct( $method, $url, $headers = array() ) { + $this->postFields = new QueryString(); + parent::__construct( $method, $url, $headers ); + } + + /** + * @return string + */ + public function __toString() { + + // Only attempt to include the POST data if it's only fields + if ( count( $this->postFields ) && empty( $this->postFiles ) ) { + return parent::__toString() . (string) $this->postFields; + } + + return parent::__toString() . $this->body; + } + + public function setState( $state, array $context = array() ) { + parent::setState( $state, $context ); + if ( $state == self::STATE_TRANSFER && ! $this->body && ! count( $this->postFields ) && ! count( $this->postFiles ) ) { + $this->setHeader( 'Content-Length', 0 )->removeHeader( 'Transfer-Encoding' ); + } + + return $this->state; + } + + public function setBody( $body, $contentType = null ) { + $this->body = EntityBody::factory( $body ); + + // Auto detect the Content-Type from the path of the request if possible + if ( $contentType === null && ! $this->hasHeader( 'Content-Type' ) ) { + $contentType = $this->body->getContentType(); + } + + if ( $contentType ) { + $this->setHeader( 'Content-Type', $contentType ); + } + + // Always add the Expect 100-Continue header if the body cannot be rewound. This helps with redirects. + if ( ! $this->body->isSeekable() && $this->expectCutoff !== false ) { + $this->setHeader( 'Expect', '100-Continue' ); + } + + // Set the Content-Length header if it can be determined + $size = $this->body->getContentLength(); + if ( $size !== null && $size !== false ) { + $this->setHeader( 'Content-Length', $size ); + if ( $size > $this->expectCutoff ) { + $this->setHeader( 'Expect', '100-Continue' ); + } + } elseif ( ! $this->hasHeader( 'Content-Length' ) ) { + if ( '1.1' == $this->protocolVersion ) { + $this->setHeader( 'Transfer-Encoding', 'chunked' ); + } else { + throw new RequestException( + 'Cannot determine Content-Length and cannot use chunked Transfer-Encoding when using HTTP/1.0' + ); + } + } + + return $this; + } + + public function getBody() { + + return $this->body; + } + + /** + * Set the size that the entity body of the request must exceed before adding the Expect: 100-Continue header. + * + * @param int|bool $size Cutoff in bytes. Set to false to never send the expect header (even with non-seekable data) + * + * @return self + */ + public function setExpectHeaderCutoff( $size ) { + $this->expectCutoff = $size; + if ( $size === false || ! $this->body ) { + $this->removeHeader( 'Expect' ); + } elseif ( $this->body && $this->body->getSize() && $this->body->getSize() > $size ) { + $this->setHeader( 'Expect', '100-Continue' ); + } + + return $this; + } + + public function configureRedirects( $strict = false, $maxRedirects = 5 ) { + $this->getParams()->set( RedirectPlugin::STRICT_REDIRECTS, $strict ); + if ( $maxRedirects == 0 ) { + $this->getParams()->set( RedirectPlugin::DISABLE, true ); + } else { + $this->getParams()->set( RedirectPlugin::MAX_REDIRECTS, $maxRedirects ); + } + + return $this; + } + + public function getPostField( $field ) { + return $this->postFields->get( $field ); + } + + public function getPostFields() { + + return $this->postFields; + } + + public function setPostField( $key, $value ) { + $this->postFields->set( $key, $value ); + $this->processPostFields(); + + return $this; + } + + public function addPostFields( $fields ) { + $this->postFields->merge( $fields ); + $this->processPostFields(); + + return $this; + } + + public function removePostField( $field ) { + $this->postFields->remove( $field ); + $this->processPostFields(); + + return $this; + } + + public function getPostFiles() { + + return $this->postFiles; + } + + public function getPostFile( $fieldName ) { + return isset( $this->postFiles[ $fieldName ] ) ? $this->postFiles[ $fieldName ] : null; + } + + public function removePostFile( $fieldName ) { + unset( $this->postFiles[ $fieldName ] ); + $this->processPostFields(); + + return $this; + } + + public function addPostFile( $field, $filename = null, $contentType = null, $postname = null ) { + $data = null; + + if ( $field instanceof PostFileInterface ) { + $data = $field; + } elseif ( is_array( $filename ) ) { + // Allow multiple values to be set in a single key + foreach ( $filename as $file ) { + $this->addPostFile( $field, $file, $contentType ); + } + return $this; + } elseif ( ! is_string( $filename ) ) { + throw new RequestException( 'The path to a file must be a string' ); + } elseif ( ! empty( $filename ) ) { + // Adding an empty file will cause cURL to error out + $data = new PostFile( $field, $filename, $contentType, $postname ); + } + + if ( $data ) { + if ( ! isset( $this->postFiles[ $data->getFieldName() ] ) ) { + $this->postFiles[ $data->getFieldName() ] = array( $data ); + } else { + $this->postFiles[ $data->getFieldName() ][] = $data; + } + $this->processPostFields(); + } + + return $this; + } + + public function addPostFiles( array $files ) { + foreach ( $files as $key => $file ) { + if ( $file instanceof PostFileInterface ) { + $this->addPostFile( $file, null, null, false ); + } elseif ( is_string( $file ) ) { + // Convert non-associative array keys into 'file' + if ( is_numeric( $key ) ) { + $key = 'file'; + } + $this->addPostFile( $key, $file, null, false ); + } else { + throw new RequestException( 'File must be a string or instance of PostFileInterface' ); + } + } + + return $this; + } + + /** + * Determine what type of request should be sent based on post fields + */ + protected function processPostFields() { + + if ( ! $this->postFiles ) { + $this->removeHeader( 'Expect' )->setHeader( 'Content-Type', self::URL_ENCODED ); + } else { + $this->setHeader( 'Content-Type', self::MULTIPART ); + if ( $this->expectCutoff !== false ) { + $this->setHeader( 'Expect', '100-Continue' ); + } + } + } } diff --git a/Postman/Postman-Mail/sendgrid-php-3.2.0/vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactory.php b/Postman/Postman-Mail/sendgrid-php-3.2.0/vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactory.php index ba00a76..b222cec 100644 --- a/Postman/Postman-Mail/sendgrid-php-3.2.0/vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactory.php +++ b/Postman/Postman-Mail/sendgrid-php-3.2.0/vendor/guzzle/guzzle/src/Guzzle/Http/Message/RequestFactory.php @@ -13,347 +13,324 @@ use Guzzle\Parser\ParserRegistry; */ class RequestFactory implements RequestFactoryInterface { - /** @var RequestFactory Singleton instance of the default request factory */ - protected static $instance; - - /** @var array Hash of methods available to the class (provides fast isset() lookups) */ - protected $methods; - - /** @var string Class to instantiate for requests with no body */ - protected $requestClass = 'Guzzle\\Http\\Message\\Request'; - - /** @var string Class to instantiate for requests with a body */ - protected $entityEnclosingRequestClass = 'Guzzle\\Http\\Message\\EntityEnclosingRequest'; - - /** - * Get a cached instance of the default request factory - * - * @return RequestFactory - */ - public static function getInstance() - { - // @codeCoverageIgnoreStart - if (!static::$instance) { - static::$instance = new static(); - } - // @codeCoverageIgnoreEnd - - return static::$instance; - } - - public function __construct() - { - $this->methods = array_flip(get_class_methods(__CLASS__)); - } - - public function fromMessage($message) - { - $parsed = ParserRegistry::getInstance()->getParser('message')->parseRequest($message); - - if (!$parsed) { - return false; - } - - $request = $this->fromParts($parsed['method'], $parsed['request_url'], - $parsed['headers'], $parsed['body'], $parsed['protocol'], - $parsed['version']); - - // EntityEnclosingRequest adds an "Expect: 100-Continue" header when using a raw request body for PUT or POST - // requests. This factory method should accurately reflect the message, so here we are removing the Expect - // header if one was not supplied in the message. - if (!isset($parsed['headers']['Expect']) && !isset($parsed['headers']['expect'])) { - $request->removeHeader('Expect'); - } - - return $request; - } - - public function fromParts( - $method, - array $urlParts, - $headers = null, - $body = null, - $protocol = 'HTTP', - $protocolVersion = '1.1' - ) { - return $this->create($method, Url::buildUrl($urlParts), $headers, $body) - ->setProtocolVersion($protocolVersion); - } - - public function create($method, $url, $headers = null, $body = null, array $options = array()) - { - $method = strtoupper($method); - - if ($method == 'GET' || $method == 'HEAD' || $method == 'TRACE') { - // Handle non-entity-enclosing request methods - $request = new $this->requestClass($method, $url, $headers); - if ($body) { - // The body is where the response body will be stored - $type = gettype($body); - if ($type == 'string' || $type == 'resource' || $type == 'object') { - $request->setResponseBody($body); - } - } - } else { - // Create an entity enclosing request by default - $request = new $this->entityEnclosingRequestClass($method, $url, $headers); - if ($body || $body === '0') { - // Add POST fields and files to an entity enclosing request if an array is used - if (is_array($body) || $body instanceof Collection) { - // Normalize PHP style cURL uploads with a leading '@' symbol - foreach ($body as $key => $value) { - if (is_string($value) && substr($value, 0, 1) == '@') { - $request->addPostFile($key, $value); - unset($body[$key]); - } - } - // Add the fields if they are still present and not all files - $request->addPostFields($body); - } else { - // Add a raw entity body body to the request - $request->setBody($body, (string) $request->getHeader('Content-Type')); - if ((string) $request->getHeader('Transfer-Encoding') == 'chunked') { - $request->removeHeader('Content-Length'); - } - } - } - } - - if ($options) { - $this->applyOptions($request, $options); - } - - return $request; - } - - /** - * Clone a request while changing the method. Emulates the behavior of - * {@see Guzzle\Http\Message\Request::clone}, but can change the HTTP method. - * - * @param RequestInterface $request Request to clone - * @param string $method Method to set - * - * @return RequestInterface - */ - public function cloneRequestWithMethod(RequestInterface $request, $method) - { - // Create the request with the same client if possible - if ($request->getClient()) { - $cloned = $request->getClient()->createRequest($method, $request->getUrl(), $request->getHeaders()); - } else { - $cloned = $this->create($method, $request->getUrl(), $request->getHeaders()); - } - - $cloned->getCurlOptions()->replace($request->getCurlOptions()->toArray()); - $cloned->setEventDispatcher(clone $request->getEventDispatcher()); - // Ensure that that the Content-Length header is not copied if changing to GET or HEAD - if (!($cloned instanceof EntityEnclosingRequestInterface)) { - $cloned->removeHeader('Content-Length'); - } elseif ($request instanceof EntityEnclosingRequestInterface) { - $cloned->setBody($request->getBody()); - } - $cloned->getParams()->replace($request->getParams()->toArray()); - $cloned->dispatch('request.clone', array('request' => $cloned)); - - return $cloned; - } - - public function applyOptions(RequestInterface $request, array $options = array(), $flags = self::OPTIONS_NONE) - { - // Iterate over each key value pair and attempt to apply a config using function visitors - foreach ($options as $key => $value) { - $method = "visit_{$key}"; - if (isset($this->methods[$method])) { - $this->{$method}($request, $value, $flags); - } - } - } - - protected function visit_headers(RequestInterface $request, $value, $flags) - { - if (!is_array($value)) { - throw new InvalidArgumentException('headers value must be an array'); - } - - if ($flags & self::OPTIONS_AS_DEFAULTS) { - // Merge headers in but do not overwrite existing values - foreach ($value as $key => $header) { - if (!$request->hasHeader($key)) { - $request->setHeader($key, $header); - } - } - } else { - $request->addHeaders($value); - } - } - - protected function visit_body(RequestInterface $request, $value, $flags) - { - if ($request instanceof EntityEnclosingRequestInterface) { - $request->setBody($value); - } else { - throw new InvalidArgumentException('Attempting to set a body on a non-entity-enclosing request'); - } - } - - protected function visit_allow_redirects(RequestInterface $request, $value, $flags) - { - if ($value === false) { - $request->getParams()->set(RedirectPlugin::DISABLE, true); - } - } - - protected function visit_auth(RequestInterface $request, $value, $flags) - { - if (!is_array($value)) { - throw new InvalidArgumentException('auth value must be an array'); - } - - $request->setAuth($value[0], isset($value[1]) ? $value[1] : null, isset($value[2]) ? $value[2] : 'basic'); - } - - protected function visit_query(RequestInterface $request, $value, $flags) - { - if (!is_array($value)) { - throw new InvalidArgumentException('query value must be an array'); - } - - if ($flags & self::OPTIONS_AS_DEFAULTS) { - // Merge query string values in but do not overwrite existing values - $query = $request->getQuery(); - $query->overwriteWith(array_diff_key($value, $query->toArray())); - } else { - $request->getQuery()->overwriteWith($value); - } - } - - protected function visit_cookies(RequestInterface $request, $value, $flags) - { - if (!is_array($value)) { - throw new InvalidArgumentException('cookies value must be an array'); - } - - foreach ($value as $name => $v) { - $request->addCookie($name, $v); - } - } - - protected function visit_events(RequestInterface $request, $value, $flags) - { - if (!is_array($value)) { - throw new InvalidArgumentException('events value must be an array'); - } - - foreach ($value as $name => $method) { - if (is_array($method)) { - $request->getEventDispatcher()->addListener($name, $method[0], $method[1]); - } else { - $request->getEventDispatcher()->addListener($name, $method); - } - } - } - - protected function visit_plugins(RequestInterface $request, $value, $flags) - { - if (!is_array($value)) { - throw new InvalidArgumentException('plugins value must be an array'); - } - - foreach ($value as $plugin) { - $request->addSubscriber($plugin); - } - } - - protected function visit_exceptions(RequestInterface $request, $value, $flags) - { - if ($value === false || $value === 0) { - $dispatcher = $request->getEventDispatcher(); - foreach ($dispatcher->getListeners('request.error') as $listener) { - if (is_array($listener) && $listener[0] == 'Guzzle\Http\Message\Request' && $listener[1] = 'onRequestError') { - $dispatcher->removeListener('request.error', $listener); - break; - } - } - } - } - - protected function visit_save_to(RequestInterface $request, $value, $flags) - { - $request->setResponseBody($value); - } - - protected function visit_params(RequestInterface $request, $value, $flags) - { - if (!is_array($value)) { - throw new InvalidArgumentException('params value must be an array'); - } - - $request->getParams()->overwriteWith($value); - } - - protected function visit_timeout(RequestInterface $request, $value, $flags) - { - if (defined('CURLOPT_TIMEOUT_MS')) { - $request->getCurlOptions()->set(CURLOPT_TIMEOUT_MS, $value * 1000); - } else { - $request->getCurlOptions()->set(CURLOPT_TIMEOUT, $value); - } - } - - protected function visit_connect_timeout(RequestInterface $request, $value, $flags) - { - if (defined('CURLOPT_CONNECTTIMEOUT_MS')) { - $request->getCurlOptions()->set(CURLOPT_CONNECTTIMEOUT_MS, $value * 1000); - } else { - $request->getCurlOptions()->set(CURLOPT_CONNECTTIMEOUT, $value); - } - } - - protected function visit_debug(RequestInterface $request, $value, $flags) - { - if ($value) { - $request->getCurlOptions()->set(CURLOPT_VERBOSE, true); - } - } - - protected function visit_verify(RequestInterface $request, $value, $flags) - { - $curl = $request->getCurlOptions(); - if ($value === true || is_string($value)) { - $curl[CURLOPT_SSL_VERIFYHOST] = 2; - $curl[CURLOPT_SSL_VERIFYPEER] = true; - if ($value !== true) { - $curl[CURLOPT_CAINFO] = $value; - } - } elseif ($value === false) { - unset($curl[CURLOPT_CAINFO]); - $curl[CURLOPT_SSL_VERIFYHOST] = 0; - $curl[CURLOPT_SSL_VERIFYPEER] = false; - } - } - - protected function visit_proxy(RequestInterface $request, $value, $flags) - { - $request->getCurlOptions()->set(CURLOPT_PROXY, $value, $flags); - } - - protected function visit_cert(RequestInterface $request, $value, $flags) - { - if (is_array($value)) { - $request->getCurlOptions()->set(CURLOPT_SSLCERT, $value[0]); - $request->getCurlOptions()->set(CURLOPT_SSLCERTPASSWD, $value[1]); - } else { - $request->getCurlOptions()->set(CURLOPT_SSLCERT, $value); - } - } - - protected function visit_ssl_key(RequestInterface $request, $value, $flags) - { - if (is_array($value)) { - $request->getCurlOptions()->set(CURLOPT_SSLKEY, $value[0]); - $request->getCurlOptions()->set(CURLOPT_SSLKEYPASSWD, $value[1]); - } else { - $request->getCurlOptions()->set(CURLOPT_SSLKEY, $value); - } - } + /** @var RequestFactory Singleton instance of the default request factory */ + protected static $instance; + + /** @var array Hash of methods available to the class (provides fast isset() lookups) */ + protected $methods; + + /** @var string Class to instantiate for requests with no body */ + protected $requestClass = 'Guzzle\\Http\\Message\\Request'; + + /** @var string Class to instantiate for requests with a body */ + protected $entityEnclosingRequestClass = 'Guzzle\\Http\\Message\\EntityEnclosingRequest'; + + /** + * Get a cached instance of the default request factory + * + * @return RequestFactory + */ + public static function getInstance() { + + // @codeCoverageIgnoreStart + if ( ! static::$instance ) { + static::$instance = new static(); + } + // @codeCoverageIgnoreEnd + return static::$instance; + } + + public function __construct() { + + $this->methods = array_flip( get_class_methods( __CLASS__ ) ); + } + + public function fromMessage( $message ) { + $parsed = ParserRegistry::getInstance()->getParser( 'message' )->parseRequest( $message ); + + if ( ! $parsed ) { + return false; + } + + $request = $this->fromParts($parsed['method'], $parsed['request_url'], + $parsed['headers'], $parsed['body'], $parsed['protocol'], + $parsed['version']); + + // EntityEnclosingRequest adds an "Expect: 100-Continue" header when using a raw request body for PUT or POST + // requests. This factory method should accurately reflect the message, so here we are removing the Expect + // header if one was not supplied in the message. + if ( ! isset( $parsed['headers']['Expect'] ) && ! isset( $parsed['headers']['expect'] ) ) { + $request->removeHeader( 'Expect' ); + } + + return $request; + } + + public function fromParts( + $method, + array $urlParts, + $headers = null, + $body = null, + $protocol = 'HTTP', + $protocolVersion = '1.1' + ) { + return $this->create( $method, Url::buildUrl( $urlParts ), $headers, $body ) + ->setProtocolVersion( $protocolVersion ); + } + + public function create( $method, $url, $headers = null, $body = null, array $options = array() ) { + $method = strtoupper( $method ); + + if ( $method == 'GET' || $method == 'HEAD' || $method == 'TRACE' ) { + // Handle non-entity-enclosing request methods + $request = new $this->requestClass( $method, $url, $headers ); + if ( $body ) { + // The body is where the response body will be stored + $type = gettype( $body ); + if ( $type == 'string' || $type == 'resource' || $type == 'object' ) { + $request->setResponseBody( $body ); + } + } + } else { + // Create an entity enclosing request by default + $request = new $this->entityEnclosingRequestClass( $method, $url, $headers ); + if ( $body || $body === '0' ) { + // Add POST fields and files to an entity enclosing request if an array is used + if ( is_array( $body ) || $body instanceof Collection ) { + // Normalize PHP style cURL uploads with a leading '@' symbol + foreach ( $body as $key => $value ) { + if ( is_string( $value ) && substr( $value, 0, 1 ) == '@' ) { + $request->addPostFile( $key, $value ); + unset( $body[ $key ] ); + } + } + // Add the fields if they are still present and not all files + $request->addPostFields( $body ); + } else { + // Add a raw entity body body to the request + $request->setBody( $body, (string) $request->getHeader( 'Content-Type' ) ); + if ( (string) $request->getHeader( 'Transfer-Encoding' ) == 'chunked' ) { + $request->removeHeader( 'Content-Length' ); + } + } + } + } + + if ( $options ) { + $this->applyOptions( $request, $options ); + } + + return $request; + } + + /** + * Clone a request while changing the method. Emulates the behavior of + * {@see Guzzle\Http\Message\Request::clone}, but can change the HTTP method. + * + * @param RequestInterface $request Request to clone + * @param string $method Method to set + * + * @return RequestInterface + */ + public function cloneRequestWithMethod( RequestInterface $request, $method ) { + // Create the request with the same client if possible + if ( $request->getClient() ) { + $cloned = $request->getClient()->createRequest( $method, $request->getUrl(), $request->getHeaders() ); + } else { + $cloned = $this->create( $method, $request->getUrl(), $request->getHeaders() ); + } + + $cloned->getCurlOptions()->replace( $request->getCurlOptions()->toArray() ); + $cloned->setEventDispatcher( clone $request->getEventDispatcher() ); + // Ensure that that the Content-Length header is not copied if changing to GET or HEAD + if ( ! ($cloned instanceof EntityEnclosingRequestInterface) ) { + $cloned->removeHeader( 'Content-Length' ); + } elseif ( $request instanceof EntityEnclosingRequestInterface ) { + $cloned->setBody( $request->getBody() ); + } + $cloned->getParams()->replace( $request->getParams()->toArray() ); + $cloned->dispatch( 'request.clone', array( 'request' => $cloned ) ); + + return $cloned; + } + + public function applyOptions( RequestInterface $request, array $options = array(), $flags = self::OPTIONS_NONE ) { + // Iterate over each key value pair and attempt to apply a config using function visitors + foreach ( $options as $key => $value ) { + $method = "visit_{$key}"; + if ( isset( $this->methods[ $method ] ) ) { + $this->{$method}($request, $value, $flags); + } + } + } + + protected function visit_headers( RequestInterface $request, $value, $flags ) { + if ( ! is_array( $value ) ) { + throw new InvalidArgumentException( 'headers value must be an array' ); + } + + if ( $flags & self::OPTIONS_AS_DEFAULTS ) { + // Merge headers in but do not overwrite existing values + foreach ( $value as $key => $header ) { + if ( ! $request->hasHeader( $key ) ) { + $request->setHeader( $key, $header ); + } + } + } else { + $request->addHeaders( $value ); + } + } + + protected function visit_body( RequestInterface $request, $value, $flags ) { + if ( $request instanceof EntityEnclosingRequestInterface ) { + $request->setBody( $value ); + } else { + throw new InvalidArgumentException( 'Attempting to set a body on a non-entity-enclosing request' ); + } + } + + protected function visit_allow_redirects( RequestInterface $request, $value, $flags ) { + if ( $value === false ) { + $request->getParams()->set( RedirectPlugin::DISABLE, true ); + } + } + + protected function visit_auth( RequestInterface $request, $value, $flags ) { + if ( ! is_array( $value ) ) { + throw new InvalidArgumentException( 'auth value must be an array' ); + } + + $request->setAuth( $value[0], isset( $value[1] ) ? $value[1] : null, isset( $value[2] ) ? $value[2] : 'basic' ); + } + + protected function visit_query( RequestInterface $request, $value, $flags ) { + if ( ! is_array( $value ) ) { + throw new InvalidArgumentException( 'query value must be an array' ); + } + + if ( $flags & self::OPTIONS_AS_DEFAULTS ) { + // Merge query string values in but do not overwrite existing values + $query = $request->getQuery(); + $query->overwriteWith( array_diff_key( $value, $query->toArray() ) ); + } else { + $request->getQuery()->overwriteWith( $value ); + } + } + + protected function visit_cookies( RequestInterface $request, $value, $flags ) { + if ( ! is_array( $value ) ) { + throw new InvalidArgumentException( 'cookies value must be an array' ); + } + + foreach ( $value as $name => $v ) { + $request->addCookie( $name, $v ); + } + } + + protected function visit_events( RequestInterface $request, $value, $flags ) { + if ( ! is_array( $value ) ) { + throw new InvalidArgumentException( 'events value must be an array' ); + } + + foreach ( $value as $name => $method ) { + if ( is_array( $method ) ) { + $request->getEventDispatcher()->addListener( $name, $method[0], $method[1] ); + } else { + $request->getEventDispatcher()->addListener( $name, $method ); + } + } + } + + protected function visit_plugins( RequestInterface $request, $value, $flags ) { + if ( ! is_array( $value ) ) { + throw new InvalidArgumentException( 'plugins value must be an array' ); + } + + foreach ( $value as $plugin ) { + $request->addSubscriber( $plugin ); + } + } + + protected function visit_exceptions( RequestInterface $request, $value, $flags ) { + if ( $value === false || $value === 0 ) { + $dispatcher = $request->getEventDispatcher(); + foreach ( $dispatcher->getListeners( 'request.error' ) as $listener ) { + if ( is_array( $listener ) && $listener[0] == 'Guzzle\Http\Message\Request' && $listener[1] = 'onRequestError' ) { + $dispatcher->removeListener( 'request.error', $listener ); + break; + } + } + } + } + + protected function visit_save_to( RequestInterface $request, $value, $flags ) { + $request->setResponseBody( $value ); + } + + protected function visit_params( RequestInterface $request, $value, $flags ) { + if ( ! is_array( $value ) ) { + throw new InvalidArgumentException( 'params value must be an array' ); + } + + $request->getParams()->overwriteWith( $value ); + } + + protected function visit_timeout( RequestInterface $request, $value, $flags ) { + if ( defined( 'CURLOPT_TIMEOUT_MS' ) ) { + $request->getCurlOptions()->set( CURLOPT_TIMEOUT_MS, $value * 1000 ); + } else { + $request->getCurlOptions()->set( CURLOPT_TIMEOUT, $value ); + } + } + + protected function visit_connect_timeout( RequestInterface $request, $value, $flags ) { + if ( defined( 'CURLOPT_CONNECTTIMEOUT_MS' ) ) { + $request->getCurlOptions()->set( CURLOPT_CONNECTTIMEOUT_MS, $value * 1000 ); + } else { + $request->getCurlOptions()->set( CURLOPT_CONNECTTIMEOUT, $value ); + } + } + + protected function visit_debug( RequestInterface $request, $value, $flags ) { + if ( $value ) { + $request->getCurlOptions()->set( CURLOPT_VERBOSE, true ); + } + } + + protected function visit_verify( RequestInterface $request, $value, $flags ) { + $curl = $request->getCurlOptions(); + if ( $value === true || is_string( $value ) ) { + $curl[ CURLOPT_SSL_VERIFYHOST ] = 2; + $curl[ CURLOPT_SSL_VERIFYPEER ] = true; + if ( $value !== true ) { + $curl[ CURLOPT_CAINFO ] = $value; + } + } elseif ( $value === false ) { + unset( $curl[ CURLOPT_CAINFO ] ); + $curl[ CURLOPT_SSL_VERIFYHOST ] = 0; + $curl[ CURLOPT_SSL_VERIFYPEER ] = false; + } + } + + protected function visit_proxy( RequestInterface $request, $value, $flags ) { + $request->getCurlOptions()->set( CURLOPT_PROXY, $value, $flags ); + } + + protected function visit_cert( RequestInterface $request, $value, $flags ) { + if ( is_array( $value ) ) { + $request->getCurlOptions()->set( CURLOPT_SSLCERT, $value[0] ); + $request->getCurlOptions()->set( CURLOPT_SSLCERTPASSWD, $value[1] ); + } else { + $request->getCurlOptions()->set( CURLOPT_SSLCERT, $value ); + } + } + + protected function visit_ssl_key( RequestInterface $request, $value, $flags ) { + if ( is_array( $value ) ) { + $request->getCurlOptions()->set( CURLOPT_SSLKEY, $value[0] ); + $request->getCurlOptions()->set( CURLOPT_SSLKEYPASSWD, $value[1] ); + } else { + $request->getCurlOptions()->set( CURLOPT_SSLKEY, $value ); + } + } } diff --git a/Postman/Postman-Send-Test-Email/PostmanSendTestEmailController.php b/Postman/Postman-Send-Test-Email/PostmanSendTestEmailController.php index 1b0d106..a65dd43 100644 --- a/Postman/Postman-Send-Test-Email/PostmanSendTestEmailController.php +++ b/Postman/Postman-Send-Test-Email/PostmanSendTestEmailController.php @@ -2,43 +2,43 @@ class PostmanSendTestEmailController { const EMAIL_TEST_SLUG = 'postman/email_test'; const RECIPIENT_EMAIL_FIELD_NAME = 'postman_recipient_email'; - + // logging private $logger; private $options; - + // Holds the values to be used in the fields callbacks private $rootPluginFilenameAndPath; - + /** * Constructor * - * @param unknown $rootPluginFilenameAndPath + * @param unknown $rootPluginFilenameAndPath */ - public function __construct($rootPluginFilenameAndPath) { - assert ( ! empty ( $rootPluginFilenameAndPath ) ); - assert ( PostmanUtils::isAdmin () ); - assert ( is_admin () ); - - $this->logger = new PostmanLogger ( get_class ( $this ) ); + public function __construct( $rootPluginFilenameAndPath ) { + assert( ! empty( $rootPluginFilenameAndPath ) ); + assert( PostmanUtils::isAdmin() ); + assert( is_admin() ); + + $this->logger = new PostmanLogger( get_class( $this ) ); $this->rootPluginFilenameAndPath = $rootPluginFilenameAndPath; - $this->options = PostmanOptions::getInstance (); - - PostmanUtils::registerAdminMenu ( $this, 'addEmailTestSubmenu' ); - + $this->options = PostmanOptions::getInstance(); + + PostmanUtils::registerAdminMenu( $this, 'addEmailTestSubmenu' ); + // hook on the init event - add_action ( 'init', array ( + add_action( 'init', array( $this, - 'on_init' + 'on_init', ) ); - + // initialize the scripts, stylesheets and form fields - add_action ( 'admin_init', array ( + add_action( 'admin_init', array( $this, - 'on_admin_init' + 'on_admin_init', ) ); } - + /** * Functions to execute on the init event * @@ -47,124 +47,122 @@ class PostmanSendTestEmailController { */ public function on_init() { // register Ajax handlers - new PostmanSendTestEmailAjaxController (); + new PostmanSendTestEmailAjaxController(); } - + /** * Fires on the admin_init method */ public function on_admin_init() { - // - $this->registerStylesAndScripts (); + $this->registerStylesAndScripts(); } - + /** * Get the settings option array and print one of its values */ public function test_email_callback() { - printf ( '<input type="text" id="%s" name="postman_test_options[test_email]" value="%s" class="required email" size="40"/>', self::RECIPIENT_EMAIL_FIELD_NAME, wp_get_current_user ()->user_email ); + printf( '<input type="text" id="%s" name="postman_test_options[test_email]" value="%s" class="required email" size="40"/>', self::RECIPIENT_EMAIL_FIELD_NAME, wp_get_current_user()->user_email ); } - + /** * Register and add settings */ private function registerStylesAndScripts() { - if ($this->logger->isTrace ()) { - $this->logger->trace ( 'registerStylesAndScripts()' ); + if ( $this->logger->isTrace() ) { + $this->logger->trace( 'registerStylesAndScripts()' ); } - - // - $pluginData = apply_filters ( 'postman_get_plugin_metadata', null ); - + + $pluginData = apply_filters( 'postman_get_plugin_metadata', null ); + // register the stylesheet resource - wp_register_style ( 'postman_send_test_email', plugins_url ( 'Postman/Postman-Send-Test-Email/postman_send_test_email.css', $this->rootPluginFilenameAndPath ), PostmanViewController::POSTMAN_STYLE, $pluginData ['version'] ); - + wp_register_style( 'postman_send_test_email', plugins_url( 'Postman/Postman-Send-Test-Email/postman_send_test_email.css', $this->rootPluginFilenameAndPath ), PostmanViewController::POSTMAN_STYLE, $pluginData ['version'] ); + // register the javascript resource - wp_register_script ( 'postman_test_email_wizard_script', plugins_url ( 'Postman/Postman-Send-Test-Email/postman_send_test_email.js', $this->rootPluginFilenameAndPath ), array ( + wp_register_script( 'postman_test_email_wizard_script', plugins_url( 'Postman/Postman-Send-Test-Email/postman_send_test_email.js', $this->rootPluginFilenameAndPath ), array( PostmanViewController::JQUERY_SCRIPT, 'jquery_validation', 'jquery_steps_script', - PostmanViewController::POSTMAN_SCRIPT + PostmanViewController::POSTMAN_SCRIPT, ), $pluginData ['version'] ); } - + /** * Register the Email Test screen */ public function addEmailTestSubmenu() { - $page = add_submenu_page ( null, sprintf ( __ ( '%s Setup', Postman::TEXT_DOMAIN ), __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ) ), __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ), Postman::MANAGE_POSTMAN_CAPABILITY_NAME, PostmanSendTestEmailController::EMAIL_TEST_SLUG, array ( + $page = add_submenu_page( null, sprintf( __( '%s Setup', Postman::TEXT_DOMAIN ), __( 'Postman SMTP', Postman::TEXT_DOMAIN ) ), __( 'Postman SMTP', Postman::TEXT_DOMAIN ), Postman::MANAGE_POSTMAN_CAPABILITY_NAME, PostmanSendTestEmailController::EMAIL_TEST_SLUG, array( $this, - 'outputTestEmailContent' + 'outputTestEmailContent', ) ); // When the plugin options page is loaded, also load the stylesheet - add_action ( 'admin_print_styles-' . $page, array ( + add_action( 'admin_print_styles-' . $page, array( $this, - 'enqueueEmailTestResources' + 'enqueueEmailTestResources', ) ); } - + /** */ function enqueueEmailTestResources() { - wp_enqueue_style ( 'jquery_steps_style' ); - wp_enqueue_style ( PostmanViewController::POSTMAN_STYLE ); - wp_enqueue_style ( 'postman_send_test_email' ); - wp_enqueue_script ( 'postman_test_email_wizard_script' ); - wp_localize_script ( PostmanViewController::POSTMAN_SCRIPT, 'postman_email_test', array ( + wp_enqueue_style( 'jquery_steps_style' ); + wp_enqueue_style( PostmanViewController::POSTMAN_STYLE ); + wp_enqueue_style( 'postman_send_test_email' ); + wp_enqueue_script( 'postman_test_email_wizard_script' ); + wp_localize_script( PostmanViewController::POSTMAN_SCRIPT, 'postman_email_test', array( 'recipient' => '#' . self::RECIPIENT_EMAIL_FIELD_NAME, - 'not_started' => _x ( 'In Outbox', 'Email Test Status', Postman::TEXT_DOMAIN ), - 'sending' => _x ( 'Sending...', 'Email Test Status', Postman::TEXT_DOMAIN ), - 'success' => _x ( 'Success', 'Email Test Status', Postman::TEXT_DOMAIN ), - 'failed' => _x ( 'Failed', 'Email Test Status', Postman::TEXT_DOMAIN ), - 'ajax_error' => __ ( 'Ajax Error', Postman::TEXT_DOMAIN ) + 'not_started' => _x( 'In Outbox', 'Email Test Status', Postman::TEXT_DOMAIN ), + 'sending' => _x( 'Sending...', 'Email Test Status', Postman::TEXT_DOMAIN ), + 'success' => _x( 'Success', 'Email Test Status', Postman::TEXT_DOMAIN ), + 'failed' => _x( 'Failed', 'Email Test Status', Postman::TEXT_DOMAIN ), + 'ajax_error' => __( 'Ajax Error', Postman::TEXT_DOMAIN ), ) ); } - + /** */ public function outputTestEmailContent() { print '<div class="wrap">'; - - PostmanViewController::outputChildPageHeader ( __ ( 'Send a Test Email', Postman::TEXT_DOMAIN ) ); - - printf ( '<form id="postman_test_email_wizard" method="post" action="%s">', PostmanUtils::getSettingsPageUrl () ); - + + PostmanViewController::outputChildPageHeader( __( 'Send a Test Email', Postman::TEXT_DOMAIN ) ); + + printf( '<form id="postman_test_email_wizard" method="post" action="%s">', PostmanUtils::getSettingsPageUrl() ); + // Step 1 - printf ( '<h5>%s</h5>', __ ( 'Specify the Recipient', Postman::TEXT_DOMAIN ) ); + printf( '<h5>%s</h5>', __( 'Specify the Recipient', Postman::TEXT_DOMAIN ) ); print '<fieldset>'; - printf ( '<legend>%s</legend>', __ ( 'Who is this message going to?', Postman::TEXT_DOMAIN ) ); - printf ( '<p>%s', __ ( 'This utility allows you to send an email message for testing.', Postman::TEXT_DOMAIN ) ); + printf( '<legend>%s</legend>', __( 'Who is this message going to?', Postman::TEXT_DOMAIN ) ); + printf( '<p>%s', __( 'This utility allows you to send an email message for testing.', Postman::TEXT_DOMAIN ) ); print ' '; /* translators: where %d is an amount of time, in seconds */ - printf ( '%s</p>', sprintf ( _n ( 'If there is a problem, Postman will give up after %d second.', 'If there is a problem, Postman will give up after %d seconds.', $this->options->getReadTimeout (), Postman::TEXT_DOMAIN ), $this->options->getReadTimeout () ) ); - printf ( '<label for="postman_test_options[test_email]">%s</label>', _x ( 'Recipient Email Address', 'Configuration Input Field', Postman::TEXT_DOMAIN ) ); - print $this->test_email_callback (); + printf( '%s</p>', sprintf( _n( 'If there is a problem, Postman will give up after %d second.', 'If there is a problem, Postman will give up after %d seconds.', $this->options->getReadTimeout(), Postman::TEXT_DOMAIN ), $this->options->getReadTimeout() ) ); + printf( '<label for="postman_test_options[test_email]">%s</label>', _x( 'Recipient Email Address', 'Configuration Input Field', Postman::TEXT_DOMAIN ) ); + print $this->test_email_callback(); print '</fieldset>'; - + // Step 2 - printf ( '<h5>%s</h5>', __ ( 'Send The Message', Postman::TEXT_DOMAIN ) ); + printf( '<h5>%s</h5>', __( 'Send The Message', Postman::TEXT_DOMAIN ) ); print '<fieldset>'; print '<legend>'; - print __ ( 'Sending the message:', Postman::TEXT_DOMAIN ); - printf ( ' <span id="postman_test_message_status">%s</span>', _x ( 'In Outbox', 'Email Test Status', Postman::TEXT_DOMAIN ) ); + print __( 'Sending the message:', Postman::TEXT_DOMAIN ); + printf( ' <span id="postman_test_message_status">%s</span>', _x( 'In Outbox', 'Email Test Status', Postman::TEXT_DOMAIN ) ); print '</legend>'; print '<section>'; - printf ( '<p><label>%s</label></p>', __ ( 'Status', Postman::TEXT_DOMAIN ) ); + printf( '<p><label>%s</label></p>', __( 'Status', Postman::TEXT_DOMAIN ) ); print '<textarea id="postman_test_message_error_message" readonly="readonly" cols="65" rows="4"></textarea>'; print '</section>'; print '</fieldset>'; - + // Step 3 - printf ( '<h5>%s</h5>', __ ( 'Session Transcript', Postman::TEXT_DOMAIN ) ); + printf( '<h5>%s</h5>', __( 'Session Transcript', Postman::TEXT_DOMAIN ) ); print '<fieldset>'; - printf ( '<legend>%s</legend>', __ ( 'Examine the Session Transcript if you need to.', Postman::TEXT_DOMAIN ) ); - printf ( '<p>%s</p>', __ ( 'This is the conversation between Postman and the mail server. It can be useful for diagnosing problems. <b>DO NOT</b> post it on-line, it may contain your account password.', Postman::TEXT_DOMAIN ) ); + printf( '<legend>%s</legend>', __( 'Examine the Session Transcript if you need to.', Postman::TEXT_DOMAIN ) ); + printf( '<p>%s</p>', __( 'This is the conversation between Postman and the mail server. It can be useful for diagnosing problems. <b>DO NOT</b> post it on-line, it may contain your account password.', Postman::TEXT_DOMAIN ) ); print '<section>'; - printf ( '<p><label for="postman_test_message_transcript">%s</label></p>', __ ( 'Session Transcript', Postman::TEXT_DOMAIN ) ); + printf( '<p><label for="postman_test_message_transcript">%s</label></p>', __( 'Session Transcript', Postman::TEXT_DOMAIN ) ); print '<textarea readonly="readonly" id="postman_test_message_transcript" cols="65" rows="8"></textarea>'; print '</section>'; print '</fieldset>'; - + print '</form>'; print '</div>'; } @@ -173,22 +171,21 @@ class PostmanSendTestEmailController { /** * * @author jasonhendriks - * */ class PostmanSendTestEmailAjaxController extends PostmanAbstractAjaxHandler { - + /** * Constructor * - * @param PostmanOptions $options - * @param PostmanOAuthToken $authorizationToken - * @param PostmanConfigTextHelper $oauthScribe + * @param PostmanOptions $options + * @param PostmanOAuthToken $authorizationToken + * @param PostmanConfigTextHelper $oauthScribe */ function __construct() { - parent::__construct (); - PostmanUtils::registerAjaxHandler ( 'postman_send_test_email', $this, 'sendTestEmailViaAjax' ); + parent::__construct(); + PostmanUtils::registerAjaxHandler( 'postman_send_test_email', $this, 'sendTestEmailViaAjax' ); } - + /** * Yes, this procedure is just for testing. * @@ -197,92 +194,90 @@ class PostmanSendTestEmailAjaxController extends PostmanAbstractAjaxHandler { function test_mode() { return true; } - + /** * This Ajax sends a test email */ function sendTestEmailViaAjax() { // get the email address of the recipient from the HTTP Request - $email = $this->getRequestParameter ( 'email' ); - + $email = $this->getRequestParameter( 'email' ); + // get the name of the server from the HTTP Request - $serverName = PostmanUtils::postmanGetServerName (); - + $serverName = PostmanUtils::postmanGetServerName(); + /* translators: where %s is the domain name of the site */ - $subject = sprintf ( _x ( 'Postman SMTP Test (%s)', 'Test Email Subject', Postman::TEXT_DOMAIN ), $serverName ); - + $subject = sprintf( _x( 'Postman SMTP Test (%s)', 'Test Email Subject', Postman::TEXT_DOMAIN ), $serverName ); + // Postman API: indicate to Postman this is just for testing - add_filter ( 'postman_test_email', array ( + add_filter( 'postman_test_email', array( $this, - 'test_mode' + 'test_mode', ) ); - + // this header specifies that there are many parts (one text part, one html part) $header = 'Content-Type: multipart/alternative;'; - + // createt the message content - $message = $this->createMessageContent (); - + $message = $this->createMessageContent(); + // send the message - $success = wp_mail ( $email, $subject, $message, $header ); - + $success = wp_mail( $email, $subject, $message, $header ); + // Postman API: remove the testing indicator - remove_filter ( 'postman_test_email', array ( + remove_filter( 'postman_test_email', array( $this, - 'test_mode' + 'test_mode', ) ); - + // Postman API: retrieve the result of sending this message from Postman - $result = apply_filters ( 'postman_wp_mail_result', null ); - + $result = apply_filters( 'postman_wp_mail_result', null ); + // post-handling - if ($success) { - $this->logger->debug ( 'Test Email delivered to server' ); + if ( $success ) { + $this->logger->debug( 'Test Email delivered to server' ); // the message was sent successfully, generate an appropriate message for the user - $statusMessage = sprintf ( __ ( 'Your message was delivered (%d ms) to the SMTP server! Congratulations :)', Postman::TEXT_DOMAIN ), $result ['time'] ); - - // - $this->logger->debug ( 'statusmessage: ' . $statusMessage ); - + $statusMessage = sprintf( __( 'Your message was delivered (%d ms) to the SMTP server! Congratulations :)', Postman::TEXT_DOMAIN ), $result ['time'] ); + + $this->logger->debug( 'statusmessage: ' . $statusMessage ); + // compose the JSON response for the caller - $response = array ( + $response = array( 'message' => $statusMessage, - 'transcript' => $result ['transcript'] + 'transcript' => $result ['transcript'], ); - + // log the response - if ($this->logger->isTrace ()) { - $this->logger->trace ( 'Ajax Response:' ); - $this->logger->trace ( $response ); + if ( $this->logger->isTrace() ) { + $this->logger->trace( 'Ajax Response:' ); + $this->logger->trace( $response ); } - + // send the JSON response - wp_send_json_success ( $response ); + wp_send_json_success( $response ); } else { - $this->logger->error ( 'Test Email NOT delivered to server - ' . $result ['exception']->getCode () ); + $this->logger->error( 'Test Email NOT delivered to server - ' . $result ['exception']->getCode() ); // the message was NOT sent successfully, generate an appropriate message for the user - $statusMessage = $result ['exception']->getMessage (); - - // - $this->logger->debug ( 'statusmessage: ' . $statusMessage ); - + $statusMessage = $result ['exception']->getMessage(); + + $this->logger->debug( 'statusmessage: ' . $statusMessage ); + // compose the JSON response for the caller - $response = array ( + $response = array( 'message' => $statusMessage, - 'transcript' => $result ['transcript'] + 'transcript' => $result ['transcript'], ); - + // log the response - if ($this->logger->isTrace ()) { - $this->logger->trace ( 'Ajax Response:' ); - $this->logger->trace ( $response ); + if ( $this->logger->isTrace() ) { + $this->logger->trace( 'Ajax Response:' ); + $this->logger->trace( $response ); } - + // send the JSON response - wp_send_json_error ( $response ); + wp_send_json_error( $response ); } } - + /** * Create the multipart message content * @@ -290,22 +285,23 @@ class PostmanSendTestEmailAjaxController extends PostmanAbstractAjaxHandler { */ private function createMessageContent() { // Postman API: Get the plugin metadata - $pluginData = apply_filters ( 'postman_get_plugin_metadata', null ); - - /* translators: where %s is the Postman plugin version number (e.g. 1.4) */ + $pluginData = apply_filters( 'postman_get_plugin_metadata', null ); + + /* + translators: where %s is the Postman plugin version number (e.g. 1.4) */ // English - Mandarin - French - Hindi - Spanish - Portuguese - Russian - Japanese // http://www.pinyin.info/tools/converter/chars2uninumbers.html $greeting = 'Hello! - 你好 - Bonjour! - नमस्ते - ¡Hola! - Olá - Привет! - 今日は'; - $sentBy = sprintf ( _x ( 'Sent by Postman %s', 'Test Email Tagline', Postman::TEXT_DOMAIN ), $pluginData ['version'] ); - $imageSource = __ ( 'Image source', Postman::TEXT_DOMAIN ); - $withPermission = __ ( 'Used with permission', Postman::TEXT_DOMAIN ); - $messageArray = array ( + $sentBy = sprintf( _x( 'Sent by Postman %s', 'Test Email Tagline', Postman::TEXT_DOMAIN ), $pluginData ['version'] ); + $imageSource = __( 'Image source', Postman::TEXT_DOMAIN ); + $withPermission = __( 'Used with permission', Postman::TEXT_DOMAIN ); + $messageArray = array( 'Content-Type: text/plain; charset = "UTF-8"', 'Content-Transfer-Encoding: 8bit', '', 'Hello!', '', - sprintf ( '%s - https://wordpress.org/plugins/postman-smtp/', $sentBy ), + sprintf( '%s - https://wordpress.org/plugins/post-smtp/', $sentBy ), '', 'Content-Type: text/html; charset=UTF-8', 'Content-Transfer-Encoding: quoted-printable', @@ -331,23 +327,23 @@ class PostmanSendTestEmailAjaxController extends PostmanAbstractAjaxHandler { ' <tr>', ' <td>', ' <div style="max-width: 600px; height: 400px; margin: 0 auto; overflow: hidden;background-image:url(\'https://ps.w.org/postman-smtp/assets/email/poofytoo.png\');background-repeat: no-repeat;">', - sprintf ( ' <div style="margin:50px 0 0 300px; width:300px; font-size:2em;">%s</div>', $greeting ), - sprintf ( ' <div style="text-align:right;font-size: 1.4em; color:black;margin:150px 0 0 200px;">%s', $sentBy ), - ' <br/><span style="font-size: 0.8em"><a style="color:#3f73b9" href="https://wordpress.org/plugins/postman-smtp/">https://wordpress.org/plugins/postman-smtp/</a></span>', + sprintf( ' <div style="margin:50px 0 0 300px; width:300px; font-size:2em;">%s</div>', $greeting ), + sprintf( ' <div style="text-align:right;font-size: 1.4em; color:black;margin:150px 0 0 200px;">%s', $sentBy ), + ' <br/><span style="font-size: 0.8em"><a style="color:#3f73b9" href="https://wordpress.org/plugins/post-smtp/">https://wordpress.org/plugins/post-smtp/</a></span>', ' </div>', ' </div>', ' </td>', ' </tr>', ' </tbody>', ' </table>', - sprintf ( ' <br><span style="font-size:0.9em;color:#94c0dc;">%s: <a style="color:#94c0dc" href="http://poofytoo.com">poofytoo.com</a> - %s</span>', $imageSource, $withPermission ), + sprintf( ' <br><span style="font-size:0.9em;color:#94c0dc;">%s: <a style="color:#94c0dc" href="http://poofytoo.com">poofytoo.com</a> - %s</span>', $imageSource, $withPermission ), ' </td>', ' </tr>', ' </tbody>', ' </table>', '</body>', - '</html>' + '</html>', ); - return implode ( PostmanMessage::EOL, $messageArray ); + return implode( PostmanMessage::EOL, $messageArray ); } } diff --git a/Postman/Postman.php b/Postman/Postman.php index 46a69f9..aabdff3 100644 --- a/Postman/Postman.php +++ b/Postman/Postman.php @@ -342,7 +342,7 @@ class Postman { * http://striderweb.com/nerdaphernalia/2008/06/give-your-wordpress-plugin-credit/ */ function print_signature() { - printf( '<a href="https://wordpress.org/plugins/postman-smtp/">%s</a> %s<br/>', $this->pluginData ['name'], $this->pluginData ['version'] ); + printf( '<a href="https://wordpress.org/plugins/post-smtp/">%s</a> %s<br/>', $this->pluginData ['name'], $this->pluginData ['version'] ); } /** diff --git a/Postman/PostmanConfigTextHelper.php b/Postman/PostmanConfigTextHelper.php index 8477b2c..1a74d9d 100644 --- a/Postman/PostmanConfigTextHelper.php +++ b/Postman/PostmanConfigTextHelper.php @@ -1,5 +1,5 @@ <?php -if (! interface_exists ( 'PostmanConfigTextHelper' )) { +if ( ! interface_exists( 'PostmanConfigTextHelper' ) ) { interface PostmanConfigTextHelper { public function isOauthHost(); public function isGoogle(); @@ -20,21 +20,21 @@ if (! interface_exists ( 'PostmanConfigTextHelper' )) { public function getEncryptionType(); } } -if (! class_exists ( 'PostmanAbstractConfigTextHelper' )) { - +if ( ! class_exists( 'PostmanAbstractConfigTextHelper' ) ) { + /** * * @author jasonhendriks */ abstract class PostmanAbstractConfigTextHelper implements PostmanConfigTextHelper { public function getOAuthHelp() { - $attention = __ ( 'Attention' ); + $attention = __( 'Attention' ); /* translators: parameters available are 1=portal-url, 2=portal-name, 3=clientId-name, 4=clientSecret-name, 5=callbackUrl, 6=service-name, 7=portal-application (e.g. Open the Google Developer Console, create a Client ID for web application using the URL's displayed below, and copy the Client ID and Client Secret here.) */ - $errorMessage = sprintf ( __ ( 'Open the <a href="%1$s" target="_new">%2$s</a>, create <b>%7$s</b> with the values displayed below, and copy the generated %3$s and %4$s here.', Postman::TEXT_DOMAIN ), $this->getApplicationPortalUrl (), $this->getApplicationPortalName (), $this->getClientIdLabel (), $this->getClientSecretLabel (), $this->getCallbackUrlLabel (), $this->getOwnerName (), $this->getApplicationDescription () ); - $text = sprintf ( '<b style="color:red">%s!</b> %s', $attention, $errorMessage ); + $errorMessage = sprintf( __( 'Open the <a href="%1$s" target="_new">%2$s</a>, create <b>%7$s</b> with the values displayed below, and copy the generated %3$s and %4$s here.', Postman::TEXT_DOMAIN ), $this->getApplicationPortalUrl(), $this->getApplicationPortalName(), $this->getClientIdLabel(), $this->getClientSecretLabel(), $this->getCallbackUrlLabel(), $this->getOwnerName(), $this->getApplicationDescription() ); + $text = sprintf( '<b style="color:red">%s!</b> %s', $attention, $errorMessage ); /* translators: parameters available are 1=clientId-name, 2=service-name, 3=FAQ-URL, 4=Video-URL (e.g. See How do I get a Google Client ID? in the F.A.Q.) */ - $howToTemplate = __ ( 'See <a href="%3$s" target="_new">How do I get a %1$s %2$s?</a> in the F.A.Q. or <a href="%4$s" target="_new">watch our How-To video 📺</a>.', Postman::TEXT_DOMAIN ); - $text .= sprintf ( ' %s', sprintf ( $howToTemplate, $this->getOwnerName (), $this->getClientIdLabel (), 'https://wordpress.org/plugins/postman-smtp/faq/', 'https://vimeo.com/128589255' ) ); + $howToTemplate = __( 'See <a href="%3$s" target="_new">How do I get a %1$s %2$s?</a> in the F.A.Q. or <a href="%4$s" target="_new">watch our How-To video 📺</a>.', Postman::TEXT_DOMAIN ); + $text .= sprintf( ' %s', sprintf( $howToTemplate, $this->getOwnerName(), $this->getClientIdLabel(), 'https://wordpress.org/plugins/post-smtp/faq/', 'https://vimeo.com/128589255' ) ); return $text; } function isOauthHost() { @@ -51,11 +51,11 @@ if (! class_exists ( 'PostmanAbstractConfigTextHelper' )) { } public function getRequestPermissionLinkText() { /* translators: where %s is the Email Service Owner (e.g. Google, Microsoft or Yahoo) */ - return sprintf ( _x ( 'Grant permission with %s', 'Command to initiate OAuth authentication', Postman::TEXT_DOMAIN ), $this->getOwnerName () ); + return sprintf( _x( 'Grant permission with %s', 'Command to initiate OAuth authentication', Postman::TEXT_DOMAIN ), $this->getOwnerName() ); } } } -if (! class_exists ( 'PostmanGoogleOAuthScribe' )) { +if ( ! class_exists( 'PostmanGoogleOAuthScribe' ) ) { class PostmanGoogleOAuthScribe extends PostmanAbstractConfigTextHelper { public function isGoogle() { return true; @@ -65,47 +65,47 @@ if (! class_exists ( 'PostmanGoogleOAuthScribe' )) { } public function getCallbackUrl() { // see https://codex.wordpress.org/Function_Reference/admin_url#Related - return admin_url ( 'options-general.php' ) . '?page=postman'; + return admin_url( 'options-general.php' ) . '?page=postman'; } function getCallbackDomain() { - $urlParts = parse_url ( $this->getCallbackUrl () ); - if (isset ( $urlParts ['scheme'] ) && isset ( $urlParts ['host'] )) { - return $urlParts ['scheme'] . "://" . $urlParts ['host']; + $urlParts = parse_url( $this->getCallbackUrl() ); + if ( isset( $urlParts ['scheme'] ) && isset( $urlParts ['host'] ) ) { + return $urlParts ['scheme'] . '://' . $urlParts ['host']; } else { - throw new Exception (); + throw new Exception(); } } public function getClientIdLabel() { /* Translators: This description is specific to Google */ - return _x ( 'Client ID', 'Name of the OAuth 2.0 Client ID', Postman::TEXT_DOMAIN ); + return _x( 'Client ID', 'Name of the OAuth 2.0 Client ID', Postman::TEXT_DOMAIN ); } public function getClientSecretLabel() { /* Translators: This description is specific to Google */ - return _x ( 'Client Secret', 'Name of the OAuth 2.0 Client Secret', Postman::TEXT_DOMAIN ); + return _x( 'Client Secret', 'Name of the OAuth 2.0 Client Secret', Postman::TEXT_DOMAIN ); } public function getCallbackUrlLabel() { /* Translators: This description is specific to Google */ - return _x ( 'Authorized redirect URI', 'Name of the Application Callback URI', Postman::TEXT_DOMAIN ); + return _x( 'Authorized redirect URI', 'Name of the Application Callback URI', Postman::TEXT_DOMAIN ); } public function getCallbackDomainLabel() { /* Translators: This description is specific to Google */ - return _x ( 'Authorized JavaScript origins', 'Name of the Application Callback Domain', Postman::TEXT_DOMAIN ); + return _x( 'Authorized JavaScript origins', 'Name of the Application Callback Domain', Postman::TEXT_DOMAIN ); } public function getOwnerName() { /* Translators: This description is specific to Google */ - return _x ( 'Google', 'Name of the email service owner', Postman::TEXT_DOMAIN ); + return _x( 'Google', 'Name of the email service owner', Postman::TEXT_DOMAIN ); } public function getServiceName() { /* Translators: This description is specific to Google */ - return _x ( 'Gmail', 'Name of the email service', Postman::TEXT_DOMAIN ); + return _x( 'Gmail', 'Name of the email service', Postman::TEXT_DOMAIN ); } public function getApplicationDescription() { /* Translators: This description is specific to Google */ - return _x ( 'a Client ID for web application', 'Description of the email service OAuth 2.0 Application', Postman::TEXT_DOMAIN ); + return _x( 'a Client ID for web application', 'Description of the email service OAuth 2.0 Application', Postman::TEXT_DOMAIN ); } public function getApplicationPortalName() { /* Translators: This description is specific to Google */ - return _x ( 'Google Developers Console Gmail Wizard', 'Name of the email service portal', Postman::TEXT_DOMAIN ); + return _x( 'Google Developers Console Gmail Wizard', 'Name of the email service portal', Postman::TEXT_DOMAIN ); } public function getApplicationPortalUrl() { return 'https://www.google.com/accounts/Logout?continue=https://console.developers.google.com/start/api?id=gmail'; @@ -118,7 +118,7 @@ if (! class_exists ( 'PostmanGoogleOAuthScribe' )) { } } } -if (! class_exists ( 'PostmanMicrosoftOAuthScribe' )) { +if ( ! class_exists( 'PostmanMicrosoftOAuthScribe' ) ) { class PostmanMicrosoftOAuthScribe extends PostmanAbstractConfigTextHelper { public function isMicrosoft() { return true; @@ -127,47 +127,47 @@ if (! class_exists ( 'PostmanMicrosoftOAuthScribe' )) { return true; } public function getCallbackUrl() { - return admin_url ( 'options-general.php' ); + return admin_url( 'options-general.php' ); } function getCallbackDomain() { - $urlParts = parse_url ( $this->getCallbackUrl () ); - if (isset ( $urlParts ['host'] )) { + $urlParts = parse_url( $this->getCallbackUrl() ); + if ( isset( $urlParts ['host'] ) ) { return $urlParts ['host']; } else { - throw new Exception (); + throw new Exception(); } } public function getClientIdLabel() { /* Translators: This description is specific to Microsoft */ - return _x ( 'Client ID', 'Name of the OAuth 2.0 Client ID', Postman::TEXT_DOMAIN ); + return _x( 'Client ID', 'Name of the OAuth 2.0 Client ID', Postman::TEXT_DOMAIN ); } public function getClientSecretLabel() { /* Translators: This description is specific to Microsoft */ - return _x ( 'Client Secret', 'Name of the OAuth 2.0 Client Secret', Postman::TEXT_DOMAIN ); + return _x( 'Client Secret', 'Name of the OAuth 2.0 Client Secret', Postman::TEXT_DOMAIN ); } public function getCallbackUrlLabel() { /* Translators: This description is specific to Microsoft */ - return _x ( 'Redirect URL', 'Name of the Application Callback URI', Postman::TEXT_DOMAIN ); + return _x( 'Redirect URL', 'Name of the Application Callback URI', Postman::TEXT_DOMAIN ); } public function getCallbackDomainLabel() { /* Translators: This description is specific to Microsoft */ - return _x ( 'Root Domain', 'Name of the Application Callback Domain', Postman::TEXT_DOMAIN ); + return _x( 'Root Domain', 'Name of the Application Callback Domain', Postman::TEXT_DOMAIN ); } public function getOwnerName() { /* Translators: This description is specific to Microsoft */ - return _x ( 'Microsoft', 'Name of the email service owner', Postman::TEXT_DOMAIN ); + return _x( 'Microsoft', 'Name of the email service owner', Postman::TEXT_DOMAIN ); } public function getServiceName() { /* Translators: This description is specific to Microsoft */ - return _x ( 'Outlook.com', 'Name of the email service', Postman::TEXT_DOMAIN ); + return _x( 'Outlook.com', 'Name of the email service', Postman::TEXT_DOMAIN ); } public function getApplicationDescription() { /* Translators: This description is specific to Microsoft */ - return _x ( 'an Application', 'Description of the email service OAuth 2.0 Application', Postman::TEXT_DOMAIN ); + return _x( 'an Application', 'Description of the email service OAuth 2.0 Application', Postman::TEXT_DOMAIN ); } public function getApplicationPortalName() { /* Translators: This description is specific to Microsoft */ - return _x ( 'Microsoft Developer Center', 'Name of the email service portal', Postman::TEXT_DOMAIN ); + return _x( 'Microsoft Developer Center', 'Name of the email service portal', Postman::TEXT_DOMAIN ); } public function getApplicationPortalUrl() { return 'https://account.live.com/developers/applications/index'; @@ -180,7 +180,7 @@ if (! class_exists ( 'PostmanMicrosoftOAuthScribe' )) { } } } -if (! class_exists ( 'PostmanYahooOAuthScribe' )) { +if ( ! class_exists( 'PostmanYahooOAuthScribe' ) ) { class PostmanYahooOAuthScribe extends PostmanAbstractConfigTextHelper { public function isYahoo() { return true; @@ -189,47 +189,47 @@ if (! class_exists ( 'PostmanYahooOAuthScribe' )) { return true; } public function getCallbackUrl() { - return admin_url ( 'options-general.php' ) . '?page=postman'; + return admin_url( 'options-general.php' ) . '?page=postman'; } function getCallbackDomain() { - $urlParts = parse_url ( $this->getCallbackUrl () ); - if (isset ( $urlParts ['host'] )) { + $urlParts = parse_url( $this->getCallbackUrl() ); + if ( isset( $urlParts ['host'] ) ) { return $urlParts ['host']; } else { - throw new Exception (); + throw new Exception(); } } public function getClientIdLabel() { /* Translators: This description is specific to Yahoo */ - return _x ( 'Client ID', 'Name of the OAuth 2.0 Client ID', Postman::TEXT_DOMAIN ); + return _x( 'Client ID', 'Name of the OAuth 2.0 Client ID', Postman::TEXT_DOMAIN ); } public function getClientSecretLabel() { /* Translators: This description is specific to Yahoo */ - return _x ( 'Client Secret', 'Name of the OAuth 2.0 Client Secret', Postman::TEXT_DOMAIN ); + return _x( 'Client Secret', 'Name of the OAuth 2.0 Client Secret', Postman::TEXT_DOMAIN ); } public function getCallbackUrlLabel() { /* Translators: This description is specific to Yahoo */ - return _x ( 'Home Page URL', 'Name of the Application Callback URI', Postman::TEXT_DOMAIN ); + return _x( 'Home Page URL', 'Name of the Application Callback URI', Postman::TEXT_DOMAIN ); } public function getCallbackDomainLabel() { /* Translators: This description is specific to Yahoo */ - return _x ( 'Callback Domain', 'Name of the Application Callback Domain', Postman::TEXT_DOMAIN ); + return _x( 'Callback Domain', 'Name of the Application Callback Domain', Postman::TEXT_DOMAIN ); } public function getOwnerName() { /* Translators: This description is specific to Yahoo */ - return _x ( 'Yahoo', 'Name of the email service owner', Postman::TEXT_DOMAIN ); + return _x( 'Yahoo', 'Name of the email service owner', Postman::TEXT_DOMAIN ); } public function getServiceName() { /* Translators: This description is specific to Yahoo */ - return _x ( 'Yahoo Mail', 'Name of the email service', Postman::TEXT_DOMAIN ); + return _x( 'Yahoo Mail', 'Name of the email service', Postman::TEXT_DOMAIN ); } public function getApplicationDescription() { /* Translators: This description is specific to Yahoo */ - return _x ( 'an Application', 'Description of the email service OAuth 2.0 Application', Postman::TEXT_DOMAIN ); + return _x( 'an Application', 'Description of the email service OAuth 2.0 Application', Postman::TEXT_DOMAIN ); } public function getApplicationPortalName() { /* Translators: This description is specific to Yahoo */ - return _x ( 'Yahoo Developer Network', 'Name of the email service portal', Postman::TEXT_DOMAIN ); + return _x( 'Yahoo Developer Network', 'Name of the email service portal', Postman::TEXT_DOMAIN ); } public function getApplicationPortalUrl() { return 'https://developer.yahoo.com/apps/'; @@ -242,24 +242,24 @@ if (! class_exists ( 'PostmanYahooOAuthScribe' )) { } } } -if (! class_exists ( 'PostmanNonOAuthScribe' )) { +if ( ! class_exists( 'PostmanNonOAuthScribe' ) ) { class PostmanNonOAuthScribe extends PostmanAbstractConfigTextHelper { protected $hostname; - public function __construct($hostname) { + public function __construct( $hostname ) { $this->hostname = $hostname; } public function isGoogle() { - return PostmanUtils::endsWith ( $this->hostname, 'gmail.com' ); + return PostmanUtils::endsWith( $this->hostname, 'gmail.com' ); } public function isMicrosoft() { - return PostmanUtils::endsWith ( $this->hostname, 'live.com' ); + return PostmanUtils::endsWith( $this->hostname, 'live.com' ); } public function isYahoo() { - return PostmanUtils::endsWith ( $this->hostname, 'yahoo.com' ); + return PostmanUtils::endsWith( $this->hostname, 'yahoo.com' ); } public function getOAuthHelp() { - $text = __ ( 'Enter an Outgoing Mail Server with OAuth2 capabilities.', Postman::TEXT_DOMAIN ); - return sprintf ( '<span style="color:red" class="normal">%s</span>', $text ); + $text = __( 'Enter an Outgoing Mail Server with OAuth2 capabilities.', Postman::TEXT_DOMAIN ); + return sprintf( '<span style="color:red" class="normal">%s</span>', $text ); } public function getCallbackUrl() { return ''; @@ -268,16 +268,16 @@ if (! class_exists ( 'PostmanNonOAuthScribe' )) { return ''; } public function getClientIdLabel() { - return _x ( 'Client ID', 'Name of the OAuth 2.0 Client ID', Postman::TEXT_DOMAIN ); + return _x( 'Client ID', 'Name of the OAuth 2.0 Client ID', Postman::TEXT_DOMAIN ); } public function getClientSecretLabel() { - return _x ( 'Client Secret', 'Name of the OAuth 2.0 Client Secret', Postman::TEXT_DOMAIN ); + return _x( 'Client Secret', 'Name of the OAuth 2.0 Client Secret', Postman::TEXT_DOMAIN ); } public function getCallbackUrlLabel() { - return _x ( 'Redirect URI', 'Name of the Application Callback URI', Postman::TEXT_DOMAIN ); + return _x( 'Redirect URI', 'Name of the Application Callback URI', Postman::TEXT_DOMAIN ); } public function getCallbackDomainLabel() { - return _x ( 'Website Domain', 'Name of the Application Callback Domain', Postman::TEXT_DOMAIN ); + return _x( 'Website Domain', 'Name of the Application Callback Domain', Postman::TEXT_DOMAIN ); } public function getOwnerName() { return ''; @@ -301,7 +301,7 @@ if (! class_exists ( 'PostmanNonOAuthScribe' )) { return ''; } public function getRequestPermissionLinkText() { - return __ ( 'Grant OAuth 2.0 Permission', Postman::TEXT_DOMAIN ); + return __( 'Grant OAuth 2.0 Permission', Postman::TEXT_DOMAIN ); } } -}
\ No newline at end of file +} diff --git a/Postman/PostmanViewController.php b/Postman/PostmanViewController.php index 55d7f2c..74f34c5 100644 --- a/Postman/PostmanViewController.php +++ b/Postman/PostmanViewController.php @@ -1,5 +1,5 @@ <?php -if (! class_exists ( 'PostmanViewController' )) { +if ( ! class_exists( 'PostmanViewController' ) ) { class PostmanViewController { private $logger; private $rootPluginFilenameAndPath; @@ -9,294 +9,292 @@ if (! class_exists ( 'PostmanViewController' )) { private $importableConfiguration; private $adminController; const POSTMAN_MENU_SLUG = 'postman'; - + // style sheets and scripts const POSTMAN_STYLE = 'postman_style'; const JQUERY_SCRIPT = 'jquery'; const POSTMAN_SCRIPT = 'postman_script'; - - // - const BACK_ARROW_SYMBOL = '⬅'; - + + const BACK_ARROW_SYMBOL = '⬅'; + /** * Constructor * - * @param PostmanOptions $options - * @param PostmanOAuthToken $authorizationToken - * @param PostmanConfigTextHelper $oauthScribe + * @param PostmanOptions $options + * @param PostmanOAuthToken $authorizationToken + * @param PostmanConfigTextHelper $oauthScribe */ - function __construct($rootPluginFilenameAndPath, PostmanOptions $options, PostmanOAuthToken $authorizationToken, PostmanConfigTextHelper $oauthScribe, PostmanAdminController $adminController) { + function __construct( $rootPluginFilenameAndPath, PostmanOptions $options, PostmanOAuthToken $authorizationToken, PostmanConfigTextHelper $oauthScribe, PostmanAdminController $adminController ) { $this->options = $options; $this->rootPluginFilenameAndPath = $rootPluginFilenameAndPath; $this->authorizationToken = $authorizationToken; $this->oauthScribe = $oauthScribe; $this->adminController = $adminController; - $this->logger = new PostmanLogger ( get_class ( $this ) ); - PostmanUtils::registerAdminMenu ( $this, 'generateDefaultContent' ); - PostmanUtils::registerAdminMenu ( $this, 'addPurgeDataSubmenu' ); - + $this->logger = new PostmanLogger( get_class( $this ) ); + PostmanUtils::registerAdminMenu( $this, 'generateDefaultContent' ); + PostmanUtils::registerAdminMenu( $this, 'addPurgeDataSubmenu' ); + // initialize the scripts, stylesheets and form fields - add_action ( 'admin_init', array ( + add_action( 'admin_init', array( $this, - 'registerStylesAndScripts' + 'registerStylesAndScripts', ), 0 ); } - public static function getPageUrl($slug) { - return PostmanUtils::getPageUrl ( $slug ); + public static function getPageUrl( $slug ) { + return PostmanUtils::getPageUrl( $slug ); } - + /** * Add options page */ public function generateDefaultContent() { // This page will be under "Settings" - $pageTitle = sprintf ( __ ( '%s Setup', Postman::TEXT_DOMAIN ), __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ) ); - $pluginName = __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ); + $pageTitle = sprintf( __( '%s Setup', Postman::TEXT_DOMAIN ), __( 'Postman SMTP', Postman::TEXT_DOMAIN ) ); + $pluginName = __( 'Postman SMTP', Postman::TEXT_DOMAIN ); $uniqueId = self::POSTMAN_MENU_SLUG; - $pageOptions = array ( + $pageOptions = array( $this, - 'outputDefaultContent' + 'outputDefaultContent', ); - $mainPostmanSettingsPage = add_options_page ( $pageTitle, $pluginName, Postman::MANAGE_POSTMAN_CAPABILITY_NAME, $uniqueId, $pageOptions ); + $mainPostmanSettingsPage = add_options_page( $pageTitle, $pluginName, Postman::MANAGE_POSTMAN_CAPABILITY_NAME, $uniqueId, $pageOptions ); // When the plugin options page is loaded, also load the stylesheet - add_action ( 'admin_print_styles-' . $mainPostmanSettingsPage, array ( + add_action( 'admin_print_styles-' . $mainPostmanSettingsPage, array( $this, - 'enqueueHomeScreenStylesheet' + 'enqueueHomeScreenStylesheet', ) ); } function enqueueHomeScreenStylesheet() { - wp_enqueue_style ( PostmanViewController::POSTMAN_STYLE ); - wp_enqueue_script ( 'postman_script' ); + wp_enqueue_style( PostmanViewController::POSTMAN_STYLE ); + wp_enqueue_script( 'postman_script' ); } - + /** * Register the Email Test screen */ public function addPurgeDataSubmenu() { - $page = add_submenu_page ( null, sprintf ( __ ( '%s Setup', Postman::TEXT_DOMAIN ), __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ) ), __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ), Postman::MANAGE_POSTMAN_CAPABILITY_NAME, PostmanAdminController::MANAGE_OPTIONS_PAGE_SLUG, array ( + $page = add_submenu_page( null, sprintf( __( '%s Setup', Postman::TEXT_DOMAIN ), __( 'Postman SMTP', Postman::TEXT_DOMAIN ) ), __( 'Postman SMTP', Postman::TEXT_DOMAIN ), Postman::MANAGE_POSTMAN_CAPABILITY_NAME, PostmanAdminController::MANAGE_OPTIONS_PAGE_SLUG, array( $this, - 'outputPurgeDataContent' + 'outputPurgeDataContent', ) ); // When the plugin options page is loaded, also load the stylesheet - add_action ( 'admin_print_styles-' . $page, array ( + add_action( 'admin_print_styles-' . $page, array( $this, - 'enqueueHomeScreenStylesheet' + 'enqueueHomeScreenStylesheet', ) ); } - + /** * Register and add settings */ public function registerStylesAndScripts() { - if ($this->logger->isTrace ()) { - $this->logger->trace ( 'registerStylesAndScripts()' ); + if ( $this->logger->isTrace() ) { + $this->logger->trace( 'registerStylesAndScripts()' ); } // register the stylesheet and javascript external resources - $pluginData = apply_filters ( 'postman_get_plugin_metadata', null ); - wp_register_style ( PostmanViewController::POSTMAN_STYLE, plugins_url ( 'style/postman.css', $this->rootPluginFilenameAndPath ), null, $pluginData ['version'] ); - wp_register_style ( 'jquery_ui_style', plugins_url ( 'style/jquery-steps/jquery-ui.css', $this->rootPluginFilenameAndPath ), PostmanViewController::POSTMAN_STYLE, '1.1.0' ); - wp_register_style ( 'jquery_steps_style', plugins_url ( 'style/jquery-steps/jquery.steps.css', $this->rootPluginFilenameAndPath ), PostmanViewController::POSTMAN_STYLE, '1.1.0' ); - - wp_register_script ( PostmanViewController::POSTMAN_SCRIPT, plugins_url ( 'script/postman.js', $this->rootPluginFilenameAndPath ), array ( - PostmanViewController::JQUERY_SCRIPT + $pluginData = apply_filters( 'postman_get_plugin_metadata', null ); + wp_register_style( PostmanViewController::POSTMAN_STYLE, plugins_url( 'style/postman.css', $this->rootPluginFilenameAndPath ), null, $pluginData ['version'] ); + wp_register_style( 'jquery_ui_style', plugins_url( 'style/jquery-steps/jquery-ui.css', $this->rootPluginFilenameAndPath ), PostmanViewController::POSTMAN_STYLE, '1.1.0' ); + wp_register_style( 'jquery_steps_style', plugins_url( 'style/jquery-steps/jquery.steps.css', $this->rootPluginFilenameAndPath ), PostmanViewController::POSTMAN_STYLE, '1.1.0' ); + + wp_register_script( PostmanViewController::POSTMAN_SCRIPT, plugins_url( 'script/postman.js', $this->rootPluginFilenameAndPath ), array( + PostmanViewController::JQUERY_SCRIPT ), $pluginData ['version'] ); - wp_register_script ( 'sprintf', plugins_url ( 'script/sprintf/sprintf.min.js', $this->rootPluginFilenameAndPath ), null, '1.0.2' ); - wp_register_script ( 'jquery_steps_script', plugins_url ( 'script/jquery-steps/jquery.steps.min.js', $this->rootPluginFilenameAndPath ), array ( - PostmanViewController::JQUERY_SCRIPT + wp_register_script( 'sprintf', plugins_url( 'script/sprintf/sprintf.min.js', $this->rootPluginFilenameAndPath ), null, '1.0.2' ); + wp_register_script( 'jquery_steps_script', plugins_url( 'script/jquery-steps/jquery.steps.min.js', $this->rootPluginFilenameAndPath ), array( + PostmanViewController::JQUERY_SCRIPT ), '1.1.0' ); - wp_register_script ( 'jquery_validation', plugins_url ( 'script/jquery-validate/jquery.validate.min.js', $this->rootPluginFilenameAndPath ), array ( - PostmanViewController::JQUERY_SCRIPT + wp_register_script( 'jquery_validation', plugins_url( 'script/jquery-validate/jquery.validate.min.js', $this->rootPluginFilenameAndPath ), array( + PostmanViewController::JQUERY_SCRIPT ), '1.13.1' ); - wp_localize_script ( PostmanViewController::POSTMAN_SCRIPT, 'postman_ajax_msg', array ( - 'bad_response' => __ ( 'An unexpected error occurred', Postman::TEXT_DOMAIN ), - 'corrupt_response' => __ ( 'Unexpected PHP messages corrupted the Ajax response', Postman::TEXT_DOMAIN ) + wp_localize_script( PostmanViewController::POSTMAN_SCRIPT, 'postman_ajax_msg', array( + 'bad_response' => __( 'An unexpected error occurred', Postman::TEXT_DOMAIN ), + 'corrupt_response' => __( 'Unexpected PHP messages corrupted the Ajax response', Postman::TEXT_DOMAIN ), ) ); - - wp_localize_script ( 'jquery_steps_script', 'steps_current_step', 'steps_current_step' ); - wp_localize_script ( 'jquery_steps_script', 'steps_pagination', 'steps_pagination' ); - wp_localize_script ( 'jquery_steps_script', 'steps_finish', _x ( 'Finish', 'Press this button to Finish this task', Postman::TEXT_DOMAIN ) ); - wp_localize_script ( 'jquery_steps_script', 'steps_next', _x ( 'Next', 'Press this button to go to the next step', Postman::TEXT_DOMAIN ) ); - wp_localize_script ( 'jquery_steps_script', 'steps_previous', _x ( 'Previous', 'Press this button to go to the previous step', Postman::TEXT_DOMAIN ) ); - wp_localize_script ( 'jquery_steps_script', 'steps_loading', 'steps_loading' ); + + wp_localize_script( 'jquery_steps_script', 'steps_current_step', 'steps_current_step' ); + wp_localize_script( 'jquery_steps_script', 'steps_pagination', 'steps_pagination' ); + wp_localize_script( 'jquery_steps_script', 'steps_finish', _x( 'Finish', 'Press this button to Finish this task', Postman::TEXT_DOMAIN ) ); + wp_localize_script( 'jquery_steps_script', 'steps_next', _x( 'Next', 'Press this button to go to the next step', Postman::TEXT_DOMAIN ) ); + wp_localize_script( 'jquery_steps_script', 'steps_previous', _x( 'Previous', 'Press this button to go to the previous step', Postman::TEXT_DOMAIN ) ); + wp_localize_script( 'jquery_steps_script', 'steps_loading', 'steps_loading' ); } - + /** * Options page callback */ public function outputDefaultContent() { // Set class property print '<div class="wrap">'; - $this->displayTopNavigation (); - if (! PostmanPreRequisitesCheck::isReady ()) { - printf ( '<p><span style="color:red; padding:2px 0; font-size:1.1em">%s</span></p>', __ ( 'Postman is unable to run. Email delivery is being handled by WordPress (or another plugin).', Postman::TEXT_DOMAIN ) ); + $this->displayTopNavigation(); + if ( ! PostmanPreRequisitesCheck::isReady() ) { + printf( '<p><span style="color:red; padding:2px 0; font-size:1.1em">%s</span></p>', __( 'Postman is unable to run. Email delivery is being handled by WordPress (or another plugin).', Postman::TEXT_DOMAIN ) ); } else { - $statusMessage = PostmanTransportRegistry::getInstance ()->getReadyMessage (); - if (PostmanTransportRegistry::getInstance ()->getActiveTransport ()->isConfiguredAndReady ()) { - if ($this->options->getRunMode () != PostmanOptions::RUN_MODE_PRODUCTION) { - printf ( '<p><span style="background-color:yellow">%s</span></p>', $statusMessage ); + $statusMessage = PostmanTransportRegistry::getInstance()->getReadyMessage(); + if ( PostmanTransportRegistry::getInstance()->getActiveTransport()->isConfiguredAndReady() ) { + if ( $this->options->getRunMode() != PostmanOptions::RUN_MODE_PRODUCTION ) { + printf( '<p><span style="background-color:yellow">%s</span></p>', $statusMessage ); } else { - printf ( '<p><span style="color:green;padding:2px 0; font-size:1.1em">%s</span></p>', $statusMessage ); + printf( '<p><span style="color:green;padding:2px 0; font-size:1.1em">%s</span></p>', $statusMessage ); } } else { - printf ( '<p><span style="color:red; padding:2px 0; font-size:1.1em">%s</span></p>', $statusMessage ); + printf( '<p><span style="color:red; padding:2px 0; font-size:1.1em">%s</span></p>', $statusMessage ); } - $this->printDeliveryDetails (); + $this->printDeliveryDetails(); /* translators: where %d is the number of emails delivered */ print '<p style="margin:10px 10px"><span>'; - printf ( _n ( 'Postman has delivered <span style="color:green">%d</span> email.', 'Postman has delivered <span style="color:green">%d</span> emails.', PostmanState::getInstance ()->getSuccessfulDeliveries (), Postman::TEXT_DOMAIN ), PostmanState::getInstance ()->getSuccessfulDeliveries () ); - if ($this->options->isMailLoggingEnabled ()) { + printf( _n( 'Postman has delivered <span style="color:green">%d</span> email.', 'Postman has delivered <span style="color:green">%d</span> emails.', PostmanState::getInstance()->getSuccessfulDeliveries(), Postman::TEXT_DOMAIN ), PostmanState::getInstance()->getSuccessfulDeliveries() ); + if ( $this->options->isMailLoggingEnabled() ) { print ' '; - printf ( __ ( 'The last %d email attempts are recorded <a href="%s">in the log</a>.', Postman::TEXT_DOMAIN ), PostmanOptions::getInstance ()->getMailLoggingMaxEntries (), PostmanUtils::getEmailLogPageUrl () ); + printf( __( 'The last %d email attempts are recorded <a href="%s">in the log</a>.', Postman::TEXT_DOMAIN ), PostmanOptions::getInstance()->getMailLoggingMaxEntries(), PostmanUtils::getEmailLogPageUrl() ); } print '</span></p>'; } - if ($this->options->isNew ()) { - printf ( '<h3 style="padding-top:10px">%s</h3>', __ ( 'Thank-you for choosing Postman!', Postman::TEXT_DOMAIN ) ); + if ( $this->options->isNew() ) { + printf( '<h3 style="padding-top:10px">%s</h3>', __( 'Thank-you for choosing Postman!', Postman::TEXT_DOMAIN ) ); /* translators: where %s is the URL of the Setup Wizard */ - printf ( '<p><span>%s</span></p>', sprintf ( __ ( 'Let\'s get started! All users are strongly encouraged to <a href="%s">run the Setup Wizard</a>.', Postman::TEXT_DOMAIN ), $this->getPageUrl ( PostmanConfigurationController::CONFIGURATION_WIZARD_SLUG ) ) ); - printf ( '<p><span>%s</span></p>', sprintf ( __ ( 'Alternately, <a href="%s">manually configure</a> your own settings and/or modify advanced options.', Postman::TEXT_DOMAIN ), $this->getPageUrl ( PostmanConfigurationController::CONFIGURATION_SLUG ) ) ); + printf( '<p><span>%s</span></p>', sprintf( __( 'Let\'s get started! All users are strongly encouraged to <a href="%s">run the Setup Wizard</a>.', Postman::TEXT_DOMAIN ), $this->getPageUrl( PostmanConfigurationController::CONFIGURATION_WIZARD_SLUG ) ) ); + printf( '<p><span>%s</span></p>', sprintf( __( 'Alternately, <a href="%s">manually configure</a> your own settings and/or modify advanced options.', Postman::TEXT_DOMAIN ), $this->getPageUrl( PostmanConfigurationController::CONFIGURATION_SLUG ) ) ); } else { - if (PostmanState::getInstance ()->isTimeToReviewPostman () && ! PostmanOptions::getInstance ()->isNew ()) { + if ( PostmanState::getInstance()->isTimeToReviewPostman() && ! PostmanOptions::getInstance()->isNew() ) { print '</br><hr width="70%"></br>'; /* translators: where %s is the URL to the WordPress.org review and ratings page */ - printf ( '%s</span></p>', sprintf ( __ ( 'Please consider <a href="%s">leaving a review</a> to help spread the word! :D', Postman::TEXT_DOMAIN ), 'https://wordpress.org/support/view/plugin-reviews/postman-smtp?filter=5' ) ); + printf( '%s</span></p>', sprintf( __( 'Please consider <a href="%s">leaving a review</a> to help spread the word! :D', Postman::TEXT_DOMAIN ), 'https://wordpress.org/support/view/plugin-reviews/postman-smtp?filter=5' ) ); } - printf ( '<p><span>%s :-)</span></p>', sprintf ( __ ( 'Postman needs translators! Please take a moment to <a href="%s">translate a few sentences on-line</a>', Postman::TEXT_DOMAIN ), 'https://translate.wordpress.org/projects/wp-plugins/postman-smtp/stable' ) ); + printf( '<p><span>%s :-)</span></p>', sprintf( __( 'Postman needs translators! Please take a moment to <a href="%s">translate a few sentences on-line</a>', Postman::TEXT_DOMAIN ), 'https://translate.wordpress.org/projects/wp-plugins/post-smtp/stable' ) ); } - printf ( '<p><span>%s</span></p>', __ ( '<b style="background-color:yellow">New for v1.7!</style></b> Send mail with the Mandrill or SendGrid APIs.', Postman::TEXT_DOMAIN ) ); + printf( '<p><span>%s</span></p>', __( '<b style="background-color:yellow">New for v1.7!</style></b> Send mail with the Mandrill or SendGrid APIs.', Postman::TEXT_DOMAIN ) ); } - + /** */ private function printDeliveryDetails() { - $currentTransport = PostmanTransportRegistry::getInstance ()->getActiveTransport (); - $deliveryDetails = $currentTransport->getDeliveryDetails ( $this->options ); - printf ( '<p style="margin:0 10px"><span>%s</span></p>', $deliveryDetails ); + $currentTransport = PostmanTransportRegistry::getInstance()->getActiveTransport(); + $deliveryDetails = $currentTransport->getDeliveryDetails( $this->options ); + printf( '<p style="margin:0 10px"><span>%s</span></p>', $deliveryDetails ); } - + /** * - * @param unknown $title - * @param string $slug + * @param unknown $title + * @param string $slug */ - public static function outputChildPageHeader($title, $slug = '') { - printf ( '<h2>%s</h2>', sprintf ( __ ( '%s Setup', Postman::TEXT_DOMAIN ), __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ) ) ); - printf ( '<div id="postman-main-menu" class="welcome-panel %s">', $slug ); + public static function outputChildPageHeader( $title, $slug = '' ) { + printf( '<h2>%s</h2>', sprintf( __( '%s Setup', Postman::TEXT_DOMAIN ), __( 'Postman SMTP', Postman::TEXT_DOMAIN ) ) ); + printf( '<div id="postman-main-menu" class="welcome-panel %s">', $slug ); print '<div class="welcome-panel-content">'; print '<div class="welcome-panel-column-container">'; print '<div class="welcome-panel-column welcome-panel-last">'; - printf ( '<h4>%s</h4>', $title ); + printf( '<h4>%s</h4>', $title ); print '</div>'; - printf ( '<p id="back_to_main_menu">%s <a id="back_to_menu_link" href="%s">%s</a></p>', self::BACK_ARROW_SYMBOL, PostmanUtils::getSettingsPageUrl (), _x ( 'Back To Main Menu', 'Return to main menu link', Postman::TEXT_DOMAIN ) ); + printf( '<p id="back_to_main_menu">%s <a id="back_to_menu_link" href="%s">%s</a></p>', self::BACK_ARROW_SYMBOL, PostmanUtils::getSettingsPageUrl(), _x( 'Back To Main Menu', 'Return to main menu link', Postman::TEXT_DOMAIN ) ); print '</div></div></div>'; } - + /** */ public function outputPurgeDataContent() { - $importTitle = __ ( 'Import', Postman::TEXT_DOMAIN ); - $exportTile = __ ( 'Export', Postman::TEXT_DOMAIN ); - $resetTitle = __ ( 'Reset Plugin', Postman::TEXT_DOMAIN ); + $importTitle = __( 'Import', Postman::TEXT_DOMAIN ); + $exportTile = __( 'Export', Postman::TEXT_DOMAIN ); + $resetTitle = __( 'Reset Plugin', Postman::TEXT_DOMAIN ); $options = $this->options; print '<div class="wrap">'; - PostmanViewController::outputChildPageHeader ( sprintf ( '%s/%s/%s', $importTitle, $exportTile, $resetTitle ) ); + PostmanViewController::outputChildPageHeader( sprintf( '%s/%s/%s', $importTitle, $exportTile, $resetTitle ) ); print '<section id="export_settings">'; - printf ( '<h3><span>%s<span></h3>', $exportTile ); - printf ( '<p><span>%s</span></p>', __ ( 'Copy this data into another instance of Postman to duplicate the configuration.', Postman::TEXT_DOMAIN ) ); + printf( '<h3><span>%s<span></h3>', $exportTile ); + printf( '<p><span>%s</span></p>', __( 'Copy this data into another instance of Postman to duplicate the configuration.', Postman::TEXT_DOMAIN ) ); $data = ''; - if (! PostmanPreRequisitesCheck::checkZlibEncode ()) { - $extraDeleteButtonAttributes = sprintf ( 'disabled="true"' ); + if ( ! PostmanPreRequisitesCheck::checkZlibEncode() ) { + $extraDeleteButtonAttributes = sprintf( 'disabled="true"' ); $data = ''; } else { $extraDeleteButtonAttributes = ''; - if (! $options->isNew ()) { - $data = $options->export (); + if ( ! $options->isNew() ) { + $data = $options->export(); } } - printf ( '<textarea cols="80" rows="5" readonly="true" name="settings" %s>%s</textarea>', $extraDeleteButtonAttributes, $data ); + printf( '<textarea cols="80" rows="5" readonly="true" name="settings" %s>%s</textarea>', $extraDeleteButtonAttributes, $data ); print '</section>'; print '<section id="import_settings">'; - printf ( '<h3><span>%s<span></h3>', $importTitle ); - print '<form method="POST" action="' . get_admin_url () . 'admin-post.php">'; - wp_nonce_field ( PostmanAdminController::IMPORT_SETTINGS_SLUG ); - printf ( '<input type="hidden" name="action" value="%s" />', PostmanAdminController::IMPORT_SETTINGS_SLUG ); + printf( '<h3><span>%s<span></h3>', $importTitle ); + print '<form method="POST" action="' . get_admin_url() . 'admin-post.php">'; + wp_nonce_field( PostmanAdminController::IMPORT_SETTINGS_SLUG ); + printf( '<input type="hidden" name="action" value="%s" />', PostmanAdminController::IMPORT_SETTINGS_SLUG ); print '<p>'; - printf ( '<span>%s</span>', __ ( 'Paste data from another instance of Postman here to duplicate the configuration.', Postman::TEXT_DOMAIN ) ); - if (PostmanTransportRegistry::getInstance ()->getSelectedTransport ()->isOAuthUsed ( PostmanOptions::getInstance ()->getAuthenticationType () )) { - $warning = __ ( 'Warning', Postman::TEXT_DOMAIN ); - $errorMessage = __ ( 'Using the same OAuth 2.0 Client ID and Client Secret from this site at the same time as another site will cause failures.', Postman::TEXT_DOMAIN ); - printf ( ' <span><b>%s</b>: %s</span>', $warning, $errorMessage ); + printf( '<span>%s</span>', __( 'Paste data from another instance of Postman here to duplicate the configuration.', Postman::TEXT_DOMAIN ) ); + if ( PostmanTransportRegistry::getInstance()->getSelectedTransport()->isOAuthUsed( PostmanOptions::getInstance()->getAuthenticationType() ) ) { + $warning = __( 'Warning', Postman::TEXT_DOMAIN ); + $errorMessage = __( 'Using the same OAuth 2.0 Client ID and Client Secret from this site at the same time as another site will cause failures.', Postman::TEXT_DOMAIN ); + printf( ' <span><b>%s</b>: %s</span>', $warning, $errorMessage ); } print '</p>'; - printf ( '<textarea cols="80" rows="5" name="settings" %s></textarea>', $extraDeleteButtonAttributes ); - submit_button ( __ ( 'Import', Postman::TEXT_DOMAIN ), 'primary', 'import', true, $extraDeleteButtonAttributes ); + printf( '<textarea cols="80" rows="5" name="settings" %s></textarea>', $extraDeleteButtonAttributes ); + submit_button( __( 'Import', Postman::TEXT_DOMAIN ), 'primary', 'import', true, $extraDeleteButtonAttributes ); print '</form>'; print '</section>'; print '<section id="delete_settings">'; - printf ( '<h3><span>%s<span></h3>', $resetTitle ); - print '<form method="POST" action="' . get_admin_url () . 'admin-post.php">'; - wp_nonce_field ( PostmanAdminController::PURGE_DATA_SLUG ); - printf ( '<input type="hidden" name="action" value="%s" />', PostmanAdminController::PURGE_DATA_SLUG ); - printf ( '<p><span>%s</span></p><p><span>%s</span></p>', __ ( 'This will purge all of Postman\'s settings, including account credentials and the email log.', Postman::TEXT_DOMAIN ), __ ( 'Are you sure?', Postman::TEXT_DOMAIN ) ); + printf( '<h3><span>%s<span></h3>', $resetTitle ); + print '<form method="POST" action="' . get_admin_url() . 'admin-post.php">'; + wp_nonce_field( PostmanAdminController::PURGE_DATA_SLUG ); + printf( '<input type="hidden" name="action" value="%s" />', PostmanAdminController::PURGE_DATA_SLUG ); + printf( '<p><span>%s</span></p><p><span>%s</span></p>', __( 'This will purge all of Postman\'s settings, including account credentials and the email log.', Postman::TEXT_DOMAIN ), __( 'Are you sure?', Postman::TEXT_DOMAIN ) ); $extraDeleteButtonAttributes = 'style="background-color:red;color:white"'; - if ($this->options->isNew ()) { + if ( $this->options->isNew() ) { $extraDeleteButtonAttributes .= ' disabled="true"'; } - submit_button ( $resetTitle, 'delete', 'submit', true, $extraDeleteButtonAttributes ); + submit_button( $resetTitle, 'delete', 'submit', true, $extraDeleteButtonAttributes ); print '</form>'; print '</section>'; print '</div>'; } - + /** */ private function displayTopNavigation() { - screen_icon (); - printf ( '<h2>%s</h2>', sprintf ( __ ( '%s Setup', Postman::TEXT_DOMAIN ), __ ( 'Postman SMTP', Postman::TEXT_DOMAIN ) ) ); + screen_icon(); + printf( '<h2>%s</h2>', sprintf( __( '%s Setup', Postman::TEXT_DOMAIN ), __( 'Postman SMTP', Postman::TEXT_DOMAIN ) ) ); print '<div id="postman-main-menu" class="welcome-panel">'; print '<div class="welcome-panel-content">'; print '<div class="welcome-panel-column-container">'; print '<div class="welcome-panel-column">'; - printf ( '<h4>%s</h4>', __ ( 'Configuration', Postman::TEXT_DOMAIN ) ); - printf ( '<a class="button button-primary button-hero" href="%s">%s</a>', $this->getPageUrl ( PostmanConfigurationController::CONFIGURATION_WIZARD_SLUG ), __ ( 'Start the Wizard', Postman::TEXT_DOMAIN ) ); - printf ( '<p class="">or <a href="%s" class="configure_manually">%s</a></p>', $this->getPageUrl ( PostmanConfigurationController::CONFIGURATION_SLUG ), __ ( 'Show All Settings', Postman::TEXT_DOMAIN ) ); + printf( '<h4>%s</h4>', __( 'Configuration', Postman::TEXT_DOMAIN ) ); + printf( '<a class="button button-primary button-hero" href="%s">%s</a>', $this->getPageUrl( PostmanConfigurationController::CONFIGURATION_WIZARD_SLUG ), __( 'Start the Wizard', Postman::TEXT_DOMAIN ) ); + printf( '<p class="">or <a href="%s" class="configure_manually">%s</a></p>', $this->getPageUrl( PostmanConfigurationController::CONFIGURATION_SLUG ), __( 'Show All Settings', Postman::TEXT_DOMAIN ) ); print '</div>'; print '<div class="welcome-panel-column">'; - printf ( '<h4>%s</h4>', _x ( 'Actions', 'Main Menu', Postman::TEXT_DOMAIN ) ); + printf( '<h4>%s</h4>', _x( 'Actions', 'Main Menu', Postman::TEXT_DOMAIN ) ); print '<ul>'; - + // Grant permission with Google - PostmanTransportRegistry::getInstance ()->getSelectedTransport ()->printActionMenuItem (); - - if (PostmanWpMailBinder::getInstance ()->isBound ()) { - printf ( '<li><a href="%s" class="welcome-icon send_test_email">%s</a></li>', $this->getPageUrl ( PostmanSendTestEmailController::EMAIL_TEST_SLUG ), __ ( 'Send a Test Email', Postman::TEXT_DOMAIN ) ); + PostmanTransportRegistry::getInstance()->getSelectedTransport()->printActionMenuItem(); + + if ( PostmanWpMailBinder::getInstance()->isBound() ) { + printf( '<li><a href="%s" class="welcome-icon send_test_email">%s</a></li>', $this->getPageUrl( PostmanSendTestEmailController::EMAIL_TEST_SLUG ), __( 'Send a Test Email', Postman::TEXT_DOMAIN ) ); } else { - printf ( '<li><div class="welcome-icon send_test_email">%s</div></li>', __ ( 'Send a Test Email', Postman::TEXT_DOMAIN ) ); + printf( '<li><div class="welcome-icon send_test_email">%s</div></li>', __( 'Send a Test Email', Postman::TEXT_DOMAIN ) ); } - + // import-export-reset menu item - if (! $this->options->isNew () || true) { + if ( ! $this->options->isNew() || true ) { $purgeLinkPattern = '<li><a href="%1$s" class="welcome-icon oauth-authorize">%2$s</a></li>'; } else { $purgeLinkPattern = '<li>%2$s</li>'; } - $importTitle = __ ( 'Import', Postman::TEXT_DOMAIN ); - $exportTile = __ ( 'Export', Postman::TEXT_DOMAIN ); - $resetTitle = __ ( 'Reset Plugin', Postman::TEXT_DOMAIN ); - $importExportReset = sprintf ( '%s/%s/%s', $importTitle, $exportTile, $resetTitle ); - printf ( $purgeLinkPattern, $this->getPageUrl ( PostmanAdminController::MANAGE_OPTIONS_PAGE_SLUG ), sprintf ( '%s', $importExportReset ) ); + $importTitle = __( 'Import', Postman::TEXT_DOMAIN ); + $exportTile = __( 'Export', Postman::TEXT_DOMAIN ); + $resetTitle = __( 'Reset Plugin', Postman::TEXT_DOMAIN ); + $importExportReset = sprintf( '%s/%s/%s', $importTitle, $exportTile, $resetTitle ); + printf( $purgeLinkPattern, $this->getPageUrl( PostmanAdminController::MANAGE_OPTIONS_PAGE_SLUG ), sprintf( '%s', $importExportReset ) ); print '</ul>'; print '</div>'; print '<div class="welcome-panel-column welcome-panel-last">'; - printf ( '<h4>%s</h4>', _x ( 'Troubleshooting', 'Main Menu', Postman::TEXT_DOMAIN ) ); + printf( '<h4>%s</h4>', _x( 'Troubleshooting', 'Main Menu', Postman::TEXT_DOMAIN ) ); print '<ul>'; - printf ( '<li><a href="%s" class="welcome-icon run-port-test">%s</a></li>', $this->getPageUrl ( PostmanConnectivityTestController::PORT_TEST_SLUG ), __ ( 'Connectivity Test', Postman::TEXT_DOMAIN ) ); - printf ( '<li><a href="%s" class="welcome-icon run-port-test">%s</a></li>', $this->getPageUrl ( PostmanDiagnosticTestController::DIAGNOSTICS_SLUG ), __ ( 'Diagnostic Test', Postman::TEXT_DOMAIN ) ); - printf ( '<li><a href="https://wordpress.org/support/plugin/postman-smtp" class="welcome-icon postman_support">%s</a></li>', __ ( 'Online Support', Postman::TEXT_DOMAIN ) ); + printf( '<li><a href="%s" class="welcome-icon run-port-test">%s</a></li>', $this->getPageUrl( PostmanConnectivityTestController::PORT_TEST_SLUG ), __( 'Connectivity Test', Postman::TEXT_DOMAIN ) ); + printf( '<li><a href="%s" class="welcome-icon run-port-test">%s</a></li>', $this->getPageUrl( PostmanDiagnosticTestController::DIAGNOSTICS_SLUG ), __( 'Diagnostic Test', Postman::TEXT_DOMAIN ) ); + printf( '<li><a href="https://wordpress.org/support/plugin/postman-smtp" class="welcome-icon postman_support">%s</a></li>', __( 'Online Support', Postman::TEXT_DOMAIN ) ); print '</ul></div></div></div></div>'; } - } } -
\ No newline at end of file + diff --git a/Postman/PostmanWpMail.php b/Postman/PostmanWpMail.php index 874a338..b39c596 100644 --- a/Postman/PostmanWpMail.php +++ b/Postman/PostmanWpMail.php @@ -1,340 +1,339 @@ <?php -if (! class_exists ( "PostmanWpMail" )) { - +if ( ! class_exists( 'PostmanWpMail' ) ) { + /** * Moved this code into a class so it could be used by both wp_mail() and PostmanSendTestEmailController * * @author jasonhendriks - * */ class PostmanWpMail { private $exception; private $transcript; private $totalTime; private $logger; - + /** * Load the dependencies */ public function init() { - $this->logger = new PostmanLogger ( get_class ( $this ) ); + $this->logger = new PostmanLogger( get_class( $this ) ); require_once 'Postman-Mail/PostmanMessage.php'; require_once 'Postman-Email-Log/PostmanEmailLogService.php'; require_once 'Postman-Mail/PostmanMailEngine.php'; require_once 'Postman-Auth/PostmanAuthenticationManagerFactory.php'; require_once 'PostmanState.php'; } - + /** * This methods follows the wp_mail function interface, but implements it Postman-style. * Exceptions are held for later inspection. * An instance of PostmanState updates the success/fail tally. * - * @param unknown $to - * @param unknown $subject - * @param unknown $body - * @param unknown $headers - * @param unknown $attachments + * @param unknown $to + * @param unknown $subject + * @param unknown $body + * @param unknown $headers + * @param unknown $attachments * @return boolean */ - public function send($to, $subject, $message, $headers = '', $attachments = array()) { - + public function send( $to, $subject, $message, $headers = '', $attachments = array() ) { + // initialize for sending - $this->init (); - + $this->init(); + // build the message - $postmanMessage = $this->processWpMailCall ( $to, $subject, $message, $headers, $attachments ); - + $postmanMessage = $this->processWpMailCall( $to, $subject, $message, $headers, $attachments ); + // build the email log entry - $log = new PostmanEmailLog (); + $log = new PostmanEmailLog(); $log->originalTo = $to; $log->originalSubject = $subject; $log->originalMessage = $message; $log->originalHeaders = $headers; - + // send the message and return the result - return $this->sendMessage ( $postmanMessage, $log ); + return $this->sendMessage( $postmanMessage, $log ); } - + /** * Builds a PostmanMessage based on the WordPress wp_mail parameters * - * @param unknown $to - * @param unknown $subject - * @param unknown $message - * @param unknown $headers - * @param unknown $attachments + * @param unknown $to + * @param unknown $subject + * @param unknown $message + * @param unknown $headers + * @param unknown $attachments */ - private function processWpMailCall($to, $subject, $message, $headers, $attachments) { - $this->logger->trace ( 'wp_mail parameters before applying WordPress wp_mail filter:' ); - $this->traceParameters ( $to, $subject, $message, $headers, $attachments ); - + private function processWpMailCall( $to, $subject, $message, $headers, $attachments ) { + $this->logger->trace( 'wp_mail parameters before applying WordPress wp_mail filter:' ); + $this->traceParameters( $to, $subject, $message, $headers, $attachments ); + /** * Filter the wp_mail() arguments. * * @since 1.5.4 - * + * * @param array $args * A compacted array of wp_mail() arguments, including the "to" email, * subject, message, headers, and attachments values. */ - $atts = apply_filters ( 'wp_mail', compact ( 'to', 'subject', 'message', 'headers', 'attachments' ) ); - if (isset ( $atts ['to'] )) { + $atts = apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ); + if ( isset( $atts ['to'] ) ) { $to = $atts ['to']; } - - if (isset ( $atts ['subject'] )) { + + if ( isset( $atts ['subject'] ) ) { $subject = $atts ['subject']; } - - if (isset ( $atts ['message'] )) { + + if ( isset( $atts ['message'] ) ) { $message = $atts ['message']; } - - if (isset ( $atts ['headers'] )) { + + if ( isset( $atts ['headers'] ) ) { $headers = $atts ['headers']; } - - if (isset ( $atts ['attachments'] )) { + + if ( isset( $atts ['attachments'] ) ) { $attachments = $atts ['attachments']; } - - if (! is_array ( $attachments )) { - $attachments = explode ( "\n", str_replace ( "\r\n", "\n", $attachments ) ); + + if ( ! is_array( $attachments ) ) { + $attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) ); } - - $this->logger->trace ( 'wp_mail parameters after applying WordPress wp_mail filter:' ); - $this->traceParameters ( $to, $subject, $message, $headers, $attachments ); - + + $this->logger->trace( 'wp_mail parameters after applying WordPress wp_mail filter:' ); + $this->traceParameters( $to, $subject, $message, $headers, $attachments ); + // Postman API: register the response hook - add_filter ( 'postman_wp_mail_result', array ( + add_filter( 'postman_wp_mail_result', array( $this, - 'postman_wp_mail_result' + 'postman_wp_mail_result', ) ); - + // create the message - $postmanMessage = $this->createNewMessage (); - $this->populateMessageFromWpMailParams ( $postmanMessage, $to, $subject, $message, $headers, $attachments ); - + $postmanMessage = $this->createNewMessage(); + $this->populateMessageFromWpMailParams( $postmanMessage, $to, $subject, $message, $headers, $attachments ); + // return the message return $postmanMessage; } - + /** * Creates a new instance of PostmanMessage with a pre-set From and Reply-To * * @return PostmanMessage */ public function createNewMessage() { - $message = new PostmanMessage (); - $options = PostmanOptions::getInstance (); + $message = new PostmanMessage(); + $options = PostmanOptions::getInstance(); // the From is set now so that it can be overridden - $transport = PostmanTransportRegistry::getInstance ()->getActiveTransport (); - $message->setFrom ( $transport->getFromEmailAddress (), $transport->getFromName () ); + $transport = PostmanTransportRegistry::getInstance()->getActiveTransport(); + $message->setFrom( $transport->getFromEmailAddress(), $transport->getFromName() ); // the Reply-To is set now so that it can be overridden - $message->setReplyTo ( $options->getReplyTo () ); - $message->setCharset ( get_bloginfo ( 'charset' ) ); + $message->setReplyTo( $options->getReplyTo() ); + $message->setCharset( get_bloginfo( 'charset' ) ); return $message; } - + /** * A convenient place for any code to inject a constructed PostmanMessage * (for example, from MyMail) * * The body parts may be set already at this time. * - * @param PostmanMessage $message + * @param PostmanMessage $message * @return boolean */ - public function sendMessage(PostmanMessage $message, PostmanEmailLog $log) { - + public function sendMessage( PostmanMessage $message, PostmanEmailLog $log ) { + // get the Options and AuthToken - $options = PostmanOptions::getInstance (); - $authorizationToken = PostmanOAuthToken::getInstance (); - + $options = PostmanOptions::getInstance(); + $authorizationToken = PostmanOAuthToken::getInstance(); + // get the transport and create the transportConfig and engine - $transport = PostmanTransportRegistry::getInstance ()->getActiveTransport (); - + $transport = PostmanTransportRegistry::getInstance()->getActiveTransport(); + // create the Mail Engine - $engine = $transport->createMailEngine (); - + $engine = $transport->createMailEngine(); + // add plugin-specific attributes to PostmanMessage - $message->addHeaders ( $options->getAdditionalHeaders () ); - $message->addTo ( $options->getForcedToRecipients () ); - $message->addCc ( $options->getForcedCcRecipients () ); - $message->addBcc ( $options->getForcedBccRecipients () ); - + $message->addHeaders( $options->getAdditionalHeaders() ); + $message->addTo( $options->getForcedToRecipients() ); + $message->addCc( $options->getForcedCcRecipients() ); + $message->addBcc( $options->getForcedBccRecipients() ); + // apply the WordPress filters // may impact the from address, from email, charset and content-type - $message->applyFilters (); - + $message->applyFilters(); + // create the body parts (if they are both missing) - if ($message->isBodyPartsEmpty ()) { - $message->createBodyParts (); + if ( $message->isBodyPartsEmpty() ) { + $message->createBodyParts(); } - + // is this a test run? - $testMode = apply_filters ( 'postman_test_email', false ); - if ($this->logger->isDebug ()) { - $this->logger->debug ( 'testMode=' . $testMode ); + $testMode = apply_filters( 'postman_test_email', false ); + if ( $this->logger->isDebug() ) { + $this->logger->debug( 'testMode=' . $testMode ); } - + // start the clock - $startTime = microtime ( true ) * 1000; - + $startTime = microtime( true ) * 1000; + try { - + // prepare the message - $message->validate ( $transport ); - + $message->validate( $transport ); + // send the message - if ($options->getRunMode () == PostmanOptions::RUN_MODE_PRODUCTION) { - if ($transport->isLockingRequired ()) { - PostmanUtils::lock (); + if ( $options->getRunMode() == PostmanOptions::RUN_MODE_PRODUCTION ) { + if ( $transport->isLockingRequired() ) { + PostmanUtils::lock(); // may throw an exception attempting to contact the OAuth2 provider - $this->ensureAuthtokenIsUpdated ( $transport, $options, $authorizationToken ); + $this->ensureAuthtokenIsUpdated( $transport, $options, $authorizationToken ); } - - $this->logger->debug ( 'Sending mail' ); + + $this->logger->debug( 'Sending mail' ); // may throw an exception attempting to contact the SMTP server - $engine->send ( $message ); - + $engine->send( $message ); + // increment the success counter, unless we are just tesitng - if (! $testMode) { - PostmanState::getInstance ()->incrementSuccessfulDelivery (); + if ( ! $testMode ) { + PostmanState::getInstance()->incrementSuccessfulDelivery(); } } - + // clean up - $this->postSend ( $engine, $startTime, $options, $transport ); - - if ($options->getRunMode () == PostmanOptions::RUN_MODE_PRODUCTION || $options->getRunMode () == PostmanOptions::RUN_MODE_LOG_ONLY) { + $this->postSend( $engine, $startTime, $options, $transport ); + + if ( $options->getRunMode() == PostmanOptions::RUN_MODE_PRODUCTION || $options->getRunMode() == PostmanOptions::RUN_MODE_LOG_ONLY ) { // log the successful delivery - PostmanEmailLogService::getInstance ()->writeSuccessLog ( $log, $message, $engine->getTranscript (), $transport ); + PostmanEmailLogService::getInstance()->writeSuccessLog( $log, $message, $engine->getTranscript(), $transport ); } - + // return successful return true; } catch ( Exception $e ) { // save the error for later $this->exception = $e; - + // write the error to the PHP log - $this->logger->error ( get_class ( $e ) . ' code=' . $e->getCode () . ' message=' . trim ( $e->getMessage () ) ); - + $this->logger->error( get_class( $e ) . ' code=' . $e->getCode() . ' message=' . trim( $e->getMessage() ) ); + // increment the failure counter, unless we are just tesitng - if (! $testMode && $options->getRunMode () == PostmanOptions::RUN_MODE_PRODUCTION) { - PostmanState::getInstance ()->incrementFailedDelivery (); + if ( ! $testMode && $options->getRunMode() == PostmanOptions::RUN_MODE_PRODUCTION ) { + PostmanState::getInstance()->incrementFailedDelivery(); } - + // clean up - $this->postSend ( $engine, $startTime, $options, $transport ); - - if ($options->getRunMode () == PostmanOptions::RUN_MODE_PRODUCTION || $options->getRunMode () == PostmanOptions::RUN_MODE_LOG_ONLY) { + $this->postSend( $engine, $startTime, $options, $transport ); + + if ( $options->getRunMode() == PostmanOptions::RUN_MODE_PRODUCTION || $options->getRunMode() == PostmanOptions::RUN_MODE_LOG_ONLY ) { // log the failed delivery - PostmanEmailLogService::getInstance ()->writeFailureLog ( $log, $message, $engine->getTranscript (), $transport, $e->getMessage () ); + PostmanEmailLogService::getInstance()->writeFailureLog( $log, $message, $engine->getTranscript(), $transport, $e->getMessage() ); } - + // return failure return false; } } - + /** * Clean up after sending the mail * - * @param PostmanZendMailEngine $engine - * @param unknown $startTime + * @param PostmanZendMailEngine $engine + * @param unknown $startTime */ - private function postSend(PostmanMailEngine $engine, $startTime, PostmanOptions $options, PostmanModuleTransport $transport) { + private function postSend( PostmanMailEngine $engine, $startTime, PostmanOptions $options, PostmanModuleTransport $transport ) { // save the transcript - $this->transcript = $engine->getTranscript (); - + $this->transcript = $engine->getTranscript(); + // log the transcript - if ($this->logger->isTrace ()) { - $this->logger->trace ( 'Transcript:' ); - $this->logger->trace ( $this->transcript ); + if ( $this->logger->isTrace() ) { + $this->logger->trace( 'Transcript:' ); + $this->logger->trace( $this->transcript ); } - + // delete the semaphore - if ($transport->isLockingRequired ()) { - PostmanUtils::unlock (); + if ( $transport->isLockingRequired() ) { + PostmanUtils::unlock(); } - + // stop the clock - $endTime = microtime ( true ) * 1000; + $endTime = microtime( true ) * 1000; $this->totalTime = $endTime - $startTime; } - + /** * Returns the result of the last call to send() * * @return multitype:Exception NULL */ function postman_wp_mail_result() { - $result = array ( + $result = array( 'time' => $this->totalTime, 'exception' => $this->exception, - 'transcript' => $this->transcript + 'transcript' => $this->transcript, ); return $result; } - + /** */ - private function ensureAuthtokenIsUpdated(PostmanModuleTransport $transport, PostmanOptions $options, PostmanOAuthToken $authorizationToken) { - assert ( ! empty ( $transport ) ); - assert ( ! empty ( $options ) ); - assert ( ! empty ( $authorizationToken ) ); + private function ensureAuthtokenIsUpdated( PostmanModuleTransport $transport, PostmanOptions $options, PostmanOAuthToken $authorizationToken ) { + assert( ! empty( $transport ) ); + assert( ! empty( $options ) ); + assert( ! empty( $authorizationToken ) ); // ensure the token is up-to-date - $this->logger->debug ( 'Ensuring Access Token is up-to-date' ); + $this->logger->debug( 'Ensuring Access Token is up-to-date' ); // interact with the Authentication Manager - $wpMailAuthManager = PostmanAuthenticationManagerFactory::getInstance ()->createAuthenticationManager (); - if ($wpMailAuthManager->isAccessTokenExpired ()) { - $this->logger->debug ( 'Access Token has expired, attempting refresh' ); - $wpMailAuthManager->refreshToken (); - $authorizationToken->save (); + $wpMailAuthManager = PostmanAuthenticationManagerFactory::getInstance()->createAuthenticationManager(); + if ( $wpMailAuthManager->isAccessTokenExpired() ) { + $this->logger->debug( 'Access Token has expired, attempting refresh' ); + $wpMailAuthManager->refreshToken(); + $authorizationToken->save(); } } - + /** * Aggregates all the content into a Message to be sent to the MailEngine * - * @param unknown $to - * @param unknown $subject - * @param unknown $body - * @param unknown $headers - * @param unknown $attachments + * @param unknown $to + * @param unknown $subject + * @param unknown $body + * @param unknown $headers + * @param unknown $attachments */ - private function populateMessageFromWpMailParams(PostmanMessage $message, $to, $subject, $body, $headers, $attachments) { - $message->addHeaders ( $headers ); - $message->setBody ( $body ); - $message->setSubject ( $subject ); - $message->addTo ( $to ); - $message->setAttachments ( $attachments ); + private function populateMessageFromWpMailParams( PostmanMessage $message, $to, $subject, $body, $headers, $attachments ) { + $message->addHeaders( $headers ); + $message->setBody( $body ); + $message->setSubject( $subject ); + $message->addTo( $to ); + $message->setAttachments( $attachments ); return $message; } - + /** * Trace the parameters to aid in debugging * - * @param unknown $to - * @param unknown $subject - * @param unknown $body - * @param unknown $headers - * @param unknown $attachments + * @param unknown $to + * @param unknown $subject + * @param unknown $body + * @param unknown $headers + * @param unknown $attachments */ - private function traceParameters($to, $subject, $message, $headers, $attachments) { - $this->logger->trace ( 'to:' ); - $this->logger->trace ( $to ); - $this->logger->trace ( 'subject:' ); - $this->logger->trace ( $subject ); - $this->logger->trace ( 'headers:' ); - $this->logger->trace ( $headers ); - $this->logger->trace ( 'attachments:' ); - $this->logger->trace ( $attachments ); - $this->logger->trace ( 'message:' ); - $this->logger->trace ( $message ); + private function traceParameters( $to, $subject, $message, $headers, $attachments ) { + $this->logger->trace( 'to:' ); + $this->logger->trace( $to ); + $this->logger->trace( 'subject:' ); + $this->logger->trace( $subject ); + $this->logger->trace( 'headers:' ); + $this->logger->trace( $headers ); + $this->logger->trace( 'attachments:' ); + $this->logger->trace( $attachments ); + $this->logger->trace( 'message:' ); + $this->logger->trace( $message ); } } -}
\ No newline at end of file +} @@ -274,6 +274,7 @@ To avoid being flagged as spam, you need to prove your email isn't forged. On a = 1.7.6 - 2017-10-17 * Missing sendgrid files * Fixed: Localization slug +* Fixed: Error sending files with sendgrid = 1.7.5 - 2017-10-07 = * Fixed: security issue (XSS) |