PageRenderTime 112ms CodeModel.GetById 3ms app.highlight 89ms RepoModel.GetById 1ms app.codeStats 1ms

/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
   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) {
1514          $result .= $this->AddrAppend('To', $this->to);
1515        } elseif (count($this->cc) == 0) {
1516          $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
1517        }
1518      }
1519    }
1520
1521    $from = array();
1522    $from[0][0] = trim($this->From);
1523    $from[0][1] = $this->FromName;
1524    $result .= $this->AddrAppend('From', $from);
1525
1526    // sendmail and mail() extract Cc from the header before sending
1527    if(count($this->cc) > 0) {
1528      $result .= $this->AddrAppend('Cc', $this->cc);
1529    }
1530
1531    // sendmail and mail() extract Bcc from the header before sending
1532    if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
1533      $result .= $this->AddrAppend('Bcc', $this->bcc);
1534    }
1535
1536    if(count($this->ReplyTo) > 0) {
1537      $result .= $this->AddrAppend('Reply-To', $this->ReplyTo);
1538    }
1539
1540    // mail() sets the subject itself
1541    if($this->Mailer != 'mail') {
1542      $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
1543    }
1544
1545    if($this->MessageID != '') {
1546      $result .= $this->HeaderLine('Message-ID', $this->MessageID);
1547    } else {
1548      $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
1549    }
1550    $result .= $this->HeaderLine('X-Priority', $this->Priority);
1551    if ($this->XMailer == '') {
1552        $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (https://github.com/PHPMailer/PHPMailer/)');
1553    } else {
1554      $myXmailer = trim($this->XMailer);
1555      if ($myXmailer) {
1556        $result .= $this->HeaderLine('X-Mailer', $myXmailer);
1557      }
1558    }
1559
1560    if($this->ConfirmReadingTo != '') {
1561      $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
1562    }
1563
1564    // Add custom headers
1565    for($index = 0; $index < count($this->CustomHeader); $index++) {
1566      $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
1567    }
1568    if (!$this->sign_key_file) {
1569      	if (strpos($result, 'MIME-Version: 1.0') == false) $result .= $this->HeaderLine('MIME-Version', '1.0');
1570      $result .= $this->GetMailMIME();
1571    }
1572
1573    return $result;
1574  }
1575
1576  /**
1577   * Returns the message MIME.
1578   * @access public
1579   * @return string
1580   */
1581  public function GetMailMIME() {
1582    $result = '';
1583    switch($this->message_type) {
1584      case 'inline':
1585        $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
1586        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"');
1587        break;
1588      case 'attach':
1589      case 'inline_attach':
1590      case 'alt_attach':
1591      case 'alt_inline_attach':
1592        $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
1593        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"');
1594        break;
1595      case 'alt':
1596      case 'alt_inline':
1597        $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
1598        $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"');
1599        break;
1600      default:
1601        // Catches case 'plain': and case '':
1602        $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset='.$this->CharSet);
1603        break;
1604    }
1605    //RFC1341 part 5 says 7bit is assumed if not specified
1606    if ($this->Encoding != '7bit') {
1607      $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
1608    }
1609
1610    if($this->Mailer != 'mail') {
1611      $result .= $this->LE;
1612    }
1613
1614    return $result;
1615  }
1616
1617  /**
1618   * Returns the MIME message (headers and body). Only really valid post PreSend().
1619   * @access public
1620   * @return string
1621   */
1622  public function GetSentMIMEMessage() {
1623    return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
1624  }
1625
1626
1627  /**
1628   * Assembles the message body.  Returns an empty string on failure.
1629   * @access public
1630   * @throws phpmailerException
1631   * @return string The assembled message body
1632   */
1633  public function CreateBody() {
1634    $body = '';
1635
1636    if ($this->sign_key_file) {
1637      $body .= $this->GetMailMIME().$this->LE;
1638    }
1639
1640    $this->SetWordWrap();
1641
1642    switch($this->message_type) {
1643      case 'inline':
1644        $body .= $this->GetBoundary($this->boundary[1], '', '', '');
1645        $body .= $this->EncodeString($this->Body, $this->Encoding);
1646        $body .= $this->LE.$this->LE;
1647        $body .= $this->AttachAll('inline', $this->boundary[1]);
1648        break;
1649      case 'attach':
1650        $body .= $this->GetBoundary($this->boundary[1], '', '', '');
1651        $body .= $this->EncodeString($this->Body, $this->Encoding);
1652        $body .= $this->LE.$this->LE;
1653        $body .= $this->AttachAll('attachment', $this->boundary[1]);
1654        break;
1655      case 'inline_attach':
1656        $body .= $this->TextLine('--' . $this->boundary[1]);
1657        $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
1658        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"');
1659        $body .= $this->LE;
1660        $body .= $this->GetBoundary($this->boundary[2], '', '', '');
1661        $body .= $this->EncodeString($this->Body, $this->Encoding);
1662        $body .= $this->LE.$this->LE;
1663        $body .= $this->AttachAll('inline', $this->boundary[2]);
1664        $body .= $this->LE;
1665        $body .= $this->AttachAll('attachment', $this->boundary[1]);
1666        break;
1667      case 'alt':
1668        $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
1669        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
1670        $body .= $this->LE.$this->LE;
1671        $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
1672        $body .= $this->EncodeString($this->Body, $this->Encoding);
1673        $body .= $this->LE.$this->LE;
1674        if(!empty($this->Ical)) {
1675          $body .= $this->GetBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
1676          $body .= $this->EncodeString($this->Ical, $this->Encoding);
1677          $body .= $this->LE.$this->LE;
1678        }
1679        $body .= $this->EndBoundary($this->boundary[1]);
1680        break;
1681      case 'alt_inline':
1682        $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
1683        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
1684        $body .= $this->LE.$this->LE;
1685        $body .= $this->TextLine('--' . $this->boundary[1]);
1686        $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
1687        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"');
1688        $body .= $this->LE;
1689        $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
1690        $body .= $this->EncodeString($this->Body, $this->Encoding);
1691        $body .= $this->LE.$this->LE;
1692        $body .= $this->AttachAll('inline', $this->boundary[2]);
1693        $body .= $this->LE;
1694        $body .= $this->EndBoundary($this->boundary[1]);
1695        break;
1696      case 'alt_attach':
1697        $body .= $this->TextLine('--' . $this->boundary[1]);
1698        $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
1699        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"');
1700        $body .= $this->LE;
1701        $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
1702        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
1703        $body .= $this->LE.$this->LE;
1704        $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
1705        $body .= $this->EncodeString($this->Body, $this->Encoding);
1706        $body .= $this->LE.$this->LE;
1707        $body .= $this->EndBoundary($this->boundary[2]);
1708        $body .= $this->LE;
1709        $body .= $this->AttachAll('attachment', $this->boundary[1]);
1710        break;
1711      case 'alt_inline_attach':
1712        $body .= $this->TextLine('--' . $this->boundary[1]);
1713        $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
1714        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"');
1715        $body .= $this->LE;
1716        $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
1717        $body .= $this->EncodeString($this->AltBody, $this->Encoding);
1718        $body .= $this->LE.$this->LE;
1719        $body .= $this->TextLine('--' . $this->boundary[2]);
1720        $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
1721        $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3].'"');
1722        $body .= $this->LE;
1723        $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', '');
1724        $body .= $this->EncodeString($this->Body, $this->Encoding);
1725        $body .= $this->LE.$this->LE;
1726        $body .= $this->AttachAll('inline', $this->boundary[3]);
1727        $body .= $this->LE;
1728        $body .= $this->EndBoundary($this->boundary[2]);
1729        $body .= $this->LE;
1730        $body .= $this->AttachAll('attachment', $this->boundary[1]);
1731        break;
1732      default:
1733        // catch case 'plain' and case ''
1734        $body .= $this->EncodeString($this->Body, $this->Encoding);
1735        break;
1736    }
1737
1738    if ($this->IsError()) {
1739      $body = '';
1740    } elseif ($this->sign_key_file) {
1741      try {
1742        if (!defined('PKCS7_TEXT')) {
1743            throw new phpmailerException($this->Lang('signing').' OpenSSL extension missing.');
1744        }
1745        $file = tempnam(sys_get_temp_dir(), 'mail');
1746        file_put_contents($file, $body); //TODO check this worked
1747        $signed = tempnam(sys_get_temp_dir(), 'signed');
1748        if (@openssl_pkcs7_sign($file, $signed, 'file://'.realpath($this->sign_cert_file), array('file://'.realpath($this->sign_key_file), $this->sign_key_pass), null)) {
1749          @unlink($file);
1750          $body = file_get_contents($signed);
1751          @unlink($signed);
1752        } else {
1753          @unlink($file);
1754          @unlink($signed);
1755          throw new phpmailerException($this->Lang('signing').openssl_error_string());
1756        }
1757      } catch (phpmailerException $e) {
1758        $body = '';
1759        if ($this->exceptions) {
1760          throw $e;
1761        }
1762      }
1763    }
1764    return $body;
1765  }
1766
1767  /**
1768   * Returns the start of a message boundary.
1769   * @access protected
1770   * @param string $boundary
1771   * @param string $charSet
1772   * @param string $contentType
1773   * @param string $encoding
1774   * @return string
1775   */
1776  protected function GetBoundary($boundary, $charSet, $contentType, $encoding) {
1777    $result = '';
1778    if($charSet == '') {
1779      $charSet = $this->CharSet;
1780    }
1781    if($contentType == '') {
1782      $contentType = $this->ContentType;
1783    }
1784    if($encoding == '') {
1785      $encoding = $this->Encoding;
1786    }
1787    $result .= $this->TextLine('--' . $boundary);
1788    $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet);
1789    $result .= $this->LE;
1790    $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
1791    $result .= $this->LE;
1792
1793    return $result;
1794  }
1795
1796  /**
1797   * Returns the end of a message boundary.
1798   * @access protected
1799   * @param string $boundary
1800   * @return string
1801   */
1802  protected function EndBoundary($boundary) {
1803    return $this->LE . '--' . $boundary . '--' . $this->LE;
1804  }
1805
1806  /**
1807   * Sets the message type.
1808   * @access protected
1809   * @return void
1810   */
1811  protected function SetMessageType() {
1812    $this->message_type = array();
1813    if($this->AlternativeExists()) $this->message_type[] = "alt";
1814    if($this->InlineImageExists()) $this->message_type[] = "inline";
1815    if($this->AttachmentExists()) $this->message_type[] = "attach";
1816    $this->message_type = implode("_", $this->message_type);
1817    if($this->message_type == "") $this->message_type = "plain";
1818  }
1819
1820  /**
1821   * Returns a formatted header line.
1822   * @access public
1823   * @param string $name
1824   * @param string $value
1825   * @return string
1826   */
1827  public function HeaderLine($name, $value) {
1828    return $name . ': ' . $value . $this->LE;
1829  }
1830
1831  /**
1832   * Returns a formatted mail line.
1833   * @access public
1834   * @param string $value
1835   * @return string
1836   */
1837  public function TextLine($value) {
1838    return $value . $this->LE;
1839  }
1840
1841  /////////////////////////////////////////////////
1842  // CLASS METHODS, ATTACHMENTS
1843  /////////////////////////////////////////////////
1844
1845  /**
1846   * Adds an attachment from a path on the filesystem.
1847   * Returns false if the file could not be found
1848   * or accessed.
1849   * @param string $path Path to the attachment.
1850   * @param string $name Overrides the attachment name.
1851   * @param string $encoding File encoding (see $Encoding).
1852   * @param string $type File extension (MIME) type.
1853   * @param string $disposition Disposition to use
1854   * @throws phpmailerException
1855   * @return bool
1856   */
1857  public function AddAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment') {
1858    try {
1859      if ( !@is_file($path) ) {
1860        throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
1861      }
1862
1863      //If a MIME type is not specified, try to work it out from the file name
1864      if ($type == '') {
1865        $type = self::filenameToType($path);
1866      }
1867
1868      $filename = basename($path);
1869      if ( $name == '' ) {
1870        $name = $filename;
1871      }
1872
1873      $this->attachment[] = array(
1874        0 => $path,
1875        1 => $filename,
1876        2 => $name,
1877        3 => $encoding,
1878        4 => $type,
1879        5 => false,  // isStringAttachment
1880        6 => $disposition,
1881        7 => 0
1882      );
1883
1884    } catch (phpmailerException $e) {
1885      $this->SetError($e->getMessage());
1886      if ($this->exceptions) {
1887        throw $e;
1888      }
1889      if ($this->SMTPDebug) {
1890        $this->edebug($e->getMessage()."\n");
1891      }
1892      return false;
1893    }
1894    return true;
1895  }
1896
1897  /**
1898  * Return the current array of attachments
1899  * @return array
1900  */
1901  public function GetAttachments() {
1902    return $this->attachment;
1903  }
1904
1905  /**
1906   * Attaches all fs, string, and binary attachments to the message.
1907   * Returns an empty string on failure.
1908   * @access protected
1909   * @param string $disposition_type
1910   * @param string $boundary
1911   * @return string
1912   */
1913  protected function AttachAll($disposition_type, $boundary) {
1914    // Return text of body
1915    $mime = array();
1916    $cidUniq = array();
1917    $incl = array();
1918
1919    // Add all attachments
1920    foreach ($this->attachment as $attachment) {
1921      // CHECK IF IT IS A VALID DISPOSITION_FILTER
1922      if($attachment[6] == $disposition_type) {
1923        // Check for string attachment
1924        $string = '';
1925        $path = '';
1926        $bString = $attachment[5];
1927        if ($bString) {
1928          $string = $attachment[0];
1929        } else {
1930          $path = $attachment[0];
1931        }
1932
1933        $inclhash = md5(serialize($attachment));
1934        if (in_array($inclhash, $incl)) { continue; }
1935        $incl[]      = $inclhash;
1936        $filename    = $attachment[1];
1937        $name        = $attachment[2];
1938        $encoding    = $attachment[3];
1939        $type        = $attachment[4];
1940        $disposition = $attachment[6];
1941        $cid         = $attachment[7];
1942        if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
1943        $cidUniq[$cid] = true;
1944
1945        $mime[] = sprintf("--%s%s", $boundary, $this->LE);
1946        $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
1947        $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
1948
1949        if($disposition == 'inline') {
1950          $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
1951        }
1952
1953        //If a filename contains any of these chars, it should be quoted, but not otherwise: RFC2183 & RFC2045 5.1
1954        //Fixes a warning in IETF's msglint MIME checker
1955        //
1956        // Allow for bypassing the Content-Disposition header totally
1957        if (!(empty($disposition))) {
1958          if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $name)) {
1959            $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
1960          } else {
1961            $mime[] = sprintf("Content-Disposition: %s; filename=%s%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
1962          }
1963        } else {
1964          $mime[] = $this->LE;
1965        }
1966
1967        // Encode as string attachment
1968        if($bString) {
1969          $mime[] = $this->EncodeString($string, $encoding);
1970          if($this->IsError()) {
1971            return '';
1972          }
1973          $mime[] = $this->LE.$this->LE;
1974        } else {
1975          $mime[] = $this->EncodeFile($path, $encoding);
1976          if($this->IsError()) {
1977            return '';
1978          }
1979          $mime[] = $this->LE.$this->LE;
1980        }
1981      }
1982    }
1983
1984    $mime[] = sprintf("--%s--%s", $boundary, $this->LE);
1985
1986    return implode("", $mime);
1987  }
1988
1989  /**
1990   * Encodes attachment in requested format.
1991   * Returns an empty string on failure.
1992   * @param string $path The full path to the file
1993   * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
1994   * @throws phpmailerException
1995   * @see EncodeFile()
1996   * @access protected
1997   * @return string
1998   */
1999  protected function EncodeFile($path, $encoding = 'base64') {
2000    try {
2001      if (!is_readable($path)) {
2002        throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
2003      }
2004      $magic_quotes = get_magic_quotes_runtime();
2005      if ($magic_quotes) {
2006        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
2007          set_magic_quotes_runtime(0);
2008        } else {
2009          ini_set('magic_quotes_runtime', 0);
2010        }
2011      }
2012      $file_buffer  = file_get_contents($path);
2013      $file_buffer  = $this->EncodeString($file_buffer, $encoding);
2014      if ($magic_quotes) {
2015        if (version_compare(PHP_VERSION, '5.3.0', '<')) {
2016          set_magic_quotes_runtime($magic_quotes);
2017        } else {
2018          ini_set('magic_quotes_runtime', $magic_quotes);
2019        }
2020      }
2021      return $file_buffer;
2022    } catch (Exception $e) {
2023      $this->SetError($e->getMessage());
2024      return '';
2025    }
2026  }
2027
2028  /**
2029   * Encodes string to requested format.
2030   * Returns an empty string on failure.
2031   * @param string $str The text to encode
2032   * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
2033   * @access public
2034   * @return string
2035   */
2036  public function EncodeString($str, $encoding = 'base64') {
2037    $encoded = '';
2038    switch(strtolower($encoding)) {
2039      case 'base64':
2040        $encoded = chunk_split(base64_encode($str), 76, $this->LE);
2041        break;
2042      case '7bit':
2043      case '8bit':
2044        $encoded = $this->FixEOL($str);
2045        //Make sure it ends with a line break
2046        if (substr($encoded, -(strlen($this->LE))) != $this->LE)
2047          $encoded .= $this->LE;
2048        break;
2049      case 'binary':
2050        $encoded = $str;
2051        break;
2052      case 'quoted-printable':
2053        $encoded = $this->EncodeQP($str);
2054        break;
2055      default:
2056        $this->SetError($this->Lang('encoding') . $encoding);
2057        break;
2058    }
2059    return $encoded;
2060  }
2061
2062  /**
2063   * Encode a header string to best (shortest) of Q, B, quoted or none.
2064   * @access public
2065   * @param string $str
2066   * @param string $position
2067   * @return string
2068   */
2069  public function EncodeHeader($str, $position = 'text') {
2070    $x = 0;
2071
2072    switch (strtolower($position)) {
2073      case 'phrase':
2074        if (!preg_match('/[\200-\377]/', $str)) {
2075          // Can't use addslashes as we don't know what value has magic_quotes_sybase
2076          $encoded = addcslashes($str, "\0..\37\177\\\"");
2077          if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
2078            return ($encoded);
2079          } else {
2080            return ("\"$encoded\"");
2081          }
2082        }
2083        $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
2084        break;
2085      case 'comment':
2086        $x = preg_match_all('/[()"]/', $str, $matches);
2087        // Fall-through
2088      case 'text':
2089      default:
2090        $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
2091        break;
2092    }
2093
2094    if ($x == 0) { //There are no chars that need encoding
2095      return ($str);
2096    }
2097
2098    $maxlen = 75 - 7 - strlen($this->CharSet);
2099    // Try to select the encoding which should produce the shortest output
2100    if ($x > strlen($str)/3) { //More than a third of the content will need encoding, so B encoding will be most efficient
2101      $encoding = 'B';
2102      if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
2103        // Use a custom function which correctly encodes and wraps long
2104        // multibyte strings without breaking lines within a character
2105        $encoded = $this->Base64EncodeWrapMB($str, "\n");
2106      } else {
2107        $encoded = base64_encode($str);
2108        $maxlen -= $maxlen % 4;
2109        $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
2110      }
2111    } else {
2112      $encoding = 'Q';
2113      $encoded = $this->EncodeQ($str, $position);
2114      $encoded = $this->WrapText($encoded, $maxlen, true);
2115      $encoded = str_replace('='.self::CRLF, "\n", trim($encoded));
2116    }
2117
2118    $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
2119    $encoded = trim(str_replace("\n", $this->LE, $encoded));
2120
2121    return $encoded;
2122  }
2123
2124  /**
2125   * Checks if a string contains multibyte characters.
2126   * @access public
2127   * @param string $str multi-byte text to wrap encode
2128   * @return bool
2129   */
2130  public function HasMultiBytes($str) {
2131    if (function_exists('mb_strlen')) {
2132      return (strlen($str) > mb_strlen($str, $this->CharSet));
2133    } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
2134      return false;
2135    }
2136  }
2137
2138  /**
2139   * Correctly encodes and wraps long multibyte strings for mail headers
2140   * without breaking lines within a character.
2141   * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
2142   * @access public
2143   * @param string $str multi-byte text to wrap encode
2144   * @param string $lf string to use as linefeed/end-of-line
2145   * @return string
2146   */
2147  public function Base64EncodeWrapMB($str, $lf=null) {
2148    $start = "=?".$this->CharSet."?B?";
2149    $end = "?=";
2150    $encoded = "";
2151    if ($lf === null) {
2152      $lf = $this->LE;
2153    }
2154
2155    $mb_length = mb_strlen($str, $this->CharSet);
2156    // Each line must have length <= 75, including $start and $end
2157    $length = 75 - strlen($start) - strlen($end);
2158    // Average multi-byte ratio
2159    $ratio = $mb_length / strlen($str);
2160    // Base64 has a 4:3 ratio
2161    $offset = $avgLength = floor($length * $ratio * .75);
2162
2163    for ($i = 0; $i < $mb_length; $i += $offset) {
2164      $lookBack = 0;
2165
2166      do {
2167        $offset = $avgLength - $lookBack;
2168        $chunk = mb_substr($str, $i, $offset, $this->CharSet);
2169        $chunk = base64_encode($chunk);
2170        $lookBack++;
2171      }
2172      while (strlen($chunk) > $length);
2173
2174      $encoded .= $chunk . $lf;
2175    }
2176
2177    // Chomp the last linefeed
2178    $encoded = substr($encoded, 0, -strlen($lf));
2179    return $encoded;
2180  }
2181
2182  /**
2183   * Encode string to RFC2045 (6.7) quoted-printable format
2184   * @access public
2185   * @param string $string The text to encode
2186   * @param integer $line_max Number of chars allowed on a line before wrapping
2187   * @return string
2188   * @link PHP version adapted from http://www.php.net/manual/en/function.quoted-printable-decode.php#89417
2189   */
2190  public function EncodeQP($string, $line_max = 76) {
2191    if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
2192      return quoted_printable_encode($string);
2193    }
2194    //Fall back to a pure PHP implementation
2195    $string = str_replace(array('%20', '%0D%0A.', '%0D%0A', '%'), array(' ', "\r\n=2E", "\r\n", '='), rawurlencode($string));
2196    $string = preg_replace('/[^\r\n]{'.($line_max - 3).'}[^=\r\n]{2}/', "$0=\r\n", $string);
2197    return $string;
2198  }
2199
2200  /**
2201   * Wrapper to preserve BC for old QP encoding function that was removed
2202   * @see EncodeQP()
2203   * @access public
2204   * @param string $string
2205   * @param integer $line_max
2206   * @param bool $space_conv
2207   * @return string
2208   */
2209  public function EncodeQPphp($string, $line_max = 76, $space_conv = false) {
2210    return $this->EncodeQP($string, $line_max);
2211  }
2212
2213  /**
2214   * Encode string to q encoding.
2215   * @link http://tools.ietf.org/html/rfc2047
2216   * @param string $str the text to encode
2217   * @param string $position Where the text is going to be used, see the RFC for what that means
2218   * @access public
2219   * @return string
2220   */
2221  public function EncodeQ($str, $position = 'text') {
2222    //There should not be any EOL in the string
2223    $pattern = '';
2224    $encoded = str_replace(array("\r", "\n"), '', $str);
2225    switch (strtolower($position)) {
2226      case 'phrase':
2227        $pattern = '^A-Za-z0-9!*+\/ -';
2228        break;
2229
2230      case 'comment':
2231        $pattern = '\(\)"';
2232        //note that we don't break here!
2233        //for this reason we build the $pattern without including delimiters and []
2234
2235      case 'text':
2236      default:
2237        //Replace every high ascii, control =, ? and _ characters
2238        //We put \075 (=) as first value to make sure it's the first one in being converted, preventing double encode
2239        $pattern = '\075\000-\011\013\014\016-\037\077\137\177-\377' . $pattern;
2240        break;
2241    }
2242
2243    if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
2244      foreach (array_unique($matches[0]) as $char) {
2245        $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
2246      }
2247    }
2248
2249    //Replace every spaces to _ (more readable than =20)
2250    return str_replace(' ', '_', $encoded);
2251}
2252
2253
2254  /**
2255   * Adds a string or binary attachment (non-filesystem) to the list.
2256   * This method can be used to attach ascii or binary data,
2257   * such as a BLOB record from a database.
2258   * @param string $string String attachment data.
2259   * @param string $filename Name of the attachment.
2260   * @param string $encoding File encoding (see $Encoding).
2261   * @param string $type File extension (MIME) type.
2262   * @param string $disposition Disposition to use
2263   * @return void
2264   */
2265  public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = '', $disposition = 'attachment') {
2266    //If a MIME type is not specified, try to work it out from the file name
2267    if ($type == '') {
2268      $type = self::filenameToType($filename);
2269    }
2270    // Append to $attachment array
2271    $this->attachment[] = array(
2272      0 => $string,
2273      1 => $filename,
2274      2 => basename($filename),
2275      3 => $encoding,
2276      4 => $type,
2277      5 => true,  // isStringAttachment
2278      6 => $disposition,
2279      7 => 0
2280    );
2281  }
2282
2283  /**
2284   * Add an embedded attachment from a file.
2285   * This can include images, sounds, and just about any other document type.
2286   * @param string $path Path to the attachment.
2287   * @param string $cid Content ID of the attachment; Use this to reference
2288   *        the content when using an embedded image in HTML.
2289   * @param string $name Overrides the attachment name.
2290   * @param string $encoding File encoding (see $Encoding).
2291   * @param string $type File MIME type.
2292   * @param string $disposition Disposition to use
2293   * @return bool True on successfully adding an attachment
2294   */
2295  public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline') {
2296    if ( !@is_file($path) ) {
2297      $this->SetError($this->Lang('file_access') . $path);
2298      return false;
2299    }
2300
2301    //If a MIME type is not specified, try to work it out from the file name
2302    if ($type == '') {
2303      $type = self::filenameToType($path);
2304    }
2305
2306    $filename = basename($path);
2307    if ( $name == '' ) {
2308      $name = $filename;
2309    }
2310
2311    // Append to $attachment array
2312    $this->attachment[] = array(
2313      0 => $path,
2314      1 => $filename,
2315      2 => $name,
2316      3 => $encoding,
2317      4 => $type,
2318      5 => false,  // isStringAttachment
2319      6 => $disposition,
2320      7 => $cid
2321    );
2322    return true;
2323  }
2324
2325
2326  /**
2327   * Add an embedded stringified attachment.
2328   * This can include images, sounds, and just about any other document type.
2329   * Be sure to set the $type to an image type for images:
2330   * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
2331   * @param string $string The attachment binary data.
2332   * @param string $cid Content ID of the attachment; Use this to reference
2333   *        the content when using an embedded image in HTML.
2334   * @param string $name
2335   * @param string $encoding File encoding (see $Encoding).
2336   * @param string $type MIME type.
2337   * @param string $disposition Disposition to use
2338   * @return bool True on successfully adding an attachment
2339   */
2340  public function AddStringEmbeddedImage($string, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline') {
2341    //If a MIME type is not specified, try to work it out from the name
2342    if ($type == '') {
2343      $type = self::filenameToType($name);
2344    }
2345
2346    // Append to $attachment array
2347    $this->attachment[] = array(
2348      0 => $string,
2349      1 => $name,
2350      2 => $name,
2351      3 => $encoding,
2352      4 => $type,
2353      5 => true,  // isStringAttachment
2354      6 => $disposition,
2355      7 => $cid
2356    );
2357    return true;
2358  }
2359
2360  /**
2361   * Returns true if an inline attachment is present.
2362   * @access public
2363   * @return bool
2364   */
2365  public function InlineImageExists() {
2366    foreach($this->attachment as $attachment) {
2367      if ($attachment[6] == 'inline') {
2368        return true;
2369      }
2370    }
2371    return false;
2372  }
2373
2374  /**
2375   * Returns true if an attachment (non-inline) is present.
2376   * @return bool
2377   */
2378  public function AttachmentExists() {
2379    foreach($this->attachment as $attachment) {
2380      if ($attachment[6] == 'attachment') {
2381        return true;
2382      }
2383    }
2384    return false;
2385  }
2386
2387  /**
2388   * Does this message have an alternative body set?
2389   * @return bool
2390   */
2391  public function AlternativeExists() {
2392    return !empty($this->AltBody);
2393  }
2394
2395  /////////////////////////////////////////////////
2396  // CLASS METHODS, MESSAGE RESET
2397  /////////////////////////////////////////////////
2398
2399  /**
2400   * Clears all recipients assigned in the TO array.  Returns void.
2401   * @return void
2402   */
2403  public function ClearAddresses() {
2404    foreach($this->to as $to) {
2405      unset($this->all_recipients[strtolower($to[0])]);
2406    }
2407    $this->to = array();
2408  }
2409
2410  /**
2411   * Clears all recipients assigned in the CC array.  Returns void.
2412   * @return void
2413   */
2414  public function ClearCCs() {
2415    foreach($this->cc as $cc) {
2416      unset($this->all_recipients[strtolower($cc[0])]);
2417    }
2418    $this->cc = array();
2419  }
2420
2421  /**
2422   * Clears all recipients assigned in the BCC array.  Returns void.
2423   * @return void
2424   */
2425  public function ClearBCCs() {
2426    foreach($this->bcc as $bcc) {
2427      unset($this->all_recipients[strtolower($bcc[0])]);
2428    }
2429    $this->bcc = array();
2430  }
2431
2432  /**
2433   * Clears all recipients assigned in the ReplyTo array.  Returns void.
2434   * @return void
2435   */
2436  public function ClearReplyTos() {
2437    $this->ReplyTo = array();
2438  }
2439
2440  /**
2441   * Clears all recipients assigned in the TO, CC and BCC
2442   * array.  Returns void.
2443   * @return void
2444   */
2445  public function ClearAllRecipients() {
2446    $this->to = array();
2447    $this->cc = array();
2448    $this->bcc = array();
2449    $this->all_recipients = array();
2450  }
2451
2452  /**
2453   * Clears all previously set filesystem, string, and binary
2454   * attachments.  Returns void.
2455   * @return void
2456   */
2457  public function ClearAttachments() {
2458    $this->attachment = array();
2459  }
2460
2461  /**
2462   * Clears all custom headers.  Returns void.
2463   * @return void
2464   */
2465  public function ClearCustomHeaders() {
2466    $this->CustomHeader = array();
2467  }
2468
2469  /////////////////////////////////////////////////
2470  // CLASS METHODS, MISCELLANEOUS
2471  /////////////////////////////////////////////////
2472
2473  /**
2474   * Adds the error message to the error container.
2475   * @access protected
2476   * @param string $msg
2477   * @return void
2478   */
2479  protected function SetError($msg) {
2480    $this->error_count++;
2481    if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
2482      $lasterror = $this->smtp->getError();
2483      if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
2484        $msg .= '<p>' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
2485      }
2486    }
2487    $this->ErrorInfo = $msg;
2488  }
2489
2490  /**
2491   * Returns the proper RFC 822 formatted date.
2492   * @access public
2493   * @return string
2494   * @static
2495   */
2496  public static function RFCDate() {
2497    //Set the time zone to whatever the default is to avoid 500 errors
2498    //Will default to UTC if it's not set properly in php.ini
2499    date_default_timezone_set(@date_default_timezone_get());
2500    return date('D, j M Y H:i:s O');
2501  }
2502
2503  /**
2504   * Returns the server hostname or 'localhost.localdomain' if unknown.
2505   * @access protected
2506   * @return string
2507   */
2508  protected function ServerHostname() {
2509    if (!empty($this->Hostname)) {
2510      $result = $this->Hostname;
2511    } elseif (isset($_SERVER['SERVER_NAME'])) {
2512      $result = $_SERVER['SERVER_NAME'];
2513    } else {
2514      $result = 'localhost.localdomain';
2515    }
2516
2517    return $result;
2518  }
2519
2520  /**
2521   * Returns a message in the appropriate language.
2522   * @access protected
2523   * @param string $key
2524   * @return string
2525   */
2526  protected function Lang($key) {
2527    if(count($this->language) < 1) {
2528      $this->SetLanguage('en'); // set the default language
2529    }
2530
2531    if(isset($this->language[$key])) {
2532      return $this->language[$key];
2533    } else {
2534      return 'Language string failed to load: ' . $key;
2535    }
2536  }
2537
2538  /**
2539   * Returns true if an error occurred.
2540   * @access public
2541   * @return bool
2542   */
2543  public function IsError() {
2544    return ($this->error_count > 0);
2545  }
2546
2547  /**
2548   * Changes every end of line from CRLF, CR or LF to $this->LE.
2549   * @access public
2550   * @param string $str String to FixEOL
2551   * @return string
2552   */
2553  public function FixEOL($str) {
2554	// condense down to \n
2555	$nstr = str_replace(array("\r\n", "\r"), "\n", $str);
2556	// Now convert LE as needed
2557	if ($this->LE !== "\n") {
2558		$nstr = str_replace("\n", $this->LE, $nstr);
2559	}
2560    return  $nstr;
2561  }
2562
2563  /**
2564   * Adds a custom header. $name value can be overloaded to contain
2565   * both header name and value (name:value)
2566   * @access public
2567   * @param string $name custom header name
2568   * @param string $value header value
2569   * @return void
2570   */
2571  public function AddCustomHeader($name, $value=null) {
2572	if ($value === null) {
2573		// Value passed in as name:value
2574		$this->CustomHeader[] = explode(':', $name, 2);
2575	} else {
2576		$this->CustomHeader[] = array($name, $value);
2577	}
2578  }
2579
2580  /**
2581   * Creates a message from an HTML string, making modifications for inline images and backgrounds
2582   * and creates a plain-text version by converting the HTML
2583   * Overwrites any existing values in $this->Body and $this->AltBody
2584   * @access public
2585   * @param string $message HTML message string
2586   * @param string $basedir baseline directory for path
2587   * @param bool $advanced Whether to use the advanced HTML to text converter
2588   * @return string $message
2589   */
2590  public function MsgHTML($message, $basedir = '', $advanced = false) {
2591    preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images);
2592    if (isset($images[2])) {
2593      foreach ($images[2] as $i => $url) {
2594        // do not change urls for absolute images (thanks to corvuscorax)
2595        if (!preg_match('#^[A-z]+://#', $url)) {
2596          $filename = basename($url);
2597          $directory = dirname($url);
2598          if ($directory == '.') {
2599            $directory = '';
2600          }
2601          $cid = md5($url).'@phpmailer.0'; //RFC2392 S 2
2602          if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
2603            $basedir .= '/';
2604          }
2605          if (strlen($directory) > 1 && substr($directory, -1) != '/') {
2606            $directory .= '/';
2607          }
2608          if ($this->AddEmbeddedImage($basedir.$directory.$filename, $cid, $filename, 'base64', self::_mime_types(self::mb_pathinfo($filename, PATHINFO_EXTENSION)))) {
2609            $message = preg_replace("/".$images[1][$i]."=[\"']".preg_quote($url, '/')."[\"']/Ui", $images[1][$i]."=\"cid:".$cid."\"", $message);
2610          }
2611        }
2612      }
2613    }
2614    $this->IsHTML(true);
2615    if (empty($this->AltBody)) {
2616      $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n";
2617    }
2618    //Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
2619    $this->Body = $this->NormalizeBreaks($message);
2620    $this->AltBody = $this->NormalizeBreaks($this->html2text($message, $advanced));
2621    return $this->Body;
2622  }
2623
2624    /**
2625     * Convert an HTML string into a plain text version
2626     * @param string $html The HTML text to convert
2627     * @param bool $advanced Should this use the more complex html2text converter or just a simple one?
2628     * @return string
2629     */
2630  public function html2text($html, $advanced = false) {
2631    if ($advanced) {
2632      require_once 'extras/class.html2text.php';
2633      $h = new html2text($html);
2634      return $h->get_text();
2635    }
2636    return html_entity_decode(trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))), ENT_QUOTES, $this->CharSet);
2637  }
2638
2639  /**
2640   * Gets the MIME type of the embedded or inline image
2641   * @param string $ext File extension
2642   * @access public
2643   * @return string MIME type of ext
2644   * @static
2645   */
2646  public static function _mime_types($ext = '') {
2647    $mimes = array(
2648      'xl'    =>  'application/excel',
2649      'hqx'   =>  'application/mac-binhex40',
2650      'cpt'   =>  'application/mac-compactpro',
2651      'bin'   =>  'application/macbinary',
2652      'doc'   =>  'application/msword',
2653      'word'  =>  'application/msword',
2654      'class' =>  'application/octet-stream',
2655      'dll'   =>  'application/octet-stream',
2656      'dms'   =>  'application/octet-stream',
2657      'exe'   =>  'application/octet-stream',
2658      'lha'   =>  'application/octet-stream',
2659      'lzh'   =>  'application/octet-stream',
2660      'psd'   =>  'application/octet-stream',
2661      'sea'   =>  'application/octet-stream',
2662      'so'    =>  'application/octet-stream',
2663      'oda'   =>  'application/oda',
2664      'pdf'   =>  'application/pdf',
2665      'ai'    =>  'application/postscript',
2666      'eps'   =>  'application/postscript',
2667      'ps'    =>  'application/postscript',
2668      'smi'   =>  'application/smil',
2669      'smil'  =>  'application/smil',
2670      'mif'   =>  'application/vnd.mif',
2671      'xls'   =>  'application/vnd.ms-excel',
2672      'ppt'   =>  'application/vnd.ms-powerpoint',
2673      'wbxml' =>  'application/vnd.wap.wbxml',
2674      'wmlc'  =>  'application/vnd.wap.wmlc',
2675      'dcr'   =>  'application/x-director',
2676      'dir'   =>  'application/x-director',
2677      'dxr'   =>  'application/x-director',
2678      'dvi'   =>  'application/x-dvi',
2679      'gtar'  =>  'application/x-gtar',
2680      'php3'  =>  'application/x-httpd-php',
2681      'php4'  =>  'application/x-httpd-php',
2682      'php'   =>  'application/x-httpd-php',
2683      'phtml' =>  'application/x-httpd-php',
2684      'phps'  =>  'application/x-httpd-php-source',
2685      'js'    =>  'application/x-javascript',
2686      'swf'   =>  'application/x-shockwave-flash',
2687      'sit'   =>  'application/x-stuffit',
2688      'tar'   =>  'application/x-tar',
2689      'tgz'   =>  'application/x-tar',
2690      'xht'   =>  'application/xhtml+xml',
2691      'xhtml' =>  'application/xhtml+xml',
2692      'zip'   =>  'application/zip',
2693      'mid'   =>  'audio/midi',
2694      'midi'  =>  'audio/midi',
2695      'mp2'   =>  'audio/mpeg',
2696      'mp3'   =>  'audio/mpeg',
2697      'mpga'  =>  'audio/mpeg',
2698      'aif'   =>  'audio/x-aiff',
2699      'aifc'  =>  'audio/x-aiff',
2700      'aiff'  =>  'audio/x-aiff',
2701      'ram'   =>  'audio/x-pn-realaudio',
2702      'rm'    =>  'audio/x-pn-realaudio',
2703      'rpm'   =>  'audio/x-pn-realaudio-plugin',
2704      'ra'    =>  'audio/x-realaudio',
2705      'wav'   =>  'audio/x-wav',
2706      'bmp'   =>  'image/bmp',
2707      'gif'   =>  'image/gif',
2708      'jpeg'  =>  'image/jpeg',
2709      'jpe'   =>  'image/jpeg',
2710      'jpg'   =>  'image/jpeg',
2711      'png'   =>  'image/png',
2712      'tiff'  =>  'image/tiff',
2713      'tif'   =>  'image/tiff',
2714      'eml'   =>  'message/rfc822',
2715      'css'   =>  'text/css',
2716      'html'  =>  'text/html',
2717      'htm'   =>  'text/html',
2718      'shtml' =>  'text/html',
2719      'log'   =>  'text/plain',
2720      'text'  =>  'text/plain',
2721      'txt'   =>  'text/plain',
2722      'rtx'   =>  'text/richtext',
2723      'rtf'   =>  'text/rtf',
2724      'xml'   =>  'text/xml',
2725      'xsl'   =>  'text/xml',
2726      'mpeg'  =>  'video/mpeg',
2727      'mpe'   =>  'video/mpeg',
2728      'mpg'   =>  'video/mpeg',
2729      'mov'   =>  'video/quicktime',
2730      'qt'    =>  'video/quicktime',
2731      'rv'    =>  'video/vnd.rn-realvideo',
2732      'avi'   =>  'video/x-msvideo',
2733      'movie' =>  'video/x-sgi-movie'
2734    );
2735    return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)];
2736  }
2737
2738  /**
2739   * Try to map a file name to a MIME type, default to application/octet-stream
2740   * @param string $filename A file name or full path, does not need to exist as a file
2741   * @return string
2742   * @static
2743   */
2744  public static function filenameToType($filename) {
2745    //In case the path is a URL, strip any query string before getting extension
2746    $qpos = strpos($filename, '?');
2747    if ($qpos !== false) {
2748      $filename = substr($filename, 0, $qpos);
2749    }
2750    $pathinfo = self::mb_pathinfo($filename);
2751    return self::_mime_types($pathinfo['extension']);
2752  }
2753
2754  /**
2755   * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe.
2756   * Works similarly to the one in PHP >= 5.2.0
2757   * @link http://www.php.net/manual/en/function.pathinfo.php#107461
2758   * @param string $path A filename or path, does not need to exist as a file
2759   * @param integer|string $options Either a PATHINFO_* constant, or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2
2760   * @return string|array
2761   * @static
2762   */
2763  public static function mb_pathinfo($path, $options = null) {
2764    $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
2765    $m = array();
2766    preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $m);
2767    if(array_key_exists(1, $m)) {
2768      $ret['dirname'] = $m[1];
2769    }
2770    if(array_key_exists(2, $m)) {
2771      $ret['basename'] = $m[2];
2772    }
2773    if(array_key_exists(5, $m)) {
2774      $ret['extension'] = $m[5];
2775    }
2776    if(array_key_exists(3, $m)) {
2777      $ret['filename'] = $m[3];
2778    }
2779    switch($options) {
2780      case PATHINFO_DIRNAME:
2781      case 'dirname':
2782        return $ret['dirname'];
2783        break;
2784      case PATHINFO_BASENAME:
2785      case 'basename':
2786        return $ret['basename'];
2787        break;
2788      case PATHINFO_EXTENSION:
2789      case 'extension':
2790        return $ret['extension'];
2791        break;
2792      case PATHINFO_FILENAME:
2793      case 'filename':
2794        return $ret['filename'];
2795        break;
2796      default:
2797        return $ret;
2798    }
2799  }
2800
2801  /**
2802   * Set (or reset) Class Objects (variables)
2803   *
2804   * Usage Example:
2805   * $page->set('X-Priority', '3');
2806   *
2807   * @access public
2808   * @param string $name
2809   * @param mixed $value
2810   * NOTE: will not work with arrays, there are no arrays to set/reset
2811   * @throws phpmailerException
2812   * @return bool
2813   * @todo Should this not be using __set() magic function?
2814   */
2815  public function set($name, $value = '') {
2816    try {
2817      if (isset($this->$name) ) {
2818        $this->$name = $value;
2819      } else {
2820        throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL);
2821      }
2822    } catch (Exception $e) {
2823      $this->SetError($e->getMessage());
2824      if ($e->getCode() == self::STOP_CRITICAL) {
2825        return false;
2826      }
2827    }
2828    return true;
2829  }
2830
2831  /**
2832   * Strips newlines to prevent header injection.
2833   * @access public
2834   * @param string $str
2835   * @return string
2836   */
2837  public function SecureHeader($str) {
2838    return trim(str_replace(array("\r", "\n"), '', $str));
2839  }
2840
2841  /**
2842   * Normalize UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format
2843   * Defaults to CRLF (for message bodies) and preserves consecutive breaks
2844   * @param string $text
2845   * @param string $breaktype What kind of line break to use, defaults to CRLF
2846   * @return string
2847   * @access public
2848   * @static
2849   */
2850  public static function NormalizeBreaks($text, $breaktype = "\r\n") {
2851    return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
2852  }
2853
2854
2855	/**
2856   * Set the private key file and password to sign the message.
2857   *
2858   * @access public
2859   * @param string $cert_filename
2860   * @param string $key_filename
2861   * @param string $key_pass Password for private key
2862   */
2863  public function Sign($cert_filename, $key_filename, $key_pass) {
2864    $this->sign_cert_file = $cert_filename;
2865    $this->sign_key_file = $key_filename;
2866    $this->sign_key_pass = $key_pass;
2867  }
2868
2869  /**
2870   * Set the private key file and password to sign the message.
2871   *
2872   * @access public
2873   * @param string $txt
2874   * @return string
2875   */
2876  public function DKIM_QP($txt) {
2877    $line = '';
2878    for ($i = 0; $i < strlen($txt); $i++) {
2879      $ord = ord($txt[$i]);
2880      if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) {
2881        $line .= $txt[$i];
2882      } else {
2883        $line .= "=".sprintf("%02X", $ord);
2884      }
2885    }
2886    return $line;
2887  }
2888
2889  /**
2890   * Generate DKIM signature
2891   *
2892   * @access public
2893   * @param string $s Header
2894   * @throws phpmailerException
2895   * @return string
2896   */
2897  public function DKIM_Sign($s) {
2898    if (!defined('PKCS7_TEXT')) {
2899        if ($this->exceptions) {
2900            throw new phpmailerException($this->Lang("signing").' OpenSSL extension missing.');
2901        }
2902        return '';
2903    }
2904    $privKeyStr = file_get_contents($this->DKIM_private);
2905    if ($this->DKIM_passphrase != '') {
2906      $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
2907    } else {
2908      $privKey = $privKeyStr;
2909    }
2910    if (openssl_sign($s, $signature, $privKey)) {
2911      return base64_encode($signature);
2912    }
2913    return '';
2914  }
2915
2916  /**
2917   * Generate DKIM Canonicalization Header
2918   *
2919   * @access public
2920   * @param string $s Header
2921   * @return string
2922   */
2923  public function DKIM_HeaderC($s) {
2924    $s = preg_replace("/\r\n\s+/", " ", $s);
2925    $lines = explode("\r\n", $s);
2926    foreach ($lines as $key => $line) {
2927      list($heading, $value) = explode(":", $line, 2);
2928      $heading = strtolower($heading);
2929      $value = preg_replace("/\s+/", " ", $value) ; // Compress useless spaces
2930      $lines[$key] = $heading.":".trim($value) ; // Don't forget to remove WSP around the value
2931    }
2932    $s = implode("\r\n", $lines);
2933    return $s;
2934  }
2935
2936  /**
2937   * Generate DKIM Canonicalization Body
2938   *
2939   * @access public
2940   * @param string $body Message Body
2941   * @return string
2942   */
2943  public function DKIM_BodyC($body) {
2944    if ($body == '') return "\r\n";
2945    // stabilize line endings
2946    $body = str_replace("\r\n", "\n", $body);
2947    $body = str_replace("\n", "\r\n", $body);
2948    // END stabilize line endings
2949    while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
2950      $body = substr($body, 0, strlen($body) - 2);
2951    }
2952    return $body;
2953  }
2954
2955  /**
2956   * Create the DKIM header, body, as new header
2957   *
2958   * @access public
2959   * @param string $headers_line Header lines
2960   * @param string $subject Subject
2961   * @param string $body Body
2962   * @return string
2963   */
2964  public function DKIM_Add($headers_line, $subject, $body) {
2965    $DKIMsignatureType    = 'rsa-sha1'; // Signature & hash algorithms
2966    $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
2967    $DKIMquery            = 'dns/txt'; // Query method
2968    $DKIMtime             = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
2969    $subject_header       = "Subject: $subject";
2970    $headers              = explode($this->LE, $headers_line);
2971    $from_header          = '';
2972    $to_header            = '';
2973    $current = '';
2974    foreach($headers as $header) {
2975      if (strpos($header, 'From:') === 0) {
2976        $from_header = $header;
2977        $current = 'from_header';
2978      } elseif (strpos($header, 'To:') === 0) {
2979        $to_header = $header;
2980        $current = 'to_header';
2981      } else {
2982        if($current && strpos($header, ' =?') === 0){
2983          $current .= $header;
2984        } else {
2985          $current = '';
2986        }
2987      }
2988    }
2989    $from     = str_replace('|', '=7C', $this->DKIM_QP($from_header));
2990    $to       = str_replace('|', '=7C', $this->DKIM_QP($to_header));
2991    $subject  = str_replace('|', '=7C', $this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable
2992    $body     = $this->DKIM_BodyC($body);
2993    $DKIMlen  = strlen($body) ; // Length of body
2994    $DKIMb64  = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body
2995    $ident    = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";";
2996    $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n".
2997                "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n".
2998                "\th=From:To:Subject;\r\n".
2999                "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n".
3000                "\tz=$from\r\n".
3001                "\t|$to\r\n".
3002                "\t|$subject;\r\n".
3003                "\tbh=" . $DKIMb64 . ";\r\n".
3004                "\tb=";
3005    $toSign   = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs);
3006    $signed   = $this->DKIM_Sign($toSign);
3007    return $dkimhdrs.$signed."\r\n";
3008  }
3009
3010  /**
3011   * Perform callback
3012   * @param boolean $isSent
3013   * @param string $to
3014   * @param string $cc
3015   * @param string $bcc
3016   * @param string $subject
3017   * @param string $body
3018   * @param string $from
3019   */
3020  protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from = null) {
3021    if (!empty($this->action_function) && is_callable($this->action_function)) {
3022      $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
3023      call_user_func_array($this->action_function, $params);
3024    }
3025  }
3026}
3027
3028/**
3029 * Exception handler for PHPMailer
3030 * @package PHPMailer
3031 */
3032class phpmailerException extends Exception {
3033  /**
3034   * Prettify error message output
3035   * @return string
3036   */
3037  public function errorMessage() {
3038    $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
3039    return $errorMsg;
3040  }
3041}