PageRenderTime 50ms CodeModel.GetById 3ms app.highlight 34ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-content/plugins/amazon-ses-and-dkim-mailer/php-mailer/class.phpmailer.php

https://bitbucket.org/broderboy/shannonbroder-wordpress
PHP | 3041 lines | 1808 code | 233 blank | 1000 comment | 294 complexity | 4b1bca0f8a005a0f460f10ea44242f04 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2/*~ class.phpmailer.php
   3.---------------------------------------------------------------------------.
   4|  Software: PHPMailer - PHP email class                                    |
   5|   Version: 5.2.6                                                          |
   6|      Site: https://github.com/PHPMailer/PHPMailer/                        |
   7| ------------------------------------------------------------------------- |
   8|    Admins: Marcus Bointon                                                 |
   9|    Admins: Jim Jagielski                                                  |
  10|   Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net |
  11|          : Marcus Bointon (coolbru) phpmailer@synchromedia.co.uk          |
  12|          : Jim Jagielski (jimjag) jimjag@gmail.com                        |
  13|   Founder: Brent R. Matzelle (original founder)                           |
  14| Copyright (c) 2010-2012, Jim Jagielski. All Rights Reserved.              |
  15| Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved.               |
  16| Copyright (c) 2001-2003, Brent R. Matzelle                                |
  17| ------------------------------------------------------------------------- |
  18|   License: Distributed under the Lesser General Public License (LGPL)     |
  19|            http://www.gnu.org/copyleft/lesser.html                        |
  20| This program is distributed in the hope that it will be useful - WITHOUT  |
  21| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or     |
  22| FITNESS FOR A PARTICULAR PURPOSE.                                         |
  23'---------------------------------------------------------------------------'
  24*/
  25
  26/**
  27 * PHPMailer - PHP email creation and transport class
  28 * NOTE: Requires PHP version 5 or later
  29 * @package PHPMailer
  30 * @author Andy Prevost
  31 * @author Marcus Bointon
  32 * @author Jim Jagielski
  33 * @copyright 2010 - 2012 Jim Jagielski
  34 * @copyright 2004 - 2009 Andy Prevost
  35 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  36 */
  37
  38if (version_compare(PHP_VERSION, '5.0.0', '<') ) {
  39  exit("Sorry, PHPMailer will only run on PHP version 5 or greater!\n");
  40}
  41
  42/**
  43 * PHP email creation and transport class
  44 * @package PHPMailer
  45 */
  46class PHPMailer {
  47
  48  /////////////////////////////////////////////////
  49  // PROPERTIES, PUBLIC
  50  /////////////////////////////////////////////////
  51
  52  /**
  53   * Email priority (1 = High, 3 = Normal, 5 = low).
  54   * @var int
  55   */
  56  public $Priority          = 3;
  57
  58  /**
  59   * Sets the CharSet of the message.
  60   * @var string
  61   */
  62  public $CharSet           = 'iso-8859-1';
  63
  64  /**
  65   * Sets the Content-type of the message.
  66   * @var string
  67   */
  68  public $ContentType       = 'text/plain';
  69
  70  /**
  71   * Sets the Encoding of the message. Options for this are
  72   *  "8bit", "7bit", "binary", "base64", and "quoted-printable".
  73   * @var string
  74   */
  75  public $Encoding          = '8bit';
  76
  77  /**
  78   * Holds the most recent mailer error message.
  79   * @var string
  80   */
  81  public $ErrorInfo         = '';
  82
  83  /**
  84   * Sets the From email address for the message.
  85   * @var string
  86   */
  87  public $From              = 'root@localhost';
  88
  89  /**
  90   * Sets the From name of the message.
  91   * @var string
  92   */
  93  public $FromName          = 'Root User';
  94
  95  /**
  96   * Sets the Sender email (Return-Path) of the message.
  97   * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  98   * @var string
  99   */
 100  public $Sender            = '';
 101
 102  /**
 103   * Sets the Return-Path of the message.  If empty, it will
 104   * be set to either From or Sender.
 105   * @var string
 106   */
 107  public $ReturnPath        = '';
 108
 109  /**
 110   * Sets the Subject of the message.
 111   * @var string
 112   */
 113  public $Subject           = '';
 114
 115  /**
 116   * An HTML or plain text message body.
 117   * If HTML then call IsHTML(true).
 118   * @var string
 119   */
 120  public $Body              = '';
 121
 122  /**
 123   * The plain-text message body.
 124   * This body can be read by mail clients that do not have HTML email
 125   * capability such as mutt & Eudora.
 126   * Clients that can read HTML will view the normal Body.
 127   * @var string
 128   */
 129  public $AltBody           = '';
 130
 131  /**
 132   * An iCal message part body
 133   * Only supported in simple alt or alt_inline message types
 134   * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator
 135   * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
 136   * @link http://kigkonsult.se/iCalcreator/
 137   * @var string
 138   */
 139  public $Ical              = '';
 140
 141  /**
 142   * Stores the complete compiled MIME message body.
 143   * @var string
 144   * @access protected
 145   */
 146  protected $MIMEBody       = '';
 147
 148  /**
 149   * Stores the complete compiled MIME message headers.
 150   * @var string
 151   * @access protected
 152   */
 153  protected $MIMEHeader     = '';
 154
 155  /**
 156   * Stores the extra header list which CreateHeader() doesn't fold in
 157   * @var string
 158   * @access protected
 159   */
 160  protected $mailHeader     = '';
 161
 162  /**
 163   * Sets word wrapping on the body of the message to a given number of
 164   * characters.
 165   * @var int
 166   */
 167  public $WordWrap          = 0;
 168
 169  /**
 170   * Method to send mail: ("mail", "sendmail", or "smtp").
 171   * @var string
 172   */
 173  public $Mailer            = 'mail';
 174
 175  /**
 176   * Sets the path of the sendmail program.
 177   * @var string
 178   */
 179  public $Sendmail          = '/usr/sbin/sendmail';
 180
 181  /**
 182   * Determine if mail() uses a fully sendmail compatible MTA that
 183   * supports sendmail's "-oi -f" options
 184   * @var boolean
 185   */
 186  public $UseSendmailOptions	= true;
 187
 188  /**
 189   * Path to PHPMailer plugins.  Useful if the SMTP class
 190   * is in a different directory than the PHP include path.
 191   * @var string
 192   */
 193  public $PluginDir         = '';
 194
 195  /**
 196   * Sets the email address that a reading confirmation will be sent.
 197   * @var string
 198   */
 199  public $ConfirmReadingTo  = '';
 200
 201  /**
 202   * Sets the hostname to use in Message-Id and Received headers
 203   * and as default HELO string. If empty, the value returned
 204   * by SERVER_NAME is used or 'localhost.localdomain'.
 205   * @var string
 206   */
 207  public $Hostname          = '';
 208
 209  /**
 210   * Sets the message ID to be used in the Message-Id header.
 211   * If empty, a unique id will be generated.
 212   * @var string
 213   */
 214  public $MessageID         = '';
 215
 216  /**
 217   * Sets the message Date to be used in the Date header.
 218   * If empty, the current date will be added.
 219   * @var string
 220   */
 221  public $MessageDate       = '';
 222
 223  /////////////////////////////////////////////////
 224  // PROPERTIES FOR SMTP
 225  /////////////////////////////////////////////////
 226
 227  /**
 228   * Sets the SMTP hosts.
 229   *
 230   * All hosts must be separated by a
 231   * semicolon.  You can also specify a different port
 232   * for each host by using this format: [hostname:port]
 233   * (e.g. "smtp1.example.com:25;smtp2.example.com").
 234   * Hosts will be tried in order.
 235   * @var string
 236   */
 237  public $Host          = 'localhost';
 238
 239  /**
 240   * Sets the default SMTP server port.
 241   * @var int
 242   */
 243  public $Port          = 25;
 244
 245  /**
 246   * Sets the SMTP HELO of the message (Default is $Hostname).
 247   * @var string
 248   */
 249  public $Helo          = '';
 250
 251  /**
 252   * Sets connection prefix. Options are "", "ssl" or "tls"
 253   * @var string
 254   */
 255  public $SMTPSecure    = '';
 256
 257  /**
 258   * Sets SMTP authentication. Utilizes the Username and Password variables.
 259   * @var bool
 260   */
 261  public $SMTPAuth      = false;
 262
 263  /**
 264   * Sets SMTP username.
 265   * @var string
 266   */
 267  public $Username      = '';
 268
 269  /**
 270   * Sets SMTP password.
 271   * @var string
 272   */
 273  public $Password      = '';
 274
 275  /**
 276   *  Sets SMTP auth type. Options are LOGIN | PLAIN | NTLM | CRAM-MD5 (default LOGIN)
 277   *  @var string
 278   */
 279  public $AuthType      = '';
 280
 281  /**
 282   *  Sets SMTP realm.
 283   *  @var string
 284   */
 285  public $Realm         = '';
 286
 287  /**
 288   *  Sets SMTP workstation.
 289   *  @var string
 290   */
 291  public $Workstation   = '';
 292
 293  /**
 294   * Sets the SMTP server timeout in seconds.
 295   * This function will not work with the win32 version.
 296   * @var int
 297   */
 298  public $Timeout       = 10;
 299
 300  /**
 301   * Sets SMTP class debugging on or off.
 302   * @var bool
 303   */
 304  public $SMTPDebug     = false;
 305
 306  /**
 307   * Sets the function/method to use for debugging output.
 308   * Right now we only honor "echo" or "error_log"
 309   * @var string
 310   */
 311  public $Debugoutput     = "echo";
 312
 313  /**
 314   * Prevents the SMTP connection from being closed after each mail
 315   * sending.  If this is set to true then to close the connection
 316   * requires an explicit call to SmtpClose().
 317   * @var bool
 318   */
 319  public $SMTPKeepAlive = false;
 320
 321  /**
 322   * Provides the ability to have the TO field process individual
 323   * emails, instead of sending to entire TO addresses
 324   * @var bool
 325   */
 326  public $SingleTo      = false;
 327
 328  /**
 329   * Should we generate VERP addresses when sending via SMTP?
 330   * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
 331   * @var bool
 332   */
 333  public $do_verp      = false;
 334
 335  /**
 336   * If SingleTo is true, this provides the array to hold the email addresses
 337   * @var bool
 338   */
 339  public $SingleToArray = array();
 340
 341  /**
 342   * Should we allow sending messages with empty body?
 343   * @var bool
 344   */
 345  public $AllowEmpty = false;
 346
 347    /**
 348   * Provides the ability to change the generic line ending
 349   * NOTE: The default remains '\n'. We force CRLF where we KNOW
 350   *        it must be used via self::CRLF
 351   * @var string
 352   */
 353  public $LE              = "\n";
 354
 355   /**
 356   * Used with DKIM Signing
 357   * required parameter if DKIM is enabled
 358   *
 359   * domain selector example domainkey
 360   * @var string
 361   */
 362  public $DKIM_selector   = '';
 363
 364  /**
 365   * Used with DKIM Signing
 366   * required if DKIM is enabled, in format of email address 'you@yourdomain.com' typically used as the source of the email
 367   * @var string
 368   */
 369  public $DKIM_identity   = '';
 370
 371  /**
 372   * Used with DKIM Signing
 373   * optional parameter if your private key requires a passphras
 374   * @var string
 375   */
 376  public $DKIM_passphrase   = '';
 377
 378  /**
 379   * Used with DKIM Singing
 380   * required if DKIM is enabled, in format of email address 'domain.com'
 381   * @var string
 382   */
 383  public $DKIM_domain     = '';
 384
 385  /**
 386   * Used with DKIM Signing
 387   * required if DKIM is enabled, path to private key file
 388   * @var string
 389   */
 390  public $DKIM_private    = '';
 391
 392  /**
 393   * Callback Action function name.
 394   * The function that handles the result of the send email action.
 395   * It is called out by Send() for each email sent.
 396   *
 397   * Value can be:
 398   * - 'function_name' for function names
 399   * - 'Class::Method' for static method calls
 400   * - array($object, 'Method') for calling methods on $object
 401   * See http://php.net/is_callable manual page for more details.
 402   *
 403   * Parameters:
 404   *   bool    $result        result of the send action
 405   *   string  $to            email address of the recipient
 406   *   string  $cc            cc email addresses
 407   *   string  $bcc           bcc email addresses
 408   *   string  $subject       the subject
 409   *   string  $body          the email body
 410   *   string  $from          email address of sender
 411   * @var string
 412   */
 413  public $action_function = ''; //'callbackAction';
 414
 415  /**
 416   * Sets the PHPMailer Version number
 417   * @var string
 418   */
 419  public $Version         = '5.2.6';
 420
 421  /**
 422   * What to use in the X-Mailer header
 423   * @var string NULL for default, whitespace for None, or actual string to use
 424   */
 425  public $XMailer         = '';
 426
 427  /////////////////////////////////////////////////
 428  // PROPERTIES, PRIVATE AND PROTECTED
 429  /////////////////////////////////////////////////
 430
 431  /**
 432   * @var SMTP An instance of the SMTP sender class
 433   * @access protected
 434   */
 435  protected   $smtp           = null;
 436  /**
 437   * @var array An array of 'to' addresses
 438   * @access protected
 439   */
 440  protected   $to             = array();
 441  /**
 442   * @var array An array of 'cc' addresses
 443   * @access protected
 444   */
 445  protected   $cc             = array();
 446  /**
 447   * @var array An array of 'bcc' addresses
 448   * @access protected
 449   */
 450  protected   $bcc            = array();
 451  /**
 452   * @var array An array of reply-to name and address
 453   * @access protected
 454   */
 455  protected   $ReplyTo        = array();
 456  /**
 457   * @var array An array of all kinds of addresses: to, cc, bcc, replyto
 458   * @access protected
 459   */
 460  protected   $all_recipients = array();
 461  /**
 462   * @var array An array of attachments
 463   * @access protected
 464   */
 465  protected   $attachment     = array();
 466  /**
 467   * @var array An array of custom headers
 468   * @access protected
 469   */
 470  protected   $CustomHeader   = array();
 471  /**
 472   * @var string The message's MIME type
 473   * @access protected
 474   */
 475  protected   $message_type   = '';
 476  /**
 477   * @var array An array of MIME boundary strings
 478   * @access protected
 479   */
 480  protected   $boundary       = array();
 481  /**
 482   * @var array An array of available languages
 483   * @access protected
 484   */
 485  protected   $language       = array();
 486  /**
 487   * @var integer The number of errors encountered
 488   * @access protected
 489   */
 490  protected   $error_count    = 0;
 491  /**
 492   * @var string The filename of a DKIM certificate file
 493   * @access protected
 494   */
 495  protected   $sign_cert_file = '';
 496  /**
 497   * @var string The filename of a DKIM key file
 498   * @access protected
 499   */
 500  protected   $sign_key_file  = '';
 501  /**
 502   * @var string The password of a DKIM key
 503   * @access protected
 504   */
 505  protected   $sign_key_pass  = '';
 506  /**
 507   * @var boolean Whether to throw exceptions for errors
 508   * @access protected
 509   */
 510  protected   $exceptions     = false;
 511  /**Amazon SES**/
 512  private   $amazonses_object = NULL;
 513  private   $amazonses_use_destinations = TRUE;
 514  private   $amazonses_use_source = TRUE;
 515  private   $amazonses_use_names = TRUE;
 516  private   $amazonses_debug = FALSE;
 517
 518  /////////////////////////////////////////////////
 519  // CONSTANTS
 520  /////////////////////////////////////////////////
 521
 522  const STOP_MESSAGE  = 0; // message only, continue processing
 523  const STOP_CONTINUE = 1; // message?, likely ok to continue processing
 524  const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
 525  const CRLF = "\r\n";     // SMTP RFC specified EOL
 526
 527  /////////////////////////////////////////////////
 528  // METHODS, VARIABLES
 529  /////////////////////////////////////////////////
 530
 531  /**
 532   * Calls actual mail() function, but in a safe_mode aware fashion
 533   * Also, unless sendmail_path points to sendmail (or something that
 534   * claims to be sendmail), don't pass params (not a perfect fix,
 535   * but it will do)
 536   * @param string $to To
 537   * @param string $subject Subject
 538   * @param string $body Message Body
 539   * @param string $header Additional Header(s)
 540   * @param string $params Params
 541   * @access private
 542   * @return bool
 543   */
 544  private function mail_passthru($to, $subject, $body, $header, $params) {
 545    if ( ini_get('safe_mode') || !($this->UseSendmailOptions) ) {
 546        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header);
 547    } else {
 548        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params);
 549    }
 550    return $rt;
 551  }
 552
 553  /**
 554   * Outputs debugging info via user-defined method
 555   * @param string $str
 556   */
 557  protected function edebug($str) {
 558    switch ($this->Debugoutput) {
 559      case 'error_log':
 560        error_log($str);
 561        break;
 562      case 'html':
 563        //Cleans up output a bit for a better looking display that's HTML-safe
 564        echo htmlentities(preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, $this->CharSet)."<br>\n";
 565        break;
 566      case 'echo':
 567      default:
 568        //Just echoes exactly what was received
 569        echo $str;
 570    }
 571  }
 572
 573  /**
 574   * Constructor
 575   * @param boolean $exceptions Should we throw external exceptions?
 576   */
 577  public function __construct($exceptions = false) {
 578    $this->exceptions = ($exceptions == true);
 579  }
 580
 581  /**
 582   * Destructor
 583   */
 584  public function __destruct() {
 585      if ($this->Mailer == 'smtp') { //Close any open SMTP connection nicely
 586          $this->SmtpClose();
 587      }
 588  }
 589
 590  /**
 591   * Sets message type to HTML.
 592   * @param bool $ishtml
 593   * @return void
 594   */
 595  public function IsHTML($ishtml = true) {
 596    if ($ishtml) {
 597      $this->ContentType = 'text/html';
 598    } else {
 599      $this->ContentType = 'text/plain';
 600    }
 601  }
 602
 603  /**
 604   * Sets Mailer to send message using SMTP.
 605   * @return void
 606   */
 607  public function IsSMTP() {
 608    $this->Mailer = 'smtp';
 609  }
 610
 611  /**
 612   * Sets Mailer to send message using PHP mail() function.
 613   * @return void
 614   */
 615  public function IsMail() {
 616    $this->Mailer = 'mail';
 617  }
 618
 619  /**
 620   * Sets Mailer to send message using the $Sendmail program.
 621   * @return void
 622   */
 623  public function IsSendmail() {
 624    if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
 625      $this->Sendmail = '/var/qmail/bin/sendmail';
 626    }
 627    $this->Mailer = 'sendmail';
 628  }
 629
 630  /**
 631   * Sets Mailer to send message using the qmail MTA.
 632   * @return void
 633   */
 634  public function IsQmail() {
 635    if (stristr(ini_get('sendmail_path'), 'qmail')) {
 636      $this->Sendmail = '/var/qmail/bin/sendmail';
 637    }
 638    $this->Mailer = 'sendmail';
 639  }
 640  
 641  /**
 642   * Sets Mailer to send message using Amazon Simple Email Service(SES).
 643   * @return void
 644   */
 645  public function IsAmazonSES() {
 646    $this->Mailer = 'amazonses';
 647  }
 648
 649  /////////////////////////////////////////////////
 650  // METHODS, RECIPIENTS
 651  /////////////////////////////////////////////////
 652
 653  /**
 654   * Adds a "To" address.
 655   * @param string $address
 656   * @param string $name
 657   * @return boolean true on success, false if address already used
 658   */
 659  public function AddAddress($address, $name = '') {
 660    return $this->AddAnAddress('to', $address, $name);
 661  }
 662
 663  /**
 664   * Adds a "Cc" address.
 665   * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
 666   * @param string $address
 667   * @param string $name
 668   * @return boolean true on success, false if address already used
 669   */
 670  public function AddCC($address, $name = '') {
 671    return $this->AddAnAddress('cc', $address, $name);
 672  }
 673
 674  /**
 675   * Adds a "Bcc" address.
 676   * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
 677   * @param string $address
 678   * @param string $name
 679   * @return boolean true on success, false if address already used
 680   */
 681  public function AddBCC($address, $name = '') {
 682    return $this->AddAnAddress('bcc', $address, $name);
 683  }
 684
 685  /**
 686   * Adds a "Reply-to" address.
 687   * @param string $address
 688   * @param string $name
 689   * @return boolean
 690   */
 691  public function AddReplyTo($address, $name = '') {
 692    return $this->AddAnAddress('Reply-To', $address, $name);
 693  }
 694
 695  /**
 696   * Adds an address to one of the recipient arrays
 697   * Addresses that have been added already return false, but do not throw exceptions
 698   * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
 699   * @param string $address The email address to send to
 700   * @param string $name
 701   * @throws phpmailerException
 702   * @return boolean true on success, false if address already used or invalid in some way
 703   * @access protected
 704   */
 705  protected function AddAnAddress($kind, $address, $name = '') {
 706    if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
 707      $this->SetError($this->Lang('Invalid recipient array').': '.$kind);
 708      if ($this->exceptions) {
 709        throw new phpmailerException('Invalid recipient array: ' . $kind);
 710      }
 711      if ($this->SMTPDebug) {
 712        $this->edebug($this->Lang('Invalid recipient array').': '.$kind);
 713      }
 714      return false;
 715    }
 716    $address = trim($address);
 717    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
 718    if (!$this->ValidateAddress($address)) {
 719      $this->SetError($this->Lang('invalid_address').': '. $address);
 720      if ($this->exceptions) {
 721        throw new phpmailerException($this->Lang('invalid_address').': '.$address);
 722      }
 723      if ($this->SMTPDebug) {
 724        $this->edebug($this->Lang('invalid_address').': '.$address);
 725      }
 726      return false;
 727    }
 728    if ($kind != 'Reply-To') {
 729      if (!isset($this->all_recipients[strtolower($address)])) {
 730        array_push($this->$kind, array($address, $name));
 731        $this->all_recipients[strtolower($address)] = true;
 732        return true;
 733      }
 734    } else {
 735      if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
 736        $this->ReplyTo[strtolower($address)] = array($address, $name);
 737      return true;
 738    }
 739  }
 740  return false;
 741}
 742
 743  /**
 744   * Set the From and FromName properties
 745   * @param string $address
 746   * @param string $name
 747   * @param boolean $auto Whether to also set the Sender address, defaults to true
 748   * @throws phpmailerException
 749   * @return boolean
 750   */
 751  public function SetFrom($address, $name = '', $auto = true) {
 752    $address = trim($address);
 753    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
 754    if (!$this->ValidateAddress($address)) {
 755      $this->SetError($this->Lang('invalid_address').': '. $address);
 756      if ($this->exceptions) {
 757        throw new phpmailerException($this->Lang('invalid_address').': '.$address);
 758      }
 759      if ($this->SMTPDebug) {
 760        $this->edebug($this->Lang('invalid_address').': '.$address);
 761      }
 762      return false;
 763    }
 764    $this->From = $address;
 765    $this->FromName = $name;
 766    if ($auto) {
 767      if (empty($this->Sender)) {
 768        $this->Sender = $address;
 769      }
 770    }
 771    return true;
 772  }
 773
 774  /**
 775   * Check that a string looks roughly like an email address should
 776   * Static so it can be used without instantiation, public so people can overload
 777   * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is
 778   * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to
 779   * not allow a@b type valid addresses :(
 780   * @link http://squiloople.com/2009/12/20/email-address-validation/
 781   * @copyright regex Copyright Michael Rushton 2009-10 | http://squiloople.com/ | Feel free to use and redistribute this code. But please keep this copyright notice.
 782   * @param string $address The email address to check
 783   * @return boolean
 784   * @static
 785   * @access public
 786   */
 787  public static function ValidateAddress($address) {
 788      if (defined('PCRE_VERSION')) { //Check this instead of extension_loaded so it works when that function is disabled
 789          if (version_compare(PCRE_VERSION, '8.0') >= 0) {
 790              return (boolean)preg_match('/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?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][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address);
 791          } else {
 792              //Fall back to an older regex that doesn't need a recent PCRE
 793              return (boolean)preg_match('/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD', $address);
 794          }
 795      } else {
 796          //No PCRE! Do something _very_ approximate!
 797          //Check the address is 3 chars or longer and contains an @ that's not the first or last char
 798          return (strlen($address) >= 3 and strpos($address, '@') >= 1 and strpos($address, '@') != strlen($address) - 1);
 799      }
 800  }
 801
 802  /////////////////////////////////////////////////
 803  // METHODS, MAIL SENDING
 804  /////////////////////////////////////////////////
 805
 806  /**
 807   * Creates message and assigns Mailer. If the message is
 808   * not sent successfully then it returns false.  Use the ErrorInfo
 809   * variable to view description of the error.
 810   * @throws phpmailerException
 811   * @return bool
 812   */
 813  public function Send() {
 814    try {
 815      if(!$this->PreSend()) return false;
 816      return $this->PostSend();
 817    } catch (phpmailerException $e) {
 818      $this->mailHeader = '';
 819      $this->SetError($e->getMessage());
 820      if ($this->exceptions) {
 821        throw $e;
 822      }
 823      return false;
 824    }
 825  }
 826
 827  /**
 828   * Prep mail by constructing all message entities
 829   * @throws phpmailerException
 830   * @return bool
 831   */
 832  public function PreSend() {
 833    try {
 834      $this->mailHeader = "";
 835      if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
 836        throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
 837      }
 838
 839      // Set whether the message is multipart/alternative
 840      if(!empty($this->AltBody)) {
 841        $this->ContentType = 'multipart/alternative';
 842      }
 843
 844      $this->error_count = 0; // reset errors
 845      $this->SetMessageType();
 846      //Refuse to send an empty message unless we are specifically allowing it
 847      if (!$this->AllowEmpty and empty($this->Body)) {
 848        throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
 849      }
 850
 851      $this->MIMEHeader = $this->CreateHeader();
 852      $this->MIMEBody = $this->CreateBody();
 853
 854      // To capture the complete message when using mail(), create
 855      // an extra header list which CreateHeader() doesn't fold in
 856      if ($this->Mailer == 'mail') {
 857        if (count($this->to) > 0) {
 858          $this->mailHeader .= $this->AddrAppend("To", $this->to);
 859        } else {
 860          $this->mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;");
 861        }
 862        $this->mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject))));
 863      }
 864
 865      // digitally sign with DKIM if enabled
 866      if (!empty($this->DKIM_domain) && !empty($this->DKIM_private) && !empty($this->DKIM_selector) && !empty($this->DKIM_domain) && file_exists($this->DKIM_private)) {
 867        $header_dkim = $this->DKIM_Add($this->MIMEHeader . $this->mailHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody);
 868        $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader;
 869      }
 870
 871      return true;
 872
 873    } catch (phpmailerException $e) {
 874      $this->SetError($e->getMessage());
 875      if ($this->exceptions) {
 876        throw $e;
 877      }
 878      return false;
 879    }
 880  }
 881
 882  /**
 883   * Actual Email transport function
 884   * Send the email via the selected mechanism
 885   * @throws phpmailerException
 886   * @return bool
 887   */
 888  public function PostSend() {
 889    try {
 890      // Choose the mailer and send through it
 891      switch($this->Mailer) {
 892        case 'sendmail':
 893          return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody);
 894        case 'smtp':
 895          return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody);
 896        case 'mail':
 897          return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
 898        case 'amazonses':
 899          return $this->AmazonSESSend($this->MIMEHeader, $this->MIMEBody);
 900        default:
 901          return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
 902      }
 903    } catch (phpmailerException $e) {
 904      $this->SetError($e->getMessage());
 905      if ($this->exceptions) {
 906        throw $e;
 907      }
 908      if ($this->SMTPDebug) {
 909        $this->edebug($e->getMessage()."\n");
 910      }
 911    }
 912    return false;
 913  }
 914  
 915  public function AddAmazonSESKey($aws_access_key_id, $aws_secret_key) {
 916    $this->InitiateAmazonSESObject();
 917
 918    $this->amazonses_object->aws_access_key_id = (string)$aws_access_key_id;
 919    $this->amazonses_object->aws_secret_key = (string)$aws_secret_key;
 920
 921    return TRUE;
 922  }
 923
 924
 925  protected function InitiateAmazonSESObject() {
 926    require_once('class.amazonses.php');
 927
 928    if (!isset($this->amazonses_object)) {
 929      $this->amazonses_object = new AmazonSES();
 930
 931      if ($this->amazonses_debug === TRUE) 
 932        { $this->amazonses_object->debug = TRUE; }
 933    }
 934  }
 935
 936
 937  protected function AmazonSESSend($header, $body) {
 938    $this->InitiateAmazonSESObject();
 939
 940    $addr_with_name = create_function (
 941       '$addr_ar',
 942       'return (trim($addr_ar[1]) !== "") ?
 943               "{$addr_ar[1]} <{$addr_ar[0]}>" : $addr_ar[0];'
 944    );
 945
 946    $recipients = array();
 947    foreach (array_merge($this->to, $this->cc, $this->bcc) as $key => $to) {
 948      $recipients[] = ($this->amazonses_use_names === TRUE) ?
 949                      $addr_with_name($to) : $to[0];
 950    }
 951
 952    $source = FALSE;
 953    if ($this->amazonses_use_source === TRUE) {
 954      $source = ($this->amazonses_use_names === TRUE) ?
 955                $addr_with_name(array($this->From, $this->FromName)) :
 956                $this->From;
 957    }
 958
 959    $destinations = FALSE;
 960    if ($this->amazonses_use_destinations === TRUE)
 961      { $destinations = $recipients; }
 962
 963    $ret = $this->amazonses_object->send_mail
 964             ($header, $this->Subject, $body, $destinations, $source);
 965
 966    $isSent = ($ret[0] === "200")?1:0;
 967	//print_r($ret);
 968    $this->doCallback($isSent, implode(',', $recipients), 
 969                      '', '', $this->Subject, $body);
 970      
 971    // Everything looks fine.
 972    if ($isSent === 1) {return TRUE; }
 973
 974    // Some sort of error occured.
 975    throw new phpmailerException
 976      ($this->Lang('amazonses_error').$ret[1], self::STOP_CRITICAL);
 977    return FALSE;
 978  }
 979
 980  /**
 981   * Sends mail using the $Sendmail program.
 982   * @param string $header The message headers
 983   * @param string $body The message body
 984   * @throws phpmailerException
 985   * @access protected
 986   * @return bool
 987   */
 988  protected function SendmailSend($header, $body) {
 989    if ($this->Sender != '') {
 990      $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
 991    } else {
 992      $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
 993    }
 994    if ($this->SingleTo === true) {
 995      foreach ($this->SingleToArray as $val) {
 996        if(!@$mail = popen($sendmail, 'w')) {
 997          throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
 998        }
 999        fputs($mail, "To: " . $val . "\n");
1000        fputs($mail, $header);
1001        fputs($mail, $body);
1002        $result = pclose($mail);
1003        // implement call back function if it exists
1004        $isSent = ($result == 0) ? 1 : 0;
1005        $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
1006        if($result != 0) {
1007          throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1008        }
1009      }
1010    } else {
1011      if(!@$mail = popen($sendmail, 'w')) {
1012        throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1013      }
1014      fputs($mail, $header);
1015      fputs($mail, $body);
1016      $result = pclose($mail);
1017      // implement call back function if it exists
1018      $isSent = ($result == 0) ? 1 : 0;
1019      $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body);
1020      if($result != 0) {
1021        throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1022      }
1023    }
1024    return true;
1025  }
1026
1027  /**
1028   * Sends mail using the PHP mail() function.
1029   * @param string $header The message headers
1030   * @param string $body The message body
1031   * @throws phpmailerException
1032   * @access protected
1033   * @return bool
1034   */
1035  protected function MailSend($header, $body) {
1036    $toArr = array();
1037    foreach($this->to as $t) {
1038      $toArr[] = $this->AddrFormat($t);
1039    }
1040    $to = implode(', ', $toArr);
1041
1042    if (empty($this->Sender)) {
1043      $params = " ";
1044    } else {
1045      $params = sprintf("-f%s", $this->Sender);
1046    }
1047    if ($this->Sender != '' and !ini_get('safe_mode')) {
1048      $old_from = ini_get('sendmail_from');
1049      ini_set('sendmail_from', $this->Sender);
1050    }
1051      $rt = false;
1052    if ($this->SingleTo === true && count($toArr) > 1) {
1053      foreach ($toArr as $val) {
1054        $rt = $this->mail_passthru($val, $this->Subject, $body, $header, $params);
1055        // implement call back function if it exists
1056        $isSent = ($rt == 1) ? 1 : 0;
1057        $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
1058      }
1059    } else {
1060      $rt = $this->mail_passthru($to, $this->Subject, $body, $header, $params);
1061      // implement call back function if it exists
1062      $isSent = ($rt == 1) ? 1 : 0;
1063      $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
1064    }
1065    if (isset($old_from)) {
1066      ini_set('sendmail_from', $old_from);
1067    }
1068    if(!$rt) {
1069      throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
1070    }
1071    return true;
1072  }
1073
1074  /**
1075   * Sends mail via SMTP using PhpSMTP
1076   * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
1077   * @param string $header The message headers
1078   * @param string $body The message body
1079   * @throws phpmailerException
1080   * @uses SMTP
1081   * @access protected
1082   * @return bool
1083   */
1084  protected function SmtpSend($header, $body) {
1085    require_once $this->PluginDir . 'class.smtp.php';
1086    $bad_rcpt = array();
1087
1088    if(!$this->SmtpConnect()) {
1089      throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
1090    }
1091    $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
1092    if(!$this->smtp->Mail($smtp_from)) {
1093      $this->SetError($this->Lang('from_failed') . $smtp_from . ' : ' .implode(',', $this->smtp->getError()));
1094      throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
1095    }
1096
1097    // Attempt to send attach all recipients
1098    foreach($this->to as $to) {
1099      if (!$this->smtp->Recipient($to[0])) {
1100        $bad_rcpt[] = $to[0];
1101        // implement call back function if it exists
1102        $isSent = 0;
1103        $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
1104      } else {
1105        // implement call back function if it exists
1106        $isSent = 1;
1107        $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
1108      }
1109    }
1110    foreach($this->cc as $cc) {
1111      if (!$this->smtp->Recipient($cc[0])) {
1112        $bad_rcpt[] = $cc[0];
1113        // implement call back function if it exists
1114        $isSent = 0;
1115        $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
1116      } else {
1117        // implement call back function if it exists
1118        $isSent = 1;
1119        $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
1120      }
1121    }
1122    foreach($this->bcc as $bcc) {
1123      if (!$this->smtp->Recipient($bcc[0])) {
1124        $bad_rcpt[] = $bcc[0];
1125        // implement call back function if it exists
1126        $isSent = 0;
1127        $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
1128      } else {
1129        // implement call back function if it exists
1130        $isSent = 1;
1131        $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
1132      }
1133    }
1134
1135
1136    if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
1137      $badaddresses = implode(', ', $bad_rcpt);
1138      throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
1139    }
1140    if(!$this->smtp->Data($header . $body)) {
1141      throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
1142    }
1143    if($this->SMTPKeepAlive == true) {
1144      $this->smtp->Reset();
1145    } else {
1146        $this->smtp->Quit();
1147        $this->smtp->Close();
1148    }
1149    return true;
1150  }
1151
1152  /**
1153   * Initiates a connection to an SMTP server.
1154   * Returns false if the operation failed.
1155   * @param array $options An array of options compatible with stream_context_create()
1156   * @uses SMTP
1157   * @access public
1158   * @throws phpmailerException
1159   * @return bool
1160   */
1161  public function SmtpConnect($options = array()) {
1162    if(is_null($this->smtp)) {
1163      $this->smtp = new SMTP;
1164    }
1165
1166    //Already connected?
1167    if ($this->smtp->Connected()) {
1168      return true;
1169    }
1170
1171    $this->smtp->Timeout = $this->Timeout;
1172    $this->smtp->do_debug = $this->SMTPDebug;
1173    $this->smtp->Debugoutput = $this->Debugoutput;
1174    $this->smtp->do_verp = $this->do_verp;
1175    $index = 0;
1176    $tls = ($this->SMTPSecure == 'tls');
1177    $ssl = ($this->SMTPSecure == 'ssl');
1178    $hosts = explode(';', $this->Host);
1179    $lastexception = null;
1180
1181    foreach ($hosts as $hostentry) {
1182      $hostinfo = array();
1183      $host = $hostentry;
1184      $port = $this->Port;
1185      if (preg_match('/^(.+):([0-9]+)$/', $hostentry, $hostinfo)) { //If $hostentry contains 'address:port', override default
1186        $host = $hostinfo[1];
1187        $port = $hostinfo[2];
1188      }
1189      if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout, $options)) {
1190        try {
1191          if ($this->Helo) {
1192            $hello = $this->Helo;
1193          } else {
1194            $hello = $this->ServerHostname();
1195          }
1196          $this->smtp->Hello($hello);
1197
1198          if ($tls) {
1199            if (!$this->smtp->StartTLS()) {
1200              throw new phpmailerException($this->Lang('connect_host'));
1201            }
1202            //We must resend HELO after tls negotiation
1203            $this->smtp->Hello($hello);
1204          }
1205          if ($this->SMTPAuth) {
1206            if (!$this->smtp->Authenticate($this->Username, $this->Password, $this->AuthType, $this->Realm, $this->Workstation)) {
1207              throw new phpmailerException($this->Lang('authenticate'));
1208            }
1209          }
1210          return true;
1211        } catch (phpmailerException $e) {
1212          $lastexception = $e;
1213          //We must have connected, but then failed TLS or Auth, so close connection nicely
1214          $this->smtp->Quit();
1215        }
1216      }
1217    }
1218    //If we get here, all connection attempts have failed, so close connection hard
1219    $this->smtp->Close();
1220    //As we've caught all exceptions, just report whatever the last one was
1221    if ($this->exceptions and !is_null($lastexception)) {
1222      throw $lastexception;
1223    }
1224    return false;
1225  }
1226
1227  /**
1228   * Closes the active SMTP session if one exists.
1229   * @return void
1230   */
1231  public function SmtpClose() {
1232    if ($this->smtp !== null) {
1233      if($this->smtp->Connected()) {
1234        $this->smtp->Quit();
1235        $this->smtp->Close();
1236      }
1237    }
1238  }
1239
1240  /**
1241   * Sets the language for all class error messages.
1242   * Returns false if it cannot load the language file.  The default language is English.
1243   * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
1244   * @param string $lang_path Path to the language file directory
1245   * @return bool
1246   * @access public
1247   */
1248  function SetLanguage($langcode = 'en', $lang_path = 'language/') {
1249    //Define full set of translatable strings
1250    $PHPMAILER_LANG = array(
1251      'authenticate'         => 'SMTP Error: Could not authenticate.',
1252      'connect_host'         => 'SMTP Error: Could not connect to SMTP host.',
1253      'data_not_accepted'    => 'SMTP Error: Data not accepted.',
1254      'empty_message'        => 'Message body empty',
1255      'encoding'             => 'Unknown encoding: ',
1256      'execute'              => 'Could not execute: ',
1257      'file_access'          => 'Could not access file: ',
1258      'file_open'            => 'File Error: Could not open file: ',
1259      'from_failed'          => 'The following From address failed: ',
1260      'instantiate'          => 'Could not instantiate mail function.',
1261      'invalid_address'      => 'Invalid address',
1262      'mailer_not_supported' => ' mailer is not supported.',
1263      'provide_address'      => 'You must provide at least one recipient email address.',
1264      'recipients_failed'    => 'SMTP Error: The following recipients failed: ',
1265      'signing'              => 'Signing Error: ',
1266      'smtp_connect_failed'  => 'SMTP Connect() failed.',
1267      'smtp_error'           => 'SMTP server error: ',
1268      'variable_set'         => 'Cannot set or reset variable: ',
1269	  'amazonses_error'      => 'AmazonSES Error: '
1270    );
1271    //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
1272    $l = true;
1273    if ($langcode != 'en') { //There is no English translation file
1274      $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
1275    }
1276    $this->language = $PHPMAILER_LANG;
1277    return ($l == true); //Returns false if language not found
1278  }
1279
1280  /**
1281  * Return the current array of language strings
1282  * @return array
1283  */
1284  public function GetTranslations() {
1285    return $this->language;
1286  }
1287
1288  /////////////////////////////////////////////////
1289  // METHODS, MESSAGE CREATION
1290  /////////////////////////////////////////////////
1291
1292  /**
1293   * Creates recipient headers.
1294   * @access public
1295   * @param string $type
1296   * @param array $addr
1297   * @return string
1298   */
1299  public function AddrAppend($type, $addr) {
1300    $addr_str = $type . ': ';
1301    $addresses = array();
1302    foreach ($addr as $a) {
1303      $addresses[] = $this->AddrFormat($a);
1304    }
1305    $addr_str .= implode(', ', $addresses);
1306    $addr_str .= $this->LE;
1307
1308    return $addr_str;
1309  }
1310
1311  /**
1312   * Formats an address correctly.
1313   * @access public
1314   * @param string $addr
1315   * @return string
1316   */
1317  public function AddrFormat($addr) {
1318    if (empty($addr[1])) {
1319      return $this->SecureHeader($addr[0]);
1320    } else {
1321      return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
1322    }
1323  }
1324
1325  /**
1326   * Wraps message for use with mailers that do not
1327   * automatically perform wrapping and for quoted-printable.
1328   * Original written by philippe.
1329   * @param string $message The message to wrap
1330   * @param integer $length The line length to wrap to
1331   * @param boolean $qp_mode Whether to run in Quoted-Printable mode
1332   * @access public
1333   * @return string
1334   */
1335  public function WrapText($message, $length, $qp_mode = false) {
1336    $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
1337    // If utf-8 encoding is used, we will need to make sure we don't
1338    // split multibyte characters when we wrap
1339    $is_utf8 = (strtolower($this->CharSet) == "utf-8");
1340    $lelen = strlen($this->LE);
1341    $crlflen = strlen(self::CRLF);
1342
1343    $message = $this->FixEOL($message);
1344    if (substr($message, -$lelen) == $this->LE) {
1345      $message = substr($message, 0, -$lelen);
1346    }
1347
1348    $line = explode($this->LE, $message);   // Magic. We know FixEOL uses $LE
1349    $message = '';
1350    for ($i = 0 ;$i < count($line); $i++) {
1351      $line_part = explode(' ', $line[$i]);
1352      $buf = '';
1353      for ($e = 0; $e<count($line_part); $e++) {
1354        $word = $line_part[$e];
1355        if ($qp_mode and (strlen($word) > $length)) {
1356          $space_left = $length - strlen($buf) - $crlflen;
1357          if ($e != 0) {
1358            if ($space_left > 20) {
1359              $len = $space_left;
1360              if ($is_utf8) {
1361                $len = $this->UTF8CharBoundary($word, $len);
1362              } elseif (substr($word, $len - 1, 1) == "=") {
1363                $len--;
1364              } elseif (substr($word, $len - 2, 1) == "=") {
1365                $len -= 2;
1366              }
1367              $part = substr($word, 0, $len);
1368              $word = substr($word, $len);
1369              $buf .= ' ' . $part;
1370              $message .= $buf . sprintf("=%s", self::CRLF);
1371            } else {
1372              $message .= $buf . $soft_break;
1373            }
1374            $buf = '';
1375          }
1376          while (strlen($word) > 0) {
1377            if ($length <= 0) {
1378                break;
1379            }
1380            $len = $length;
1381            if ($is_utf8) {
1382              $len = $this->UTF8CharBoundary($word, $len);
1383            } elseif (substr($word, $len - 1, 1) == "=") {
1384              $len--;
1385            } elseif (substr($word, $len - 2, 1) == "=") {
1386              $len -= 2;
1387            }
1388            $part = substr($word, 0, $len);
1389            $word = substr($word, $len);
1390
1391            if (strlen($word) > 0) {
1392              $message .= $part . sprintf("=%s", self::CRLF);
1393            } else {
1394              $buf = $part;
1395            }
1396          }
1397        } else {
1398          $buf_o = $buf;
1399          $buf .= ($e == 0) ? $word : (' ' . $word);
1400
1401          if (strlen($buf) > $length and $buf_o != '') {
1402            $message .= $buf_o . $soft_break;
1403            $buf = $word;
1404          }
1405        }
1406      }
1407      $message .= $buf . self::CRLF;
1408    }
1409
1410    return $message;
1411  }
1412
1413  /**
1414   * Finds last character boundary prior to maxLength in a utf-8
1415   * quoted (printable) encoded string.
1416   * Original written by Colin Brown.
1417   * @access public
1418   * @param string $encodedText utf-8 QP text
1419   * @param int    $maxLength   find last character boundary prior to this length
1420   * @return int
1421   */
1422  public function UTF8CharBoundary($encodedText, $maxLength) {
1423    $foundSplitPos = false;
1424    $lookBack = 3;
1425    while (!$foundSplitPos) {
1426      $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
1427      $encodedCharPos = strpos($lastChunk, "=");
1428      if ($encodedCharPos !== false) {
1429        // Found start of encoded character byte within $lookBack block.
1430        // Check the encoded byte value (the 2 chars after the '=')
1431        $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
1432        $dec = hexdec($hex);
1433        if ($dec < 128) { // Single byte character.
1434          // If the encoded char was found at pos 0, it will fit
1435          // otherwise reduce maxLength to start of the encoded char
1436          $maxLength = ($encodedCharPos == 0) ? $maxLength :
1437          $maxLength - ($lookBack - $encodedCharPos);
1438          $foundSplitPos = true;
1439        } elseif ($dec >= 192) { // First byte of a multi byte character
1440          // Reduce maxLength to split at start of character
1441          $maxLength = $maxLength - ($lookBack - $encodedCharPos);
1442          $foundSplitPos = true;
1443        } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
1444          $lookBack += 3;
1445        }
1446      } else {
1447        // No encoded character found
1448        $foundSplitPos = true;
1449      }
1450    }
1451    return $maxLength;
1452  }
1453
1454
1455  /**
1456   * Set the body wrapping.
1457   * @access public
1458   * @return void
1459   */
1460  public function SetWordWrap() {
1461    if($this->WordWrap < 1) {
1462      return;
1463    }
1464
1465    switch($this->message_type) {
1466      case 'alt':
1467      case 'alt_inline':
1468      case 'alt_attach':
1469      case 'alt_inline_attach':
1470        $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
1471        break;
1472      default:
1473        $this->Body = $this->WrapText($this->Body, $this->WordWrap);
1474        break;
1475    }
1476  }
1477
1478  /**
1479   * Assembles message header.
1480   * @access public
1481   * @return string The assembled header
1482   */
1483  public function CreateHeader() {
1484    $result = '';
1485
1486    // Set the boundaries
1487    $uniq_id = md5(uniqid(time()));
1488    $this->boundary[1] = 'b1_' . $uniq_id;
1489    $this->boundary[2] = 'b2_' . $uniq_id;
1490    $this->boundary[3] = 'b3_' . $uniq_id;
1491
1492    if ($this->MessageDate == '') {
1493      $result .= $this->HeaderLine('Date', self::RFCDate());
1494    } else {
1495      $result .= $this->HeaderLine('Date', $this->MessageDate);
1496    }
1497
1498    if ($this->ReturnPath) {
1499      $result .= $this->HeaderLine('Return-Path', '<'.trim($this->ReturnPath).'>');
1500    } elseif ($this->Sender == '') {
1501      $result .= $this->HeaderLine('Return-Path', '<'.trim($this->From).'>');
1502    } else {
1503      $result .= $this->HeaderLine('Return-Path', '<'.trim($this->Sender).'>');
1504    }
1505
1506    // To be created automatically by mail()
1507    if($this->Mailer != 'mail') {
1508      if ($this->SingleTo === true) {
1509        foreach($this->to as $t) {
1510          $this->SingleToArray[] = $this->AddrFormat($t);
1511        }
1512      } else {
1513        if(count($this->to) > 0

Large files files are truncated, but you can click here to view the full file