From 0e5055bf5b513df03b0f9ac8bd2810ffe72ed744 Mon Sep 17 00:00:00 2001 From: yehudah Date: Tue, 17 Oct 2017 19:09:18 +0000 Subject: = 1.7.6 - 2017-10-17 * Missing sendgrid files * Fixed: Localization slug * Fixed: Error sending files with sendgrid --- Postman/Postman-Mail/PostmanMandrillMailEngine.php | 269 ++-- Postman/Postman-Mail/PostmanMessage.php | 435 ++++--- Postman/Postman-Mail/PostmanSendGridMailEngine.php | 222 ++-- .../Postman-Mail/PostmanSmtpModuleTransport.php | 465 ++++--- Postman/Postman-Mail/PostmanZendMailEngine.php | 242 ++-- .../sendgrid-php-3.2.0/lib/SendGrid/Email.php | 1289 ++++++++++---------- .../Guzzle/Http/Message/EntityEnclosingRequest.php | 449 ++++--- .../src/Guzzle/Http/Message/RequestFactory.php | 663 +++++----- 8 files changed, 1967 insertions(+), 2067 deletions(-) (limited to 'Postman/Postman-Mail') 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 @@ 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 @@ 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 @@ 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 ( ' %s.', 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( ' %s.', 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 ( '%s', $oauthScribe->getCallbackDomainLabel () ), array ( + + add_settings_field( 'callback_domain', sprintf( '%s', $oauthScribe->getCallbackDomainLabel() ), array( $this, - 'callback_domain_callback' + 'callback_domain_callback', ), PostmanAdminController::OAUTH_AUTH_OPTIONS, PostmanAdminController::OAUTH_SECTION ); - - add_settings_field ( 'redirect_url', sprintf ( '%s', $oauthScribe->getCallbackUrlLabel () ), array ( + + add_settings_field( 'redirect_url', sprintf( '%s', $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 ( '', null !== $this->options->getHostname () ? esc_attr ( $this->options->getHostname () ) : '', __ ( 'Required', Postman::TEXT_DOMAIN ) ); + printf( '', 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 ( '', null !== $this->options->getPort () ? esc_attr ( $this->options->getPort () ) : '', isset ( $args ['style'] ) ? $args ['style'] : '', __ ( 'Required', Postman::TEXT_DOMAIN ) ); + public function port_callback( $args ) { + printf( '', 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 ''; } - + /** * Get the settings option array and print one of its values */ public function authentication_type_callback() { - $authType = $this->options->getAuthenticationType (); - printf ( '', PostmanOptions::POSTMAN_OPTIONS, PostmanOptions::AUTHENTICATION_TYPE ); + printf( '', PostmanOptions::AUTHENTICATION_TYPE_NONE, $authType == PostmanOptions::AUTHENTICATION_TYPE_NONE ? 'selected="selected"' : '', 'None' ); + printf( '', PostmanOptions::AUTHENTICATION_TYPE_PLAIN, $authType == PostmanOptions::AUTHENTICATION_TYPE_PLAIN ? 'selected="selected"' : '', 'Plain' ); + printf( '', PostmanOptions::AUTHENTICATION_TYPE_LOGIN, $authType == PostmanOptions::AUTHENTICATION_TYPE_LOGIN ? 'selected="selected"' : '', 'Login' ); + printf( '', PostmanOptions::AUTHENTICATION_TYPE_CRAMMD5, $authType == PostmanOptions::AUTHENTICATION_TYPE_CRAMMD5 ? 'selected="selected"' : '', 'CRAM-MD5' ); + printf( '', PostmanOptions::AUTHENTICATION_TYPE_OAUTH2, $authType == PostmanOptions::AUTHENTICATION_TYPE_OAUTH2 ? 'selected="selected"' : '', 'OAuth 2.0' ); print ''; } - + /** * 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 ('') ; - printf ( '
%s', $inputValue, __ ( 'Required', Postman::TEXT_DOMAIN ), $inputDescription ); + printf( '
%s', $inputValue, __( 'Required', Postman::TEXT_DOMAIN ), $inputDescription ); } - + /** * Get the settings option array and print one of its values */ public function basic_auth_password_callback() { print ('') ; - printf ( '', null !== $this->options->getPassword () ? esc_attr ( PostmanUtils::obfuscatePassword ( $this->options->getPassword () ) ) : '', __ ( 'Required', Postman::TEXT_DOMAIN ) ); + printf( '', null !== $this->options->getPassword() ? esc_attr( PostmanUtils::obfuscatePassword( $this->options->getPassword() ) ) : '', __( 'Required', Postman::TEXT_DOMAIN ) ); print ' '; } - + /** * Get the settings option array and print one of its values */ public function oauth_client_id_callback() { - printf ( '', null !== $this->options->getClientId () ? esc_attr ( $this->options->getClientId () ) : '', __ ( 'Required', Postman::TEXT_DOMAIN ) ); + printf( '', 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 ( '', null !== $this->options->getClientSecret () ? esc_attr ( $this->options->getClientSecret () ) : '', __ ( 'Required', Postman::TEXT_DOMAIN ) ); + printf( '', 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 ( '

%s

', $oauthScribe->getOAuthHelp () ); + $oauthScribe = $transport->getScribe(); + printf( '

%s

', $oauthScribe->getOAuthHelp() ); } - + /** * Get the settings option array and print one of its values */ public function callback_domain_callback() { - printf ( '', $this->getCallbackDomain () ); + printf( '', $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 ( '', $oauthScribe->getCallbackUrl () ); + $oauthScribe = $transport->getScribe(); + printf( '', $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 return address 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 SPF record permitting the use of the SMTP server named above.', Postman::TEXT_DOMAIN ), 'https://www.mail-tester.com/spf/' ); - printf ( '
%s %s', $inputValue, $requiredLabel, $envelopeFromMessage, $spfMessage ); + $inputValue = (null !== $this->options->getEnvelopeSender() ? esc_attr( $this->options->getEnvelopeSender() ) : ''); + $requiredLabel = __( 'Required', Postman::TEXT_DOMAIN ); + $envelopeFromMessage = __( 'This address, like the return address 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 SPF record permitting the use of the SMTP server named above.', Postman::TEXT_DOMAIN ), 'https://www.mail-tester.com/spf/' ); + printf( '
%s %s', $inputValue, $requiredLabel, $envelopeFromMessage, $spfMessage ); } - + /** */ public function printWizardMailServerHostnameStep() { - printf ( '%s', _x ( 'Which host will relay the mail?', 'Wizard Step Title', Postman::TEXT_DOMAIN ) ); - printf ( '

%s

', __ ( '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 ( '

%s

', __ ( '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 ( '', __ ( 'Outgoing Mail Server Hostname', Postman::TEXT_DOMAIN ) ); - print $this->hostname_callback (); - printf ( '', plugins_url ( 'postman-smtp/style/ajax-loader.gif' ) ); - $warning = __ ( 'Warning', Postman::TEXT_DOMAIN ); + printf( '%s', _x( 'Which host will relay the mail?', 'Wizard Step Title', Postman::TEXT_DOMAIN ) ); + printf( '

%s

', __( '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( '

%s

', __( '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( '', __( 'Outgoing Mail Server Hostname', Postman::TEXT_DOMAIN ) ); + print $this->hostname_callback(); + printf( '', 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 requires 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 ( '

%s: %s

', $warning, $nonGodaddyDomainMessage ); + $nonGodaddyDomainMessage = sprintf( __( 'Your email address requires 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( '

%s: %s

', $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 SPF record authorizing %2$s as a relay, or you will have delivery problems.', Postman::TEXT_DOMAIN ), 'http://www.mail-tester.com/spf/godaddy', 'GoDaddy' ); - printf ( '

%s: %s

', $warning, $godaddyCustomDomainMessage ); + $godaddyCustomDomainMessage = sprintf( __( 'If you own this domain, make sure it has an SPF record authorizing %2$s as a relay, or you will have delivery problems.', Postman::TEXT_DOMAIN ), 'http://www.mail-tester.com/spf/godaddy', 'GoDaddy' ); + printf( '

%s: %s

', $warning, $godaddyCustomDomainMessage ); } - + /** */ public function printWizardAuthenticationStep() { print '
'; print '

'; - printf ( '', $this->getScribe ()->getCallbackDomainLabel () ); + printf( '', $this->getScribe()->getCallbackDomainLabel() ); print '
'; - print $this->callback_domain_callback (); + print $this->callback_domain_callback(); print '
'; - printf ( '', $this->getScribe ()->getCallbackUrlLabel () ); + printf( '', $this->getScribe()->getCallbackUrlLabel() ); print '
'; - print $this->redirect_url_callback (); + print $this->redirect_url_callback(); print '
'; - printf ( '', $this->getScribe ()->getClientIdLabel () ); + printf( '', $this->getScribe()->getClientIdLabel() ); print '
'; - print $this->oauth_client_id_callback (); + print $this->oauth_client_id_callback(); print '
'; - printf ( '', $this->getScribe ()->getClientSecretLabel () ); + printf( '', $this->getScribe()->getClientSecretLabel() ); print '
'; - print $this->oauth_client_secret_callback (); + print $this->oauth_client_secret_callback(); print '
'; print '
'; - + print '
'; - printf ( '

%s

', __ ( 'Enter the account credentials.', Postman::TEXT_DOMAIN ) ); - printf ( '', __ ( 'Username', Postman::TEXT_DOMAIN ) ); + printf( '

%s

', __( 'Enter the account credentials.', Postman::TEXT_DOMAIN ) ); + printf( '', __( 'Username', Postman::TEXT_DOMAIN ) ); print '
'; - print $this->basic_auth_username_callback (); + print $this->basic_auth_username_callback(); print '
'; - printf ( '', __ ( 'Password', Postman::TEXT_DOMAIN ) ); + printf( '', __( 'Password', Postman::TEXT_DOMAIN ) ); print '
'; - print $this->basic_auth_password_callback (); + print $this->basic_auth_password_callback(); print '
'; } } 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 @@ 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 ); + } + } } -- cgit v1.2.3