WordPress.org

Make WordPress Core

Ticket #21074: 21074-phpmailer-5.2.2-r23022.patch

File 21074-phpmailer-5.2.2-r23022.patch, 81.5 KB (added by bpetty, 5 years ago)

Refreshed patch based on PHPMailer 5.2.2 release.

  • wp-includes/class-phpmailer.php

    diff --git wp-includes/class-phpmailer.php wp-includes/class-phpmailer.php
    index df533c2..146bc52 100644
     
    22/*~ class.phpmailer.php
    33.---------------------------------------------------------------------------.
    44|  Software: PHPMailer - PHP email class                                    |
    5 |   Version: 5.2.1                                                          |
     5|   Version: 5.2.2                                                          |
    66|      Site: https://code.google.com/a/apache-extras.org/p/phpmailer/       |
    77| ------------------------------------------------------------------------- |
    88|     Admin: Jim Jagielski (project admininistrator)                        |
     
    2323*/
    2424
    2525/**
    26  * PHPMailer - PHP email transport class
     26 * PHPMailer - PHP email creation and transport class
    2727 * NOTE: Requires PHP version 5 or later
    2828 * @package PHPMailer
    2929 * @author Andy Prevost
     
    3131 * @author Jim Jagielski
    3232 * @copyright 2010 - 2012 Jim Jagielski
    3333 * @copyright 2004 - 2009 Andy Prevost
    34  * @version $Id: class.phpmailer.php 450 2010-06-23 16:46:33Z coolbru $
    3534 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
    3635 */
    3736
    3837if (version_compare(PHP_VERSION, '5.0.0', '<') ) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n");
    3938
     39/**
     40 * PHP email creation and transport class
     41 * @package PHPMailer
     42 */
    4043class PHPMailer {
    4144
    4245  /////////////////////////////////////////////////
    class PHPMailer { 
    9497  public $Sender            = '';
    9598
    9699  /**
     100   * Sets the Return-Path of the message.  If empty, it will
     101   * be set to either From or Sender.
     102   * @var string
     103   */
     104  public $ReturnPath        = '';
     105
     106  /**
    97107   * Sets the Subject of the message.
    98108   * @var string
    99109   */
    class PHPMailer { 
    130140  protected $MIMEHeader     = '';
    131141
    132142  /**
    133    * Stores the complete sent MIME message (Body and Headers)
     143   * Stores the extra header list which CreateHeader() doesn't fold in
    134144   * @var string
    135145   * @access protected
    136146  */
    137   protected $SentMIMEMessage     = '';
     147  protected $mailHeader     = '';
    138148
    139149  /**
    140150   * Sets word wrapping on the body of the message to a given number of
    class PHPMailer { 
    156166  public $Sendmail          = '/usr/sbin/sendmail';
    157167
    158168  /**
     169   * Determine if mail() uses a fully sendmail compatible MTA that
     170   * supports sendmail's "-oi -f" options
     171   * @var boolean
     172   */
     173  public $UseSendmailOptions    = true;
     174 
     175  /**
    159176   * Path to PHPMailer plugins.  Useful if the SMTP class
    160177   * is in a different directory than the PHP include path.
    161178   * @var string
    class PHPMailer { 
    183200   */
    184201  public $MessageID         = '';
    185202
     203  /**
     204   * Sets the message Date to be used in the Date header.
     205   * If empty, the current date will be added.
     206   * @var string
     207   */
     208  public $MessageDate       = '';
     209
    186210  /////////////////////////////////////////////////
    187211  // PROPERTIES FOR SMTP
    188212  /////////////////////////////////////////////////
    189213
    190214  /**
    191    * Sets the SMTP hosts.  All hosts must be separated by a
     215   * Sets the SMTP hosts.
     216   *
     217   * All hosts must be separated by a
    192218   * semicolon.  You can also specify a different port
    193219   * for each host by using this format: [hostname:port]
    194220   * (e.g. "smtp1.example.com:25;smtp2.example.com").
    class PHPMailer { 
    210236  public $Helo          = '';
    211237
    212238  /**
    213    * Sets connection prefix.
    214    * Options are "", "ssl" or "tls"
     239   * Sets connection prefix. Options are "", "ssl" or "tls"
    215240   * @var string
    216241   */
    217242  public $SMTPSecure    = '';
    class PHPMailer { 
    235260  public $Password      = '';
    236261
    237262  /**
     263   *  Sets SMTP auth type. Options are LOGIN | PLAIN | NTLM  (default LOGIN)
     264   *  @var string
     265   */
     266  public $AuthType      = '';
     267 
     268  /**
     269   *  Sets SMTP realm.
     270   *  @var string
     271   */
     272  public $Realm         = '';
     273
     274  /**
     275   *  Sets SMTP workstation.
     276   *  @var string
     277   */
     278  public $Workstation   = '';
     279
     280  /**
    238281   * Sets the SMTP server timeout in seconds.
    239282   * This function will not work with the win32 version.
    240283   * @var int
    class PHPMailer { 
    248291  public $SMTPDebug     = false;
    249292
    250293  /**
     294   * Sets the function/method to use for debugging output.
     295   * Right now we only honor "echo" or "error_log"
     296   * @var string
     297   */
     298  public $Debugoutput     = "echo";
     299
     300  /**
    251301   * Prevents the SMTP connection from being closed after each mail
    252302   * sending.  If this is set to true then to close the connection
    253303   * requires an explicit call to SmtpClose().
    class PHPMailer { 
    269319  public $SingleToArray = array();
    270320
    271321 /**
    272    * Provides the ability to change the line ending
     322   * Provides the ability to change the generic line ending
     323   * NOTE: The default remains '\n'. We force CRLF where we KNOW
     324   *        it must be used via self::CRLF
    273325   * @var string
    274326   */
    275327  public $LE              = "\n";
    276328
    277   /**
    278    * Used with DKIM DNS Resource Record
     329   /**
     330   * Used with DKIM Signing
     331   * required parameter if DKIM is enabled
     332   *
     333   * domain selector example domainkey
    279334   * @var string
    280335   */
    281   public $DKIM_selector   = 'phpmailer';
     336  public $DKIM_selector   = '';
    282337
    283338  /**
    284    * Used with DKIM DNS Resource Record
    285    * optional, in format of email address 'you@yourdomain.com'
     339   * Used with DKIM Signing
     340   * required if DKIM is enabled, in format of email address 'you@yourdomain.com' typically used as the source of the email
    286341   * @var string
    287342   */
    288343  public $DKIM_identity   = '';
    289344
    290345  /**
    291    * Used with DKIM DNS Resource Record
     346   * Used with DKIM Signing
     347   * optional parameter if your private key requires a passphras
    292348   * @var string
    293349   */
    294350  public $DKIM_passphrase   = '';
    295351
    296352  /**
    297    * Used with DKIM DNS Resource Record
    298    * optional, in format of email address 'you@yourdomain.com'
     353   * Used with DKIM Singing
     354   * required if DKIM is enabled, in format of email address 'domain.com'
    299355   * @var string
    300356   */
    301357  public $DKIM_domain     = '';
    302358
    303359  /**
    304    * Used with DKIM DNS Resource Record
    305    * optional, in format of email address 'you@yourdomain.com'
     360   * Used with DKIM Signing
     361   * required if DKIM is enabled, path to private key file
    306362   * @var string
    307363   */
    308364  public $DKIM_private    = '';
    309365
    310366  /**
    311    * Callback Action function name
    312    * the function that handles the result of the send email action. Parameters:
     367   * Callback Action function name.
     368   * The function that handles the result of the send email action.
     369   * It is called out by Send() for each email sent.
     370   *
     371   * Value can be:
     372   * - 'function_name' for function names
     373   * - 'Class::Method' for static method calls
     374   * - array($object, 'Method') for calling methods on $object
     375   * See http://php.net/is_callable manual page for more details.
     376   *
     377   * Parameters:
    313378   *   bool    $result        result of the send action
    314379   *   string  $to            email address of the recipient
    315380   *   string  $cc            cc email addresses
    316381   *   string  $bcc           bcc email addresses
    317382   *   string  $subject       the subject
    318383   *   string  $body          the email body
     384   *   string  $from          email address of sender
    319385   * @var string
    320386   */
    321387  public $action_function = ''; //'callbackAction';
    class PHPMailer { 
    324390   * Sets the PHPMailer Version number
    325391   * @var string
    326392   */
    327   public $Version         = '5.2.1';
     393  public $Version         = '5.2.2';
    328394
    329395  /**
    330396   * What to use in the X-Mailer header
    331    * @var string
     397   * @var string NULL for default, whitespace for None, or actual string to use
    332398   */
    333399  public $XMailer         = '';
    334400
    class PHPMailer { 
    336402  // PROPERTIES, PRIVATE AND PROTECTED
    337403  /////////////////////////////////////////////////
    338404
    339   protected   $smtp           = NULL;
     405  /**
     406   * @var SMTP An instance of the SMTP sender class
     407   * @access protected
     408   */
     409  protected   $smtp           = null;
     410  /**
     411   * @var array An array of 'to' addresses
     412   * @access protected
     413   */
    340414  protected   $to             = array();
     415  /**
     416   * @var array An array of 'cc' addresses
     417   * @access protected
     418   */
    341419  protected   $cc             = array();
     420  /**
     421   * @var array An array of 'bcc' addresses
     422   * @access protected
     423   */
    342424  protected   $bcc            = array();
     425  /**
     426   * @var array An array of reply-to name and address
     427   * @access protected
     428   */
    343429  protected   $ReplyTo        = array();
     430  /**
     431   * @var array An array of all kinds of addresses: to, cc, bcc, replyto
     432   * @access protected
     433   */
    344434  protected   $all_recipients = array();
     435  /**
     436   * @var array An array of attachments
     437   * @access protected
     438   */
    345439  protected   $attachment     = array();
     440  /**
     441   * @var array An array of custom headers
     442   * @access protected
     443   */
    346444  protected   $CustomHeader   = array();
     445  /**
     446   * @var string The message's MIME type
     447   * @access protected
     448   */
    347449  protected   $message_type   = '';
     450  /**
     451   * @var array An array of MIME boundary strings
     452   * @access protected
     453   */
    348454  protected   $boundary       = array();
     455  /**
     456   * @var array An array of available languages
     457   * @access protected
     458   */
    349459  protected   $language       = array();
     460  /**
     461   * @var integer The number of errors encountered
     462   * @access protected
     463   */
    350464  protected   $error_count    = 0;
     465  /**
     466   * @var string The filename of a DKIM certificate file
     467   * @access protected
     468   */
    351469  protected   $sign_cert_file = '';
     470  /**
     471   * @var string The filename of a DKIM key file
     472   * @access protected
     473   */
    352474  protected   $sign_key_file  = '';
     475  /**
     476   * @var string The password of a DKIM key
     477   * @access protected
     478   */
    353479  protected   $sign_key_pass  = '';
     480  /**
     481   * @var boolean Whether to throw exceptions for errors
     482   * @access protected
     483   */
    354484  protected   $exceptions     = false;
    355485
    356486  /////////////////////////////////////////////////
    class PHPMailer { 
    360490  const STOP_MESSAGE  = 0; // message only, continue processing
    361491  const STOP_CONTINUE = 1; // message?, likely ok to continue processing
    362492  const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
    363 
     493  const CRLF = "\r\n";     // SMTP RFC specified EOL
     494 
    364495  /////////////////////////////////////////////////
    365496  // METHODS, VARIABLES
    366497  /////////////////////////////////////////////////
    367498
    368499  /**
     500   * Calls actual mail() function, but in a safe_mode aware fashion
     501   * Also, unless sendmail_path points to sendmail (or something that
     502   * claims to be sendmail), don't pass params (not a perfect fix,
     503   * but it will do)
     504   * @param string $to To
     505   * @param string $subject Subject
     506   * @param string $body Message Body
     507   * @param string $header Additional Header(s)
     508   * @param string $params Params
     509   * @access private
     510   * @return bool
     511   */
     512  private function mail_passthru($to, $subject, $body, $header, $params) {
     513    if ( ini_get('safe_mode') || !($this->UseSendmailOptions) ) {
     514        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header);
     515    } else {
     516        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params);
     517    }
     518    return $rt;
     519  }
     520
     521  /**
     522   * Outputs debugging info via user-defined method
     523   * @param string $str
     524   */
     525  private function edebug($str) {
     526    if ($this->Debugoutput == "error_log") {
     527        error_log($str);
     528    } else {
     529        echo $str;
     530    }
     531  }
     532
     533  /**
    369534   * Constructor
    370535   * @param boolean $exceptions Should we throw external exceptions?
    371536   */
    class PHPMailer { 
    389554  /**
    390555   * Sets Mailer to send message using SMTP.
    391556   * @return void
     557   * @deprecated
    392558   */
    393559  public function IsSMTP() {
    394560    $this->Mailer = 'smtp';
    class PHPMailer { 
    397563  /**
    398564   * Sets Mailer to send message using PHP mail() function.
    399565   * @return void
     566   * @deprecated
    400567   */
    401568  public function IsMail() {
    402569    $this->Mailer = 'mail';
    class PHPMailer { 
    405572  /**
    406573   * Sets Mailer to send message using the $Sendmail program.
    407574   * @return void
     575   * @deprecated
    408576   */
    409577  public function IsSendmail() {
    410578    if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
    class PHPMailer { 
    416584  /**
    417585   * Sets Mailer to send message using the qmail MTA.
    418586   * @return void
     587   * @deprecated
    419588   */
    420589  public function IsQmail() {
    421590    if (stristr(ini_get('sendmail_path'), 'qmail')) {
    class PHPMailer { 
    476645   * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
    477646   * @param string $address The email address to send to
    478647   * @param string $name
     648   * @throws phpmailerException
    479649   * @return boolean true on success, false if address already used or invalid in some way
    480650   * @access protected
    481651   */
    class PHPMailer { 
    485655      if ($this->exceptions) {
    486656        throw new phpmailerException('Invalid recipient array: ' . $kind);
    487657      }
    488           if ($this->SMTPDebug) {
    489         echo $this->Lang('Invalid recipient array').': '.$kind;
     658      if ($this->SMTPDebug) {
     659        $this->edebug($this->Lang('Invalid recipient array').': '.$kind);
    490660      }
    491661      return false;
    492662    }
    493663    $address = trim($address);
    494664    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
    495     if (!self::ValidateAddress($address)) {
     665    if (!$this->ValidateAddress($address)) {
    496666      $this->SetError($this->Lang('invalid_address').': '. $address);
    497667      if ($this->exceptions) {
    498668        throw new phpmailerException($this->Lang('invalid_address').': '.$address);
    499669      }
    500           if ($this->SMTPDebug) {
    501         echo $this->Lang('invalid_address').': '.$address;
     670      if ($this->SMTPDebug) {
     671        $this->edebug($this->Lang('invalid_address').': '.$address);
    502672      }
    503673      return false;
    504674    }
    class PHPMailer { 
    521691 * Set the From and FromName properties
    522692 * @param string $address
    523693 * @param string $name
     694 * @param int $auto Also set Reply-To and Sender
     695   * @throws phpmailerException
    524696 * @return boolean
    525697 */
    526698  public function SetFrom($address, $name = '', $auto = 1) {
    527699    $address = trim($address);
    528700    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
    529     if (!self::ValidateAddress($address)) {
     701    if (!$this->ValidateAddress($address)) {
    530702      $this->SetError($this->Lang('invalid_address').': '. $address);
    531703      if ($this->exceptions) {
    532704        throw new phpmailerException($this->Lang('invalid_address').': '.$address);
    533705      }
    534           if ($this->SMTPDebug) {
    535         echo $this->Lang('invalid_address').': '.$address;
     706      if ($this->SMTPDebug) {
     707        $this->edebug($this->Lang('invalid_address').': '.$address);
    536708      }
    537709      return false;
    538710    }
    class PHPMailer { 
    551723
    552724  /**
    553725   * Check that a string looks roughly like an email address should
    554    * Static so it can be used without instantiation
    555    * Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator
    556    * Conforms approximately to RFC2822
    557    * @link http://www.hexillion.com/samples/#Regex Original pattern found here
     726   * Static so it can be used without instantiation, public so people can overload
     727   * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is
     728   * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to
     729   * not allow a@b type valid addresses :(
     730   * @link http://squiloople.com/2009/12/20/email-address-validation/
     731   * @copyright regex Copyright Michael Rushton 2009-10 | http://squiloople.com/ | Feel free to use and redistribute this code. But please keep this copyright notice.
    558732   * @param string $address The email address to check
    559733   * @return boolean
    560734   * @static
    561735   * @access public
    562736   */
    563737  public static function ValidateAddress($address) {
    564     if (function_exists('filter_var')) { //Introduced in PHP 5.2
    565       if(filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) {
    566         return false;
    567       } else {
    568         return true;
    569       }
    570     } else {
    571       return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address);
    572     }
     738        return preg_match('/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\x0D\x0A)?[       ])+|(?>[        ]*\x0D\x0A)?[   ]+)?)(\((?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f0-9][:\]]){7,})((?6)(?>:(?6)){0,5})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f0-9]:){5,})(?8)?::(?>((?6)(?>:(?6)){0,3}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address);
    573739  }
    574740
    575741  /////////////////////////////////////////////////
    class PHPMailer { 
    580746   * Creates message and assigns Mailer. If the message is
    581747   * not sent successfully then it returns false.  Use the ErrorInfo
    582748   * variable to view description of the error.
     749   * @throws phpmailerException
    583750   * @return bool
    584751   */
    585752  public function Send() {
    class PHPMailer { 
    587754      if(!$this->PreSend()) return false;
    588755      return $this->PostSend();
    589756    } catch (phpmailerException $e) {
    590           $this->SentMIMEMessage = '';
     757      $this->mailHeader = '';
    591758      $this->SetError($e->getMessage());
    592759      if ($this->exceptions) {
    593760        throw $e;
    class PHPMailer { 
    596763    }
    597764  }
    598765
    599   protected function PreSend() {
     766  /**
     767   * Prep mail by constructing all message entities
     768   * @throws phpmailerException
     769   * @return bool
     770   */
     771  public function PreSend() {
    600772    try {
    601           $mailHeader = "";
     773      $this->mailHeader = "";
    602774      if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
    603775        throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
    604776      }
    class PHPMailer { 
    619791      $this->MIMEBody = $this->CreateBody();
    620792
    621793      // To capture the complete message when using mail(), create
    622           // an extra header list which CreateHeader() doesn't fold in
     794      // an extra header list which CreateHeader() doesn't fold in
    623795      if ($this->Mailer == 'mail') {
    624796        if (count($this->to) > 0) {
    625           $mailHeader .= $this->AddrAppend("To", $this->to);
     797          $this->mailHeader .= $this->AddrAppend("To", $this->to);
    626798        } else {
    627           $mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;");
     799          $this->mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;");
    628800        }
    629         $mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject))));
     801        $this->mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject))));
    630802        // if(count($this->cc) > 0) {
    631             // $mailHeader .= $this->AddrAppend("Cc", $this->cc);
     803            // $this->mailHeader .= $this->AddrAppend("Cc", $this->cc);
    632804        // }
    633805      }
    634806
    635807      // digitally sign with DKIM if enabled
    636       if ($this->DKIM_domain && $this->DKIM_private) {
     808      if (!empty($this->DKIM_domain) && !empty($this->DKIM_private) && !empty($this->DKIM_selector) && !empty($this->DKIM_domain) && file_exists($this->DKIM_private)) {
    637809        $header_dkim = $this->DKIM_Add($this->MIMEHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody);
    638810        $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader;
    639811      }
    640812
    641       $this->SentMIMEMessage = sprintf("%s%s\r\n\r\n%s",$this->MIMEHeader,$mailHeader,$this->MIMEBody);
    642813      return true;
    643814
    644815    } catch (phpmailerException $e) {
    class PHPMailer { 
    650821    }
    651822  }
    652823
    653   protected function PostSend() {
     824  /**
     825   * Actual Email transport function
     826   * Send the email via the selected mechanism
     827   * @throws phpmailerException
     828   * @return bool
     829   */
     830  public function PostSend() {
    654831    try {
    655832      // Choose the mailer and send through it
    656833      switch($this->Mailer) {
    class PHPMailer { 
    663840        default:
    664841          return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
    665842      }
    666 
    667843    } catch (phpmailerException $e) {
    668844      $this->SetError($e->getMessage());
    669845      if ($this->exceptions) {
    670846        throw $e;
    671847      }
    672           if ($this->SMTPDebug) {
    673         echo $e->getMessage()."\n";
     848      if ($this->SMTPDebug) {
     849        $this->edebug($e->getMessage()."\n");
    674850      }
    675       return false;
    676851    }
     852    return false;
    677853  }
    678854
    679855  /**
    680856   * Sends mail using the $Sendmail program.
    681857   * @param string $header The message headers
    682858   * @param string $body The message body
     859   * @throws phpmailerException
    683860   * @access protected
    684861   * @return bool
    685862   */
    686863  protected function SendmailSend($header, $body) {
    687864    if ($this->Sender != '') {
    688       $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
     865      $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
    689866    } else {
    690867      $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
    691868    }
    692869    if ($this->SingleTo === true) {
    693       foreach ($this->SingleToArray as $key => $val) {
     870      foreach ($this->SingleToArray as $val) {
    694871        if(!@$mail = popen($sendmail, 'w')) {
    695872          throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
    696873        }
    class PHPMailer { 
    726903   * Sends mail using the PHP mail() function.
    727904   * @param string $header The message headers
    728905   * @param string $body The message body
     906     * @throws phpmailerException
    729907   * @access protected
    730908   * @return bool
    731909   */
    class PHPMailer { 
    739917    if (empty($this->Sender)) {
    740918      $params = "-oi ";
    741919    } else {
    742       $params = sprintf("-oi -f %s", $this->Sender);
     920      $params = sprintf("-oi -f%s", $this->Sender);
    743921    }
    744922    if ($this->Sender != '' and !ini_get('safe_mode')) {
    745923      $old_from = ini_get('sendmail_from');
    746924      ini_set('sendmail_from', $this->Sender);
    747       if ($this->SingleTo === true && count($toArr) > 1) {
    748         foreach ($toArr as $key => $val) {
    749           $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
    750           // implement call back function if it exists
    751           $isSent = ($rt == 1) ? 1 : 0;
    752           $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
    753         }
    754       } else {
    755         $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
     925    }
     926      $rt = false;
     927    if ($this->SingleTo === true && count($toArr) > 1) {
     928      foreach ($toArr as $val) {
     929        $rt = $this->mail_passthru($val, $this->Subject, $body, $header, $params);
    756930        // implement call back function if it exists
    757931        $isSent = ($rt == 1) ? 1 : 0;
    758         $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
     932        $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
    759933      }
    760934    } else {
    761       if ($this->SingleTo === true && count($toArr) > 1) {
    762         foreach ($toArr as $key => $val) {
    763           $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);
    764           // implement call back function if it exists
    765           $isSent = ($rt == 1) ? 1 : 0;
    766           $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
    767         }
    768       } else {
    769         $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);
    770         // implement call back function if it exists
    771         $isSent = ($rt == 1) ? 1 : 0;
    772         $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
    773       }
     935      $rt = $this->mail_passthru($to, $this->Subject, $body, $header, $params);
     936      // implement call back function if it exists
     937      $isSent = ($rt == 1) ? 1 : 0;
     938      $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
    774939    }
    775940    if (isset($old_from)) {
    776941      ini_set('sendmail_from', $old_from);
    class PHPMailer { 
    786951   * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
    787952   * @param string $header The message headers
    788953   * @param string $body The message body
     954   * @throws phpmailerException
    789955   * @uses SMTP
    790956   * @access protected
    791957   * @return bool
    class PHPMailer { 
    8501016    }
    8511017    if($this->SMTPKeepAlive == true) {
    8521018      $this->smtp->Reset();
     1019    } else {
     1020        $this->smtp->Quit();
     1021        $this->smtp->Close();
    8531022    }
    8541023    return true;
    8551024  }
    class PHPMailer { 
    8591028   * Returns false if the operation failed.
    8601029   * @uses SMTP
    8611030   * @access public
     1031   * @throws phpmailerException
    8621032   * @return bool
    8631033   */
    8641034  public function SmtpConnect() {
    8651035    if(is_null($this->smtp)) {
    866       $this->smtp = new SMTP();
     1036      $this->smtp = new SMTP;
    8671037    }
    8681038
     1039    $this->smtp->Timeout = $this->Timeout;
    8691040    $this->smtp->do_debug = $this->SMTPDebug;
    8701041    $hosts = explode(';', $this->Host);
    8711042    $index = 0;
    class PHPMailer { 
    9021073
    9031074          $connection = true;
    9041075          if ($this->SMTPAuth) {
    905             if (!$this->smtp->Authenticate($this->Username, $this->Password)) {
     1076            if (!$this->smtp->Authenticate($this->Username, $this->Password, $this->AuthType,
     1077                                           $this->Realm, $this->Workstation)) {
    9061078              throw new phpmailerException($this->Lang('authenticate'));
    9071079            }
    9081080          }
    9091081        }
    9101082        $index++;
    911         if (!$connection) {
    912           throw new phpmailerException($this->Lang('connect_host'));
    913         }
     1083      if (!$connection) {
     1084        throw new phpmailerException($this->Lang('connect_host'));
     1085      }
    9141086      }
    9151087    } catch (phpmailerException $e) {
    9161088      $this->smtp->Reset();
    917           if ($this->exceptions) {
     1089      if ($this->exceptions) {
    9181090        throw $e;
    9191091      }
    9201092    }
    class PHPMailer { 
    9261098   * @return void
    9271099   */
    9281100  public function SmtpClose() {
    929     if(!is_null($this->smtp)) {
     1101    if ($this->smtp !== null) {
    9301102      if($this->smtp->Connected()) {
    9311103        $this->smtp->Quit();
    9321104        $this->smtp->Close();
    class PHPMailer { 
    9391111  * Returns false if it cannot load the language file.  The default language is English.
    9401112  * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
    9411113  * @param string $lang_path Path to the language file directory
     1114   * @return bool
    9421115  * @access public
    9431116  */
    9441117  function SetLanguage($langcode = 'en', $lang_path = 'language/') {
    9451118    //Define full set of translatable strings
    9461119    $PHPMAILER_LANG = array(
    947       'provide_address' => 'You must provide at least one recipient email address.',
     1120      'authenticate'         => 'SMTP Error: Could not authenticate.',
     1121      'connect_host'         => 'SMTP Error: Could not connect to SMTP host.',
     1122      'data_not_accepted'    => 'SMTP Error: Data not accepted.',
     1123      'empty_message'        => 'Message body empty',
     1124      'encoding'             => 'Unknown encoding: ',
     1125      'execute'              => 'Could not execute: ',
     1126      'file_access'          => 'Could not access file: ',
     1127      'file_open'            => 'File Error: Could not open file: ',
     1128      'from_failed'          => 'The following From address failed: ',
     1129      'instantiate'          => 'Could not instantiate mail function.',
     1130      'invalid_address'      => 'Invalid address',
    9481131      'mailer_not_supported' => ' mailer is not supported.',
    949       'execute' => 'Could not execute: ',
    950       'instantiate' => 'Could not instantiate mail function.',
    951       'authenticate' => 'SMTP Error: Could not authenticate.',
    952       'from_failed' => 'The following From address failed: ',
    953       'recipients_failed' => 'SMTP Error: The following recipients failed: ',
    954       'data_not_accepted' => 'SMTP Error: Data not accepted.',
    955       'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
    956       'file_access' => 'Could not access file: ',
    957       'file_open' => 'File Error: Could not open file: ',
    958       'encoding' => 'Unknown encoding: ',
    959       'signing' => 'Signing Error: ',
    960       'smtp_error' => 'SMTP server error: ',
    961       'empty_message' => 'Message body empty',
    962       'invalid_address' => 'Invalid address',
    963       'variable_set' => 'Cannot set or reset variable: '
     1132      'provide_address'      => 'You must provide at least one recipient email address.',
     1133      'recipients_failed'    => 'SMTP Error: The following recipients failed: ',
     1134      'signing'              => 'Signing Error: ',
     1135      'smtp_connect_failed'  => 'SMTP Connect() failed.',
     1136      'smtp_error'           => 'SMTP server error: ',
     1137      'variable_set'         => 'Cannot set or reset variable: '
    9641138    );
    9651139    //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
    9661140    $l = true;
    class PHPMailer { 
    9861160  /**
    9871161   * Creates recipient headers.
    9881162   * @access public
     1163   * @param string $type
     1164   * @param array $addr
    9891165   * @return string
    9901166   */
    9911167  public function AddrAppend($type, $addr) {
    class PHPMailer { 
    10031179  /**
    10041180   * Formats an address correctly.
    10051181   * @access public
     1182   * @param string $addr
    10061183   * @return string
    10071184   */
    10081185  public function AddrFormat($addr) {
    class PHPMailer { 
    10281205    // If utf-8 encoding is used, we will need to make sure we don't
    10291206    // split multibyte characters when we wrap
    10301207    $is_utf8 = (strtolower($this->CharSet) == "utf-8");
     1208    $lelen = strlen($this->LE);
     1209    $crlflen = strlen(self::CRLF);
    10311210
    10321211    $message = $this->FixEOL($message);
    1033     if (substr($message, -1) == $this->LE) {
    1034       $message = substr($message, 0, -1);
     1212    if (substr($message, -$lelen) == $this->LE) {
     1213      $message = substr($message, 0, -$lelen);
    10351214    }
    10361215
    1037     $line = explode($this->LE, $message);
     1216    $line = explode($this->LE, $message);   // Magic. We know FixEOL uses $LE
    10381217    $message = '';
    10391218    for ($i = 0 ;$i < count($line); $i++) {
    10401219      $line_part = explode(' ', $line[$i]);
    class PHPMailer { 
    10421221      for ($e = 0; $e<count($line_part); $e++) {
    10431222        $word = $line_part[$e];
    10441223        if ($qp_mode and (strlen($word) > $length)) {
    1045           $space_left = $length - strlen($buf) - 1;
     1224          $space_left = $length - strlen($buf) - $crlflen;
    10461225          if ($e != 0) {
    10471226            if ($space_left > 20) {
    10481227              $len = $space_left;
    class PHPMailer { 
    10561235              $part = substr($word, 0, $len);
    10571236              $word = substr($word, $len);
    10581237              $buf .= ' ' . $part;
    1059               $message .= $buf . sprintf("=%s", $this->LE);
     1238              $message .= $buf . sprintf("=%s", self::CRLF);
    10601239            } else {
    10611240              $message .= $buf . $soft_break;
    10621241            }
    class PHPMailer { 
    10751254            $word = substr($word, $len);
    10761255
    10771256            if (strlen($word) > 0) {
    1078               $message .= $part . sprintf("=%s", $this->LE);
     1257              $message .= $part . sprintf("=%s", self::CRLF);
    10791258            } else {
    10801259              $buf = $part;
    10811260            }
    class PHPMailer { 
    10901269          }
    10911270        }
    10921271      }
    1093       $message .= $buf . $this->LE;
     1272      $message .= $buf . self::CRLF;
    10941273    }
    10951274
    10961275    return $message;
    class PHPMailer { 
    11751354    $this->boundary[2] = 'b2_' . $uniq_id;
    11761355    $this->boundary[3] = 'b3_' . $uniq_id;
    11771356
    1178     $result .= $this->HeaderLine('Date', self::RFCDate());
    1179     if($this->Sender == '') {
     1357    if ($this->MessageDate == '') {
     1358      $result .= $this->HeaderLine('Date', self::RFCDate());
     1359    } else {
     1360      $result .= $this->HeaderLine('Date', $this->MessageDate);
     1361    }
     1362
     1363    if ($this->ReturnPath) {
     1364      $result .= $this->HeaderLine('Return-Path', trim($this->ReturnPath));
     1365    } elseif ($this->Sender == '') {
    11801366      $result .= $this->HeaderLine('Return-Path', trim($this->From));
    11811367    } else {
    11821368      $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
    class PHPMailer { 
    11951381          $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
    11961382        }
    11971383      }
    1198         }
     1384    }
    11991385
    12001386    $from = array();
    12011387    $from[0][0] = trim($this->From);
    class PHPMailer { 
    12271413      $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
    12281414    }
    12291415    $result .= $this->HeaderLine('X-Priority', $this->Priority);
    1230     if($this->XMailer) {
    1231       $result .= $this->HeaderLine('X-Mailer', $this->XMailer);
     1416    if ($this->XMailer == '') {
     1417        $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (http://code.google.com/a/apache-extras.org/p/phpmailer/)');
    12321418    } else {
    1233       $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (http://code.google.com/a/apache-extras.org/p/phpmailer/)');
     1419      $myXmailer = trim($this->XMailer);
     1420      if ($myXmailer) {
     1421        $result .= $this->HeaderLine('X-Mailer', $myXmailer);
     1422      }
    12341423    }
    12351424
    12361425    if($this->ConfirmReadingTo != '') {
    class PHPMailer { 
    12571446  public function GetMailMIME() {
    12581447    $result = '';
    12591448    switch($this->message_type) {
    1260       case 'plain':
    1261         $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
    1262         $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset="'.$this->CharSet.'"');
    1263         break;
    12641449      case 'inline':
    12651450        $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
    12661451        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
    class PHPMailer { 
    12771462        $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
    12781463        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
    12791464        break;
     1465      default:
     1466        // Catches case 'plain': and case '':
     1467        $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
     1468        $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset='.$this->CharSet);
     1469        break;
    12801470    }
    12811471
    12821472    if($this->Mailer != 'mail') {
    1283       $result .= $this->LE.$this->LE;
     1473      $result .= $this->LE;
    12841474    }
    12851475
    12861476    return $result;
    class PHPMailer { 
    12921482   * @return string
    12931483   */
    12941484  public function GetSentMIMEMessage() {
    1295     return $this->SentMIMEMessage;
     1485    return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
    12961486  }
    12971487
    12981488
    12991489  /**
    13001490   * Assembles the message body.  Returns an empty string on failure.
    13011491   * @access public
     1492   * @throws phpmailerException
    13021493   * @return string The assembled message body
    13031494   */
    13041495  public function CreateBody() {
    13051496    $body = '';
    13061497
    13071498    if ($this->sign_key_file) {
    1308       $body .= $this->GetMailMIME();
     1499      $body .= $this->GetMailMIME().$this->LE;
    13091500    }
    13101501
    13111502    $this->SetWordWrap();
    13121503
    13131504    switch($this->message_type) {
    1314       case 'plain':
    1315         $body .= $this->EncodeString($this->Body, $this->Encoding);
    1316         break;
    13171505      case 'inline':
    13181506        $body .= $this->GetBoundary($this->boundary[1], '', '', '');
    13191507        $body .= $this->EncodeString($this->Body, $this->Encoding);
    class PHPMailer { 
    13981586        $body .= $this->LE;
    13991587        $body .= $this->AttachAll("attachment", $this->boundary[1]);
    14001588        break;
     1589      default:
     1590        // catch case 'plain' and case ''
     1591        $body .= $this->EncodeString($this->Body, $this->Encoding);
     1592        break;
    14011593    }
    14021594
    14031595    if ($this->IsError()) {
    class PHPMailer { 
    14301622  /**
    14311623   * Returns the start of a message boundary.
    14321624   * @access protected
     1625   * @param string $boundary
     1626   * @param string $charSet
     1627   * @param string $contentType
     1628   * @param string $encoding
    14331629   * @return string
    14341630   */
    14351631  protected function GetBoundary($boundary, $charSet, $contentType, $encoding) {
    class PHPMailer { 
    14441640      $encoding = $this->Encoding;
    14451641    }
    14461642    $result .= $this->TextLine('--' . $boundary);
    1447     $result .= sprintf("Content-Type: %s; charset=\"%s\"", $contentType, $charSet);
     1643    $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet);
    14481644    $result .= $this->LE;
    14491645    $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
    14501646    $result .= $this->LE;
    class PHPMailer { 
    14551651  /**
    14561652   * Returns the end of a message boundary.
    14571653   * @access protected
     1654   * @param string $boundary
    14581655   * @return string
    14591656   */
    14601657  protected function EndBoundary($boundary) {
    class PHPMailer { 
    14781675  /**
    14791676   *  Returns a formatted header line.
    14801677   * @access public
     1678   * @param string $name
     1679   * @param string $value
    14811680   * @return string
    14821681   */
    14831682  public function HeaderLine($name, $value) {
    class PHPMailer { 
    14871686  /**
    14881687   * Returns a formatted mail line.
    14891688   * @access public
     1689   * @param string $value
    14901690   * @return string
    14911691   */
    14921692  public function TextLine($value) {
    class PHPMailer { 
    15051705   * @param string $name Overrides the attachment name.
    15061706   * @param string $encoding File encoding (see $Encoding).
    15071707   * @param string $type File extension (MIME) type.
     1708   * @throws phpmailerException
    15081709   * @return bool
    15091710   */
    15101711  public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
    class PHPMailer { 
    15331734      if ($this->exceptions) {
    15341735        throw $e;
    15351736      }
    1536           if ($this->SMTPDebug) {
    1537         echo $e->getMessage()."\n";
     1737      if ($this->SMTPDebug) {
     1738        $this->edebug($e->getMessage()."\n");
    15381739      }
    15391740      if ( $e->getCode() == self::STOP_CRITICAL ) {
    15401741        return false;
    class PHPMailer { 
    15551756   * Attaches all fs, string, and binary attachments to the message.
    15561757   * Returns an empty string on failure.
    15571758   * @access protected
     1759   * @param string $disposition_type
     1760   * @param string $boundary
    15581761   * @return string
    15591762   */
    15601763  protected function AttachAll($disposition_type, $boundary) {
    class PHPMailer { 
    15681771      // CHECK IF IT IS A VALID DISPOSITION_FILTER
    15691772      if($attachment[6] == $disposition_type) {
    15701773        // Check for string attachment
     1774        $string = '';
     1775        $path = '';
    15711776        $bString = $attachment[5];
    15721777        if ($bString) {
    15731778          $string = $attachment[0];
    class PHPMailer { 
    16241829   * Returns an empty string on failure.
    16251830   * @param string $path The full path to the file
    16261831   * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
     1832   * @throws phpmailerException
    16271833   * @see EncodeFile()
    16281834   * @access protected
    16291835   * @return string
    class PHPMailer { 
    16331839      if (!is_readable($path)) {
    16341840        throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
    16351841      }
    1636       if (function_exists('get_magic_quotes')) {
    1637         function get_magic_quotes() {
    1638           return false;
    1639         }
    1640       }
    1641           $magic_quotes = get_magic_quotes_runtime();
    1642           if ($magic_quotes) {
     1842      //  if (!function_exists('get_magic_quotes')) {
     1843      //    function get_magic_quotes() {
     1844      //      return false;
     1845      //    }
     1846      //  }
     1847      $magic_quotes = get_magic_quotes_runtime();
     1848      if ($magic_quotes) {
    16431849        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
    16441850          set_magic_quotes_runtime(0);
    16451851        } else {
    1646                   ini_set('magic_quotes_runtime', 0);
    1647                 }
    1648           }
     1852          ini_set('magic_quotes_runtime', 0);
     1853        }
     1854      }
    16491855      $file_buffer  = file_get_contents($path);
    16501856      $file_buffer  = $this->EncodeString($file_buffer, $encoding);
    1651           if ($magic_quotes) {
     1857      if ($magic_quotes) {
    16521858        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
    16531859          set_magic_quotes_runtime($magic_quotes);
    16541860        } else {
    1655                   ini_set('magic_quotes_runtime', $magic_quotes);
    1656             }
    1657           }
     1861          ini_set('magic_quotes_runtime', $magic_quotes);
     1862        }
     1863      }
    16581864      return $file_buffer;
    16591865    } catch (Exception $e) {
    16601866      $this->SetError($e->getMessage());
    class PHPMailer { 
    16991905  /**
    17001906   * Encode a header string to best (shortest) of Q, B, quoted or none.
    17011907   * @access public
     1908   * @param string $str
     1909   * @param string $position
    17021910   * @return string
    17031911   */
    17041912  public function EncodeHeader($str, $position = 'text') {
    class PHPMailer { 
    17371945      if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
    17381946        // Use a custom function which correctly encodes and wraps long
    17391947        // multibyte strings without breaking lines within a character
    1740         $encoded = $this->Base64EncodeWrapMB($str);
     1948        $encoded = $this->Base64EncodeWrapMB($str, "\n");
    17411949      } else {
    17421950        $encoded = base64_encode($str);
    17431951        $maxlen -= $maxlen % 4;
    class PHPMailer { 
    17471955      $encoding = 'Q';
    17481956      $encoded = $this->EncodeQ($str, $position);
    17491957      $encoded = $this->WrapText($encoded, $maxlen, true);
    1750       $encoded = str_replace('='.$this->LE, "\n", trim($encoded));
     1958      $encoded = str_replace('='.self::CRLF, "\n", trim($encoded));
    17511959    }
    17521960
    17531961    $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
    class PHPMailer { 
    17761984   * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
    17771985   * @access public
    17781986   * @param string $str multi-byte text to wrap encode
     1987   * @param string $lf string to use as linefeed/end-of-line
    17791988   * @return string
    17801989   */
    1781   public function Base64EncodeWrapMB($str) {
     1990  public function Base64EncodeWrapMB($str, $lf=null) {
    17821991    $start = "=?".$this->CharSet."?B?";
    17831992    $end = "?=";
    17841993    $encoded = "";
     1994    if ($lf === null) {
     1995      $lf = $this->LE;
     1996    }
    17851997
    17861998    $mb_length = mb_strlen($str, $this->CharSet);
    17871999    // Each line must have length <= 75, including $start and $end
    class PHPMailer { 
    18022014      }
    18032015      while (strlen($chunk) > $length);
    18042016
    1805       $encoded .= $chunk . $this->LE;
     2017      $encoded .= $chunk . $lf;
    18062018    }
    18072019
    18082020    // Chomp the last linefeed
    1809     $encoded = substr($encoded, 0, -strlen($this->LE));
     2021    $encoded = substr($encoded, 0, -strlen($lf));
    18102022    return $encoded;
    18112023  }
    18122024
    class PHPMailer { 
    18142026  * Encode string to quoted-printable.
    18152027  * Only uses standard PHP, slow, but will always work
    18162028  * @access public
    1817   * @param string $string the text to encode
     2029   * @param string $input
    18182030  * @param integer $line_max Number of chars allowed on a line before wrapping
     2031   * @param bool $space_conv
     2032   * @internal param string $string the text to encode
    18192033  * @return string
    18202034  */
    18212035  public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) {
    class PHPMailer { 
    18402054            $c = '=20';
    18412055          }
    18422056        } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
    1843           $h2 = floor($dec/16);
    1844           $h1 = floor($dec%16);
     2057          $h2 = (integer)floor($dec/16);
     2058          $h1 = (integer)floor($dec%16);
    18452059          $c = $escape.$hex[$h2].$hex[$h1];
    18462060        }
    18472061        if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
    class PHPMailer { 
    19012115   * @return string
    19022116   */
    19032117  public function EncodeQ($str, $position = 'text') {
    1904     // There should not be any EOL in the string
    1905     $encoded = preg_replace('/[\r\n]*/', '', $str);
    1906 
     2118    //There should not be any EOL in the string
     2119        $pattern="";
     2120    $encoded = str_replace(array("\r", "\n"), '', $str);
    19072121    switch (strtolower($position)) {
    19082122      case 'phrase':
    1909         $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
     2123        $pattern = '^A-Za-z0-9!*+\/ -';
    19102124        break;
     2125
    19112126      case 'comment':
    1912         $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded);
     2127        $pattern = '\(\)"';
     2128        //note that we dont break here!
     2129        //for this reason we build the $pattern withoud including delimiters and []
     2130
    19132131      case 'text':
    19142132      default:
    1915         // Replace every high ascii, control =, ? and _ characters
    1916         //TODO using /e (equivalent to eval()) is probably not a good idea
    1917         $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e',
    1918                                 "'='.sprintf('%02X', ord(stripslashes('\\1')))", $encoded);
     2133        //Replace every high ascii, control =, ? and _ characters
     2134        //We put \075 (=) as first value to make sure it's the first one in being converted, preventing double encode
     2135        $pattern = '\075\000-\011\013\014\016-\037\077\137\177-\377' . $pattern;
    19192136        break;
    19202137    }
     2138   
     2139    if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
     2140      foreach (array_unique($matches[0]) as $char) {
     2141        $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
     2142      }
     2143    }
     2144   
     2145    //Replace every spaces to _ (more readable than =20)
     2146    return str_replace(' ', '_', $encoded);
     2147}
    19212148
    1922     // Replace every spaces to _ (more readable than =20)
    1923     $encoded = str_replace(' ', '_', $encoded);
    1924 
    1925     return $encoded;
    1926   }
    19272149
    19282150  /**
    19292151   * Adds a string or binary attachment (non-filesystem) to the list.
    class PHPMailer { 
    19892211    return true;
    19902212  }
    19912213
    1992   public function AddStringEmbeddedImage($string, $cid, $filename = '', $encoding = 'base64', $type = 'application/octet-stream') {
     2214  /**
     2215   * Adds an embedded stringified attachment.  This can include images, sounds, and
     2216   * just about any other document.  Make sure to set the $type to an
     2217   * image type.  For JPEG images use "image/jpeg" and for GIF images
     2218   * use "image/gif".
     2219   * @param string $string The attachment.
     2220   * @param string $cid Content ID of the attachment.  Use this to identify
     2221   *        the Id for accessing the image in an HTML form.
     2222   * @param string $name Overrides the attachment name.
     2223   * @param string $encoding File encoding (see $Encoding).
     2224   * @param string $type File extension (MIME) type.
     2225   * @return bool
     2226   */
     2227  public function AddStringEmbeddedImage($string, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
    19932228    // Append to $attachment array
    19942229    $this->attachment[] = array(
    19952230      0 => $string,
    1996       1 => $filename,
    1997       2 => basename($filename),
     2231      1 => $name,
     2232      2 => $name,
    19982233      3 => $encoding,
    19992234      4 => $type,
    20002235      5 => true,  // isStringAttachment
    class PHPMailer { 
    20172252    return false;
    20182253  }
    20192254
     2255  /**
     2256   * Returns true if an attachment (non-inline) is present.
     2257   * @return bool
     2258   */
    20202259  public function AttachmentExists() {
    20212260    foreach($this->attachment as $attachment) {
    20222261      if ($attachment[6] == 'attachment') {
    class PHPMailer { 
    20262265    return false;
    20272266  }
    20282267
     2268  /**
     2269   * Does this message have an alternative body set?
     2270   * @return bool
     2271   */
    20292272  public function AlternativeExists() {
    2030     return strlen($this->AltBody)>0;
     2273    return !empty($this->AltBody);
    20312274  }
    20322275
    20332276  /////////////////////////////////////////////////
    class PHPMailer { 
    21112354  /**
    21122355   * Adds the error message to the error container.
    21132356   * @access protected
     2357   * @param string $msg
    21142358   * @return void
    21152359   */
    21162360  protected function SetError($msg) {
    class PHPMailer { 
    21602404  /**
    21612405   * Returns a message in the appropriate language.
    21622406   * @access protected
     2407   * @param string $key
    21632408   * @return string
    21642409   */
    21652410  protected function Lang($key) {
    class PHPMailer { 
    21842429  }
    21852430
    21862431  /**
    2187    * Changes every end of line from CR or LF to CRLF.
     2432   * Changes every end of line from CRLF, CR or LF to $this->LE.
    21882433   * @access public
     2434   * @param string $str String to FixEOL
    21892435   * @return string
    21902436   */
    21912437  public function FixEOL($str) {
    2192     $str = str_replace("\r\n", "\n", $str);
    2193     $str = str_replace("\r", "\n", $str);
    2194     $str = str_replace("\n", $this->LE, $str);
    2195     return $str;
     2438        // condense down to \n
     2439        $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
     2440        // Now convert LE as needed
     2441        if ($this->LE !== "\n") {
     2442                $nstr = str_replace("\n", $this->LE, $nstr);
     2443        }
     2444    return  $nstr;
    21962445  }
    21972446
    21982447  /**
    2199    * Adds a custom header.
     2448   * Adds a custom header. $name value can be overloaded to contain
     2449   * both header name and value (name:value)
    22002450   * @access public
     2451   * @param string $name custom header name
     2452   * @param string $value header value
    22012453   * @return void
    22022454   */
    2203   public function AddCustomHeader($custom_header) {
    2204     $this->CustomHeader[] = explode(':', $custom_header, 2);
     2455  public function AddCustomHeader($name, $value=null) {
     2456        if ($value === null) {
     2457                // Value passed in as name:value
     2458                $this->CustomHeader[] = explode(':', $name, 2);
     2459        } else {
     2460                $this->CustomHeader[] = array($name, $value);
     2461        }
    22052462  }
    22062463
    22072464  /**
    22082465   * Evaluates the message and returns modifications for inline images and backgrounds
    22092466   * @access public
    2210    * @return $message
     2467   * @param string $message Text to be HTML modified
     2468   * @param string $basedir baseline directory for path
     2469   * @return string $message
    22112470   */
    22122471  public function MsgHTML($message, $basedir = '') {
    22132472    preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images);
    class PHPMailer { 
    22172476        if (!preg_match('#^[A-z]+://#', $url)) {
    22182477          $filename = basename($url);
    22192478          $directory = dirname($url);
    2220           ($directory == '.') ? $directory='': '';
     2479          if ($directory == '.') {
     2480            $directory = '';
     2481          }
    22212482          $cid = 'cid:' . md5($filename);
    22222483          $ext = pathinfo($filename, PATHINFO_EXTENSION);
    22232484          $mimeType  = self::_mime_types($ext);
    class PHPMailer { 
    22312492    }
    22322493    $this->IsHTML(true);
    22332494    $this->Body = $message;
    2234         if (empty($this->AltBody)) {
    2235                 $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $message)));
    2236                 if (!empty($textMsg)) {
    2237                         $this->AltBody = html_entity_decode($textMsg, ENT_QUOTES, $this->CharSet);
    2238                 }
    2239         }
     2495    if (empty($this->AltBody)) {
     2496        $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $message)));
     2497        if (!empty($textMsg)) {
     2498            $this->AltBody = html_entity_decode($textMsg, ENT_QUOTES, $this->CharSet);
     2499        }
     2500    }
    22402501    if (empty($this->AltBody)) {
    22412502      $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
    22422503    }
    2243         return $message;
     2504    return $message;
    22442505  }
    22452506
    22462507  /**
    22472508   * Gets the MIME type of the embedded or inline image
    2248    * @param string File extension
     2509   * @param string $ext File extension
    22492510   * @access public
    22502511   * @return string MIME type of ext
    22512512   * @static
    22522513   */
    22532514  public static function _mime_types($ext = '') {
    22542515    $mimes = array(
     2516      'xl'    =>  'application/excel',
    22552517      'hqx'   =>  'application/mac-binhex40',
    22562518      'cpt'   =>  'application/mac-compactpro',
    2257       'doc'   =>  'application/msword',
    22582519      'bin'   =>  'application/macbinary',
     2520      'doc'   =>  'application/msword',
     2521      'word'  =>  'application/msword',
     2522      'class' =>  'application/octet-stream',
     2523      'dll'   =>  'application/octet-stream',
    22592524      'dms'   =>  'application/octet-stream',
     2525      'exe'   =>  'application/octet-stream',
    22602526      'lha'   =>  'application/octet-stream',
    22612527      'lzh'   =>  'application/octet-stream',
    2262       'exe'   =>  'application/octet-stream',
    2263       'class' =>  'application/octet-stream',
    22642528      'psd'   =>  'application/octet-stream',
    2265       'so'    =>  'application/octet-stream',
    22662529      'sea'   =>  'application/octet-stream',
    2267       'dll'   =>  'application/octet-stream',
     2530      'so'    =>  'application/octet-stream',
    22682531      'oda'   =>  'application/oda',
    22692532      'pdf'   =>  'application/pdf',
    22702533      'ai'    =>  'application/postscript',
    class PHPMailer { 
    22822545      'dxr'   =>  'application/x-director',
    22832546      'dvi'   =>  'application/x-dvi',
    22842547      'gtar'  =>  'application/x-gtar',
    2285       'php'   =>  'application/x-httpd-php',
    2286       'php4'  =>  'application/x-httpd-php',
    22872548      'php3'  =>  'application/x-httpd-php',
     2549      'php4'  =>  'application/x-httpd-php',
     2550      'php'   =>  'application/x-httpd-php',
    22882551      'phtml' =>  'application/x-httpd-php',
    22892552      'phps'  =>  'application/x-httpd-php-source',
    22902553      'js'    =>  'application/x-javascript',
    class PHPMailer { 
    22922555      'sit'   =>  'application/x-stuffit',
    22932556      'tar'   =>  'application/x-tar',
    22942557      'tgz'   =>  'application/x-tar',
    2295       'xhtml' =>  'application/xhtml+xml',
    22962558      'xht'   =>  'application/xhtml+xml',
     2559      'xhtml' =>  'application/xhtml+xml',
    22972560      'zip'   =>  'application/zip',
    22982561      'mid'   =>  'audio/midi',
    22992562      'midi'  =>  'audio/midi',
    2300       'mpga'  =>  'audio/mpeg',
    23012563      'mp2'   =>  'audio/mpeg',
    23022564      'mp3'   =>  'audio/mpeg',
     2565      'mpga'  =>  'audio/mpeg',
    23032566      'aif'   =>  'audio/x-aiff',
    2304       'aiff'  =>  'audio/x-aiff',
    23052567      'aifc'  =>  'audio/x-aiff',
     2568      'aiff'  =>  'audio/x-aiff',
    23062569      'ram'   =>  'audio/x-pn-realaudio',
    23072570      'rm'    =>  'audio/x-pn-realaudio',
    23082571      'rpm'   =>  'audio/x-pn-realaudio-plugin',
    23092572      'ra'    =>  'audio/x-realaudio',
    2310       'rv'    =>  'video/vnd.rn-realvideo',
    23112573      'wav'   =>  'audio/x-wav',
    23122574      'bmp'   =>  'image/bmp',
    23132575      'gif'   =>  'image/gif',
    23142576      'jpeg'  =>  'image/jpeg',
    2315       'jpg'   =>  'image/jpeg',
    23162577      'jpe'   =>  'image/jpeg',
     2578      'jpg'   =>  'image/jpeg',
    23172579      'png'   =>  'image/png',
    23182580      'tiff'  =>  'image/tiff',
    23192581      'tif'   =>  'image/tiff',
     2582      'eml'   =>  'message/rfc822',
    23202583      'css'   =>  'text/css',
    23212584      'html'  =>  'text/html',
    23222585      'htm'   =>  'text/html',
    23232586      'shtml' =>  'text/html',
    2324       'txt'   =>  'text/plain',
    2325       'text'  =>  'text/plain',
    23262587      'log'   =>  'text/plain',
     2588      'text'  =>  'text/plain',
     2589      'txt'   =>  'text/plain',
    23272590      'rtx'   =>  'text/richtext',
    23282591      'rtf'   =>  'text/rtf',
    23292592      'xml'   =>  'text/xml',
    23302593      'xsl'   =>  'text/xml',
    23312594      'mpeg'  =>  'video/mpeg',
    2332       'mpg'   =>  'video/mpeg',
    23332595      'mpe'   =>  'video/mpeg',
    2334       'qt'    =>  'video/quicktime',
     2596      'mpg'   =>  'video/mpeg',
    23352597      'mov'   =>  'video/quicktime',
     2598      'qt'    =>  'video/quicktime',
     2599      'rv'    =>  'video/vnd.rn-realvideo',
    23362600      'avi'   =>  'video/x-msvideo',
    2337       'movie' =>  'video/x-sgi-movie',
    2338       'doc'   =>  'application/msword',
    2339       'word'  =>  'application/msword',
    2340       'xl'    =>  'application/excel',
    2341       'eml'   =>  'message/rfc822'
     2601      'movie' =>  'video/x-sgi-movie'
    23422602    );
    23432603    return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
    23442604  }
    class PHPMailer { 
    23532613  * @param string $name Parameter Name
    23542614  * @param mixed $value Parameter Value
    23552615  * NOTE: will not work with arrays, there are no arrays to set/reset
     2616   * @throws phpmailerException
     2617   * @return bool
    23562618  * @todo Should this not be using __set() magic function?
    23572619  */
    23582620  public function set($name, $value = '') {
    class PHPMailer { 
    23782640   * @return string
    23792641   */
    23802642  public function SecureHeader($str) {
    2381     $str = str_replace("\r", '', $str);
    2382     $str = str_replace("\n", '', $str);
    2383     return trim($str);
     2643    return trim(str_replace(array("\r", "\n"), '', $str));
    23842644  }
    23852645
    23862646  /**
    23872647   * Set the private key file and password to sign the message.
    23882648   *
    23892649   * @access public
     2650   * @param $cert_filename
    23902651   * @param string $key_filename Parameter File Name
    23912652   * @param string $key_pass Password for private key
    23922653   */
    class PHPMailer { 
    24002661   * Set the private key file and password to sign the message.
    24012662   *
    24022663   * @access public
    2403    * @param string $key_filename Parameter File Name
    2404    * @param string $key_pass Password for private key
     2664   * @param string $txt
     2665   * @return string
    24052666   */
    24062667  public function DKIM_QP($txt) {
    2407     $tmp = '';
    24082668    $line = '';
    24092669    for ($i = 0; $i < strlen($txt); $i++) {
    24102670      $ord = ord($txt[$i]);
    class PHPMailer { 
    24222682   *
    24232683   * @access public
    24242684   * @param string $s Header
     2685   * @return string
    24252686   */
    24262687  public function DKIM_Sign($s) {
    24272688    $privKeyStr = file_get_contents($this->DKIM_private);
    class PHPMailer { 
    24332694    if (openssl_sign($s, $signature, $privKey)) {
    24342695      return base64_encode($signature);
    24352696    }
     2697    return '';
    24362698  }
    24372699
    24382700  /**
    class PHPMailer { 
    24402702   *
    24412703   * @access public
    24422704   * @param string $s Header
     2705   * @return string
    24432706   */
    24442707  public function DKIM_HeaderC($s) {
    24452708    $s = preg_replace("/\r\n\s+/", " ", $s);
    class PHPMailer { 
    24592722   *
    24602723   * @access public
    24612724   * @param string $body Message Body
     2725   * @return string
    24622726   */
    24632727  public function DKIM_BodyC($body) {
    24642728    if ($body == '') return "\r\n";
    class PHPMailer { 
    24792743   * @param string $headers_line Header lines
    24802744   * @param string $subject Subject
    24812745   * @param string $body Body
     2746   * @return string
    24822747   */
    24832748  public function DKIM_Add($headers_line, $subject, $body) {
    24842749    $DKIMsignatureType    = 'rsa-sha1'; // Signature & hash algorithms
    class PHPMailer { 
    24872752    $DKIMtime             = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
    24882753    $subject_header       = "Subject: $subject";
    24892754    $headers              = explode($this->LE, $headers_line);
     2755        $from_header          = "";
     2756        $to_header            = "";
    24902757    foreach($headers as $header) {
    24912758      if (strpos($header, 'From:') === 0) {
    24922759        $from_header = $header;
    class PHPMailer { 
    25122779                "\tb=";
    25132780    $toSign   = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs);
    25142781    $signed   = $this->DKIM_Sign($toSign);
    2515     return "X-PHPMAILER-DKIM: phpmailer.worxware.com\r\n".$dkimhdrs.$signed."\r\n";
     2782    return "X-PHPMAILER-DKIM: code.google.com/a/apache-extras.org/p/phpmailer/\r\n".$dkimhdrs.$signed."\r\n";
    25162783  }
    25172784
    2518   protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body) {
    2519     if (!empty($this->action_function) && function_exists($this->action_function)) {
    2520       $params = array($isSent, $to, $cc, $bcc, $subject, $body);
     2785  /**
     2786   * Perform callback
     2787   * @param boolean $isSent
     2788   * @param string $to
     2789   * @param string $cc
     2790   * @param string $bcc
     2791   * @param string $subject
     2792   * @param string $body
     2793   * @param string $from
     2794   */
     2795  protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from=null) {
     2796    if (!empty($this->action_function) && is_callable($this->action_function)) {
     2797      $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
    25212798      call_user_func_array($this->action_function, $params);
    25222799    }
    25232800  }
    25242801}
    25252802
     2803/**
     2804 * Exception handler for PHPMailer
     2805 * @package PHPMailer
     2806 */
    25262807class phpmailerException extends Exception {
     2808  /**
     2809   * Prettify error message output
     2810   * @return string
     2811   */
    25272812  public function errorMessage() {
    25282813    $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
    25292814    return $errorMsg;
  • wp-includes/class-smtp.php

    diff --git wp-includes/class-smtp.php wp-includes/class-smtp.php
    index 6977bff..8d9cd7d 100644
     
    22/*~ class.smtp.php
    33.---------------------------------------------------------------------------.
    44|  Software: PHPMailer - PHP email class                                    |
    5 |   Version: 5.2.1                                                          |
     5|   Version: 5.2.2                                                          |
    66|      Site: https://code.google.com/a/apache-extras.org/p/phpmailer/       |
    77| ------------------------------------------------------------------------- |
    88|     Admin: Jim Jagielski (project admininistrator)                        |
     
    3232 * @author Jim Jagielski
    3333 * @copyright 2010 - 2012 Jim Jagielski
    3434 * @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL)
    35  * @version $Id: class.smtp.php 450 2010-06-23 16:46:33Z coolbru $
    3635 */
    3736
    3837/**
    39  * SMTP is rfc 821 compliant and implements all the rfc 821 SMTP
    40  * commands except TURN which will always return a not implemented
    41  * error. SMTP also provides some utility methods for sending mail
    42  * to an SMTP server.
    43  * original author: Chris Ryan
     38 * PHP RFC821 SMTP client
     39 *
     40 * Implements all the RFC 821 SMTP commands except TURN which will always return a not implemented error.
     41 * SMTP also provides some utility methods for sending mail to an SMTP server.
     42 * @author Chris Ryan
     43 * @package PHPMailer
    4444 */
    4545
    4646class SMTP {
    class SMTP { 
    5151  public $SMTP_PORT = 25;
    5252
    5353  /**
    54    *  SMTP reply line ending
     54   *  SMTP reply line ending (don't change)
    5555   *  @var string
    5656   */
    5757  public $CRLF = "\r\n";
    class SMTP { 
    6363  public $do_debug;       // the level of debug to perform
    6464
    6565  /**
     66   * Sets the function/method to use for debugging output.
     67   * Right now we only honor "echo" or "error_log"
     68   * @var string
     69   */
     70  public $Debugoutput     = "echo";
     71
     72  /**
    6673   *  Sets VERP use on/off (default is off)
    6774   *  @var bool
    6875   */
    6976  public $do_verp = false;
    7077
    7178  /**
     79   * Sets the SMTP timeout value for reads, in seconds
     80   * @var int
     81   */
     82  public $Timeout         = 15;
     83
     84  /**
     85   * Sets the SMTP timelimit value for reads, in seconds
     86   * @var int
     87   */
     88  public $Timelimit       = 30;
     89
     90  /**
    7291   * Sets the SMTP PHPMailer Version number
    7392   * @var string
    7493   */
    75   public $Version         = '5.2.1';
     94  public $Version         = '5.2.2';
    7695
    7796  /////////////////////////////////////////////////
    7897  // PROPERTIES, PRIVATE AND PROTECTED
    7998  /////////////////////////////////////////////////
    8099
    81   private $smtp_conn; // the socket to the server
    82   private $error;     // error if any on the last call
    83   private $helo_rply; // the reply the server sent to us for HELO
     100  /**
     101   * @var resource The socket to the server
     102   */
     103  private $smtp_conn;
     104  /**
     105   * @var string Error message, if any, for the last call
     106   */
     107  private $error;
     108  /**
     109   * @var string The reply the server sent to us for HELO
     110   */
     111  private $helo_rply;
     112
     113  /**
     114   * Outputs debugging info via user-defined method
     115   * @param string $str
     116   */
     117  private function edebug($str) {
     118    if ($this->Debugoutput == "error_log") {
     119        error_log($str);
     120    } else {
     121        echo $str;
     122    }
     123  }
    84124
    85125  /**
    86126   * Initialize the class so that the data is in a known state.
    87127   * @access public
    88    * @return void
     128   * @return SMTP
    89129   */
    90130  public function __construct() {
    91131    $this->smtp_conn = 0;
    class SMTP { 
    110150   * SMTP CODE SUCCESS: 220
    111151   * SMTP CODE FAILURE: 421
    112152   * @access public
     153   * @param string $host
     154   * @param int $port
     155   * @param int $tval
    113156   * @return bool
    114157   */
    115158  public function Connect($host, $port = 0, $tval = 30) {
    class SMTP { 
    139182                           "errno" => $errno,
    140183                           "errstr" => $errstr);
    141184      if($this->do_debug >= 1) {
    142         echo "SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF . '<br />';
     185        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF . '<br />');
    143186      }
    144187      return false;
    145188    }
    146189
    147190    // SMTP server can take longer to respond, give longer timeout for first read
    148191    // Windows does not have support for this timeout function
    149     if(substr(PHP_OS, 0, 3) != "WIN")
    150      socket_set_timeout($this->smtp_conn, $tval, 0);
     192    if(substr(PHP_OS, 0, 3) != "WIN") {
     193     $max = ini_get('max_execution_time');
     194     if ($max != 0 && $tval > $max) { // don't bother if unlimited
     195      @set_time_limit($tval);
     196     }
     197     stream_set_timeout($this->smtp_conn, $tval, 0);
     198    }
    151199
    152200    // get any announcement
    153201    $announce = $this->get_lines();
    154202
    155203    if($this->do_debug >= 2) {
    156       echo "SMTP -> FROM SERVER:" . $announce . $this->CRLF . '<br />';
     204      $this->edebug("SMTP -> FROM SERVER:" . $announce . $this->CRLF . '<br />');
    157205    }
    158206
    159207    return true;
    class SMTP { 
    182230    $code = substr($rply,0,3);
    183231
    184232    if($this->do_debug >= 2) {
    185       echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
     233      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />');
    186234    }
    187235
    188236    if($code != 220) {
    class SMTP { 
    191239               "smtp_code" => $code,
    192240               "smtp_msg"  => substr($rply,4));
    193241      if($this->do_debug >= 1) {
    194         echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
     242        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
    195243      }
    196244      return false;
    197245    }
    class SMTP { 
    208256   * Performs SMTP authentication.  Must be run after running the
    209257   * Hello() method.  Returns true if successfully authenticated.
    210258   * @access public
     259   * @param string $username
     260   * @param string $password
     261   * @param string $authtype
     262   * @param string $realm
     263   * @param string $workstation
    211264   * @return bool
    212265   */
    213   public function Authenticate($username, $password) {
    214     // Start authentication
    215     fputs($this->smtp_conn,"AUTH LOGIN" . $this->CRLF);
    216 
    217     $rply = $this->get_lines();
    218     $code = substr($rply,0,3);
    219 
    220     if($code != 334) {
    221       $this->error =
    222         array("error" => "AUTH not accepted from server",
    223               "smtp_code" => $code,
    224               "smtp_msg" => substr($rply,4));
    225       if($this->do_debug >= 1) {
    226         echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
    227       }
    228       return false;
    229     }
    230 
    231     // Send encoded username
    232     fputs($this->smtp_conn, base64_encode($username) . $this->CRLF);
    233 
    234     $rply = $this->get_lines();
    235     $code = substr($rply,0,3);
    236 
    237     if($code != 334) {
    238       $this->error =
    239         array("error" => "Username not accepted from server",
    240               "smtp_code" => $code,
    241               "smtp_msg" => substr($rply,4));
    242       if($this->do_debug >= 1) {
    243         echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
    244       }
    245       return false;
    246     }
    247 
    248     // Send encoded password
    249     fputs($this->smtp_conn, base64_encode($password) . $this->CRLF);
    250 
    251     $rply = $this->get_lines();
    252     $code = substr($rply,0,3);
    253 
    254     if($code != 235) {
    255       $this->error =
    256         array("error" => "Password not accepted from server",
    257               "smtp_code" => $code,
    258               "smtp_msg" => substr($rply,4));
    259       if($this->do_debug >= 1) {
    260         echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
    261       }
    262       return false;
     266  public function Authenticate($username, $password, $authtype='LOGIN', $realm='', $workstation='') {
     267    if (empty($authtype)) {
     268      $authtype = 'LOGIN';
     269    }
     270
     271    switch ($authtype) {
     272      case 'PLAIN':
     273        // Start authentication
     274        fputs($this->smtp_conn,"AUTH PLAIN" . $this->CRLF);
     275   
     276        $rply = $this->get_lines();
     277        $code = substr($rply,0,3);
     278   
     279        if($code != 334) {
     280          $this->error =
     281            array("error" => "AUTH not accepted from server",
     282                  "smtp_code" => $code,
     283                  "smtp_msg" => substr($rply,4));
     284          if($this->do_debug >= 1) {
     285            $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
     286          }
     287          return false;
     288        }
     289        // Send encoded username and password
     290        fputs($this->smtp_conn, base64_encode("\0".$username."\0".$password) . $this->CRLF);
     291
     292        $rply = $this->get_lines();
     293        $code = substr($rply,0,3);
     294   
     295        if($code != 235) {
     296          $this->error =
     297            array("error" => "Authentication not accepted from server",
     298                  "smtp_code" => $code,
     299                  "smtp_msg" => substr($rply,4));
     300          if($this->do_debug >= 1) {
     301            $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
     302          }
     303          return false;
     304        }
     305        break;
     306      case 'LOGIN':
     307        // Start authentication
     308        fputs($this->smtp_conn,"AUTH LOGIN" . $this->CRLF);
     309   
     310        $rply = $this->get_lines();
     311        $code = substr($rply,0,3);
     312   
     313        if($code != 334) {
     314          $this->error =
     315            array("error" => "AUTH not accepted from server",
     316                  "smtp_code" => $code,
     317                  "smtp_msg" => substr($rply,4));
     318          if($this->do_debug >= 1) {
     319            $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
     320          }
     321          return false;
     322        }
     323   
     324        // Send encoded username
     325        fputs($this->smtp_conn, base64_encode($username) . $this->CRLF);
     326   
     327        $rply = $this->get_lines();
     328        $code = substr($rply,0,3);
     329   
     330        if($code != 334) {
     331          $this->error =
     332            array("error" => "Username not accepted from server",
     333                  "smtp_code" => $code,
     334                  "smtp_msg" => substr($rply,4));
     335          if($this->do_debug >= 1) {
     336            $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
     337          }
     338          return false;
     339        }
     340   
     341        // Send encoded password
     342        fputs($this->smtp_conn, base64_encode($password) . $this->CRLF);
     343   
     344        $rply = $this->get_lines();
     345        $code = substr($rply,0,3);
     346   
     347        if($code != 235) {
     348          $this->error =
     349            array("error" => "Password not accepted from server",
     350                  "smtp_code" => $code,
     351                  "smtp_msg" => substr($rply,4));
     352          if($this->do_debug >= 1) {
     353            $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
     354          }
     355          return false;
     356        }
     357        break;
     358      case 'NTLM':
     359        /*
     360         * ntlm_sasl_client.php
     361         ** Bundled with Permission
     362         **
     363         ** How to telnet in windows: http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx
     364         ** PROTOCOL Documentation http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication
     365         */
     366        require_once('ntlm_sasl_client.php');
     367        $temp = new stdClass();
     368        $ntlm_client = new ntlm_sasl_client_class;
     369        if(! $ntlm_client->Initialize($temp)){//let's test if every function its available
     370            $this->error = array("error" => $temp->error);
     371            if($this->do_debug >= 1) {
     372                $this->edebug("You need to enable some modules in your php.ini file: " . $this->error["error"] . $this->CRLF);
     373            }
     374            return false;
     375        }
     376        $msg1 = $ntlm_client->TypeMsg1($realm, $workstation);//msg1
     377       
     378        fputs($this->smtp_conn,"AUTH NTLM " . base64_encode($msg1) . $this->CRLF);
     379
     380        $rply = $this->get_lines();
     381        $code = substr($rply,0,3);
     382       
     383
     384        if($code != 334) {
     385            $this->error =
     386                array("error" => "AUTH not accepted from server",
     387                      "smtp_code" => $code,
     388                      "smtp_msg" => substr($rply,4));
     389            if($this->do_debug >= 1) {
     390                $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF);
     391            }
     392            return false;
     393        }
     394       
     395        $challange = substr($rply,3);//though 0 based, there is a white space after the 3 digit number....//msg2
     396        $challange = base64_decode($challange);
     397        $ntlm_res = $ntlm_client->NTLMResponse(substr($challange,24,8),$password);
     398        $msg3 = $ntlm_client->TypeMsg3($ntlm_res,$username,$realm,$workstation);//msg3
     399        // Send encoded username
     400        fputs($this->smtp_conn, base64_encode($msg3) . $this->CRLF);
     401
     402        $rply = $this->get_lines();
     403        $code = substr($rply,0,3);
     404
     405        if($code != 235) {
     406            $this->error =
     407                array("error" => "Could not authenticate",
     408                      "smtp_code" => $code,
     409                      "smtp_msg" => substr($rply,4));
     410            if($this->do_debug >= 1) {
     411                $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF);
     412            }
     413            return false;
     414        }
     415        break;
    263416    }
    264 
    265417    return true;
    266418  }
    267419
    class SMTP { 
    276428      if($sock_status["eof"]) {
    277429        // the socket is valid but we are not connected
    278430        if($this->do_debug >= 1) {
    279             echo "SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected";
     431            $this->edebug("SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected");
    280432        }
    281433        $this->Close();
    282434        return false;
    class SMTP { 
    324476   * SMTP CODE FAILURE: 451,554
    325477   * SMTP CODE ERROR  : 500,501,503,421
    326478   * @access public
     479   * @param string $msg_data
    327480   * @return bool
    328481   */
    329482  public function Data($msg_data) {
    class SMTP { 
    341494    $code = substr($rply,0,3);
    342495
    343496    if($this->do_debug >= 2) {
    344       echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
     497      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />');
    345498    }
    346499
    347500    if($code != 354) {
    class SMTP { 
    350503              "smtp_code" => $code,
    351504              "smtp_msg" => substr($rply,4));
    352505      if($this->do_debug >= 1) {
    353         echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
     506        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
    354507      }
    355508      return false;
    356509    }
    class SMTP { 
    435588    $code = substr($rply,0,3);
    436589
    437590    if($this->do_debug >= 2) {
    438       echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
     591      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />');
    439592    }
    440593
    441594    if($code != 250) {
    class SMTP { 
    444597              "smtp_code" => $code,
    445598              "smtp_msg" => substr($rply,4));
    446599      if($this->do_debug >= 1) {
    447         echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
     600        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
    448601      }
    449602      return false;
    450603    }
    class SMTP { 
    461614   * SMTP CODE SUCCESS: 250
    462615   * SMTP CODE ERROR  : 500, 501, 504, 421
    463616   * @access public
     617   * @param string $host
    464618   * @return bool
    465619   */
    466620  public function Hello($host = '') {
    class SMTP { 
    491645  /**
    492646   * Sends a HELO/EHLO command.
    493647   * @access private
     648   * @param string $hello
     649   * @param string $host
    494650   * @return bool
    495651   */
    496652  private function SendHello($hello, $host) {
    class SMTP { 
    500656    $code = substr($rply,0,3);
    501657
    502658    if($this->do_debug >= 2) {
    503       echo "SMTP -> FROM SERVER: " . $rply . $this->CRLF . '<br />';
     659      $this->edebug("SMTP -> FROM SERVER: " . $rply . $this->CRLF . '<br />');
    504660    }
    505661
    506662    if($code != 250) {
    class SMTP { 
    509665              "smtp_code" => $code,
    510666              "smtp_msg" => substr($rply,4));
    511667      if($this->do_debug >= 1) {
    512         echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
     668        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
    513669      }
    514670      return false;
    515671    }
    class SMTP { 
    531687   * SMTP CODE SUCCESS: 552,451,452
    532688   * SMTP CODE SUCCESS: 500,501,421
    533689   * @access public
     690   * @param string $from
    534691   * @return bool
    535692   */
    536693  public function Mail($from) {
    class SMTP { 
    542699      return false;
    543700    }
    544701
    545     $useVerp = ($this->do_verp ? "XVERP" : "");
     702    $useVerp = ($this->do_verp ? " XVERP" : "");
    546703    fputs($this->smtp_conn,"MAIL FROM:<" . $from . ">" . $useVerp . $this->CRLF);
    547704
    548705    $rply = $this->get_lines();
    549706    $code = substr($rply,0,3);
    550707
    551708    if($this->do_debug >= 2) {
    552       echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
     709      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />');
    553710    }
    554711
    555712    if($code != 250) {
    class SMTP { 
    558715              "smtp_code" => $code,
    559716              "smtp_msg" => substr($rply,4));
    560717      if($this->do_debug >= 1) {
    561         echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
     718        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
    562719      }
    563720      return false;
    564721    }
    class SMTP { 
    574731   * SMTP CODE SUCCESS: 221
    575732   * SMTP CODE ERROR  : 500
    576733   * @access public
     734   * @param bool $close_on_error
    577735   * @return bool
    578736   */
    579737  public function Quit($close_on_error = true) {
    class SMTP { 
    592750    $byemsg = $this->get_lines();
    593751
    594752    if($this->do_debug >= 2) {
    595       echo "SMTP -> FROM SERVER:" . $byemsg . $this->CRLF . '<br />';
     753      $this->edebug("SMTP -> FROM SERVER:" . $byemsg . $this->CRLF . '<br />');
    596754    }
    597755
    598756    $rval = true;
    class SMTP { 
    606764                 "smtp_rply" => substr($byemsg,4));
    607765      $rval = false;
    608766      if($this->do_debug >= 1) {
    609         echo "SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF . '<br />';
     767        $this->edebug("SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF . '<br />');
    610768      }
    611769    }
    612770
    class SMTP { 
    627785   * SMTP CODE FAILURE: 550,551,552,553,450,451,452
    628786   * SMTP CODE ERROR  : 500,501,503,421
    629787   * @access public
     788   * @param string $to
    630789   * @return bool
    631790   */
    632791  public function Recipient($to) {
    class SMTP { 
    644803    $code = substr($rply,0,3);
    645804
    646805    if($this->do_debug >= 2) {
    647       echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
     806      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />');
    648807    }
    649808
    650809    if($code != 250 && $code != 251) {
    class SMTP { 
    653812              "smtp_code" => $code,
    654813              "smtp_msg" => substr($rply,4));
    655814      if($this->do_debug >= 1) {
    656         echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
     815        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
    657816      }
    658817      return false;
    659818    }
    class SMTP { 
    687846    $code = substr($rply,0,3);
    688847
    689848    if($this->do_debug >= 2) {
    690       echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
     849      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />');
    691850    }
    692851
    693852    if($code != 250) {
    class SMTP { 
    696855              "smtp_code" => $code,
    697856              "smtp_msg" => substr($rply,4));
    698857      if($this->do_debug >= 1) {
    699         echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
     858        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
    700859      }
    701860      return false;
    702861    }
    class SMTP { 
    718877   * SMTP CODE SUCCESS: 552,451,452
    719878   * SMTP CODE SUCCESS: 500,501,502,421
    720879   * @access public
     880   * @param string $from
    721881   * @return bool
    722882   */
    723883  public function SendAndMail($from) {
    class SMTP { 
    735895    $code = substr($rply,0,3);
    736896
    737897    if($this->do_debug >= 2) {
    738       echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />';
     898      $this->edebug("SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />');
    739899    }
    740900
    741901    if($code != 250) {
    class SMTP { 
    744904              "smtp_code" => $code,
    745905              "smtp_msg" => substr($rply,4));
    746906      if($this->do_debug >= 1) {
    747         echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />';
     907        $this->edebug("SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />');
    748908      }
    749909      return false;
    750910    }
    class SMTP { 
    768928    $this->error = array("error" => "This method, TURN, of the SMTP ".
    769929                                    "is not implemented");
    770930    if($this->do_debug >= 1) {
    771       echo "SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF . '<br />';
     931      $this->edebug("SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF . '<br />');
    772932    }
    773933    return false;
    774934  }
    class SMTP { 
    797957   */
    798958  private function get_lines() {
    799959    $data = "";
    800     while(!feof($this->smtp_conn)) {
     960    $endtime = 0;
     961    /* If for some reason the fp is bad, don't inf loop */
     962    if (!is_resource($this->smtp_conn)) {
     963      return $data;
     964    }
     965    stream_set_timeout($this->smtp_conn, $this->Timeout);
     966    if ($this->Timelimit > 0) {
     967      $endtime = time() + $this->Timelimit;
     968    }
     969    while(is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
    801970      $str = @fgets($this->smtp_conn,515);
    802971      if($this->do_debug >= 4) {
    803         echo "SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '<br />';
    804         echo "SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '<br />';
     972        $this->edebug("SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '<br />');
     973        $this->edebug("SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '<br />');
    805974      }
    806975      $data .= $str;
    807976      if($this->do_debug >= 4) {
    808         echo "SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '<br />';
     977        $this->edebug("SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '<br />');
    809978      }
    810979      // if 4th character is a space, we are done reading, break the loop
    811980      if(substr($str,3,1) == " ") { break; }
     981      // Timed-out? Log and break
     982      $info = stream_get_meta_data($this->smtp_conn);
     983      if ($info['timed_out']) {
     984        if($this->do_debug >= 4) {
     985          $this->edebug("SMTP -> get_lines(): timed-out (" . $this->Timeout . " seconds) <br />");
     986        }
     987        break;
     988      }
     989      // Now check if reads took too long
     990      if ($endtime) {
     991        if (time() > $endtime) {
     992          if($this->do_debug >= 4) {
     993            $this->edebug("SMTP -> get_lines(): timelimit reached (" . $this->Timelimit . " seconds) <br />");
     994          }
     995          break;
     996        }
     997      }
    812998    }
    813999    return $data;
    8141000  }
    8151001
    8161002}
    817 
    8181003?>