PageRenderTime 103ms CodeModel.GetById 56ms app.highlight 34ms RepoModel.GetById 1ms app.codeStats 1ms

/_app/vendor/PHPMailer/class.phpmailer.php

https://bitbucket.org/sirestudios/fortis-wellness
PHP | 2959 lines | 1752 code | 215 blank | 992 comment | 287 complexity | 3b7364f5c9dbc757dc4c01330bc135ee 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
 512  /////////////////////////////////////////////////
 513  // CONSTANTS
 514  /////////////////////////////////////////////////
 515
 516  const STOP_MESSAGE  = 0; // message only, continue processing
 517  const STOP_CONTINUE = 1; // message?, likely ok to continue processing
 518  const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
 519  const CRLF = "\r\n";     // SMTP RFC specified EOL
 520
 521  /////////////////////////////////////////////////
 522  // METHODS, VARIABLES
 523  /////////////////////////////////////////////////
 524
 525  /**
 526   * Calls actual mail() function, but in a safe_mode aware fashion
 527   * Also, unless sendmail_path points to sendmail (or something that
 528   * claims to be sendmail), don't pass params (not a perfect fix,
 529   * but it will do)
 530   * @param string $to To
 531   * @param string $subject Subject
 532   * @param string $body Message Body
 533   * @param string $header Additional Header(s)
 534   * @param string $params Params
 535   * @access private
 536   * @return bool
 537   */
 538  private function mail_passthru($to, $subject, $body, $header, $params) {
 539    if ( ini_get('safe_mode') || !($this->UseSendmailOptions) ) {
 540        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header);
 541    } else {
 542        $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params);
 543    }
 544    return $rt;
 545  }
 546
 547  /**
 548   * Outputs debugging info via user-defined method
 549   * @param string $str
 550   */
 551  protected function edebug($str) {
 552    switch ($this->Debugoutput) {
 553      case 'error_log':
 554        error_log($str);
 555        break;
 556      case 'html':
 557        //Cleans up output a bit for a better looking display that's HTML-safe
 558        echo htmlentities(preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, $this->CharSet)."<br>\n";
 559        break;
 560      case 'echo':
 561      default:
 562        //Just echoes exactly what was received
 563        echo $str;
 564    }
 565  }
 566
 567  /**
 568   * Constructor
 569   * @param boolean $exceptions Should we throw external exceptions?
 570   */
 571  public function __construct($exceptions = false) {
 572    $this->exceptions = ($exceptions == true);
 573  }
 574
 575  /**
 576   * Destructor
 577   */
 578  public function __destruct() {
 579      if ($this->Mailer == 'smtp') { //Close any open SMTP connection nicely
 580          $this->SmtpClose();
 581      }
 582  }
 583
 584  /**
 585   * Sets message type to HTML.
 586   * @param bool $ishtml
 587   * @return void
 588   */
 589  public function IsHTML($ishtml = true) {
 590    if ($ishtml) {
 591      $this->ContentType = 'text/html';
 592    } else {
 593      $this->ContentType = 'text/plain';
 594    }
 595  }
 596
 597  /**
 598   * Sets Mailer to send message using SMTP.
 599   * @return void
 600   */
 601  public function IsSMTP() {
 602    $this->Mailer = 'smtp';
 603  }
 604
 605  /**
 606   * Sets Mailer to send message using PHP mail() function.
 607   * @return void
 608   */
 609  public function IsMail() {
 610    $this->Mailer = 'mail';
 611  }
 612
 613  /**
 614   * Sets Mailer to send message using the $Sendmail program.
 615   * @return void
 616   */
 617  public function IsSendmail() {
 618    if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
 619      $this->Sendmail = '/var/qmail/bin/sendmail';
 620    }
 621    $this->Mailer = 'sendmail';
 622  }
 623
 624  /**
 625   * Sets Mailer to send message using the qmail MTA.
 626   * @return void
 627   */
 628  public function IsQmail() {
 629    if (stristr(ini_get('sendmail_path'), 'qmail')) {
 630      $this->Sendmail = '/var/qmail/bin/sendmail';
 631    }
 632    $this->Mailer = 'sendmail';
 633  }
 634
 635  /////////////////////////////////////////////////
 636  // METHODS, RECIPIENTS
 637  /////////////////////////////////////////////////
 638
 639  /**
 640   * Adds a "To" address.
 641   * @param string $address
 642   * @param string $name
 643   * @return boolean true on success, false if address already used
 644   */
 645  public function AddAddress($address, $name = '') {
 646    return $this->AddAnAddress('to', $address, $name);
 647  }
 648
 649  /**
 650   * Adds a "Cc" address.
 651   * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
 652   * @param string $address
 653   * @param string $name
 654   * @return boolean true on success, false if address already used
 655   */
 656  public function AddCC($address, $name = '') {
 657    return $this->AddAnAddress('cc', $address, $name);
 658  }
 659
 660  /**
 661   * Adds a "Bcc" address.
 662   * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
 663   * @param string $address
 664   * @param string $name
 665   * @return boolean true on success, false if address already used
 666   */
 667  public function AddBCC($address, $name = '') {
 668    return $this->AddAnAddress('bcc', $address, $name);
 669  }
 670
 671  /**
 672   * Adds a "Reply-to" address.
 673   * @param string $address
 674   * @param string $name
 675   * @return boolean
 676   */
 677  public function AddReplyTo($address, $name = '') {
 678    return $this->AddAnAddress('Reply-To', $address, $name);
 679  }
 680
 681  /**
 682   * Adds an address to one of the recipient arrays
 683   * Addresses that have been added already return false, but do not throw exceptions
 684   * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
 685   * @param string $address The email address to send to
 686   * @param string $name
 687   * @throws phpmailerException
 688   * @return boolean true on success, false if address already used or invalid in some way
 689   * @access protected
 690   */
 691  protected function AddAnAddress($kind, $address, $name = '') {
 692    if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
 693      $this->SetError($this->Lang('Invalid recipient array').': '.$kind);
 694      if ($this->exceptions) {
 695        throw new phpmailerException('Invalid recipient array: ' . $kind);
 696      }
 697      if ($this->SMTPDebug) {
 698        $this->edebug($this->Lang('Invalid recipient array').': '.$kind);
 699      }
 700      return false;
 701    }
 702    $address = trim($address);
 703    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
 704    if (!$this->ValidateAddress($address)) {
 705      $this->SetError($this->Lang('invalid_address').': '. $address);
 706      if ($this->exceptions) {
 707        throw new phpmailerException($this->Lang('invalid_address').': '.$address);
 708      }
 709      if ($this->SMTPDebug) {
 710        $this->edebug($this->Lang('invalid_address').': '.$address);
 711      }
 712      return false;
 713    }
 714    if ($kind != 'Reply-To') {
 715      if (!isset($this->all_recipients[strtolower($address)])) {
 716        array_push($this->$kind, array($address, $name));
 717        $this->all_recipients[strtolower($address)] = true;
 718        return true;
 719      }
 720    } else {
 721      if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
 722        $this->ReplyTo[strtolower($address)] = array($address, $name);
 723      return true;
 724    }
 725  }
 726  return false;
 727}
 728
 729  /**
 730   * Set the From and FromName properties
 731   * @param string $address
 732   * @param string $name
 733   * @param boolean $auto Whether to also set the Sender address, defaults to true
 734   * @throws phpmailerException
 735   * @return boolean
 736   */
 737  public function SetFrom($address, $name = '', $auto = true) {
 738    $address = trim($address);
 739    $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
 740    if (!$this->ValidateAddress($address)) {
 741      $this->SetError($this->Lang('invalid_address').': '. $address);
 742      if ($this->exceptions) {
 743        throw new phpmailerException($this->Lang('invalid_address').': '.$address);
 744      }
 745      if ($this->SMTPDebug) {
 746        $this->edebug($this->Lang('invalid_address').': '.$address);
 747      }
 748      return false;
 749    }
 750    $this->From = $address;
 751    $this->FromName = $name;
 752    if ($auto) {
 753      if (empty($this->Sender)) {
 754        $this->Sender = $address;
 755      }
 756    }
 757    return true;
 758  }
 759
 760  /**
 761   * Check that a string looks roughly like an email address should
 762   * Static so it can be used without instantiation, public so people can overload
 763   * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is
 764   * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to
 765   * not allow a@b type valid addresses :(
 766   * @link http://squiloople.com/2009/12/20/email-address-validation/
 767   * @copyright regex Copyright Michael Rushton 2009-10 | http://squiloople.com/ | Feel free to use and redistribute this code. But please keep this copyright notice.
 768   * @param string $address The email address to check
 769   * @return boolean
 770   * @static
 771   * @access public
 772   */
 773  public static function ValidateAddress($address) {
 774      if (defined('PCRE_VERSION')) { //Check this instead of extension_loaded so it works when that function is disabled
 775          if (version_compare(PCRE_VERSION, '8.0') >= 0) {
 776              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);
 777          } else {
 778              //Fall back to an older regex that doesn't need a recent PCRE
 779              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);
 780          }
 781      } else {
 782          //No PCRE! Do something _very_ approximate!
 783          //Check the address is 3 chars or longer and contains an @ that's not the first or last char
 784          return (strlen($address) >= 3 and strpos($address, '@') >= 1 and strpos($address, '@') != strlen($address) - 1);
 785      }
 786  }
 787
 788  /////////////////////////////////////////////////
 789  // METHODS, MAIL SENDING
 790  /////////////////////////////////////////////////
 791
 792  /**
 793   * Creates message and assigns Mailer. If the message is
 794   * not sent successfully then it returns false.  Use the ErrorInfo
 795   * variable to view description of the error.
 796   * @throws phpmailerException
 797   * @return bool
 798   */
 799  public function Send() {
 800    try {
 801      if(!$this->PreSend()) return false;
 802      return $this->PostSend();
 803    } catch (phpmailerException $e) {
 804      $this->mailHeader = '';
 805      $this->SetError($e->getMessage());
 806      if ($this->exceptions) {
 807        throw $e;
 808      }
 809      return false;
 810    }
 811  }
 812
 813  /**
 814   * Prep mail by constructing all message entities
 815   * @throws phpmailerException
 816   * @return bool
 817   */
 818  public function PreSend() {
 819    try {
 820      $this->mailHeader = "";
 821      if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
 822        throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
 823      }
 824
 825      // Set whether the message is multipart/alternative
 826      if(!empty($this->AltBody)) {
 827        $this->ContentType = 'multipart/alternative';
 828      }
 829
 830      $this->error_count = 0; // reset errors
 831      $this->SetMessageType();
 832      //Refuse to send an empty message unless we are specifically allowing it
 833      if (!$this->AllowEmpty and empty($this->Body)) {
 834        throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
 835      }
 836
 837      $this->MIMEHeader = $this->CreateHeader();
 838      $this->MIMEBody = $this->CreateBody();
 839
 840      // To capture the complete message when using mail(), create
 841      // an extra header list which CreateHeader() doesn't fold in
 842      if ($this->Mailer == 'mail') {
 843        if (count($this->to) > 0) {
 844          $this->mailHeader .= $this->AddrAppend("To", $this->to);
 845        } else {
 846          $this->mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;");
 847        }
 848        $this->mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject))));
 849      }
 850
 851      // digitally sign with DKIM if enabled
 852      if (!empty($this->DKIM_domain) && !empty($this->DKIM_private) && !empty($this->DKIM_selector) && !empty($this->DKIM_domain) && file_exists($this->DKIM_private)) {
 853        $header_dkim = $this->DKIM_Add($this->MIMEHeader . $this->mailHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody);
 854        $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader;
 855      }
 856
 857      return true;
 858
 859    } catch (phpmailerException $e) {
 860      $this->SetError($e->getMessage());
 861      if ($this->exceptions) {
 862        throw $e;
 863      }
 864      return false;
 865    }
 866  }
 867
 868  /**
 869   * Actual Email transport function
 870   * Send the email via the selected mechanism
 871   * @throws phpmailerException
 872   * @return bool
 873   */
 874  public function PostSend() {
 875    try {
 876      // Choose the mailer and send through it
 877      switch($this->Mailer) {
 878        case 'sendmail':
 879          return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody);
 880        case 'smtp':
 881          return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody);
 882        case 'mail':
 883          return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
 884        default:
 885          return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
 886      }
 887    } catch (phpmailerException $e) {
 888      $this->SetError($e->getMessage());
 889      if ($this->exceptions) {
 890        throw $e;
 891      }
 892      if ($this->SMTPDebug) {
 893        $this->edebug($e->getMessage()."\n");
 894      }
 895    }
 896    return false;
 897  }
 898
 899  /**
 900   * Sends mail using the $Sendmail program.
 901   * @param string $header The message headers
 902   * @param string $body The message body
 903   * @throws phpmailerException
 904   * @access protected
 905   * @return bool
 906   */
 907  protected function SendmailSend($header, $body) {
 908    if ($this->Sender != '') {
 909      $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
 910    } else {
 911      $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
 912    }
 913    if ($this->SingleTo === true) {
 914      foreach ($this->SingleToArray as $val) {
 915        if(!@$mail = popen($sendmail, 'w')) {
 916          throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
 917        }
 918        fputs($mail, "To: " . $val . "\n");
 919        fputs($mail, $header);
 920        fputs($mail, $body);
 921        $result = pclose($mail);
 922        // implement call back function if it exists
 923        $isSent = ($result == 0) ? 1 : 0;
 924        $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
 925        if($result != 0) {
 926          throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
 927        }
 928      }
 929    } else {
 930      if(!@$mail = popen($sendmail, 'w')) {
 931        throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
 932      }
 933      fputs($mail, $header);
 934      fputs($mail, $body);
 935      $result = pclose($mail);
 936      // implement call back function if it exists
 937      $isSent = ($result == 0) ? 1 : 0;
 938      $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body);
 939      if($result != 0) {
 940        throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
 941      }
 942    }
 943    return true;
 944  }
 945
 946  /**
 947   * Sends mail using the PHP mail() function.
 948   * @param string $header The message headers
 949   * @param string $body The message body
 950   * @throws phpmailerException
 951   * @access protected
 952   * @return bool
 953   */
 954  protected function MailSend($header, $body) {
 955    $toArr = array();
 956    foreach($this->to as $t) {
 957      $toArr[] = $this->AddrFormat($t);
 958    }
 959    $to = implode(', ', $toArr);
 960
 961    if (empty($this->Sender)) {
 962      $params = " ";
 963    } else {
 964      $params = sprintf("-f%s", $this->Sender);
 965    }
 966    if ($this->Sender != '' and !ini_get('safe_mode')) {
 967      $old_from = ini_get('sendmail_from');
 968      ini_set('sendmail_from', $this->Sender);
 969    }
 970      $rt = false;
 971    if ($this->SingleTo === true && count($toArr) > 1) {
 972      foreach ($toArr as $val) {
 973        $rt = $this->mail_passthru($val, $this->Subject, $body, $header, $params);
 974        // implement call back function if it exists
 975        $isSent = ($rt == 1) ? 1 : 0;
 976        $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
 977      }
 978    } else {
 979      $rt = $this->mail_passthru($to, $this->Subject, $body, $header, $params);
 980      // implement call back function if it exists
 981      $isSent = ($rt == 1) ? 1 : 0;
 982      $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
 983    }
 984    if (isset($old_from)) {
 985      ini_set('sendmail_from', $old_from);
 986    }
 987    if(!$rt) {
 988      throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
 989    }
 990    return true;
 991  }
 992
 993  /**
 994   * Sends mail via SMTP using PhpSMTP
 995   * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
 996   * @param string $header The message headers
 997   * @param string $body The message body
 998   * @throws phpmailerException
 999   * @uses SMTP
1000   * @access protected
1001   * @return bool
1002   */
1003  protected function SmtpSend($header, $body) {
1004    require_once $this->PluginDir . 'class.smtp.php';
1005    $bad_rcpt = array();
1006
1007    if(!$this->SmtpConnect()) {
1008      throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
1009    }
1010    $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
1011    if(!$this->smtp->Mail($smtp_from)) {
1012      $this->SetError($this->Lang('from_failed') . $smtp_from . ' : ' .implode(',', $this->smtp->getError()));
1013      throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
1014    }
1015
1016    // Attempt to send attach all recipients
1017    foreach($this->to as $to) {
1018      if (!$this->smtp->Recipient($to[0])) {
1019        $bad_rcpt[] = $to[0];
1020        // implement call back function if it exists
1021        $isSent = 0;
1022        $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
1023      } else {
1024        // implement call back function if it exists
1025        $isSent = 1;
1026        $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
1027      }
1028    }
1029    foreach($this->cc as $cc) {
1030      if (!$this->smtp->Recipient($cc[0])) {
1031        $bad_rcpt[] = $cc[0];
1032        // implement call back function if it exists
1033        $isSent = 0;
1034        $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
1035      } else {
1036        // implement call back function if it exists
1037        $isSent = 1;
1038        $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
1039      }
1040    }
1041    foreach($this->bcc as $bcc) {
1042      if (!$this->smtp->Recipient($bcc[0])) {
1043        $bad_rcpt[] = $bcc[0];
1044        // implement call back function if it exists
1045        $isSent = 0;
1046        $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
1047      } else {
1048        // implement call back function if it exists
1049        $isSent = 1;
1050        $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
1051      }
1052    }
1053
1054
1055    if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
1056      $badaddresses = implode(', ', $bad_rcpt);
1057      throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
1058    }
1059    if(!$this->smtp->Data($header . $body)) {
1060      throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
1061    }
1062    if($this->SMTPKeepAlive == true) {
1063      $this->smtp->Reset();
1064    } else {
1065        $this->smtp->Quit();
1066        $this->smtp->Close();
1067    }
1068    return true;
1069  }
1070
1071  /**
1072   * Initiates a connection to an SMTP server.
1073   * Returns false if the operation failed.
1074   * @param array $options An array of options compatible with stream_context_create()
1075   * @uses SMTP
1076   * @access public
1077   * @throws phpmailerException
1078   * @return bool
1079   */
1080  public function SmtpConnect($options = array()) {
1081    if(is_null($this->smtp)) {
1082      $this->smtp = new SMTP;
1083    }
1084
1085    //Already connected?
1086    if ($this->smtp->Connected()) {
1087      return true;
1088    }
1089
1090    $this->smtp->Timeout = $this->Timeout;
1091    $this->smtp->do_debug = $this->SMTPDebug;
1092    $this->smtp->Debugoutput = $this->Debugoutput;
1093    $this->smtp->do_verp = $this->do_verp;
1094    $index = 0;
1095    $tls = ($this->SMTPSecure == 'tls');
1096    $ssl = ($this->SMTPSecure == 'ssl');
1097    $hosts = explode(';', $this->Host);
1098    $lastexception = null;
1099
1100    foreach ($hosts as $hostentry) {
1101      $hostinfo = array();
1102      $host = $hostentry;
1103      $port = $this->Port;
1104      if (preg_match('/^(.+):([0-9]+)$/', $hostentry, $hostinfo)) { //If $hostentry contains 'address:port', override default
1105        $host = $hostinfo[1];
1106        $port = $hostinfo[2];
1107      }
1108      if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout, $options)) {
1109        try {
1110          if ($this->Helo) {
1111            $hello = $this->Helo;
1112          } else {
1113            $hello = $this->ServerHostname();
1114          }
1115          $this->smtp->Hello($hello);
1116
1117          if ($tls) {
1118            if (!$this->smtp->StartTLS()) {
1119              throw new phpmailerException($this->Lang('connect_host'));
1120            }
1121            //We must resend HELO after tls negotiation
1122            $this->smtp->Hello($hello);
1123          }
1124          if ($this->SMTPAuth) {
1125            if (!$this->smtp->Authenticate($this->Username, $this->Password, $this->AuthType, $this->Realm, $this->Workstation)) {
1126              throw new phpmailerException($this->Lang('authenticate'));
1127            }
1128          }
1129          return true;
1130        } catch (phpmailerException $e) {
1131          $lastexception = $e;
1132          //We must have connected, but then failed TLS or Auth, so close connection nicely
1133          $this->smtp->Quit();
1134        }
1135      }
1136    }
1137    //If we get here, all connection attempts have failed, so close connection hard
1138    $this->smtp->Close();
1139    //As we've caught all exceptions, just report whatever the last one was
1140    if ($this->exceptions and !is_null($lastexception)) {
1141      throw $lastexception;
1142    }
1143    return false;
1144  }
1145
1146  /**
1147   * Closes the active SMTP session if one exists.
1148   * @return void
1149   */
1150  public function SmtpClose() {
1151    if ($this->smtp !== null) {
1152      if($this->smtp->Connected()) {
1153        $this->smtp->Quit();
1154        $this->smtp->Close();
1155      }
1156    }
1157  }
1158
1159  /**
1160   * Sets the language for all class error messages.
1161   * Returns false if it cannot load the language file.  The default language is English.
1162   * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
1163   * @param string $lang_path Path to the language file directory
1164   * @return bool
1165   * @access public
1166   */
1167  function SetLanguage($langcode = 'en', $lang_path = 'language/') {
1168    //Define full set of translatable strings
1169    $PHPMAILER_LANG = array(
1170      'authenticate'         => 'SMTP Error: Could not authenticate.',
1171      'connect_host'         => 'SMTP Error: Could not connect to SMTP host.',
1172      'data_not_accepted'    => 'SMTP Error: Data not accepted.',
1173      'empty_message'        => 'Message body empty',
1174      'encoding'             => 'Unknown encoding: ',
1175      'execute'              => 'Could not execute: ',
1176      'file_access'          => 'Could not access file: ',
1177      'file_open'            => 'File Error: Could not open file: ',
1178      'from_failed'          => 'The following From address failed: ',
1179      'instantiate'          => 'Could not instantiate mail function.',
1180      'invalid_address'      => 'Invalid address',
1181      'mailer_not_supported' => ' mailer is not supported.',
1182      'provide_address'      => 'You must provide at least one recipient email address.',
1183      'recipients_failed'    => 'SMTP Error: The following recipients failed: ',
1184      'signing'              => 'Signing Error: ',
1185      'smtp_connect_failed'  => 'SMTP Connect() failed.',
1186      'smtp_error'           => 'SMTP server error: ',
1187      'variable_set'         => 'Cannot set or reset variable: '
1188    );
1189    //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
1190    $l = true;
1191    if ($langcode != 'en') { //There is no English translation file
1192      $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
1193    }
1194    $this->language = $PHPMAILER_LANG;
1195    return ($l == true); //Returns false if language not found
1196  }
1197
1198  /**
1199  * Return the current array of language strings
1200  * @return array
1201  */
1202  public function GetTranslations() {
1203    return $this->language;
1204  }
1205
1206  /////////////////////////////////////////////////
1207  // METHODS, MESSAGE CREATION
1208  /////////////////////////////////////////////////
1209
1210  /**
1211   * Creates recipient headers.
1212   * @access public
1213   * @param string $type
1214   * @param array $addr
1215   * @return string
1216   */
1217  public function AddrAppend($type, $addr) {
1218    $addr_str = $type . ': ';
1219    $addresses = array();
1220    foreach ($addr as $a) {
1221      $addresses[] = $this->AddrFormat($a);
1222    }
1223    $addr_str .= implode(', ', $addresses);
1224    $addr_str .= $this->LE;
1225
1226    return $addr_str;
1227  }
1228
1229  /**
1230   * Formats an address correctly.
1231   * @access public
1232   * @param string $addr
1233   * @return string
1234   */
1235  public function AddrFormat($addr) {
1236    if (empty($addr[1])) {
1237      return $this->SecureHeader($addr[0]);
1238    } else {
1239      return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
1240    }
1241  }
1242
1243  /**
1244   * Wraps message for use with mailers that do not
1245   * automatically perform wrapping and for quoted-printable.
1246   * Original written by philippe.
1247   * @param string $message The message to wrap
1248   * @param integer $length The line length to wrap to
1249   * @param boolean $qp_mode Whether to run in Quoted-Printable mode
1250   * @access public
1251   * @return string
1252   */
1253  public function WrapText($message, $length, $qp_mode = false) {
1254    $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
1255    // If utf-8 encoding is used, we will need to make sure we don't
1256    // split multibyte characters when we wrap
1257    $is_utf8 = (strtolower($this->CharSet) == "utf-8");
1258    $lelen = strlen($this->LE);
1259    $crlflen = strlen(self::CRLF);
1260
1261    $message = $this->FixEOL($message);
1262    if (substr($message, -$lelen) == $this->LE) {
1263      $message = substr($message, 0, -$lelen);
1264    }
1265
1266    $line = explode($this->LE, $message);   // Magic. We know FixEOL uses $LE
1267    $message = '';
1268    for ($i = 0 ;$i < count($line); $i++) {
1269      $line_part = explode(' ', $line[$i]);
1270      $buf = '';
1271      for ($e = 0; $e<count($line_part); $e++) {
1272        $word = $line_part[$e];
1273        if ($qp_mode and (strlen($word) > $length)) {
1274          $space_left = $length - strlen($buf) - $crlflen;
1275          if ($e != 0) {
1276            if ($space_left > 20) {
1277              $len = $space_left;
1278              if ($is_utf8) {
1279                $len = $this->UTF8CharBoundary($word, $len);
1280              } elseif (substr($word, $len - 1, 1) == "=") {
1281                $len--;
1282              } elseif (substr($word, $len - 2, 1) == "=") {
1283                $len -= 2;
1284              }
1285              $part = substr($word, 0, $len);
1286              $word = substr($word, $len);
1287              $buf .= ' ' . $part;
1288              $message .= $buf . sprintf("=%s", self::CRLF);
1289            } else {
1290              $message .= $buf . $soft_break;
1291            }
1292            $buf = '';
1293          }
1294          while (strlen($word) > 0) {
1295            if ($length <= 0) {
1296                break;
1297            }
1298            $len = $length;
1299            if ($is_utf8) {
1300              $len = $this->UTF8CharBoundary($word, $len);
1301            } elseif (substr($word, $len - 1, 1) == "=") {
1302              $len--;
1303            } elseif (substr($word, $len - 2, 1) == "=") {
1304              $len -= 2;
1305            }
1306            $part = substr($word, 0, $len);
1307            $word = substr($word, $len);
1308
1309            if (strlen($word) > 0) {
1310              $message .= $part . sprintf("=%s", self::CRLF);
1311            } else {
1312              $buf = $part;
1313            }
1314          }
1315        } else {
1316          $buf_o = $buf;
1317          $buf .= ($e == 0) ? $word : (' ' . $word);
1318
1319          if (strlen($buf) > $length and $buf_o != '') {
1320            $message .= $buf_o . $soft_break;
1321            $buf = $word;
1322          }
1323        }
1324      }
1325      $message .= $buf . self::CRLF;
1326    }
1327
1328    return $message;
1329  }
1330
1331  /**
1332   * Finds last character boundary prior to maxLength in a utf-8
1333   * quoted (printable) encoded string.
1334   * Original written by Colin Brown.
1335   * @access public
1336   * @param string $encodedText utf-8 QP text
1337   * @param int    $maxLength   find last character boundary prior to this length
1338   * @return int
1339   */
1340  public function UTF8CharBoundary($encodedText, $maxLength) {
1341    $foundSplitPos = false;
1342    $lookBack = 3;
1343    while (!$foundSplitPos) {
1344      $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
1345      $encodedCharPos = strpos($lastChunk, "=");
1346      if ($encodedCharPos !== false) {
1347        // Found start of encoded character byte within $lookBack block.
1348        // Check the encoded byte value (the 2 chars after the '=')
1349        $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
1350        $dec = hexdec($hex);
1351        if ($dec < 128) { // Single byte character.
1352          // If the encoded char was found at pos 0, it will fit
1353          // otherwise reduce maxLength to start of the encoded char
1354          $maxLength = ($encodedCharPos == 0) ? $maxLength :
1355          $maxLength - ($lookBack - $encodedCharPos);
1356          $foundSplitPos = true;
1357        } elseif ($dec >= 192) { // First byte of a multi byte character
1358          // Reduce maxLength to split at start of character
1359          $maxLength = $maxLength - ($lookBack - $encodedCharPos);
1360          $foundSplitPos = true;
1361        } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
1362          $lookBack += 3;
1363        }
1364      } else {
1365        // No encoded character found
1366        $foundSplitPos = true;
1367      }
1368    }
1369    return $maxLength;
1370  }
1371
1372
1373  /**
1374   * Set the body wrapping.
1375   * @access public
1376   * @return void
1377   */
1378  public function SetWordWrap() {
1379    if($this->WordWrap < 1) {
1380      return;
1381    }
1382
1383    switch($this->message_type) {
1384      case 'alt':
1385      case 'alt_inline':
1386      case 'alt_attach':
1387      case 'alt_inline_attach':
1388        $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
1389        break;
1390      default:
1391        $this->Body = $this->WrapText($this->Body, $this->WordWrap);
1392        break;
1393    }
1394  }
1395
1396  /**
1397   * Assembles message header.
1398   * @access public
1399   * @return string The assembled header
1400   */
1401  public function CreateHeader() {
1402    $result = '';
1403
1404    // Set the boundaries
1405    $uniq_id = md5(uniqid(time()));
1406    $this->boundary[1] = 'b1_' . $uniq_id;
1407    $this->boundary[2] = 'b2_' . $uniq_id;
1408    $this->boundary[3] = 'b3_' . $uniq_id;
1409
1410    if ($this->MessageDate == '') {
1411      $result .= $this->HeaderLine('Date', self::RFCDate());
1412    } else {
1413      $result .= $this->HeaderLine('Date', $this->MessageDate);
1414    }
1415
1416    if ($this->ReturnPath) {
1417      $result .= $this->HeaderLine('Return-Path', '<'.trim($this->ReturnPath).'>');
1418    } elseif ($this->Sender == '') {
1419      $result .= $this->HeaderLine('Return-Path', '<'.trim($this->From).'>');
1420    } else {
1421      $result .= $this->HeaderLine('Return-Path', '<'.trim($this->Sender).'>');
1422    }
1423
1424    // To be created automatically by mail()
1425    if($this->Mailer != 'mail') {
1426      if ($this->SingleTo === true) {
1427        foreach($this->to as $t) {
1428          $this->SingleToArray[] = $this->AddrFormat($t);
1429        }
1430      } else {
1431        if(count($this->to) > 0) {
1432          $result .= $this->AddrAppend('To', $this->to);
1433        } elseif (count($this->cc) == 0) {
1434          $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
1435        }
1436      }
1437    }
1438
1439    $from = array();
1440    $from[0][0] = trim($this->From);
1441    $from[0][1] = $this->FromName;
1442    $result .= $this->AddrAppend('From', $from);
1443
1444    // sendmail and mail() extract Cc from the header before sending
1445    if(count($this->cc) > 0) {
1446      $result .= $this->AddrAppend('Cc', $this->cc);
1447    }
1448
1449    // sendmail and mail() extract Bcc from the header before sending
1450    if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
1451      $result .= $this->AddrAppend('Bcc', $this->bcc);
1452    }
1453
1454    if(count($this->ReplyTo) > 0) {
1455      $result .= $this->AddrAppend('Reply-To', $this->ReplyTo);
1456    }
1457
1458    // mail() sets the subject itself
1459    if($this->Mailer != 'mail') {
1460      $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
1461    }
1462
1463    if($this->MessageID != '') {
1464      $result .= $this->HeaderLine('Message-ID', $this->MessageID);
1465    } else {
1466      $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
1467    }
1468    $result .= $this->HeaderLine('X-Priority', $this->Priority);
1469    if ($this->XMailer == '') {
1470        $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (https://github.com/PHPMailer/PHPMailer/)');
1471    } else {
1472      $myXmailer = trim($this->XMailer);
1473      if ($myXmailer) {
1474        $result .= $this->HeaderLine('X-Mailer', $myXmailer);
1475      }
1476    }
1477
1478    if($this->ConfirmReadingTo != '') {
1479      $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
1480    }
1481
1482    // Add custom headers
1483    for($index = 0; $index < count($this->CustomHeader); $index++) {
1484      $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
1485    }
1486    if (!$this->sign_key_file) {
1487      $result .= $this->HeaderLine('MIME-Version', '1.0');
1488      $result .= $this->GetMailMIME();
1489    }
1490
1491    return $result;
1492  }
1493
1494  /**
1495   * Returns the message MIME.
1496   * @access public
1497   * @return string
1498   */
1499  public function GetMailMIME() {
1500    $result = '';
1501    switch($this->message_type) {
1502      case 'inline':
1503        $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
1504        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"');
1505        break;
1506      case 'attach':
1507      case 'inline_attach':
1508      case 'alt_attach':
1509      case 'alt_inline_attach':
1510        $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
1511        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"');
1512        break;
1513      case 'alt':
1514      case 'alt_inline':
1515        $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
1516        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"');
1517        break;
1518      default:
1519        // Catches case 'plain': and case '':
1520        $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset='.$this->CharSet);
1521        break;
1522    }
1523    //RFC1341 part 5 says 7bit is assumed if not specified
1524    if ($this->Encoding != '7bit') {
1525      $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
1526    }
1527
1528    if($this->Mailer != 'mail') {
1529      $result .= $this->LE;
1530    }
1531
1532    return $result;
1533  }
1534
1535  /**
1536   * Returns the MIME message (headers and body). Only really valid post PreSend().
1537   * @access public
1538   * @return string
1539   */
1540  public function GetSentMIMEMessage() {
1541    return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
1542  }
1543
1544
1545  /**
1546   * Assembles the message body.  Returns an empty string on failure.
1547   * @access public
1548   * @throws phpmailerException
1549   * @return string The assembled message body
1550   */
1551  public function CreateBody() {
1552    $body = '';
1553
1554    if ($this->sign_key_file) {

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