Make WordPress Core

Ticket #37210: 0001-Upgrade-PHPMailer-from-5.2.14-to-5.2.19.patch

File 0001-Upgrade-PHPMailer-from-5.2.14-to-5.2.19.patch, 31.6 KB (added by sfpt, 9 years ago)
  • wp-includes/class-phpmailer.php

    From 485b44a703e97f2fd72801543777df6a64768d0a Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?S=C3=A9rgio=20Faria?= <sergio91pt@gmail.com>
    Date: Tue, 27 Dec 2016 12:40:08 +0000
    Subject: [PATCH] Upgrade PHPMailer from 5.2.14 to 5.2.19
    
    Merged update with conflicts.
    Fixes CVE-2016-10033.
    ---
     wp-includes/class-phpmailer.php | 229 +++++++++++++++++++++++++++++-----------
     wp-includes/class-smtp.php      |  82 ++++++++++++--
     2 files changed, 240 insertions(+), 71 deletions(-)
    
    diff --git a/wp-includes/class-phpmailer.php b/wp-includes/class-phpmailer.php
    index 2c481c0..6230829 100644
    a b class PHPMailer 
    3131     * The PHPMailer Version number.
    3232     * @var string
    3333     */
    34     public $Version = '5.2.14';
     34    public $Version = '5.2.19';
    3535
    3636    /**
    3737     * Email priority.
    class PHPMailer 
    201201    /**
    202202     * An ID to be used in the Message-ID header.
    203203     * If empty, a unique id will be generated.
     204     * You can set your own, but it must be in the format "<id@domain>",
     205     * as defined in RFC5322 section 3.6.4 or it will be ignored.
     206     * @see https://tools.ietf.org/html/rfc5322#section-3.6.4
    204207     * @var string
    205208     */
    206209    public $MessageID = '';
    class PHPMailer 
    352355    /**
    353356     * Whether to split multiple to addresses into multiple messages
    354357     * or send them all in one message.
     358     * Only supported in `mail` and `sendmail` transports, not in SMTP.
    355359     * @var boolean
    356360     */
    357361    public $SingleTo = false;
    class PHPMailer 
    394398
    395399    /**
    396400     * DKIM Identity.
    397      * Usually the email address used as the source of the email
     401     * Usually the email address used as the source of the email.
    398402     * @var string
    399403     */
    400404    public $DKIM_identity = '';
    class PHPMailer 
    420424    public $DKIM_private = '';
    421425
    422426    /**
     427     * DKIM private key string.
     428     * If set, takes precedence over `$DKIM_private`.
     429     * @var string
     430     */
     431    public $DKIM_private_string = '';
     432
     433    /**
    423434     * Callback Action function name.
    424435     *
    425436     * The function that handles the result of the send email action.
    class PHPMailer 
    447458    public $XMailer = '';
    448459
    449460    /**
     461     * Which validator to use by default when validating email addresses.
     462     * May be a callable to inject your own validator, but there are several built-in validators.
     463     * @see PHPMailer::validateAddress()
     464     * @var string|callable
     465     * @static
     466     */
     467    public static $validator = 'auto';
     468
     469    /**
    450470     * An instance of the SMTP sender class.
    451471     * @var SMTP
    452472     * @access protected
    class PHPMailer 
    634654     * Constructor.
    635655     * @param boolean $exceptions Should we throw external exceptions?
    636656     */
    637     public function __construct($exceptions = false)
     657    public function __construct($exceptions = null)
    638658    {
    639         $this->exceptions = (boolean)$exceptions;
     659        if ($exceptions !== null) {
     660            $this->exceptions = (boolean)$exceptions;
     661        }
    640662    }
    641663
    642664    /**
    class PHPMailer 
    645667    public function __destruct()
    646668    {
    647669        //Close any open SMTP connection nicely
    648         if ($this->Mailer == 'smtp') {
    649             $this->smtpClose();
    650         }
     670        $this->smtpClose();
    651671    }
    652672
    653673    /**
    class PHPMailer 
    671691        } else {
    672692            $subject = $this->encodeHeader($this->secureHeader($subject));
    673693        }
    674         if (ini_get('safe_mode') || !($this->UseSendmailOptions)) {
     694
     695        //Can't use additional_parameters in safe_mode, calling mail() with null params breaks
     696        //@link http://php.net/manual/en/function.mail.php
     697        if (ini_get('safe_mode') or !$this->UseSendmailOptions or is_null($params)) {
    675698            $result = @mail($to, $subject, $body, $header);
    676699        } else {
    677700            $result = @mail($to, $subject, $body, $header, $params);
    678701        }
    679702        return $result;
    680703    }
    681 
    682704    /**
    683705     * Output debugging info via user-defined method.
    684706     * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
    class PHPMailer 
    713735            case 'echo':
    714736            default:
    715737                //Normalize line breaks
    716                 $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
     738                $str = preg_replace('/\r\n?/ms', "\n", $str);
    717739                echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
    718740                    "\n",
    719741                    "\n                   \t                  ",
    class PHPMailer 
    850872        $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
    851873        if (($pos = strrpos($address, '@')) === false) {
    852874            // At-sign is misssing.
    853             $error_message = $this->lang('invalid_address') . $address;
     875            $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address";
    854876            $this->setError($error_message);
    855877            $this->edebug($error_message);
    856878            if ($this->exceptions) {
    class PHPMailer 
    900922            return false;
    901923        }
    902924        if (!$this->validateAddress($address)) {
    903             $error_message = $this->lang('invalid_address') . $address;
     925            $error_message = $this->lang('invalid_address') . " (addAnAddress $kind): $address";
    904926            $this->setError($error_message);
    905927            $this->edebug($error_message);
    906928            if ($this->exceptions) {
    class PHPMailer 
    939961        if (($pos = strrpos($address, '@')) === false or
    940962            (!$this->has8bitChars(substr($address, ++$pos)) or !$this->idnSupported()) and
    941963            !$this->validateAddress($address)) {
    942             $error_message = $this->lang('invalid_address') . $address;
     964            $error_message = $this->lang('invalid_address') . " (setFrom) $address";
    943965            $this->setError($error_message);
    944966            $this->edebug($error_message);
    945967            if ($this->exceptions) {
    class PHPMailer 
    972994    /**
    973995     * Check that a string looks like an email address.
    974996     * @param string $address The email address to check
    975      * @param string $patternselect A selector for the validation pattern to use :
     997     * @param string|callable $patternselect A selector for the validation pattern to use :
    976998     * * `auto` Pick best pattern automatically;
    977999     * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
    9781000     * * `pcre` Use old PCRE implementation;
    9791001     * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
    9801002     * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
    9811003     * * `noregex` Don't use a regex: super fast, really dumb.
     1004     * Alternatively you may pass in a callable to inject your own validator, for example:
     1005     * PHPMailer::validateAddress('user@example.com', function($address) {
     1006     *     return (strpos($address, '@') !== false);
     1007     * });
     1008     * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.
    9821009     * @return boolean
    9831010     * @static
    9841011     * @access public
    9851012     */
    986     public static function validateAddress($address, $patternselect = 'auto')
     1013    public static function validateAddress($address, $patternselect = null)
    9871014    {
     1015        if (is_null($patternselect)) {
     1016            $patternselect = self::$validator;
     1017        }
     1018        if (is_callable($patternselect)) {
     1019            return call_user_func($patternselect, $address);
     1020        }
    9881021        //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
    9891022        if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) {
    9901023            return false;
    class PHPMailer 
    11611194                }
    11621195                $this->$address_kind = $this->punyencodeAddress($this->$address_kind);
    11631196                if (!$this->validateAddress($this->$address_kind)) {
    1164                     $error_message = $this->lang('invalid_address') . $this->$address_kind;
     1197                    $error_message = $this->lang('invalid_address') . ' (punyEncode) ' . $this->$address_kind;
    11651198                    $this->setError($error_message);
    11661199                    $this->edebug($error_message);
    11671200                    if ($this->exceptions) {
    class PHPMailer 
    11721205            }
    11731206
    11741207            // Set whether the message is multipart/alternative
    1175             if (!empty($this->AltBody)) {
     1208            if ($this->alternativeExists()) {
    11761209                $this->ContentType = 'multipart/alternative';
    11771210            }
    11781211
    class PHPMailer 
    12061239
    12071240            // Sign with DKIM if enabled
    12081241            if (!empty($this->DKIM_domain)
    1209                 && !empty($this->DKIM_private)
    12101242                && !empty($this->DKIM_selector)
    1211                 && file_exists($this->DKIM_private)) {
     1243                && (!empty($this->DKIM_private_string)
     1244                   || (!empty($this->DKIM_private) && file_exists($this->DKIM_private))
     1245                )
     1246            ) {
    12121247                $header_dkim = $this->DKIM_Add(
    12131248                    $this->MIMEHeader . $this->mailHeader,
    12141249                    $this->encodeHeader($this->secureHeader($this->Subject)),
    class PHPMailer 
    12741309     */
    12751310    protected function sendmailSend($header, $body)
    12761311    {
    1277         if ($this->Sender != '') {
     1312        if (!empty($this->Sender)) {
    12781313            if ($this->Mailer == 'qmail') {
    12791314                $sendmail = sprintf('%s -f%s', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
    12801315            } else {
    class PHPMailer 
    13491384        }
    13501385        $to = implode(', ', $toArr);
    13511386
    1352         if (empty($this->Sender)) {
    1353             $params = ' ';
    1354         } else {
    1355             $params = sprintf('-f%s', $this->Sender);
     1387        $params = null;
     1388        //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
     1389        if (!empty($this->Sender) and $this->validateAddress($this->Sender)) {
     1390            $params = sprintf('-f%s', escapeshellarg($this->Sender));
    13561391        }
    1357         if ($this->Sender != '' and !ini_get('safe_mode')) {
     1392        if (!empty($this->Sender) and !ini_get('safe_mode') and $this->validateAddress($this->Sender)) {
    13581393            $old_from = ini_get('sendmail_from');
    13591394            ini_set('sendmail_from', $this->Sender);
    13601395        }
    13611396        $result = false;
    1362         if ($this->SingleTo && count($toArr) > 1) {
     1397        if ($this->SingleTo and count($toArr) > 1) {
    13631398            foreach ($toArr as $toAddr) {
    13641399                $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
    13651400                $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From);
    class PHPMailer 
    14091444        if (!$this->smtpConnect($this->SMTPOptions)) {
    14101445            throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
    14111446        }
    1412         if ('' == $this->Sender) {
    1413             $smtp_from = $this->From;
    1414         } else {
     1447        if (!empty($this->Sender) and $this->validateAddress($this->Sender)) {
    14151448            $smtp_from = $this->Sender;
     1449        } else {
     1450            $smtp_from = $this->From;
    14161451        }
    14171452        if (!$this->smtp->mail($smtp_from)) {
    14181453            $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
    class PHPMailer 
    14661501     * @throws phpmailerException
    14671502     * @return boolean
    14681503     */
    1469     public function smtpConnect($options = array())
     1504    public function smtpConnect($options = null)
    14701505    {
    14711506        if (is_null($this->smtp)) {
    14721507            $this->smtp = $this->getSMTPInstance();
    14731508        }
    14741509
     1510        //If no options are provided, use whatever is set in the instance
     1511        if (is_null($options)) {
     1512            $options = $this->SMTPOptions;
     1513        }
     1514
    14751515        // Already connected?
    14761516        if ($this->smtp->connected()) {
    14771517            return true;
    class PHPMailer 
    15411581                        if (!$this->smtp->startTLS()) {
    15421582                            throw new phpmailerException($this->lang('connect_host'));
    15431583                        }
    1544                         // We must resend HELO after tls negotiation
     1584                        // We must resend EHLO after TLS negotiation
    15451585                        $this->smtp->hello($hello);
    15461586                    }
    15471587                    if ($this->SMTPAuth) {
    class PHPMailer 
    15801620     */
    15811621    public function smtpClose()
    15821622    {
    1583         if ($this->smtp !== null) {
     1623        if (is_a($this->smtp, 'SMTP')) {
    15841624            if ($this->smtp->connected()) {
    15851625                $this->smtp->quit();
    15861626                $this->smtp->close();
    class PHPMailer 
    15991639     */
    16001640    public function setLanguage($langcode = 'en', $lang_path = '')
    16011641    {
     1642        // Backwards compatibility for renamed language codes
     1643        $renamed_langcodes = array(
     1644            'br' => 'pt_br',
     1645            'cz' => 'cs',
     1646            'dk' => 'da',
     1647            'no' => 'nb',
     1648            'se' => 'sv',
     1649        );
     1650
     1651        if (isset($renamed_langcodes[$langcode])) {
     1652            $langcode = $renamed_langcodes[$langcode];
     1653        }
     1654
    16021655        // Define full set of translatable strings in English
    16031656        $PHPMAILER_LANG = array(
    16041657            'authenticate' => 'SMTP Error: Could not authenticate.',
    class PHPMailer 
    16251678            // Calculate an absolute path so it can work if CWD is not here
    16261679            $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR;
    16271680        }
     1681        //Validate $langcode
     1682        if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) {
     1683            $langcode = 'en';
     1684        }
    16281685        $foundlang = true;
    16291686        $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
    16301687        // There is no English translation file
    class PHPMailer 
    19181975            $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
    19191976        }
    19201977
    1921         if ($this->MessageID != '') {
     1978        // Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
     1979        // https://tools.ietf.org/html/rfc5322#section-3.6.4
     1980        if ('' != $this->MessageID and preg_match('/^<.*@.*>$/', $this->MessageID)) {
    19221981            $this->lastMessageID = $this->MessageID;
    19231982        } else {
    19241983            $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
    class PHPMailer 
    20202079     */
    20212080    public function getSentMIMEMessage()
    20222081    {
    2023         return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
     2082        return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . self::CRLF . self::CRLF . $this->MIMEBody;
     2083    }
     2084
     2085    /**
     2086     * Create unique ID
     2087     * @return string
     2088     */
     2089    protected function generateId() {
     2090        return md5(uniqid(time()));
    20242091    }
    20252092
    20262093    /**
    class PHPMailer 
    20342101    {
    20352102        $body = '';
    20362103        //Create unique IDs and preset boundaries
    2037         $this->uniqueid = md5(uniqid(time()));
     2104        $this->uniqueid = $this->generateId();
    20382105        $this->boundary[1] = 'b1_' . $this->uniqueid;
    20392106        $this->boundary[2] = 'b2_' . $this->uniqueid;
    20402107        $this->boundary[3] = 'b3_' . $this->uniqueid;
    class PHPMailer 
    20502117        //Can we do a 7-bit downgrade?
    20512118        if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) {
    20522119            $bodyEncoding = '7bit';
     2120            //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
    20532121            $bodyCharSet = 'us-ascii';
    20542122        }
    2055         //If lines are too long, change to quoted-printable transfer encoding
     2123        //If lines are too long, and we're not already using an encoding that will shorten them,
     2124        //change to quoted-printable transfer encoding for the body part only
    20562125        if (self::hasLineLongerThanMax($this->Body)) {
    2057             $this->Encoding = 'quoted-printable';
    20582126            $bodyEncoding = 'quoted-printable';
    20592127        }
    20602128
    20612129        $altBodyEncoding = $this->Encoding;
    20622130        $altBodyCharSet = $this->CharSet;
    2063         //Can we do a 7-bit downgrade?
     2131         //Can we do a 7-bit downgrade?
    20642132        if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) {
    20652133            $altBodyEncoding = '7bit';
     2134            //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
    20662135            $altBodyCharSet = 'us-ascii';
    2067         }
    2068         //If lines are too long, change to quoted-printable transfer encoding
    2069         if (self::hasLineLongerThanMax($this->AltBody)) {
     2136         }
     2137        //If lines are too long, and we're not already using an encoding that will shorten them,
     2138        //change to quoted-printable transfer encoding for the alt body part only
     2139        if ('base64' != $altBodyEncoding and self::hasLineLongerThanMax($this->AltBody)) {
    20702140            $altBodyEncoding = 'quoted-printable';
    20712141        }
    20722142        //Use this as a preamble in all multipart message types
    class PHPMailer 
    21692239                $body .= $this->attachAll('attachment', $this->boundary[1]);
    21702240                break;
    21712241            default:
    2172                 // catch case 'plain' and case ''
    2173                 $body .= $this->encodeString($this->Body, $bodyEncoding);
     2242                // Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
     2243                //Reset the `Encoding` property in case we changed it for line length reasons
     2244                $this->Encoding = $bodyEncoding;
     2245                $body .= $this->encodeString($this->Body, $this->Encoding);
    21742246                break;
    21752247        }
    21762248
    class PHPMailer 
    22762348
    22772349    /**
    22782350     * Set the message type.
    2279      * PHPMailer only supports some preset message types,
    2280      * not arbitrary MIME structures.
     2351     * PHPMailer only supports some preset message types, not arbitrary MIME structures.
    22812352     * @access protected
    22822353     * @return void
    22832354     */
    class PHPMailer 
    22952366        }
    22962367        $this->message_type = implode('_', $type);
    22972368        if ($this->message_type == '') {
     2369            //The 'plain' message_type refers to the message having a single body element, not that it is plain-text
    22982370            $this->message_type = 'plain';
    22992371        }
    23002372    }
    class PHPMailer 
    32093281    }
    32103282
    32113283    /**
    3212      * Create a message from an HTML string.
    3213      * Automatically makes modifications for inline images and backgrounds
    3214      * and creates a plain-text version by converting the HTML.
    3215      * Overwrites any existing values in $this->Body and $this->AltBody
     3284     * Create a message body from an HTML string.
     3285     * Automatically inlines images and creates a plain-text version by converting the HTML,
     3286     * overwriting any existing values in Body and AltBody.
     3287     * $basedir is used when handling relative image paths, e.g. <img src="images/a.png">
     3288     * will look for an image file in $basedir/images/a.png and convert it to inline.
     3289     * If you don't want to apply these transformations to your HTML, just set Body and AltBody yourself.
    32163290     * @access public
    32173291     * @param string $message HTML message string
    3218      * @param string $basedir baseline directory for path
     3292     * @param string $basedir base directory for relative paths to images
    32193293     * @param boolean|callable $advanced Whether to use the internal HTML to text converter
    32203294     *    or your own custom converter @see PHPMailer::html2text()
    3221      * @return string $message
     3295     * @return string $message The transformed message Body
    32223296     */
    32233297    public function msgHTML($message, $basedir = '', $advanced = false)
    32243298    {
    class PHPMailer 
    32413315                            $message
    32423316                        );
    32433317                    }
    3244                 } elseif (substr($url, 0, 4) !== 'cid:' && !preg_match('#^[A-z]+://#', $url)) {
     3318                } elseif (substr($url, 0, 4) !== 'cid:' && !preg_match('#^[a-z][a-z0-9+.-]*://#i', $url)) {
    32453319                    // Do not change urls for absolute images (thanks to corvuscorax)
    32463320                    // Do not change urls that are already inline images
    32473321                    $filename = basename($url);
    class PHPMailer 
    32773351        // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
    32783352        $this->Body = $this->normalizeBreaks($message);
    32793353        $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
    3280         if (empty($this->AltBody)) {
     3354        if (!$this->alternativeExists()) {
    32813355            $this->AltBody = 'To view this email message, open it in a program that understands HTML!' .
    32823356                self::CRLF . self::CRLF;
    32833357        }
    class PHPMailer 
    32883362     * Convert an HTML string into plain text.
    32893363     * This is used by msgHTML().
    32903364     * Note - older versions of this function used a bundled advanced converter
    3291      * which was been removed for license reasons in #232
     3365     * which was been removed for license reasons in #232.
    32923366     * Example usage:
    32933367     * <code>
    32943368     * // Use default conversion
    class PHPMailer 
    35883662     * @access public
    35893663     * @param string $signHeader
    35903664     * @throws phpmailerException
    3591      * @return string
     3665     * @return string The DKIM signature value
    35923666     */
    35933667    public function DKIM_Sign($signHeader)
    35943668    {
    class PHPMailer 
    35983672            }
    35993673            return '';
    36003674        }
    3601         $privKeyStr = file_get_contents($this->DKIM_private);
    3602         if ($this->DKIM_passphrase != '') {
     3675        $privKeyStr = !empty($this->DKIM_private_string) ? $this->DKIM_private_string : file_get_contents($this->DKIM_private);
     3676        if ('' != $this->DKIM_passphrase) {
    36033677            $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
    36043678        } else {
    3605             $privKey = $privKeyStr;
     3679            $privKey = openssl_pkey_get_private($privKeyStr);
    36063680        }
    3607         if (openssl_sign($signHeader, $signature, $privKey)) {
    3608             return base64_encode($signature);
     3681        //Workaround for missing digest algorithms in old PHP & OpenSSL versions
     3682        //@link http://stackoverflow.com/a/11117338/333340
     3683        if (version_compare(PHP_VERSION, '5.3.0') >= 0 and
     3684            in_array('sha256WithRSAEncryption', openssl_get_md_methods(true))) {
     3685            if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
     3686                openssl_pkey_free($privKey);
     3687                return base64_encode($signature);
     3688            }
     3689        } else {
     3690            $pinfo = openssl_pkey_get_details($privKey);
     3691            $hash = hash('sha256', $signHeader);
     3692            //'Magic' constant for SHA256 from RFC3447
     3693            //@link https://tools.ietf.org/html/rfc3447#page-43
     3694            $t = '3031300d060960864801650304020105000420' . $hash;
     3695            $pslen = $pinfo['bits'] / 8 - (strlen($t) / 2 + 3);
     3696            $eb = pack('H*', '0001' . str_repeat('FF', $pslen) . '00' . $t);
     3697
     3698            if (openssl_private_encrypt($eb, $signature, $privKey, OPENSSL_NO_PADDING)) {
     3699                openssl_pkey_free($privKey);
     3700                return base64_encode($signature);
     3701            }
    36093702        }
     3703        openssl_pkey_free($privKey);
    36103704        return '';
    36113705    }
    36123706
    class PHPMailer 
    36233717        foreach ($lines as $key => $line) {
    36243718            list($heading, $value) = explode(':', $line, 2);
    36253719            $heading = strtolower($heading);
    3626             $value = preg_replace('/\s+/', ' ', $value); // Compress useless spaces
     3720            $value = preg_replace('/\s{2,}/', ' ', $value); // Compress useless spaces
    36273721            $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value
    36283722        }
    36293723        $signHeader = implode("\r\n", $lines);
    class PHPMailer 
    36613755     */
    36623756    public function DKIM_Add($headers_line, $subject, $body)
    36633757    {
    3664         $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
     3758        $DKIMsignatureType = 'rsa-sha256'; // Signature & hash algorithms
    36653759        $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
    36663760        $DKIMquery = 'dns/txt'; // Query method
    36673761        $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
    class PHPMailer 
    36693763        $headers = explode($this->LE, $headers_line);
    36703764        $from_header = '';
    36713765        $to_header = '';
     3766        $date_header = '';
    36723767        $current = '';
    36733768        foreach ($headers as $header) {
    36743769            if (strpos($header, 'From:') === 0) {
    class PHPMailer 
    36773772            } elseif (strpos($header, 'To:') === 0) {
    36783773                $to_header = $header;
    36793774                $current = 'to_header';
     3775            } elseif (strpos($header, 'Date:') === 0) {
     3776                $date_header = $header;
     3777                $current = 'date_header';
    36803778            } else {
    36813779                if (!empty($$current) && strpos($header, ' =?') === 0) {
    36823780                    $$current .= $header;
    class PHPMailer 
    36873785        }
    36883786        $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
    36893787        $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
     3788        $date = str_replace('|', '=7C', $this->DKIM_QP($date_header));
    36903789        $subject = str_replace(
    36913790            '|',
    36923791            '=7C',
    class PHPMailer 
    36943793        ); // Copied header fields (dkim-quoted-printable)
    36953794        $body = $this->DKIM_BodyC($body);
    36963795        $DKIMlen = strlen($body); // Length of body
    3697         $DKIMb64 = base64_encode(pack('H*', sha1($body))); // Base64 of packed binary SHA-1 hash of body
     3796        $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); // Base64 of packed binary SHA-256 hash of body
    36983797        if ('' == $this->DKIM_identity) {
    36993798            $ident = '';
    37003799        } else {
    class PHPMailer 
    37073806            $this->DKIM_selector .
    37083807            ";\r\n" .
    37093808            "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
    3710             "\th=From:To:Subject;\r\n" .
     3809            "\th=From:To:Date:Subject;\r\n" .
    37113810            "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
    37123811            "\tz=$from\r\n" .
    37133812            "\t|$to\r\n" .
     3813            "\t|$date\r\n" .
    37143814            "\t|$subject;\r\n" .
    37153815            "\tbh=" . $DKIMb64 . ";\r\n" .
    37163816            "\tb=";
    37173817        $toSign = $this->DKIM_HeaderC(
    37183818            $from_header . "\r\n" .
    37193819            $to_header . "\r\n" .
     3820            $date_header . "\r\n" .
    37203821            $subject_header . "\r\n" .
    37213822            $dkimhdrs
    37223823        );
  • wp-includes/class-smtp.php

    diff --git a/wp-includes/class-smtp.php b/wp-includes/class-smtp.php
    index f17ca0f..61056cf 100644
    a b class SMTP 
    3030     * The PHPMailer SMTP version number.
    3131     * @var string
    3232     */
    33     const VERSION = '5.2.14';
     33    const VERSION = '5.2.19';
    3434
    3535    /**
    3636     * SMTP line break constant.
    class SMTP 
    8181     * @deprecated Use the `VERSION` constant instead
    8282     * @see SMTP::VERSION
    8383     */
    84     public $Version = '5.2.14';
     84    public $Version = '5.2.19';
    8585
    8686    /**
    8787     * SMTP server port number.
    class SMTP 
    150150     */
    151151    public $Timelimit = 300;
    152152
     153        /**
     154         * @var array patterns to extract smtp transaction id from smtp reply
     155         * Only first capture group will be use, use non-capturing group to deal with it
     156         * Extend this class to override this property to fulfil your needs.
     157         */
     158        protected $smtp_transaction_id_patterns = array(
     159                'exim' => '/[0-9]{3} OK id=(.*)/',
     160                'sendmail' => '/[0-9]{3} 2.0.0 (.*) Message/',
     161                'postfix' => '/[0-9]{3} 2.0.0 Ok: queued as (.*)/'
     162        );
     163
    153164    /**
    154165     * The socket for the server connection.
    155166     * @var resource
    class SMTP 
    206217        }
    207218        //Avoid clash with built-in function names
    208219        if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
    209             call_user_func($this->Debugoutput, $str, $this->do_debug);
     220            call_user_func($this->Debugoutput, $str, $level);
    210221            return;
    211222        }
    212223        switch ($this->Debugoutput) {
    class SMTP 
    272283        $errstr = '';
    273284        if ($streamok) {
    274285            $socket_context = stream_context_create($options);
    275             //Suppress errors; connection failures are handled at a higher level
    276             $this->smtp_conn = @stream_socket_client(
     286            set_error_handler(array($this, 'errorHandler'));
     287            $this->smtp_conn = stream_socket_client(
    277288                $host . ":" . $port,
    278289                $errno,
    279290                $errstr,
    class SMTP 
    281292                STREAM_CLIENT_CONNECT,
    282293                $socket_context
    283294            );
     295            restore_error_handler();
    284296        } else {
    285297            //Fall back to fsockopen which should work in more places, but is missing some features
    286298            $this->edebug(
    287299                "Connection: stream_socket_client not available, falling back to fsockopen",
    288300                self::DEBUG_CONNECTION
    289301            );
     302            set_error_handler(array($this, 'errorHandler'));
    290303            $this->smtp_conn = fsockopen(
    291304                $host,
    292305                $port,
    class SMTP 
    294307                $errstr,
    295308                $timeout
    296309            );
     310            restore_error_handler();
    297311        }
    298312        // Verify we connected properly
    299313        if (!is_resource($this->smtp_conn)) {
    class SMTP 
    336350        if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
    337351            return false;
    338352        }
     353
     354        //Allow the best TLS version(s) we can
     355        $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;
     356
     357        //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT
     358        //so add them back in manually if we can
     359        if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {
     360            $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
     361            $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
     362        }
     363
    339364        // Begin encrypted connection
    340365        if (!stream_socket_enable_crypto(
    341366            $this->smtp_conn,
    342367            true,
    343             STREAM_CRYPTO_METHOD_TLS_CLIENT
     368            $crypto_method
    344369        )) {
    345370            return false;
    346371        }
    class SMTP 
    673698    protected function parseHelloFields($type)
    674699    {
    675700        $this->server_caps = array();
    676         $lines = explode("\n", $this->last_reply);
     701        $lines = explode("\n", $this->helo_rply);
    677702
    678703        foreach ($lines as $n => $s) {
    679704            //First 4 chars contain response code followed by - or space
    class SMTP 
    11151140    {
    11161141        return $this->Timeout;
    11171142    }
     1143
     1144    /**
     1145     * Reports an error number and string.
     1146     * @param integer $errno The error number returned by PHP.
     1147     * @param string $errmsg The error message returned by PHP.
     1148     */
     1149    protected function errorHandler($errno, $errmsg)
     1150    {
     1151        $notice = 'Connection: Failed to connect to server.';
     1152        $this->setError(
     1153            $notice,
     1154            $errno,
     1155            $errmsg
     1156        );
     1157        $this->edebug(
     1158            $notice . ' Error number ' . $errno . '. "Error notice: ' . $errmsg,
     1159            self::DEBUG_CONNECTION
     1160        );
     1161    }
     1162
     1163        /**
     1164         * Will return the ID of the last smtp transaction based on a list of patterns provided
     1165         * in SMTP::$smtp_transaction_id_patterns.
     1166         * If no reply has been received yet, it will return null.
     1167         * If no pattern has been matched, it will return false.
     1168         * @return bool|null|string
     1169         */
     1170        public function getLastTransactionID()
     1171        {
     1172                $reply = $this->getLastReply();
     1173
     1174                if (empty($reply)) {
     1175                        return null;
     1176                }
     1177
     1178                foreach($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {
     1179                        if(preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
     1180                                return $matches[1];
     1181                        }
     1182                }
     1183
     1184                return false;
     1185    }
    11181186}