PageRenderTime 215ms CodeModel.GetById 123ms app.highlight 69ms RepoModel.GetById 1ms app.codeStats 1ms

/common/include/mailer/class.phpmailer.php

https://github.com/tematres/TemaTres-Vocabulary-Server
PHP | 3690 lines | 2178 code | 232 blank | 1280 comment | 355 complexity | 8478e9afa002a4f95d653628a75feca9 MD5 | raw file
   1<?php
   2/**
   3 * PHPMailer - PHP email creation and transport class.
   4 * PHP Version 5
   5 * @package PHPMailer
   6 * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
   7 * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
   8 * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
   9 * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  10 * @author Brent R. Matzelle (original founder)
  11 * @copyright 2012 - 2014 Marcus Bointon
  12 * @copyright 2010 - 2012 Jim Jagielski
  13 * @copyright 2004 - 2009 Andy Prevost
  14 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  15 * @note This program is distributed in the hope that it will be useful - WITHOUT
  16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  17 * FITNESS FOR A PARTICULAR PURPOSE.
  18 */
  19
  20/**
  21 * PHPMailer - PHP email creation and transport class.
  22 * @package PHPMailer
  23 * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  24 * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  25 * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  26 * @author Brent R. Matzelle (original founder)
  27 */
  28class PHPMailer
  29{
  30    /**
  31     * The PHPMailer Version number.
  32     * @type string
  33     */
  34    public $Version = '5.2.10';
  35
  36    /**
  37     * Email priority.
  38     * Options: null (default), 1 = High, 3 = Normal, 5 = low.
  39     * When null, the header is not set at all.
  40     * @type integer
  41     */
  42    public $Priority = null;
  43
  44    /**
  45     * The character set of the message.
  46     * @type string
  47     */
  48    public $CharSet = 'iso-8859-1';
  49
  50    /**
  51     * The MIME Content-type of the message.
  52     * @type string
  53     */
  54    public $ContentType = 'text/plain';
  55
  56    /**
  57     * The message encoding.
  58     * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
  59     * @type string
  60     */
  61    public $Encoding = '8bit';
  62
  63    /**
  64     * Holds the most recent mailer error message.
  65     * @type string
  66     */
  67    public $ErrorInfo = '';
  68
  69    /**
  70     * The From email address for the message.
  71     * @type string
  72     */
  73    public $From = 'root@localhost';
  74
  75    /**
  76     * The From name of the message.
  77     * @type string
  78     */
  79    public $FromName = 'Root User';
  80
  81    /**
  82     * The Sender email (Return-Path) of the message.
  83     * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  84     * @type string
  85     */
  86    public $Sender = '';
  87
  88    /**
  89     * The Return-Path of the message.
  90     * If empty, it will be set to either From or Sender.
  91     * @type string
  92     * @deprecated Email senders should never set a return-path header;
  93     * it's the receiver's job (RFC5321 section 4.4), so this no longer does anything.
  94     * @link https://tools.ietf.org/html/rfc5321#section-4.4 RFC5321 reference
  95     */
  96    public $ReturnPath = '';
  97
  98    /**
  99     * The Subject of the message.
 100     * @type string
 101     */
 102    public $Subject = '';
 103
 104    /**
 105     * An HTML or plain text message body.
 106     * If HTML then call isHTML(true).
 107     * @type string
 108     */
 109    public $Body = '';
 110
 111    /**
 112     * The plain-text message body.
 113     * This body can be read by mail clients that do not have HTML email
 114     * capability such as mutt & Eudora.
 115     * Clients that can read HTML will view the normal Body.
 116     * @type string
 117     */
 118    public $AltBody = '';
 119
 120    /**
 121     * An iCal message part body.
 122     * Only supported in simple alt or alt_inline message types
 123     * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator
 124     * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
 125     * @link http://kigkonsult.se/iCalcreator/
 126     * @type string
 127     */
 128    public $Ical = '';
 129
 130    /**
 131     * The complete compiled MIME message body.
 132     * @access protected
 133     * @type string
 134     */
 135    protected $MIMEBody = '';
 136
 137    /**
 138     * The complete compiled MIME message headers.
 139     * @type string
 140     * @access protected
 141     */
 142    protected $MIMEHeader = '';
 143
 144    /**
 145     * Extra headers that createHeader() doesn't fold in.
 146     * @type string
 147     * @access protected
 148     */
 149    protected $mailHeader = '';
 150
 151    /**
 152     * Word-wrap the message body to this number of chars.
 153     * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
 154     * @type integer
 155     */
 156    public $WordWrap = 0;
 157
 158    /**
 159     * Which method to use to send mail.
 160     * Options: "mail", "sendmail", or "smtp".
 161     * @type string
 162     */
 163    public $Mailer = 'mail';
 164
 165    /**
 166     * The path to the sendmail program.
 167     * @type string
 168     */
 169    public $Sendmail = '/usr/sbin/sendmail';
 170
 171    /**
 172     * Whether mail() uses a fully sendmail-compatible MTA.
 173     * One which supports sendmail's "-oi -f" options.
 174     * @type boolean
 175     */
 176    public $UseSendmailOptions = true;
 177
 178    /**
 179     * Path to PHPMailer plugins.
 180     * Useful if the SMTP class is not in the PHP include path.
 181     * @type string
 182     * @deprecated Should not be needed now there is an autoloader.
 183     */
 184    public $PluginDir = '';
 185
 186    /**
 187     * The email address that a reading confirmation should be sent to.
 188     * @type string
 189     */
 190    public $ConfirmReadingTo = '';
 191
 192    /**
 193     * The hostname to use in Message-Id and Received headers
 194     * and as default HELO string.
 195     * If empty, the value returned
 196     * by SERVER_NAME is used or 'localhost.localdomain'.
 197     * @type string
 198     */
 199    public $Hostname = '';
 200
 201    /**
 202     * An ID to be used in the Message-Id header.
 203     * If empty, a unique id will be generated.
 204     * @type string
 205     */
 206    public $MessageID = '';
 207
 208    /**
 209     * The message Date to be used in the Date header.
 210     * If empty, the current date will be added.
 211     * @type string
 212     */
 213    public $MessageDate = '';
 214
 215    /**
 216     * SMTP hosts.
 217     * Either a single hostname or multiple semicolon-delimited hostnames.
 218     * You can also specify a different port
 219     * for each host by using this format: [hostname:port]
 220     * (e.g. "smtp1.example.com:25;smtp2.example.com").
 221     * You can also specify encryption type, for example:
 222     * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
 223     * Hosts will be tried in order.
 224     * @type string
 225     */
 226    public $Host = 'localhost';
 227
 228    /**
 229     * The default SMTP server port.
 230     * @type integer
 231     * @TODO Why is this needed when the SMTP class takes care of it?
 232     */
 233    public $Port = 25;
 234
 235    /**
 236     * The SMTP HELO of the message.
 237     * Default is $Hostname.
 238     * @type string
 239     * @see PHPMailer::$Hostname
 240     */
 241    public $Helo = '';
 242
 243    /**
 244     * What kind of encryption to use on the SMTP connection.
 245     * Options: '', 'ssl' or 'tls'
 246     * @type string
 247     */
 248    public $SMTPSecure = '';
 249
 250    /**
 251     * Whether to enable TLS encryption automatically if a server supports it,
 252     * even if `SMTPSecure` is not set to 'tls'.
 253     * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
 254     * @type boolean
 255     */
 256    public $SMTPAutoTLS = true;
 257
 258    /**
 259     * Whether to use SMTP authentication.
 260     * Uses the Username and Password properties.
 261     * @type boolean
 262     * @see PHPMailer::$Username
 263     * @see PHPMailer::$Password
 264     */
 265    public $SMTPAuth = false;
 266
 267    /**
 268     * Options array passed to stream_context_create when connecting via SMTP.
 269     * @type array
 270     */
 271    public $SMTPOptions = array();
 272
 273    /**
 274     * SMTP username.
 275     * @type string
 276     */
 277    public $Username = '';
 278
 279    /**
 280     * SMTP password.
 281     * @type string
 282     */
 283    public $Password = '';
 284
 285    /**
 286     * SMTP auth type.
 287     * Options are LOGIN (default), PLAIN, NTLM, CRAM-MD5
 288     * @type string
 289     */
 290    public $AuthType = '';
 291
 292    /**
 293     * SMTP realm.
 294     * Used for NTLM auth
 295     * @type string
 296     */
 297    public $Realm = '';
 298
 299    /**
 300     * SMTP workstation.
 301     * Used for NTLM auth
 302     * @type string
 303     */
 304    public $Workstation = '';
 305
 306    /**
 307     * The SMTP server timeout in seconds.
 308     * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
 309     * @type integer
 310     */
 311    public $Timeout = 300;
 312
 313    /**
 314     * SMTP class debug output mode.
 315     * Debug output level.
 316     * Options:
 317     * * `0` No output
 318     * * `1` Commands
 319     * * `2` Data and commands
 320     * * `3` As 2 plus connection status
 321     * * `4` Low-level data output
 322     * @type integer
 323     * @see SMTP::$do_debug
 324     */
 325    public $SMTPDebug = 0;
 326
 327    /**
 328     * How to handle debug output.
 329     * Options:
 330     * * `echo` Output plain-text as-is, appropriate for CLI
 331     * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
 332     * * `error_log` Output to error log as configured in php.ini
 333     *
 334     * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
 335     * <code>
 336     * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
 337     * </code>
 338     * @type string|callable
 339     * @see SMTP::$Debugoutput
 340     */
 341    public $Debugoutput = 'echo';
 342
 343    /**
 344     * Whether to keep SMTP connection open after each message.
 345     * If this is set to true then to close the connection
 346     * requires an explicit call to smtpClose().
 347     * @type boolean
 348     */
 349    public $SMTPKeepAlive = false;
 350
 351    /**
 352     * Whether to split multiple to addresses into multiple messages
 353     * or send them all in one message.
 354     * @type boolean
 355     */
 356    public $SingleTo = false;
 357
 358    /**
 359     * Storage for addresses when SingleTo is enabled.
 360     * @type array
 361     * @TODO This should really not be public
 362     */
 363    public $SingleToArray = array();
 364
 365    /**
 366     * Whether to generate VERP addresses on send.
 367     * Only applicable when sending via SMTP.
 368     * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
 369     * @link http://www.postfix.org/VERP_README.html Postfix VERP info
 370     * @type boolean
 371     */
 372    public $do_verp = false;
 373
 374    /**
 375     * Whether to allow sending messages with an empty body.
 376     * @type boolean
 377     */
 378    public $AllowEmpty = false;
 379
 380    /**
 381     * The default line ending.
 382     * @note The default remains "\n". We force CRLF where we know
 383     *        it must be used via self::CRLF.
 384     * @type string
 385     */
 386    public $LE = "\n";
 387
 388    /**
 389     * DKIM selector.
 390     * @type string
 391     */
 392    public $DKIM_selector = '';
 393
 394    /**
 395     * DKIM Identity.
 396     * Usually the email address used as the source of the email
 397     * @type string
 398     */
 399    public $DKIM_identity = '';
 400
 401    /**
 402     * DKIM passphrase.
 403     * Used if your key is encrypted.
 404     * @type string
 405     */
 406    public $DKIM_passphrase = '';
 407
 408    /**
 409     * DKIM signing domain name.
 410     * @example 'example.com'
 411     * @type string
 412     */
 413    public $DKIM_domain = '';
 414
 415    /**
 416     * DKIM private key file path.
 417     * @type string
 418     */
 419    public $DKIM_private = '';
 420
 421    /**
 422     * Callback Action function name.
 423     *
 424     * The function that handles the result of the send email action.
 425     * It is called out by send() for each email sent.
 426     *
 427     * Value can be any php callable: http://www.php.net/is_callable
 428     *
 429     * Parameters:
 430     *   boolean $result        result of the send action
 431     *   string  $to            email address of the recipient
 432     *   string  $cc            cc email addresses
 433     *   string  $bcc           bcc email addresses
 434     *   string  $subject       the subject
 435     *   string  $body          the email body
 436     *   string  $from          email address of sender
 437     * @type string
 438     */
 439    public $action_function = '';
 440
 441    /**
 442     * What to put in the X-Mailer header.
 443     * Options: An empty string for PHPMailer default, whitespace for none, or a string to use
 444     * @type string
 445     */
 446    public $XMailer = '';
 447
 448    /**
 449     * An instance of the SMTP sender class.
 450     * @type SMTP
 451     * @access protected
 452     */
 453    protected $smtp = null;
 454
 455    /**
 456     * The array of 'to' addresses.
 457     * @type array
 458     * @access protected
 459     */
 460    protected $to = array();
 461
 462    /**
 463     * The array of 'cc' addresses.
 464     * @type array
 465     * @access protected
 466     */
 467    protected $cc = array();
 468
 469    /**
 470     * The array of 'bcc' addresses.
 471     * @type array
 472     * @access protected
 473     */
 474    protected $bcc = array();
 475
 476    /**
 477     * The array of reply-to names and addresses.
 478     * @type array
 479     * @access protected
 480     */
 481    protected $ReplyTo = array();
 482
 483    /**
 484     * An array of all kinds of addresses.
 485     * Includes all of $to, $cc, $bcc
 486     * @type array
 487     * @access protected
 488     */
 489    protected $all_recipients = array();
 490
 491    /**
 492     * The array of attachments.
 493     * @type array
 494     * @access protected
 495     */
 496    protected $attachment = array();
 497
 498    /**
 499     * The array of custom headers.
 500     * @type array
 501     * @access protected
 502     */
 503    protected $CustomHeader = array();
 504
 505    /**
 506     * The most recent Message-ID (including angular brackets).
 507     * @type string
 508     * @access protected
 509     */
 510    protected $lastMessageID = '';
 511
 512    /**
 513     * The message's MIME type.
 514     * @type string
 515     * @access protected
 516     */
 517    protected $message_type = '';
 518
 519    /**
 520     * The array of MIME boundary strings.
 521     * @type array
 522     * @access protected
 523     */
 524    protected $boundary = array();
 525
 526    /**
 527     * The array of available languages.
 528     * @type array
 529     * @access protected
 530     */
 531    protected $language = array();
 532
 533    /**
 534     * The number of errors encountered.
 535     * @type integer
 536     * @access protected
 537     */
 538    protected $error_count = 0;
 539
 540    /**
 541     * The S/MIME certificate file path.
 542     * @type string
 543     * @access protected
 544     */
 545    protected $sign_cert_file = '';
 546
 547    /**
 548     * The S/MIME key file path.
 549     * @type string
 550     * @access protected
 551     */
 552    protected $sign_key_file = '';
 553
 554    /**
 555     * The optional S/MIME extra certificates ("CA Chain") file path.
 556     * @type string
 557     * @access protected
 558     */
 559    protected $sign_extracerts_file = '';
 560
 561    /**
 562     * The S/MIME password for the key.
 563     * Used only if the key is encrypted.
 564     * @type string
 565     * @access protected
 566     */
 567    protected $sign_key_pass = '';
 568
 569    /**
 570     * Whether to throw exceptions for errors.
 571     * @type boolean
 572     * @access protected
 573     */
 574    protected $exceptions = false;
 575
 576    /**
 577     * Unique ID used for message ID and boundaries.
 578     * @type string
 579     * @access protected
 580     */
 581    protected $uniqueid = '';
 582
 583    /**
 584     * Error severity: message only, continue processing.
 585     */
 586    const STOP_MESSAGE = 0;
 587
 588    /**
 589     * Error severity: message, likely ok to continue processing.
 590     */
 591    const STOP_CONTINUE = 1;
 592
 593    /**
 594     * Error severity: message, plus full stop, critical error reached.
 595     */
 596    const STOP_CRITICAL = 2;
 597
 598    /**
 599     * SMTP RFC standard line ending.
 600     */
 601    const CRLF = "\r\n";
 602
 603    /**
 604     * The maximum line length allowed by RFC 2822 section 2.1.1
 605     * @type integer
 606     */
 607    const MAX_LINE_LENGTH = 998;
 608
 609    /**
 610     * Constructor.
 611     * @param boolean $exceptions Should we throw external exceptions?
 612     */
 613    public function __construct($exceptions = false)
 614    {
 615        $this->exceptions = (boolean)$exceptions;
 616    }
 617
 618    /**
 619     * Destructor.
 620     */
 621    public function __destruct()
 622    {
 623        //Close any open SMTP connection nicely
 624        if ($this->Mailer == 'smtp') {
 625            $this->smtpClose();
 626        }
 627    }
 628
 629    /**
 630     * Call mail() in a safe_mode-aware fashion.
 631     * Also, unless sendmail_path points to sendmail (or something that
 632     * claims to be sendmail), don't pass params (not a perfect fix,
 633     * but it will do)
 634     * @param string $to To
 635     * @param string $subject Subject
 636     * @param string $body Message Body
 637     * @param string $header Additional Header(s)
 638     * @param string $params Params
 639     * @access private
 640     * @return boolean
 641     */
 642    private function mailPassthru($to, $subject, $body, $header, $params)
 643    {
 644        //Check overloading of mail function to avoid double-encoding
 645        if (ini_get('mbstring.func_overload') & 1) {
 646            $subject = $this->secureHeader($subject);
 647        } else {
 648            $subject = $this->encodeHeader($this->secureHeader($subject));
 649        }
 650        if (ini_get('safe_mode') || !($this->UseSendmailOptions)) {
 651            $result = @mail($to, $subject, $body, $header);
 652        } else {
 653            $result = @mail($to, $subject, $body, $header, $params);
 654        }
 655        return $result;
 656    }
 657
 658    /**
 659     * Output debugging info via user-defined method.
 660     * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
 661     * @see PHPMailer::$Debugoutput
 662     * @see PHPMailer::$SMTPDebug
 663     * @param string $str
 664     */
 665    protected function edebug($str)
 666    {
 667        if ($this->SMTPDebug <= 0) {
 668            return;
 669        }
 670        //Avoid clash with built-in function names
 671        if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
 672            call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
 673            return;
 674        }
 675        switch ($this->Debugoutput) {
 676            case 'error_log':
 677                //Don't output, just log
 678                error_log($str);
 679                break;
 680            case 'html':
 681                //Cleans up output a bit for a better looking, HTML-safe output
 682                echo htmlentities(
 683                    preg_replace('/[\r\n]+/', '', $str),
 684                    ENT_QUOTES,
 685                    'UTF-8'
 686                )
 687                . "<br>\n";
 688                break;
 689            case 'echo':
 690            default:
 691                //Normalize line breaks
 692                $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
 693                echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
 694                    "\n",
 695                    "\n                   \t                  ",
 696                    trim($str)
 697                ) . "\n";
 698        }
 699    }
 700
 701    /**
 702     * Sets message type to HTML or plain.
 703     * @param boolean $isHtml True for HTML mode.
 704     * @return void
 705     */
 706    public function isHTML($isHtml = true)
 707    {
 708        if ($isHtml) {
 709            $this->ContentType = 'text/html';
 710        } else {
 711            $this->ContentType = 'text/plain';
 712        }
 713    }
 714
 715    /**
 716     * Send messages using SMTP.
 717     * @return void
 718     */
 719    public function isSMTP()
 720    {
 721        $this->Mailer = 'smtp';
 722    }
 723
 724    /**
 725     * Send messages using PHP's mail() function.
 726     * @return void
 727     */
 728    public function isMail()
 729    {
 730        $this->Mailer = 'mail';
 731    }
 732
 733    /**
 734     * Send messages using $Sendmail.
 735     * @return void
 736     */
 737    public function isSendmail()
 738    {
 739        $ini_sendmail_path = ini_get('sendmail_path');
 740
 741        if (!stristr($ini_sendmail_path, 'sendmail')) {
 742            $this->Sendmail = '/usr/sbin/sendmail';
 743        } else {
 744            $this->Sendmail = $ini_sendmail_path;
 745        }
 746        $this->Mailer = 'sendmail';
 747    }
 748
 749    /**
 750     * Send messages using qmail.
 751     * @return void
 752     */
 753    public function isQmail()
 754    {
 755        $ini_sendmail_path = ini_get('sendmail_path');
 756
 757        if (!stristr($ini_sendmail_path, 'qmail')) {
 758            $this->Sendmail = '/var/qmail/bin/qmail-inject';
 759        } else {
 760            $this->Sendmail = $ini_sendmail_path;
 761        }
 762        $this->Mailer = 'qmail';
 763    }
 764
 765    /**
 766     * Add a "To" address.
 767     * @param string $address
 768     * @param string $name
 769     * @return boolean true on success, false if address already used
 770     */
 771    public function addAddress($address, $name = '')
 772    {
 773        return $this->addAnAddress('to', $address, $name);
 774    }
 775
 776    /**
 777     * Add a "CC" address.
 778     * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
 779     * @param string $address
 780     * @param string $name
 781     * @return boolean true on success, false if address already used
 782     */
 783    public function addCC($address, $name = '')
 784    {
 785        return $this->addAnAddress('cc', $address, $name);
 786    }
 787
 788    /**
 789     * Add a "BCC" address.
 790     * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
 791     * @param string $address
 792     * @param string $name
 793     * @return boolean true on success, false if address already used
 794     */
 795    public function addBCC($address, $name = '')
 796    {
 797        return $this->addAnAddress('bcc', $address, $name);
 798    }
 799
 800    /**
 801     * Add a "Reply-to" address.
 802     * @param string $address
 803     * @param string $name
 804     * @return boolean
 805     */
 806    public function addReplyTo($address, $name = '')
 807    {
 808        return $this->addAnAddress('Reply-To', $address, $name);
 809    }
 810
 811    /**
 812     * Add an address to one of the recipient arrays.
 813     * Addresses that have been added already return false, but do not throw exceptions
 814     * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
 815     * @param string $address The email address to send to
 816     * @param string $name
 817     * @throws phpmailerException
 818     * @return boolean true on success, false if address already used or invalid in some way
 819     * @access protected
 820     */
 821    protected function addAnAddress($kind, $address, $name = '')
 822    {
 823        if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
 824            $this->setError($this->lang('Invalid recipient array') . ': ' . $kind);
 825            $this->edebug($this->lang('Invalid recipient array') . ': ' . $kind);
 826            if ($this->exceptions) {
 827                throw new phpmailerException('Invalid recipient array: ' . $kind);
 828            }
 829            return false;
 830        }
 831        $address = trim($address);
 832        $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
 833        if (!$this->validateAddress($address)) {
 834            $this->setError($this->lang('invalid_address') . ': ' . $address);
 835            $this->edebug($this->lang('invalid_address') . ': ' . $address);
 836            if ($this->exceptions) {
 837                throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
 838            }
 839            return false;
 840        }
 841        if ($kind != 'Reply-To') {
 842            if (!isset($this->all_recipients[strtolower($address)])) {
 843                array_push($this->$kind, array($address, $name));
 844                $this->all_recipients[strtolower($address)] = true;
 845                return true;
 846            }
 847        } else {
 848            if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
 849                $this->ReplyTo[strtolower($address)] = array($address, $name);
 850                return true;
 851            }
 852        }
 853        return false;
 854    }
 855
 856    /**
 857     * Parse and validate a string containing one or more RFC822-style comma-separated email addresses
 858     * of the form "display name <address>" into an array of name/address pairs.
 859     * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
 860     * Note that quotes in the name part are removed.
 861     * @param string $addrstr The address list string
 862     * @param bool $useimap Whether to use the IMAP extension to parse the list
 863     * @return array
 864     * @link http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
 865     */
 866    public function parseAddresses($addrstr, $useimap = true)
 867    {
 868        $addresses = array();
 869        if ($useimap and function_exists('imap_rfc822_parse_adrlist')) {
 870            //Use this built-in parser if it's available
 871            $list = imap_rfc822_parse_adrlist($addrstr, '');
 872            foreach ($list as $address) {
 873                if ($address->host != '.SYNTAX-ERROR.') {
 874                    if ($this->validateAddress($address->mailbox . '@' . $address->host)) {
 875                        $addresses[] = array(
 876                            'name' => (property_exists($address, 'personal') ? $address->personal : ''),
 877                            'address' => $address->mailbox . '@' . $address->host
 878                        );
 879                    }
 880                }
 881            }
 882        } else {
 883            //Use this simpler parser
 884            $list = explode(',', $addrstr);
 885            foreach ($list as $address) {
 886                $address = trim($address);
 887                //Is there a separate name part?
 888                if (strpos($address, '<') === false) {
 889                    //No separate name, just use the whole thing
 890                    if ($this->validateAddress($address)) {
 891                        $addresses[] = array(
 892                            'name' => '',
 893                            'address' => $address
 894                        );
 895                    }
 896                } else {
 897                    list($name, $email) = explode('<', $address);
 898                    $email = trim(str_replace('>', '', $email));
 899                    if ($this->validateAddress($email)) {
 900                        $addresses[] = array(
 901                            'name' => trim(str_replace(array('"', "'"), '', $name)),
 902                            'address' => $email
 903                        );
 904                    }
 905                }
 906            }
 907        }
 908        return $addresses;
 909    }
 910
 911    /**
 912     * Set the From and FromName properties.
 913     * @param string $address
 914     * @param string $name
 915     * @param boolean $auto Whether to also set the Sender address, defaults to true
 916     * @throws phpmailerException
 917     * @return boolean
 918     */
 919    public function setFrom($address, $name = '', $auto = true)
 920    {
 921        $address = trim($address);
 922        $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
 923        if (!$this->validateAddress($address)) {
 924            $this->setError($this->lang('invalid_address') . ': ' . $address);
 925            $this->edebug($this->lang('invalid_address') . ': ' . $address);
 926            if ($this->exceptions) {
 927                throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
 928            }
 929            return false;
 930        }
 931        $this->From = $address;
 932        $this->FromName = $name;
 933        if ($auto) {
 934            if (empty($this->Sender)) {
 935                $this->Sender = $address;
 936            }
 937        }
 938        return true;
 939    }
 940
 941    /**
 942     * Return the Message-ID header of the last email.
 943     * Technically this is the value from the last time the headers were created,
 944     * but it's also the message ID of the last sent message except in
 945     * pathological cases.
 946     * @return string
 947     */
 948    public function getLastMessageID()
 949    {
 950        return $this->lastMessageID;
 951    }
 952
 953    /**
 954     * Check that a string looks like an email address.
 955     * @param string $address The email address to check
 956     * @param string $patternselect A selector for the validation pattern to use :
 957     * * `auto` Pick strictest one automatically;
 958     * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
 959     * * `pcre` Use old PCRE implementation;
 960     * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; same as pcre8 but does not allow 'dotless' domains;
 961     * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
 962     * * `noregex` Don't use a regex: super fast, really dumb.
 963     * @return boolean
 964     * @static
 965     * @access public
 966     */
 967    public static function validateAddress($address, $patternselect = 'auto')
 968    {
 969        if (!$patternselect or $patternselect == 'auto') {
 970            //Check this constant first so it works when extension_loaded() is disabled by safe mode
 971            //Constant was added in PHP 5.2.4
 972            if (defined('PCRE_VERSION')) {
 973                //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2
 974                if (version_compare(PCRE_VERSION, '8.0.3') >= 0) {
 975                    $patternselect = 'pcre8';
 976                } else {
 977                    $patternselect = 'pcre';
 978                }
 979            } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) {
 980                //Fall back to older PCRE
 981                $patternselect = 'pcre';
 982            } else {
 983                //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
 984                if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
 985                    $patternselect = 'php';
 986                } else {
 987                    $patternselect = 'noregex';
 988                }
 989            }
 990        }
 991        switch ($patternselect) {
 992            case 'pcre8':
 993                /**
 994                 * Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains.
 995                 * @link http://squiloople.com/2009/12/20/email-address-validation/
 996                 * @copyright 2009-2010 Michael Rushton
 997                 * Feel free to use and redistribute this code. But please keep this copyright notice.
 998                 */
 999                return (boolean)preg_match(
1000                    '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
1001                    '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
1002                    '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
1003                    '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
1004                    '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
1005                    '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
1006                    '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
1007                    '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
1008                    '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
1009                    $address
1010                );
1011            case 'pcre':
1012                //An older regex that doesn't need a recent PCRE
1013                return (boolean)preg_match(
1014                    '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
1015                    '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
1016                    '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
1017                    '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
1018                    '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
1019                    '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
1020                    '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
1021                    '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
1022                    '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
1023                    '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
1024                    $address
1025                );
1026            case 'html5':
1027                /**
1028                 * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
1029                 * @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
1030                 */
1031                return (boolean)preg_match(
1032                    '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
1033                    '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
1034                    $address
1035                );
1036            case 'noregex':
1037                //No PCRE! Do something _very_ approximate!
1038                //Check the address is 3 chars or longer and contains an @ that's not the first or last char
1039                return (strlen($address) >= 3
1040                    and strpos($address, '@') >= 1
1041                    and strpos($address, '@') != strlen($address) - 1);
1042            case 'php':
1043            default:
1044                return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
1045        }
1046    }
1047
1048    /**
1049     * Create a message and send it.
1050     * Uses the sending method specified by $Mailer.
1051     * @throws phpmailerException
1052     * @return boolean false on error - See the ErrorInfo property for details of the error.
1053     */
1054    public function send()
1055    {
1056        try {
1057            if (!$this->preSend()) {
1058                return false;
1059            }
1060            return $this->postSend();
1061        } catch (phpmailerException $exc) {
1062            $this->mailHeader = '';
1063            $this->setError($exc->getMessage());
1064            if ($this->exceptions) {
1065                throw $exc;
1066            }
1067            return false;
1068        }
1069    }
1070
1071    /**
1072     * Prepare a message for sending.
1073     * @throws phpmailerException
1074     * @return boolean
1075     */
1076    public function preSend()
1077    {
1078        try {
1079            $this->mailHeader = '';
1080            if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
1081                throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
1082            }
1083
1084            // Set whether the message is multipart/alternative
1085            if (!empty($this->AltBody)) {
1086                $this->ContentType = 'multipart/alternative';
1087            }
1088
1089            $this->error_count = 0; // Reset errors
1090            $this->setMessageType();
1091            // Refuse to send an empty message unless we are specifically allowing it
1092            if (!$this->AllowEmpty and empty($this->Body)) {
1093                throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
1094            }
1095
1096            // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
1097            $this->MIMEHeader = '';
1098            $this->MIMEBody = $this->createBody();
1099            // createBody may have added some headers, so retain them
1100            $tempheaders = $this->MIMEHeader;
1101            $this->MIMEHeader = $this->createHeader();
1102            $this->MIMEHeader .= $tempheaders;
1103
1104            // To capture the complete message when using mail(), create
1105            // an extra header list which createHeader() doesn't fold in
1106            if ($this->Mailer == 'mail') {
1107                if (count($this->to) > 0) {
1108                    $this->mailHeader .= $this->addrAppend('To', $this->to);
1109                } else {
1110                    $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
1111                }
1112                $this->mailHeader .= $this->headerLine(
1113                    'Subject',
1114                    $this->encodeHeader($this->secureHeader(trim($this->Subject)))
1115                );
1116            }
1117
1118            // Sign with DKIM if enabled
1119            if (!empty($this->DKIM_domain)
1120                && !empty($this->DKIM_private)
1121                && !empty($this->DKIM_selector)
1122                && file_exists($this->DKIM_private)) {
1123                $header_dkim = $this->DKIM_Add(
1124                    $this->MIMEHeader . $this->mailHeader,
1125                    $this->encodeHeader($this->secureHeader($this->Subject)),
1126                    $this->MIMEBody
1127                );
1128                $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
1129                    str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
1130            }
1131            return true;
1132        } catch (phpmailerException $exc) {
1133            $this->setError($exc->getMessage());
1134            if ($this->exceptions) {
1135                throw $exc;
1136            }
1137            return false;
1138        }
1139    }
1140
1141    /**
1142     * Actually send a message.
1143     * Send the email via the selected mechanism
1144     * @throws phpmailerException
1145     * @return boolean
1146     */
1147    public function postSend()
1148    {
1149        try {
1150            // Choose the mailer and send through it
1151            switch ($this->Mailer) {
1152                case 'sendmail':
1153                case 'qmail':
1154                    return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
1155                case 'smtp':
1156                    return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
1157                case 'mail':
1158                    return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1159                default:
1160                    $sendMethod = $this->Mailer.'Send';
1161                    if (method_exists($this, $sendMethod)) {
1162                        return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
1163                    }
1164
1165                    return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1166            }
1167        } catch (phpmailerException $exc) {
1168            $this->setError($exc->getMessage());
1169            $this->edebug($exc->getMessage());
1170            if ($this->exceptions) {
1171                throw $exc;
1172            }
1173        }
1174        return false;
1175    }
1176
1177    /**
1178     * Send mail using the $Sendmail program.
1179     * @param string $header The message headers
1180     * @param string $body The message body
1181     * @see PHPMailer::$Sendmail
1182     * @throws phpmailerException
1183     * @access protected
1184     * @return boolean
1185     */
1186    protected function sendmailSend($header, $body)
1187    {
1188        if ($this->Sender != '') {
1189            if ($this->Mailer == 'qmail') {
1190                $sendmail = sprintf('%s -f%s', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
1191            } else {
1192                $sendmail = sprintf('%s -oi -f%s -t', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
1193            }
1194        } else {
1195            if ($this->Mailer == 'qmail') {
1196                $sendmail = sprintf('%s', escapeshellcmd($this->Sendmail));
1197            } else {
1198                $sendmail = sprintf('%s -oi -t', escapeshellcmd($this->Sendmail));
1199            }
1200        }
1201        if ($this->SingleTo) {
1202            foreach ($this->SingleToArray as $toAddr) {
1203                if (!@$mail = popen($sendmail, 'w')) {
1204                    throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1205                }
1206                fputs($mail, 'To: ' . $toAddr . "\n");
1207                fputs($mail, $header);
1208                fputs($mail, $body);
1209                $result = pclose($mail);
1210                $this->doCallback(
1211                    ($result == 0),
1212                    array($toAddr),
1213                    $this->cc,
1214                    $this->bcc,
1215                    $this->Subject,
1216                    $body,
1217                    $this->From
1218                );
1219                if ($result != 0) {
1220                    throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1221                }
1222            }
1223        } else {
1224            if (!@$mail = popen($sendmail, 'w')) {
1225                throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1226            }
1227            fputs($mail, $header);
1228            fputs($mail, $body);
1229            $result = pclose($mail);
1230            $this->doCallback(($result == 0), $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
1231            if ($result != 0) {
1232                throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1233            }
1234        }
1235        return true;
1236    }
1237
1238    /**
1239     * Send mail using the PHP mail() function.
1240     * @param string $header The message headers
1241     * @param string $body The message body
1242     * @link http://www.php.net/manual/en/book.mail.php
1243     * @throws phpmailerException
1244     * @access protected
1245     * @return boolean
1246     */
1247    protected function mailSend($header, $body)
1248    {
1249        $toArr = array();
1250        foreach ($this->to as $toaddr) {
1251            $toArr[] = $this->addrFormat($toaddr);
1252        }
1253        $to = implode(', ', $toArr);
1254
1255        if (empty($this->Sender)) {
1256            $params = ' ';
1257        } else {
1258            $params = sprintf('-f%s', $this->Sender);
1259        }
1260        if ($this->Sender != '' and !ini_get('safe_mode')) {
1261            $old_from = ini_get('sendmail_from');
1262            ini_set('sendmail_from', $this->Sender);
1263        }
1264        $result = false;
1265        if ($this->SingleTo && count($toArr) > 1) {
1266            foreach ($toArr as $toAddr) {
1267                $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
1268                $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From);
1269            }
1270        } else {
1271            $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
1272            $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
1273        }
1274        if (isset($old_from)) {
1275            ini_set('sendmail_from', $old_from);
1276        }
1277        if (!$result) {
1278            throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
1279        }
1280        return true;
1281    }
1282
1283    /**
1284     * Get an instance to use for SMTP operations.
1285     * Override this function to load your own SMTP implementation
1286     * @return SMTP
1287     */
1288    public function getSMTPInstance()
1289    {
1290        if (!is_object($this->smtp)) {
1291            $this->smtp = new SMTP;
1292        }
1293        return $this->smtp;
1294    }
1295
1296    /**
1297     * Send mail via SMTP.
1298     * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
1299     * Uses the PHPMailerSMTP class by default.
1300     * @see PHPMailer::getSMTPInstance() to use a different class.
1301     * @param string $header The message headers
1302     * @param string $body The message body
1303     * @throws phpmailerException
1304     * @uses SMTP
1305     * @access protected
1306     * @return boolean
1307     */
1308    protected function smtpSend($header, $body)
1309    {
1310        $bad_rcpt = array();
1311        if (!$this->smtpConnect($this->SMTPOptions)) {
1312            throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
1313        }
1314        if ('' == $this->Sender) {
1315            $smtp_from = $this->From;
1316        } else {
1317            $smtp_from = $this->Sender;
1318        }
1319        if (!$this->smtp->mail($smtp_from)) {
1320            $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
1321            throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
1322        }
1323
1324        // Attempt to send to all recipients
1325        foreach (array($this->to, $this->cc, $this->bcc) as $togroup) {
1326            foreach ($togroup as $to) {
1327                if (!$this->smtp->recipient($to[0])) {
1328                    $error = $this->smtp->getError();
1329                    $bad_rcpt[] = array('to' => $to[0], 'error' => $error['detail']);
1330                    $isSent = false;
1331                } else {
1332                    $isSent = true;
1333                }
1334                $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From);
1335            }
1336        }
1337
1338        // Only send the DATA command if we have viable recipients
1339        if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
1340            throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
1341        }
1342        if ($this->SMTPKeepAlive) {
1343            $this->smtp->reset();
1344        } else {
1345            $this->smtp->quit();
1346            $this->smtp->close();
1347        }
1348        //Create error message for any bad addresses
1349        if (count($bad_rcpt) > 0) {
1350            $errstr = '';
1351            foreach ($bad_rcpt as $bad) {
1352                $errstr .= $bad['to'] . ': ' . $bad['error'];
1353            }
1354            throw new phpmailerException(
1355                $this->lang('recipients_failed') . $errstr,
1356                self::STOP_CONTINUE
1357            );
1358        }
1359        return true;
1360    }
1361
1362    /**
1363     * Initiate a connection to an SMTP server.
1364     * Returns false if the operation failed.
1365     * @param array $options An array of options compatible with stream_context_create()
1366     * @uses SMTP
1367     * @access public
1368     * @throws phpmailerException
1369     * @return boolean
1370     */
1371    public function smtpConnect($options = array())
1372    {
1373        if (is_null($this->smtp)) {
1374            $this->smtp = $this->getSMTPInstance();
1375        }
1376
1377        // Already connected?
1378        if ($this->smtp->connected()) {
1379            return true;
1380        }
1381
1382        $this->smtp->setTimeout($this->Timeout);
1383        $this->smtp->setDebugLevel($this->SMTPDebug);
1384        $this->smtp->setDebugOutput($this->Debugoutput);
1385        $this->smtp->setVerp($this->do_verp);
1386        $hosts = explode(';', $this->Host);
1387        $lastexception = null;
1388
1389        foreach ($hosts as $hostentry) {
1390            $hostinfo = array();
1391            if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
1392                // Not a valid host entry
1393                continue;
1394            }
1395            // $hostinfo[2]: optional ssl or tls prefix
1396            // $hostinfo[3]: the hostname
1397            // $hostinfo[4]: optional port number
1398            // The host string prefix can temporarily override the current setting for SMTPSecure
1399            // If it's not specified, the default value is used
1400            $prefix = '';
1401            $secure = $this->SMTPSecure;
1402            $tls = ($this->SMTPSecure == 'tls');
1403            if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
1404                $prefix = 'ssl://';
1405                $tls = false; // Can't have SSL and TLS at the same time
1406                $secure = 'ssl';
1407            } elseif ($hostinfo[2] == 'tls') {
1408                $tls = true;
1409                // tls doesn't use a prefix
1410                $secure = 'tls';
1411            }
1412            //Do we need the OpenSSL extension?
1413            $sslext = defined('OPENSSL_ALGO_SHA1');
1414            if ('tls' === $secure or 'ssl' === $secure) {
1415                //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
1416                if (!$sslext) {
1417                    throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL);
1418                }
1419            }
1420            $host = $hostinfo[3];
1421            $port = $this->Port;
1422            $tport = (integer)$hostinfo[4];
1423            if ($tport > 0 and $tport < 65536) {
1424                $port = $tport;
1425            }
1426            if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
1427                try {
1428                    if ($this->Helo) {
1429                        $hello = $this->Helo;
1430                    } else {
1431                        $hello = $this->serverHostname();
1432                    }
1433                    $this->smtp->hello($hello);
1434                    //Automatically enable TLS encryption if:
1435                    // * it's not disabled
1436                    // * we have openssl extension
1437                    // * we are not already using SSL
1438                    // * the server offers STARTTLS
1439                    if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) {
1440                        $tls = true;
1441                    }
1442                    if ($tls) {
1443                        if (!$this->smtp->startTLS()) {
1444                            throw new phpmailerException($this->lang('connect_host'));
1445                        }
1446                        // We must resend HELO after tls negotiation
1447                        $this->smtp->hello($hello);
1448                    }
1449                    if ($this->SMTPAuth) {
1450                        if (!$this->smtp->authenticate(
1451                            $this->Username,
1452                            $this->Password,
1453                            $this->AuthType,
1454                            $this->Realm,
1455                            $this->Workstation
1456                        )
1457                        ) {
1458                            throw new phpmailerException($this->lang('authenticate'));
1459                        }
1460                    }
1461                    return true;
1462                } catch (phpmailerException $exc) {
1463                    $lastexception = $exc;
1464                    $this->edebug($exc->getMessage());
1465                    // We must have connected, but then failed TLS or Auth, so close connection nicely
1466                    $this->smtp->quit();
1467                }
1468            }
1469        }
1470        // If we get here, all connection attempts have failed, so close connection hard
1471        $this->smtp->close();
1472        // As we've caught all exceptions, just report whatever the last one was
1473        if ($this->exceptions and !is_null($lastexception)) {
1474            throw $lastexception;
1475        }
1476        return false;
1477    }
1478
1479    /**
1480     * Close the active SMTP session if one exists.
1481     * @return void
1482     */
1483    public function smtpClose()
1484    {
1485        if ($this->smtp !== null) {
1486            if ($this->smtp->connected()) {
1487                $this->smtp->quit();
1488                $this->smtp->close();
1489            }
1490        }
1491    }
1492
1493    /**
1494     * Set the language for error messages.
1495     * Returns false if it cannot load the language file.
1496     * The default language is English.
1497     * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
1498     * @param string $lang_path Path to the language file directory, with trailing separator (slash)
1499     * @return boolean
1500     * @access public
1501     */
1502    public function setLanguage($langcode = 'en', $lang_path = '')
1503    {
1504        // Define full set of translatable strings in English
1505        $PHPMAILER_LANG = array(
1506            'authenticate' => 'SMTP Error: Could not authenticate.',
1507            'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
1508            'data_not_accepted' => 'SMTP Error: data not accepted.',
1509            'empty_message' => 'Message body empty',
1510            'encoding' => 'Unknown encoding: ',
1511            'execute' => 'Could not execute: ',
1512            'file_access' => 'Could not access file: ',
1513            'file_open' => 'File Error: Could not open file: ',
1514            'from_failed' => 'The following From address failed: ',
1515            'instantiate' => 'Could not instantiate mail function.',
1516            'invalid_address' => 'Invalid address',
1517            'mailer_not_supported' => ' mailer is not supported.',
1518            'provide_address' => 'You must provide at least one recipient email address.',
1519            'recipients_failed' => 'SMTP Error: The following recipients failed: ',
1520            'signing' => 'Signing Error: ',
1521            'smtp_connect_failed' => 'SMTP connect() failed.',
1522            'smtp_error' => 'SMTP server error: ',
1523            'variable_set' => 'Cannot set or reset variable: ',
1524            'extension_missing' => 'Extension missing: '
1525        );
1526        if (empty($lang_path)) {
1527            // Calculate an absolute path so it can work if CWD is not here
1528            $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR;
1529        }
1530        $foundlang = true;
1531        $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
1532        // There is no English translation file
1533        if ($langcode != 'en') {
1534            // Make sure language file path is readable
1535            if (!is_readable($lang_file)) {
1536                $foundlang = false;
1537            } else {
1538                // Overwrite language-specific strings.
1539                // This way we'll never have missing translation keys.
1540                $foundlang = include $lang_file;
1541            }
1542        }
1543        $this->language = $PHPMAILER_LANG;
1544        return (boolean)$foundlang; // Returns false if language not found
1545    }
1546
1547    /**
1548     * Get the array of strings for the current language.
1549     * @return array
1550     */
1551    public function getTranslations()
1552    {
1553        return $this->language;
1554    }
1555
1556    /**
1557     * Create recipient headers.
1558     * @access public
1559     * @param string $type
1560     * @param array $addr An array of recipient,
1561     * where each recipient is a 2-element indexed array with element 0 containing an address
1562     * and element 1 containing a name, like:
1563     * array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User'))
1564     * @return string
1565     */
1566    public function addrAppend($type, $addr)
1567    {
1568        $addresses = array();
1569        foreach ($addr as $address) {
1570            $addresses[] = $this->addrFormat($address);
1571        }
1572        return $type . ': ' . implode(', ', $addresses) . $this->LE;
1573    }
1574
1575    /**
1576     * Format an address for use in a message header.
1577     * @access public
1578     * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name
1579     *      like array('joe@example.com', 'Joe User')
1580     * @return string
1581     */
1582    public function addrFormat($addr)
1583    {
1584        if (empty($addr[1])) { // No name provided
1585            return $this->secureHeader($addr[0]);
1586        } else {
1587            return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
1588                $addr[0]
1589            ) . '>';
1590        }
1591    }
1592
1593    /**
1594     * Word-wrap message.
1595     * For use with mailers that do not automatically perform wrapping
1596     * and for quoted-printable encoded messages.
1597     * Original written by philippe.
1598     * @param string $message The message to wrap
1599     * @param integer $length The line length to wrap to
1600     * @param boolean $qp_mode Whether to run in Quoted-Printable mode
1601     * @access public
1602     * @return string
1603     */
1604    public function wrapText($message, $length, $qp_mode = false)
1605    {
1606        if ($qp_mode) {
1607            $soft_break = sprintf(' =%s', $this->LE);
1608        } else {
1609            $soft_break = $this->LE;
1610        }
1611        // If utf-8 encoding is used, we will need to make sure we don't
1612        // split multibyte characters when we wrap
1613        $is_utf8 = (strtolower($this->CharSet) == 'utf-8');
1614        $lelen = strlen($this->LE);
1615        $crlflen = strlen(self::CRLF);
1616
1617        $message = $this->fixEOL($message);
1618        //Remove a trailing line break
1619        if (substr($message, -$lelen) == $this->LE) {
1620            $message = substr($message, 0, -$lelen);
1621        }
1622
1623        //Split message into lines
1624        $lines = explode($this->LE, $message);
1625        //Message will be rebuilt in here
1626        $message = '';
1627        foreach ($lines as $line) {
1628            $words = explode(' ', $line);
1629            $buf = '';
1630            $firstword = true;
1631            foreach ($words as $word) {
1632                if ($qp_mode and (strlen($word) > $length)) {
1633                    $space_left = $length - strlen($buf) - $crlflen;
1634                    if (!$firstword) {
1635                        if ($space_left > 20) {
1636                            $len = $space_left;
1637                            if ($is_utf8) {
1638                                $len = $this->utf8CharBoundary($word, $len);
1639                            } elseif (substr($word, $len - 1, 1) == '=') {
1640                                $len--;
1641                            } elseif (substr($word, $len - 2, 1) == '=') {
1642                                $len -= 2;
1643                            }
1644                            $part = substr($word, 0, $len);
1645                            $word = substr($word, $len);
1646                            $buf .= ' ' . $part;
1647                            $message .= $buf . sprintf('=%s', self::CRLF);
1648                        } else {
1649                            $message .= $buf . $soft_break;
1650                        }
1651                        $buf = '';
1652                    }
1653                    while (strlen($word) > 0) {
1654                        if ($length <= 0) {
1655                            break;
1656                        }
1657                        $len = $length;
1658                        if ($is_utf8) {
1659                            $len = $this->utf8CharBoundary($word, $len);
1660                        } elseif (substr($word, $len - 1, 1) == '=') {
1661                            $len--;
1662                        } elseif (substr($word, $len - 2, 1) == '=') {
1663                            $len -= 2;
1664                        }
1665                        $part = substr($word, 0, $len);
1666                        $word = substr($word, $len);
1667
1668                        if (strlen($word) > 0) {
1669                            $message .= $part . sprintf('=%s', self::CRLF);
1670                        } else {
1671                            $buf = $part;
1672                        }
1673                    }
1674                } else {
1675                    $buf_o = $buf;
1676                    if (!$firstword) {
1677                        $buf .= ' ';
1678                    }
1679                    $buf .= $word;
1680
1681                    if (strlen($buf) > $length and $buf_o != '') {
1682                        $message .= $buf_o . $soft_break;
1683                        $buf = $word;
1684                    }
1685                }
1686                $firstword = false;
1687            }
1688            $message .= $buf . self::CRLF;
1689        }
1690
1691        return $message;
1692    }
1693
1694    /**
1695     * Find the last character boundary prior to $maxLength in a utf-8
1696     * quoted-printable encoded string.
1697     * Original written by Colin Brown.
1698     * @access public
1699     * @param string $encodedText utf-8 QP text
1700     * @param integer $maxLength Find the last character boundary prior to this length
1701     * @return integer
1702     */
1703    public function utf8CharBoundary($encodedText, $maxLength)
1704    {
1705        $foundSplitPos = false;
1706        $lookBack = 3;
1707        while (!$foundSplitPos) {
1708            $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
1709            $encodedCharPos = strpos($lastChunk, '=');
1710            if (false !== $encodedCharPos) {
1711                // Found start of encoded character byte within $lookBack block.
1712                // Check the encoded byte value (the 2 chars after the '=')
1713                $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
1714                $dec = hexdec($hex);
1715                if ($dec < 128) {
1716                    // Single byte character.
1717                    // If the encoded char was found at pos 0, it will fit
1718                    // otherwise reduce maxLength to start of the encoded char
1719                    if ($encodedCharPos > 0) {
1720                        $maxLength = $maxLength - ($lookBack - $encodedCharPos);
1721                    }
1722                    $foundSplitPos = true;
1723                } elseif ($dec >= 192) {
1724                    // First byte of a multi byte character
1725                    // Reduce maxLength to split at start of character
1726                    $maxLength = $maxLength - ($lookBack - $encodedCharPos);
1727                    $foundSplitPos = true;
1728                } elseif ($dec < 192) {
1729                    // Middle byte of a multi byte character, look further back
1730                    $lookBack += 3;
1731                }
1732            } else {
1733                // No encoded character found
1734                $foundSplitPos = true;
1735            }
1736        }
1737        return $maxLength;
1738    }
1739
1740    /**
1741     * Apply word wrapping to the message body.
1742     * Wraps the message body to the number of chars set in the WordWrap property.
1743     * You should only do this to plain-text bodies as wrapping HTML tags may break them.
1744     * This is called automatically by createBody(), so you don't need to call it yourself.
1745     * @access public
1746     * @return void
1747     */
1748    public function setWordWrap()
1749    {
1750        if ($this->WordWrap < 1) {
1751            return;
1752        }
1753
1754        switch ($this->message_type) {
1755            case 'alt':
1756            case 'alt_inline':
1757            case 'alt_attach':
1758            case 'alt_inline_attach':
1759                $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
1760                break;
1761            default:
1762                $this->Body = $this->wrapText($this->Body, $this->WordWrap);
1763                break;
1764        }
1765    }
1766
1767    /**
1768     * Assemble message headers.
1769     * @access public
1770     * @return string The assembled headers
1771     */
1772    public function createHeader()
1773    {
1774        $result = '';
1775
1776        if ($this->MessageDate == '') {
1777            $this->MessageDate = self::rfcDate();
1778        }
1779        $result .= $this->headerLine('Date', $this->MessageDate);
1780
1781
1782        // To be created automatically by mail()
1783        if ($this->SingleTo) {
1784            if ($this->Mailer != 'mail') {
1785                foreach ($this->to as $toaddr) {
1786                    $this->SingleToArray[] = $this->addrFormat($toaddr);
1787                }
1788            }
1789        } else {
1790            if (count($this->to) > 0) {
1791                if ($this->Mailer != 'mail') {
1792                    $result .= $this->addrAppend('To', $this->to);
1793                }
1794            } elseif (count($this->cc) == 0) {
1795                $result .= $this->headerLine('To', 'undisclosed-recipients:;');
1796            }
1797        }
1798
1799        $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName)));
1800
1801        // sendmail and mail() extract Cc from the header before sending
1802        if (count($this->cc) > 0) {
1803            $result .= $this->addrAppend('Cc', $this->cc);
1804        }
1805
1806        // sendmail and mail() extract Bcc from the header before sending
1807        if ((
1808                $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail'
1809            )
1810            and count($this->bcc) > 0
1811        ) {
1812            $result .= $this->addrAppend('Bcc', $this->bcc);
1813        }
1814
1815        if (count($this->ReplyTo) > 0) {
1816            $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
1817        }
1818
1819        // mail() sets the subject itself
1820        if ($this->Mailer != 'mail') {
1821            $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
1822        }
1823
1824        if ($this->MessageID != '') {
1825            $this->lastMessageID = $this->MessageID;
1826        } else {
1827            $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->ServerHostname());
1828        }
1829        $result .= $this->headerLine('Message-ID', $this->lastMessageID);
1830        if (!is_null($this->Priority)) {
1831            $result .= $this->headerLine('X-Priority', $this->Priority);
1832        }
1833        if ($this->XMailer == '') {
1834            $result .= $this->headerLine(
1835                'X-Mailer',
1836                'PHPMailer ' . $this->Version . ' (https://github.com/PHPMailer/PHPMailer/)'
1837            );
1838        } else {
1839            $myXmailer = trim($this->XMailer);
1840            if ($myXmailer) {
1841                $result .= $this->headerLine('X-Mailer', $myXmailer);
1842            }
1843        }
1844
1845        if ($this->ConfirmReadingTo != '') {
1846            $result .= $this->headerLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
1847        }
1848
1849        // Add custom headers
1850        foreach ($this->CustomHeader as $header) {
1851            $result .= $this->headerLine(
1852                trim($header[0]),
1853                $this->encodeHeader(trim($header[1]))
1854            );
1855        }
1856        if (!$this->sign_key_file) {
1857            $result .= $this->headerLine('MIME-Version', '1.0');
1858            $result .= $this->getMailMIME();
1859        }
1860
1861        return $result;
1862    }
1863
1864    /**
1865     * Get the message MIME type headers.
1866     * @access public
1867     * @return string
1868     */
1869    public function getMailMIME()
1870    {
1871        $result = '';
1872        $ismultipart = true;
1873        switch ($this->message_type) {
1874            case 'inline':
1875                $result .= $this->headerLine('Content-Type', 'multipart/related;');
1876                $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
1877                break;
1878            case 'attach':
1879            case 'inline_attach':
1880            case 'alt_attach':
1881            case 'alt_inline_attach':
1882                $result .= $this->headerLine('Content-Type', 'multipart/mixed;');
1883                $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
1884                break;
1885            case 'alt':
1886            case 'alt_inline':
1887                $result .= $this->headerLine('Content-Type', 'multipart/alternative;');
1888                $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
1889                break;
1890            default:
1891                // Catches case 'plain': and case '':
1892                $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
1893                $ismultipart = false;
1894                break;
1895        }
1896        // RFC1341 part 5 says 7bit is assumed if not specified
1897        if ($this->Encoding != '7bit') {
1898            // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
1899            if ($ismultipart) {
1900                if ($this->Encoding == '8bit') {
1901                    $result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
1902                }
1903                // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
1904            } else {
1905                $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
1906            }
1907        }
1908
1909        if ($this->Mailer != 'mail') {
1910            $result .= $this->LE;
1911        }
1912
1913        return $result;
1914    }
1915
1916    /**
1917     * Returns the whole MIME message.
1918     * Includes complete headers and body.
1919     * Only valid post preSend().
1920     * @see PHPMailer::preSend()
1921     * @access public
1922     * @return string
1923     */
1924    public function getSentMIMEMessage()
1925    {
1926        return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
1927    }
1928
1929    /**
1930     * Assemble the message body.
1931     * Returns an empty string on failure.
1932     * @access public
1933     * @throws phpmailerException
1934     * @return string The assembled message body
1935     */
1936    public function createBody()
1937    {
1938        $body = '';
1939        //Create unique IDs and preset boundaries
1940        $this->uniqueid = md5(uniqid(time()));
1941        $this->boundary[1] = 'b1_' . $this->uniqueid;
1942        $this->boundary[2] = 'b2_' . $this->uniqueid;
1943        $this->boundary[3] = 'b3_' . $this->uniqueid;
1944
1945        if ($this->sign_key_file) {
1946            $body .= $this->getMailMIME() . $this->LE;
1947        }
1948
1949        $this->setWordWrap();
1950
1951        $bodyEncoding = $this->Encoding;
1952        $bodyCharSet = $this->CharSet;
1953        //Can we do a 7-bit downgrade?
1954        if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) {
1955            $bodyEncoding = '7bit';
1956            $bodyCharSet = 'us-ascii';
1957        }
1958        //If lines are too long, and we're not already using an encoding that will shorten them,
1959        //change to quoted-printable transfer encoding
1960        if ('base64' != $this->Encoding and self::hasLineLongerThanMax($this->Body)) {
1961            $this->Encoding = 'quoted-printable';
1962            $bodyEncoding = 'quoted-printable';
1963        }
1964
1965        $altBodyEncoding = $this->Encoding;
1966        $altBodyCharSet = $this->CharSet;
1967        //Can we do a 7-bit downgrade?
1968        if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) {
1969            $altBodyEncoding = '7bit';
1970            $altBodyCharSet = 'us-ascii';
1971        }
1972        //If lines are too long, change to quoted-printable transfer encoding
1973        if (self::hasLineLongerThanMax($this->AltBody)) {
1974            $altBodyEncoding = 'quoted-printable';
1975        }
1976        //Use this as a preamble in all multipart message types
1977        $mimepre = "This is a multi-part message in MIME format." . $this->LE . $this->LE;
1978        switch ($this->message_type) {
1979            case 'inline':
1980                $body .= $mimepre;
1981                $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
1982                $body .= $this->encodeString($this->Body, $bodyEncoding);
1983                $body .= $this->LE . $this->LE;
1984                $body .= $this->attachAll('inline', $this->boundary[1]);
1985                break;
1986            case 'attach':
1987                $body .= $mimepre;
1988                $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
1989                $body .= $this->encodeString($this->Body, $bodyEncoding);
1990                $body .= $this->LE . $this->LE;
1991                $body .= $this->attachAll('attachment', $this->boundary[1]);
1992                break;
1993            case 'inline_attach':
1994                $body .= $mimepre;
1995                $body .= $this->textLine('--' . $this->boundary[1]);
1996                $body .= $this->headerLine('Content-Type', 'multipart/related;');
1997                $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
1998                $body .= $this->LE;
1999                $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
2000                $body .= $this->encodeString($this->Body, $bodyEncoding);
2001                $body .= $this->LE . $this->LE;
2002                $body .= $this->attachAll('inline', $this->boundary[2]);
2003                $body .= $this->LE;
2004                $body .= $this->attachAll('attachment', $this->boundary[1]);
2005                break;
2006            case 'alt':
2007                $body .= $mimepre;
2008                $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2009                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2010                $body .= $this->LE . $this->LE;
2011                $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
2012                $body .= $this->encodeString($this->Body, $bodyEncoding);
2013                $body .= $this->LE . $this->LE;
2014                if (!empty($this->Ical)) {
2015                    $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
2016                    $body .= $this->encodeString($this->Ical, $this->Encoding);
2017                    $body .= $this->LE . $this->LE;
2018                }
2019                $body .= $this->endBoundary($this->boundary[1]);
2020                break;
2021            case 'alt_inline':
2022                $body .= $mimepre;
2023                $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2024                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2025                $body .= $this->LE . $this->LE;
2026                $body .= $this->textLine('--' . $this->boundary[1]);
2027                $body .= $this->headerLine('Content-Type', 'multipart/related;');
2028                $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
2029                $body .= $this->LE;
2030                $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
2031                $body .= $this->encodeString($this->Body, $bodyEncoding);
2032                $body .= $this->LE . $this->LE;
2033                $body .= $this->attachAll('inline', $this->boundary[2]);
2034                $body .= $this->LE;
2035                $body .= $this->endBoundary($this->boundary[1]);
2036                break;
2037            case 'alt_attach':
2038                $body .= $mimepre;
2039                $body .= $this->textLine('--' . $this->boundary[1]);
2040                $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
2041                $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
2042                $body .= $this->LE;
2043                $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2044                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2045                $body .= $this->LE . $this->LE;
2046                $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
2047                $body .= $this->encodeString($this->Body, $bodyEncoding);
2048                $body .= $this->LE . $this->LE;
2049                $body .= $this->endBoundary($this->boundary[2]);
2050                $body .= $this->LE;
2051                $body .= $this->attachAll('attachment', $this->boundary[1]);
2052                break;
2053            case 'alt_inline_attach':
2054                $body .= $mimepre;
2055                $body .= $this->textLine('--' . $this->boundary[1]);
2056                $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
2057                $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
2058                $body .= $this->LE;
2059                $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
2060                $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2061                $body .= $this->LE . $this->LE;
2062                $body .= $this->textLine('--' . $this->boundary[2]);
2063                $body .= $this->headerLine('Content-Type', 'multipart/related;');
2064                $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
2065                $body .= $this->LE;
2066                $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
2067                $body .= $this->encodeString($this->Body, $bodyEncoding);
2068                $body .= $this->LE . $this->LE;
2069                $body .= $this->attachAll('inline', $this->boundary[3]);
2070                $body .= $this->LE;
2071                $body .= $this->endBoundary($this->boundary[2]);
2072                $body .= $this->LE;
2073                $body .= $this->attachAll('attachment', $this->boundary[1]);
2074                break;
2075            default:
2076                // catch case 'plain' and case ''
2077                $body .= $this->encodeString($this->Body, $bodyEncoding);
2078                break;
2079        }
2080
2081        if ($this->isError()) {
2082            $body = '';
2083        } elseif ($this->sign_key_file) {
2084            try {
2085                if (!defined('PKCS7_TEXT')) {
2086                    throw new phpmailerException($this->lang('extension_missing') . 'openssl');
2087                }
2088                // @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1
2089                $file = tempnam(sys_get_temp_dir(), 'mail');
2090                if (false === file_put_contents($file, $body)) {
2091                    throw new phpmailerException($this->lang('signing') . ' Could not write temp file');
2092                }
2093                $signed = tempnam(sys_get_temp_dir(), 'signed');
2094                //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
2095                if (empty($this->sign_extracerts_file)) {
2096                    $sign = @openssl_pkcs7_sign(
2097                        $file,
2098                        $signed,
2099                        'file://' . realpath($this->sign_cert_file),
2100                        array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
2101                        null
2102                    );
2103                } else {
2104                    $sign = @openssl_pkcs7_sign(
2105                        $file,
2106                        $signed,
2107                        'file://' . realpath($this->sign_cert_file),
2108                        array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
2109                        null,
2110                        PKCS7_DETACHED,
2111                        $this->sign_extracerts_file
2112                    );
2113                }
2114                if ($sign) {
2115                    @unlink($file);
2116                    $body = file_get_contents($signed);
2117                    @unlink($signed);
2118                    //The message returned by openssl contains both headers and body, so need to split them up
2119                    $parts = explode("\n\n", $body, 2);
2120                    $this->MIMEHeader .= $parts[0] . $this->LE . $this->LE;
2121                    $body = $parts[1];
2122                } else {
2123                    @unlink($file);
2124                    @unlink($signed);
2125                    throw new phpmailerException($this->lang('signing') . openssl_error_string());
2126                }
2127            } catch (phpmailerException $exc) {
2128                $body = '';
2129                if ($this->exceptions) {
2130                    throw $exc;
2131                }
2132            }
2133        }
2134        return $body;
2135    }
2136
2137    /**
2138     * Return the start of a message boundary.
2139     * @access protected
2140     * @param string $boundary
2141     * @param string $charSet
2142     * @param string $contentType
2143     * @param string $encoding
2144     * @return string
2145     */
2146    protected function getBoundary($boundary, $charSet, $contentType, $encoding)
2147    {
2148        $result = '';
2149        if ($charSet == '') {
2150            $charSet = $this->CharSet;
2151        }
2152        if ($contentType == '') {
2153            $contentType = $this->ContentType;
2154        }
2155        if ($encoding == '') {
2156            $encoding = $this->Encoding;
2157        }
2158        $result .= $this->textLine('--' . $boundary);
2159        $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
2160        $result .= $this->LE;
2161        // RFC1341 part 5 says 7bit is assumed if not specified
2162        if ($encoding != '7bit') {
2163            $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
2164        }
2165        $result .= $this->LE;
2166
2167        return $result;
2168    }
2169
2170    /**
2171     * Return the end of a message boundary.
2172     * @access protected
2173     * @param string $boundary
2174     * @return string
2175     */
2176    protected function endBoundary($boundary)
2177    {
2178        return $this->LE . '--' . $boundary . '--' . $this->LE;
2179    }
2180
2181    /**
2182     * Set the message type.
2183     * PHPMailer only supports some preset message types,
2184     * not arbitrary MIME structures.
2185     * @access protected
2186     * @return void
2187     */
2188    protected function setMessageType()
2189    {
2190        $type = array();
2191        if ($this->alternativeExists()) {
2192            $type[] = 'alt';
2193        }
2194        if ($this->inlineImageExists()) {
2195            $type[] = 'inline';
2196        }
2197        if ($this->attachmentExists()) {
2198            $type[] = 'attach';
2199        }
2200        $this->message_type = implode('_', $type);
2201        if ($this->message_type == '') {
2202            $this->message_type = 'plain';
2203        }
2204    }
2205
2206    /**
2207     * Format a header line.
2208     * @access public
2209     * @param string $name
2210     * @param string $value
2211     * @return string
2212     */
2213    public function headerLine($name, $value)
2214    {
2215        return $name . ': ' . $value . $this->LE;
2216    }
2217
2218    /**
2219     * Return a formatted mail line.
2220     * @access public
2221     * @param string $value
2222     * @return string
2223     */
2224    public function textLine($value)
2225    {
2226        return $value . $this->LE;
2227    }
2228
2229    /**
2230     * Add an attachment from a path on the filesystem.
2231     * Returns false if the file could not be found or read.
2232     * @param string $path Path to the attachment.
2233     * @param string $name Overrides the attachment name.
2234     * @param string $encoding File encoding (see $Encoding).
2235     * @param string $type File extension (MIME) type.
2236     * @param string $disposition Disposition to use
2237     * @throws phpmailerException
2238     * @return boolean
2239     */
2240    public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment')
2241    {
2242        try {
2243            if (!@is_file($path)) {
2244                throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE);
2245            }
2246
2247            // If a MIME type is not specified, try to work it out from the file name
2248            if ($type == '') {
2249                $type = self::filenameToType($path);
2250            }
2251
2252            $filename = basename($path);
2253            if ($name == '') {
2254                $name = $filename;
2255            }
2256
2257            $this->attachment[] = array(
2258                0 => $path,
2259                1 => $filename,
2260                2 => $name,
2261                3 => $encoding,
2262                4 => $type,
2263                5 => false, // isStringAttachment
2264                6 => $disposition,
2265                7 => 0
2266            );
2267
2268        } catch (phpmailerException $exc) {
2269            $this->setError($exc->getMessage());
2270            $this->edebug($exc->getMessage());
2271            if ($this->exceptions) {
2272                throw $exc;
2273            }
2274            return false;
2275        }
2276        return true;
2277    }
2278
2279    /**
2280     * Return the array of attachments.
2281     * @return array
2282     */
2283    public function getAttachments()
2284    {
2285        return $this->attachment;
2286    }
2287
2288    /**
2289     * Attach all file, string, and binary attachments to the message.
2290     * Returns an empty string on failure.
2291     * @access protected
2292     * @param string $disposition_type
2293     * @param string $boundary
2294     * @return string
2295     */
2296    protected function attachAll($disposition_type, $boundary)
2297    {
2298        // Return text of body
2299        $mime = array();
2300        $cidUniq = array();
2301        $incl = array();
2302
2303        // Add all attachments
2304        foreach ($this->attachment as $attachment) {
2305            // Check if it is a valid disposition_filter
2306            if ($attachment[6] == $disposition_type) {
2307                // Check for string attachment
2308                $string = '';
2309                $path = '';
2310                $bString = $attachment[5];
2311                if ($bString) {
2312                    $string = $attachment[0];
2313                } else {
2314                    $path = $attachment[0];
2315                }
2316
2317                $inclhash = md5(serialize($attachment));
2318                if (in_array($inclhash, $incl)) {
2319                    continue;
2320                }
2321                $incl[] = $inclhash;
2322                $name = $attachment[2];
2323                $encoding = $attachment[3];
2324                $type = $attachment[4];
2325                $disposition = $attachment[6];
2326                $cid = $attachment[7];
2327                if ($disposition == 'inline' && isset($cidUniq[$cid])) {
2328                    continue;
2329                }
2330                $cidUniq[$cid] = true;
2331
2332                $mime[] = sprintf('--%s%s', $boundary, $this->LE);
2333                $mime[] = sprintf(
2334                    'Content-Type: %s; name="%s"%s',
2335                    $type,
2336                    $this->encodeHeader($this->secureHeader($name)),
2337                    $this->LE
2338                );
2339                // RFC1341 part 5 says 7bit is assumed if not specified
2340                if ($encoding != '7bit') {
2341                    $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE);
2342                }
2343
2344                if ($disposition == 'inline') {
2345                    $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE);
2346                }
2347
2348                // If a filename contains any of these chars, it should be quoted,
2349                // but not otherwise: RFC2183 & RFC2045 5.1
2350                // Fixes a warning in IETF's msglint MIME checker
2351                // Allow for bypassing the Content-Disposition header totally
2352                if (!(empty($disposition))) {
2353                    $encoded_name = $this->encodeHeader($this->secureHeader($name));
2354                    if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
2355                        $mime[] = sprintf(
2356                            'Content-Disposition: %s; filename="%s"%s',
2357                            $disposition,
2358                            $encoded_name,
2359                            $this->LE . $this->LE
2360                        );
2361                    } else {
2362                        $mime[] = sprintf(
2363                            'Content-Disposition: %s; filename=%s%s',
2364                            $disposition,
2365                            $encoded_name,
2366                            $this->LE . $this->LE
2367                        );
2368                    }
2369                } else {
2370                    $mime[] = $this->LE;
2371                }
2372
2373                // Encode as string attachment
2374                if ($bString) {
2375                    $mime[] = $this->encodeString($string, $encoding);
2376                    if ($this->isError()) {
2377                        return '';
2378                    }
2379                    $mime[] = $this->LE . $this->LE;
2380                } else {
2381                    $mime[] = $this->encodeFile($path, $encoding);
2382                    if ($this->isError()) {
2383                        return '';
2384                    }
2385                    $mime[] = $this->LE . $this->LE;
2386                }
2387            }
2388        }
2389
2390        $mime[] = sprintf('--%s--%s', $boundary, $this->LE);
2391
2392        return implode('', $mime);
2393    }
2394
2395    /**
2396     * Encode a file attachment in requested format.
2397     * Returns an empty string on failure.
2398     * @param string $path The full path to the file
2399     * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
2400     * @throws phpmailerException
2401     * @see EncodeFile(encodeFile
2402     * @access protected
2403     * @return string
2404     */
2405    protected function encodeFile($path, $encoding = 'base64')
2406    {
2407        try {
2408            if (!is_readable($path)) {
2409                throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE);
2410            }
2411            $magic_quotes = get_magic_quotes_runtime();
2412            if ($magic_quotes) {
2413                if (version_compare(PHP_VERSION, '5.3.0', '<')) {
2414                    set_magic_quotes_runtime(false);
2415                } else {
2416                    //Doesn't exist in PHP 5.4, but we don't need to check because
2417                    //get_magic_quotes_runtime always returns false in 5.4+
2418                    //so it will never get here
2419                    ini_set('magic_quotes_runtime', false);
2420                }
2421            }
2422            $file_buffer = file_get_contents($path);
2423            $file_buffer = $this->encodeString($file_buffer, $encoding);
2424            if ($magic_quotes) {
2425                if (version_compare(PHP_VERSION, '5.3.0', '<')) {
2426                    set_magic_quotes_runtime($magic_quotes);
2427                } else {
2428                    ini_set('magic_quotes_runtime', $magic_quotes);
2429                }
2430            }
2431            return $file_buffer;
2432        } catch (Exception $exc) {
2433            $this->setError($exc->getMessage());
2434            return '';
2435        }
2436    }
2437
2438    /**
2439     * Encode a string in requested format.
2440     * Returns an empty string on failure.
2441     * @param string $str The text to encode
2442     * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
2443     * @access public
2444     * @return string
2445     */
2446    public function encodeString($str, $encoding = 'base64')
2447    {
2448        $encoded = '';
2449        switch (strtolower($encoding)) {
2450            case 'base64':
2451                $encoded = chunk_split(base64_encode($str), 76, $this->LE);
2452                break;
2453            case '7bit':
2454            case '8bit':
2455                $encoded = $this->fixEOL($str);
2456                // Make sure it ends with a line break
2457                if (substr($encoded, -(strlen($this->LE))) != $this->LE) {
2458                    $encoded .= $this->LE;
2459                }
2460                break;
2461            case 'binary':
2462                $encoded = $str;
2463                break;
2464            case 'quoted-printable':
2465                $encoded = $this->encodeQP($str);
2466                break;
2467            default:
2468                $this->setError($this->lang('encoding') . $encoding);
2469                break;
2470        }
2471        return $encoded;
2472    }
2473
2474    /**
2475     * Encode a header string optimally.
2476     * Picks shortest of Q, B, quoted-printable or none.
2477     * @access public
2478     * @param string $str
2479     * @param string $position
2480     * @return string
2481     */
2482    public function encodeHeader($str, $position = 'text')
2483    {
2484        $matchcount = 0;
2485        switch (strtolower($position)) {
2486            case 'phrase':
2487                if (!preg_match('/[\200-\377]/', $str)) {
2488                    // Can't use addslashes as we don't know the value of magic_quotes_sybase
2489                    $encoded = addcslashes($str, "\0..\37\177\\\"");
2490                    if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
2491                        return ($encoded);
2492                    } else {
2493                        return ("\"$encoded\"");
2494                    }
2495                }
2496                $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
2497                break;
2498            /** @noinspection PhpMissingBreakStatementInspection */
2499            case 'comment':
2500                $matchcount = preg_match_all('/[()"]/', $str, $matches);
2501                // Intentional fall-through
2502            case 'text':
2503            default:
2504                $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
2505                break;
2506        }
2507
2508        //There are no chars that need encoding
2509        if ($matchcount == 0) {
2510            return ($str);
2511        }
2512
2513        $maxlen = 75 - 7 - strlen($this->CharSet);
2514        // Try to select the encoding which should produce the shortest output
2515        if ($matchcount > strlen($str) / 3) {
2516            // More than a third of the content will need encoding, so B encoding will be most efficient
2517            $encoding = 'B';
2518            if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) {
2519                // Use a custom function which correctly encodes and wraps long
2520                // multibyte strings without breaking lines within a character
2521                $encoded = $this->base64EncodeWrapMB($str, "\n");
2522            } else {
2523                $encoded = base64_encode($str);
2524                $maxlen -= $maxlen % 4;
2525                $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
2526            }
2527        } else {
2528            $encoding = 'Q';
2529            $encoded = $this->encodeQ($str, $position);
2530            $encoded = $this->wrapText($encoded, $maxlen, true);
2531            $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
2532        }
2533
2534        $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
2535        $encoded = trim(str_replace("\n", $this->LE, $encoded));
2536
2537        return $encoded;
2538    }
2539
2540    /**
2541     * Check if a string contains multi-byte characters.
2542     * @access public
2543     * @param string $str multi-byte text to wrap encode
2544     * @return boolean
2545     */
2546    public function hasMultiBytes($str)
2547    {
2548        if (function_exists('mb_strlen')) {
2549            return (strlen($str) > mb_strlen($str, $this->CharSet));
2550        } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
2551            return false;
2552        }
2553    }
2554
2555    /**
2556     * Does a string contain any 8-bit chars (in any charset)?
2557     * @param string $text
2558     * @return boolean
2559     */
2560    public function has8bitChars($text)
2561    {
2562        return (boolean)preg_match('/[\x80-\xFF]/', $text);
2563    }
2564
2565    /**
2566     * Encode and wrap long multibyte strings for mail headers
2567     * without breaking lines within a character.
2568     * Adapted from a function by paravoid
2569     * @link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
2570     * @access public
2571     * @param string $str multi-byte text to wrap encode
2572     * @param string $linebreak string to use as linefeed/end-of-line
2573     * @return string
2574     */
2575    public function base64EncodeWrapMB($str, $linebreak = null)
2576    {
2577        $start = '=?' . $this->CharSet . '?B?';
2578        $end = '?=';
2579        $encoded = '';
2580        if ($linebreak === null) {
2581            $linebreak = $this->LE;
2582        }
2583
2584        $mb_length = mb_strlen($str, $this->CharSet);
2585        // Each line must have length <= 75, including $start and $end
2586        $length = 75 - strlen($start) - strlen($end);
2587        // Average multi-byte ratio
2588        $ratio = $mb_length / strlen($str);
2589        // Base64 has a 4:3 ratio
2590        $avgLength = floor($length * $ratio * .75);
2591
2592        for ($i = 0; $i < $mb_length; $i += $offset) {
2593            $lookBack = 0;
2594            do {
2595                $offset = $avgLength - $lookBack;
2596                $chunk = mb_substr($str, $i, $offset, $this->CharSet);
2597                $chunk = base64_encode($chunk);
2598                $lookBack++;
2599            } while (strlen($chunk) > $length);
2600            $encoded .= $chunk . $linebreak;
2601        }
2602
2603        // Chomp the last linefeed
2604        $encoded = substr($encoded, 0, -strlen($linebreak));
2605        return $encoded;
2606    }
2607
2608    /**
2609     * Encode a string in quoted-printable format.
2610     * According to RFC2045 section 6.7.
2611     * @access public
2612     * @param string $string The text to encode
2613     * @param integer $line_max Number of chars allowed on a line before wrapping
2614     * @return string
2615     * @link http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 Adapted from this comment
2616     */
2617    public function encodeQP($string, $line_max = 76)
2618    {
2619        // Use native function if it's available (>= PHP5.3)
2620        if (function_exists('quoted_printable_encode')) {
2621            return $this->fixEOL(quoted_printable_encode($string));
2622        }
2623        // Fall back to a pure PHP implementation
2624        $string = str_replace(
2625            array('%20', '%0D%0A.', '%0D%0A', '%'),
2626            array(' ', "\r\n=2E", "\r\n", '='),
2627            rawurlencode($string)
2628        );
2629        $string = preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string);
2630        return $this->fixEOL($string);
2631    }
2632
2633    /**
2634     * Backward compatibility wrapper for an old QP encoding function that was removed.
2635     * @see PHPMailer::encodeQP()
2636     * @access public
2637     * @param string $string
2638     * @param integer $line_max
2639     * @param boolean $space_conv
2640     * @return string
2641     * @deprecated Use encodeQP instead.
2642     */
2643    public function encodeQPphp(
2644        $string,
2645        $line_max = 76,
2646        /** @noinspection PhpUnusedParameterInspection */ $space_conv = false
2647    ) {
2648        return $this->encodeQP($string, $line_max);
2649    }
2650
2651    /**
2652     * Encode a string using Q encoding.
2653     * @link http://tools.ietf.org/html/rfc2047
2654     * @param string $str the text to encode
2655     * @param string $position Where the text is going to be used, see the RFC for what that means
2656     * @access public
2657     * @return string
2658     */
2659    public function encodeQ($str, $position = 'text')
2660    {
2661        // There should not be any EOL in the string
2662        $pattern = '';
2663        $encoded = str_replace(array("\r", "\n"), '', $str);
2664        switch (strtolower($position)) {
2665            case 'phrase':
2666                // RFC 2047 section 5.3
2667                $pattern = '^A-Za-z0-9!*+\/ -';
2668                break;
2669            /** @noinspection PhpMissingBreakStatementInspection */
2670            case 'comment':
2671                // RFC 2047 section 5.2
2672                $pattern = '\(\)"';
2673                // intentional fall-through
2674                // for this reason we build the $pattern without including delimiters and []
2675            case 'text':
2676            default:
2677                // RFC 2047 section 5.1
2678                // Replace every high ascii, control, =, ? and _ characters
2679                $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
2680                break;
2681        }
2682        $matches = array();
2683        if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
2684            // If the string contains an '=', make sure it's the first thing we replace
2685            // so as to avoid double-encoding
2686            $eqkey = array_search('=', $matches[0]);
2687            if (false !== $eqkey) {
2688                unset($matches[0][$eqkey]);
2689                array_unshift($matches[0], '=');
2690            }
2691            foreach (array_unique($matches[0]) as $char) {
2692                $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
2693            }
2694        }
2695        // Replace every spaces to _ (more readable than =20)
2696        return str_replace(' ', '_', $encoded);
2697    }
2698
2699
2700    /**
2701     * Add a string or binary attachment (non-filesystem).
2702     * This method can be used to attach ascii or binary data,
2703     * such as a BLOB record from a database.
2704     * @param string $string String attachment data.
2705     * @param string $filename Name of the attachment.
2706     * @param string $encoding File encoding (see $Encoding).
2707     * @param string $type File extension (MIME) type.
2708     * @param string $disposition Disposition to use
2709     * @return void
2710     */
2711    public function addStringAttachment(
2712        $string,
2713        $filename,
2714        $encoding = 'base64',
2715        $type = '',
2716        $disposition = 'attachment'
2717    ) {
2718        // If a MIME type is not specified, try to work it out from the file name
2719        if ($type == '') {
2720            $type = self::filenameToType($filename);
2721        }
2722        // Append to $attachment array
2723        $this->attachment[] = array(
2724            0 => $string,
2725            1 => $filename,
2726            2 => basename($filename),
2727            3 => $encoding,
2728            4 => $type,
2729            5 => true, // isStringAttachment
2730            6 => $disposition,
2731            7 => 0
2732        );
2733    }
2734
2735    /**
2736     * Add an embedded (inline) attachment from a file.
2737     * This can include images, sounds, and just about any other document type.
2738     * These differ from 'regular' attachments in that they are intended to be
2739     * displayed inline with the message, not just attached for download.
2740     * This is used in HTML messages that embed the images
2741     * the HTML refers to using the $cid value.
2742     * @param string $path Path to the attachment.
2743     * @param string $cid Content ID of the attachment; Use this to reference
2744     *        the content when using an embedded image in HTML.
2745     * @param string $name Overrides the attachment name.
2746     * @param string $encoding File encoding (see $Encoding).
2747     * @param string $type File MIME type.
2748     * @param string $disposition Disposition to use
2749     * @return boolean True on successfully adding an attachment
2750     */
2751    public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
2752    {
2753        if (!@is_file($path)) {
2754            $this->setError($this->lang('file_access') . $path);
2755            return false;
2756        }
2757
2758        // If a MIME type is not specified, try to work it out from the file name
2759        if ($type == '') {
2760            $type = self::filenameToType($path);
2761        }
2762
2763        $filename = basename($path);
2764        if ($name == '') {
2765            $name = $filename;
2766        }
2767
2768        // Append to $attachment array
2769        $this->attachment[] = array(
2770            0 => $path,
2771            1 => $filename,
2772            2 => $name,
2773            3 => $encoding,
2774            4 => $type,
2775            5 => false, // isStringAttachment
2776            6 => $disposition,
2777            7 => $cid
2778        );
2779        return true;
2780    }
2781
2782    /**
2783     * Add an embedded stringified attachment.
2784     * This can include images, sounds, and just about any other document type.
2785     * Be sure to set the $type to an image type for images:
2786     * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
2787     * @param string $string The attachment binary data.
2788     * @param string $cid Content ID of the attachment; Use this to reference
2789     *        the content when using an embedded image in HTML.
2790     * @param string $name
2791     * @param string $encoding File encoding (see $Encoding).
2792     * @param string $type MIME type.
2793     * @param string $disposition Disposition to use
2794     * @return boolean True on successfully adding an attachment
2795     */
2796    public function addStringEmbeddedImage(
2797        $string,
2798        $cid,
2799        $name = '',
2800        $encoding = 'base64',
2801        $type = '',
2802        $disposition = 'inline'
2803    ) {
2804        // If a MIME type is not specified, try to work it out from the name
2805        if ($type == '') {
2806            $type = self::filenameToType($name);
2807        }
2808
2809        // Append to $attachment array
2810        $this->attachment[] = array(
2811            0 => $string,
2812            1 => $name,
2813            2 => $name,
2814            3 => $encoding,
2815            4 => $type,
2816            5 => true, // isStringAttachment
2817            6 => $disposition,
2818            7 => $cid
2819        );
2820        return true;
2821    }
2822
2823    /**
2824     * Check if an inline attachment is present.
2825     * @access public
2826     * @return boolean
2827     */
2828    public function inlineImageExists()
2829    {
2830        foreach ($this->attachment as $attachment) {
2831            if ($attachment[6] == 'inline') {
2832                return true;
2833            }
2834        }
2835        return false;
2836    }
2837
2838    /**
2839     * Check if an attachment (non-inline) is present.
2840     * @return boolean
2841     */
2842    public function attachmentExists()
2843    {
2844        foreach ($this->attachment as $attachment) {
2845            if ($attachment[6] == 'attachment') {
2846                return true;
2847            }
2848        }
2849        return false;
2850    }
2851
2852    /**
2853     * Check if this message has an alternative body set.
2854     * @return boolean
2855     */
2856    public function alternativeExists()
2857    {
2858        return !empty($this->AltBody);
2859    }
2860
2861    /**
2862     * Clear all To recipients.
2863     * @return void
2864     */
2865    public function clearAddresses()
2866    {
2867        foreach ($this->to as $to) {
2868            unset($this->all_recipients[strtolower($to[0])]);
2869        }
2870        $this->to = array();
2871    }
2872
2873    /**
2874     * Clear all CC recipients.
2875     * @return void
2876     */
2877    public function clearCCs()
2878    {
2879        foreach ($this->cc as $cc) {
2880            unset($this->all_recipients[strtolower($cc[0])]);
2881        }
2882        $this->cc = array();
2883    }
2884
2885    /**
2886     * Clear all BCC recipients.
2887     * @return void
2888     */
2889    public function clearBCCs()
2890    {
2891        foreach ($this->bcc as $bcc) {
2892            unset($this->all_recipients[strtolower($bcc[0])]);
2893        }
2894        $this->bcc = array();
2895    }
2896
2897    /**
2898     * Clear all ReplyTo recipients.
2899     * @return void
2900     */
2901    public function clearReplyTos()
2902    {
2903        $this->ReplyTo = array();
2904    }
2905
2906    /**
2907     * Clear all recipient types.
2908     * @return void
2909     */
2910    public function clearAllRecipients()
2911    {
2912        $this->to = array();
2913        $this->cc = array();
2914        $this->bcc = array();
2915        $this->all_recipients = array();
2916    }
2917
2918    /**
2919     * Clear all filesystem, string, and binary attachments.
2920     * @return void
2921     */
2922    public function clearAttachments()
2923    {
2924        $this->attachment = array();
2925    }
2926
2927    /**
2928     * Clear all custom headers.
2929     * @return void
2930     */
2931    public function clearCustomHeaders()
2932    {
2933        $this->CustomHeader = array();
2934    }
2935
2936    /**
2937     * Add an error message to the error container.
2938     * @access protected
2939     * @param string $msg
2940     * @return void
2941     */
2942    protected function setError($msg)
2943    {
2944        $this->error_count++;
2945        if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
2946            $lasterror = $this->smtp->getError();
2947            if (!empty($lasterror['error'])) {
2948                $msg .= $this->lang('smtp_error') . $lasterror['error'];
2949                if (!empty($lasterror['detail'])) {
2950                    $msg .= ' Detail: '. $lasterror['detail'];
2951                }
2952                if (!empty($lasterror['smtp_code'])) {
2953                    $msg .= ' SMTP code: ' . $lasterror['smtp_code'];
2954                }
2955                if (!empty($lasterror['smtp_code_ex'])) {
2956                    $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex'];
2957                }
2958            }
2959        }
2960        $this->ErrorInfo = $msg;
2961    }
2962
2963    /**
2964     * Return an RFC 822 formatted date.
2965     * @access public
2966     * @return string
2967     * @static
2968     */
2969    public static function rfcDate()
2970    {
2971        // Set the time zone to whatever the default is to avoid 500 errors
2972        // Will default to UTC if it's not set properly in php.ini
2973        date_default_timezone_set(@date_default_timezone_get());
2974        return date('D, j M Y H:i:s O');
2975    }
2976
2977    /**
2978     * Get the server hostname.
2979     * Returns 'localhost.localdomain' if unknown.
2980     * @access protected
2981     * @return string
2982     */
2983    protected function serverHostname()
2984    {
2985        $result = 'localhost.localdomain';
2986        if (!empty($this->Hostname)) {
2987            $result = $this->Hostname;
2988        } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) {
2989            $result = $_SERVER['SERVER_NAME'];
2990        } elseif (function_exists('gethostname') && gethostname() !== false) {
2991            $result = gethostname();
2992        } elseif (php_uname('n') !== false) {
2993            $result = php_uname('n');
2994        }
2995        return $result;
2996    }
2997
2998    /**
2999     * Get an error message in the current language.
3000     * @access protected
3001     * @param string $key
3002     * @return string
3003     */
3004    protected function lang($key)
3005    {
3006        if (count($this->language) < 1) {
3007            $this->setLanguage('en'); // set the default language
3008        }
3009
3010        if (array_key_exists($key, $this->language)) {
3011            if ($key == 'smtp_connect_failed') {
3012                //Include a link to troubleshooting docs on SMTP connection failure
3013                //this is by far the biggest cause of support questions
3014                //but it's usually not PHPMailer's fault.
3015                return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
3016            }
3017            return $this->language[$key];
3018        } else {
3019            //Return the key as a fallback
3020            return $key;
3021        }
3022    }
3023
3024    /**
3025     * Check if an error occurred.
3026     * @access public
3027     * @return boolean True if an error did occur.
3028     */
3029    public function isError()
3030    {
3031        return ($this->error_count > 0);
3032    }
3033
3034    /**
3035     * Ensure consistent line endings in a string.
3036     * Changes every end of line from CRLF, CR or LF to $this->LE.
3037     * @access public
3038     * @param string $str String to fixEOL
3039     * @return string
3040     */
3041    public function fixEOL($str)
3042    {
3043        // Normalise to \n
3044        $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
3045        // Now convert LE as needed
3046        if ($this->LE !== "\n") {
3047            $nstr = str_replace("\n", $this->LE, $nstr);
3048        }
3049        return $nstr;
3050    }
3051
3052    /**
3053     * Add a custom header.
3054     * $name value can be overloaded to contain
3055     * both header name and value (name:value)
3056     * @access public
3057     * @param string $name Custom header name
3058     * @param string $value Header value
3059     * @return void
3060     */
3061    public function addCustomHeader($name, $value = null)
3062    {
3063        if ($value === null) {
3064            // Value passed in as name:value
3065            $this->CustomHeader[] = explode(':', $name, 2);
3066        } else {
3067            $this->CustomHeader[] = array($name, $value);
3068        }
3069    }
3070
3071    /**
3072     * Returns all custom headers
3073     *
3074     * @return array
3075     */
3076    public function getCustomHeaders()
3077    {
3078        return $this->CustomHeader;
3079    }
3080
3081    /**
3082     * Create a message from an HTML string.
3083     * Automatically makes modifications for inline images and backgrounds
3084     * and creates a plain-text version by converting the HTML.
3085     * Overwrites any existing values in $this->Body and $this->AltBody
3086     * @access public
3087     * @param string $message HTML message string
3088     * @param string $basedir baseline directory for path
3089     * @param boolean|callable $advanced Whether to use the internal HTML to text converter
3090     *    or your own custom converter @see html2text()
3091     * @return string $message
3092     */
3093    public function msgHTML($message, $basedir = '', $advanced = false)
3094    {
3095        preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
3096        if (isset($images[2])) {
3097            foreach ($images[2] as $imgindex => $url) {
3098                // Convert data URIs into embedded images
3099                if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) {
3100                    $data = substr($url, strpos($url, ','));
3101                    if ($match[2]) {
3102                        $data = base64_decode($data);
3103                    } else {
3104                        $data = rawurldecode($data);
3105                    }
3106                    $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
3107                    if ($this->addStringEmbeddedImage($data, $cid, '', 'base64', $match[1])) {
3108                        $message = str_replace(
3109                            $images[0][$imgindex],
3110                            $images[1][$imgindex] . '="cid:' . $cid . '"',
3111                            $message
3112                        );
3113                    }
3114                } elseif (!preg_match('#^[A-z]+://#', $url)) {
3115                    // Do not change urls for absolute images (thanks to corvuscorax)
3116                    $filename = basename($url);
3117                    $directory = dirname($url);
3118                    if ($directory == '.') {
3119                        $directory = '';
3120                    }
3121                    $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
3122                    if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
3123                        $basedir .= '/';
3124                    }
3125                    if (strlen($directory) > 1 && substr($directory, -1) != '/') {
3126                        $directory .= '/';
3127                    }
3128                    if ($this->addEmbeddedImage(
3129                        $basedir . $directory . $filename,
3130                        $cid,
3131                        $filename,
3132                        'base64',
3133                        self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION))
3134                    )
3135                    ) {
3136                        $message = preg_replace(
3137                            '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
3138                            $images[1][$imgindex] . '="cid:' . $cid . '"',
3139                            $message
3140                        );
3141                    }
3142                }
3143            }
3144        }
3145        $this->isHTML(true);
3146        // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
3147        $this->Body = $this->normalizeBreaks($message);
3148        $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
3149        if (empty($this->AltBody)) {
3150            $this->AltBody = 'To view this email message, open it in a program that understands HTML!' .
3151                self::CRLF . self::CRLF;
3152        }
3153        return $this->Body;
3154    }
3155
3156    /**
3157     * Convert an HTML string into plain text.
3158     * This is used by msgHTML().
3159     * Note - older versions of this function used a bundled advanced converter
3160     * which was been removed for license reasons in #232
3161     * Example usage:
3162     * <code>
3163     * // Use default conversion
3164     * $plain = $mail->html2text($html);
3165     * // Use your own custom converter
3166     * $plain = $mail->html2text($html, function($html) {
3167     *     $converter = new MyHtml2text($html);
3168     *     return $converter->get_text();
3169     * });
3170     * </code>
3171     * @param string $html The HTML text to convert
3172     * @param boolean|callable $advanced Any boolean value to use the internal converter,
3173     *   or provide your own callable for custom conversion.
3174     * @return string
3175     */
3176    public function html2text($html, $advanced = false)
3177    {
3178        if (is_callable($advanced)) {
3179            return call_user_func($advanced, $html);
3180        }
3181        return html_entity_decode(
3182            trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
3183            ENT_QUOTES,
3184            $this->CharSet
3185        );
3186    }
3187
3188    /**
3189     * Get the MIME type for a file extension.
3190     * @param string $ext File extension
3191     * @access public
3192     * @return string MIME type of file.
3193     * @static
3194     */
3195    public static function _mime_types($ext = '')
3196    {
3197        $mimes = array(
3198            'xl'    => 'application/excel',
3199            'js'    => 'application/javascript',
3200            'hqx'   => 'application/mac-binhex40',
3201            'cpt'   => 'application/mac-compactpro',
3202            'bin'   => 'application/macbinary',
3203            'doc'   => 'application/msword',
3204            'word'  => 'application/msword',
3205            'xlsx'  => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
3206            'xltx'  => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
3207            'potx'  => 'application/vnd.openxmlformats-officedocument.presentationml.template',
3208            'ppsx'  => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
3209            'pptx'  => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
3210            'sldx'  => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
3211            'docx'  => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
3212            'dotx'  => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
3213            'xlam'  => 'application/vnd.ms-excel.addin.macroEnabled.12',
3214            'xlsb'  => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
3215            'class' => 'application/octet-stream',
3216            'dll'   => 'application/octet-stream',
3217            'dms'   => 'application/octet-stream',
3218            'exe'   => 'application/octet-stream',
3219            'lha'   => 'application/octet-stream',
3220            'lzh'   => 'application/octet-stream',
3221            'psd'   => 'application/octet-stream',
3222            'sea'   => 'application/octet-stream',
3223            'so'    => 'application/octet-stream',
3224            'oda'   => 'application/oda',
3225            'pdf'   => 'application/pdf',
3226            'ai'    => 'application/postscript',
3227            'eps'   => 'application/postscript',
3228            'ps'    => 'application/postscript',
3229            'smi'   => 'application/smil',
3230            'smil'  => 'application/smil',
3231            'mif'   => 'application/vnd.mif',
3232            'xls'   => 'application/vnd.ms-excel',
3233            'ppt'   => 'application/vnd.ms-powerpoint',
3234            'wbxml' => 'application/vnd.wap.wbxml',
3235            'wmlc'  => 'application/vnd.wap.wmlc',
3236            'dcr'   => 'application/x-director',
3237            'dir'   => 'application/x-director',
3238            'dxr'   => 'application/x-director',
3239            'dvi'   => 'application/x-dvi',
3240            'gtar'  => 'application/x-gtar',
3241            'php3'  => 'application/x-httpd-php',
3242            'php4'  => 'application/x-httpd-php',
3243            'php'   => 'application/x-httpd-php',
3244            'phtml' => 'application/x-httpd-php',
3245            'phps'  => 'application/x-httpd-php-source',
3246            'swf'   => 'application/x-shockwave-flash',
3247            'sit'   => 'application/x-stuffit',
3248            'tar'   => 'application/x-tar',
3249            'tgz'   => 'application/x-tar',
3250            'xht'   => 'application/xhtml+xml',
3251            'xhtml' => 'application/xhtml+xml',
3252            'zip'   => 'application/zip',
3253            'mid'   => 'audio/midi',
3254            'midi'  => 'audio/midi',
3255            'mp2'   => 'audio/mpeg',
3256            'mp3'   => 'audio/mpeg',
3257            'mpga'  => 'audio/mpeg',
3258            'aif'   => 'audio/x-aiff',
3259            'aifc'  => 'audio/x-aiff',
3260            'aiff'  => 'audio/x-aiff',
3261            'ram'   => 'audio/x-pn-realaudio',
3262            'rm'    => 'audio/x-pn-realaudio',
3263            'rpm'   => 'audio/x-pn-realaudio-plugin',
3264            'ra'    => 'audio/x-realaudio',
3265            'wav'   => 'audio/x-wav',
3266            'bmp'   => 'image/bmp',
3267            'gif'   => 'image/gif',
3268            'jpeg'  => 'image/jpeg',
3269            'jpe'   => 'image/jpeg',
3270            'jpg'   => 'image/jpeg',
3271            'png'   => 'image/png',
3272            'tiff'  => 'image/tiff',
3273            'tif'   => 'image/tiff',
3274            'eml'   => 'message/rfc822',
3275            'css'   => 'text/css',
3276            'html'  => 'text/html',
3277            'htm'   => 'text/html',
3278            'shtml' => 'text/html',
3279            'log'   => 'text/plain',
3280            'text'  => 'text/plain',
3281            'txt'   => 'text/plain',
3282            'rtx'   => 'text/richtext',
3283            'rtf'   => 'text/rtf',
3284            'vcf'   => 'text/vcard',
3285            'vcard' => 'text/vcard',
3286            'xml'   => 'text/xml',
3287            'xsl'   => 'text/xml',
3288            'mpeg'  => 'video/mpeg',
3289            'mpe'   => 'video/mpeg',
3290            'mpg'   => 'video/mpeg',
3291            'mov'   => 'video/quicktime',
3292            'qt'    => 'video/quicktime',
3293            'rv'    => 'video/vnd.rn-realvideo',
3294            'avi'   => 'video/x-msvideo',
3295            'movie' => 'video/x-sgi-movie'
3296        );
3297        if (array_key_exists(strtolower($ext), $mimes)) {
3298            return $mimes[strtolower($ext)];
3299        }
3300        return 'application/octet-stream';
3301    }
3302
3303    /**
3304     * Map a file name to a MIME type.
3305     * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
3306     * @param string $filename A file name or full path, does not need to exist as a file
3307     * @return string
3308     * @static
3309     */
3310    public static function filenameToType($filename)
3311    {
3312        // In case the path is a URL, strip any query string before getting extension
3313        $qpos = strpos($filename, '?');
3314        if (false !== $qpos) {
3315            $filename = substr($filename, 0, $qpos);
3316        }
3317        $pathinfo = self::mb_pathinfo($filename);
3318        return self::_mime_types($pathinfo['extension']);
3319    }
3320
3321    /**
3322     * Multi-byte-safe pathinfo replacement.
3323     * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe.
3324     * Works similarly to the one in PHP >= 5.2.0
3325     * @link http://www.php.net/manual/en/function.pathinfo.php#107461
3326     * @param string $path A filename or path, does not need to exist as a file
3327     * @param integer|string $options Either a PATHINFO_* constant,
3328     *      or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2
3329     * @return string|array
3330     * @static
3331     */
3332    public static function mb_pathinfo($path, $options = null)
3333    {
3334        $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
3335        $pathinfo = array();
3336        if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) {
3337            if (array_key_exists(1, $pathinfo)) {
3338                $ret['dirname'] = $pathinfo[1];
3339            }
3340            if (array_key_exists(2, $pathinfo)) {
3341                $ret['basename'] = $pathinfo[2];
3342            }
3343            if (array_key_exists(5, $pathinfo)) {
3344                $ret['extension'] = $pathinfo[5];
3345            }
3346            if (array_key_exists(3, $pathinfo)) {
3347                $ret['filename'] = $pathinfo[3];
3348            }
3349        }
3350        switch ($options) {
3351            case PATHINFO_DIRNAME:
3352            case 'dirname':
3353                return $ret['dirname'];
3354            case PATHINFO_BASENAME:
3355            case 'basename':
3356                return $ret['basename'];
3357            case PATHINFO_EXTENSION:
3358            case 'extension':
3359                return $ret['extension'];
3360            case PATHINFO_FILENAME:
3361            case 'filename':
3362                return $ret['filename'];
3363            default:
3364                return $ret;
3365        }
3366    }
3367
3368    /**
3369     * Set or reset instance properties.
3370     * You should avoid this function - it's more verbose, less efficient, more error-prone and
3371     * harder to debug than setting properties directly.
3372     * Usage Example:
3373     * `$mail->set('SMTPSecure', 'tls');`
3374     *   is the same as:
3375     * `$mail->SMTPSecure = 'tls';`
3376     * @access public
3377     * @param string $name The property name to set
3378     * @param mixed $value The value to set the property to
3379     * @return boolean
3380     * @TODO Should this not be using the __set() magic function?
3381     */
3382    public function set($name, $value = '')
3383    {
3384        if (property_exists($this, $name)) {
3385            $this->$name = $value;
3386            return true;
3387        } else {
3388            $this->setError($this->lang('variable_set') . $name);
3389            return false;
3390        }
3391    }
3392
3393    /**
3394     * Strip newlines to prevent header injection.
3395     * @access public
3396     * @param string $str
3397     * @return string
3398     */
3399    public function secureHeader($str)
3400    {
3401        return trim(str_replace(array("\r", "\n"), '', $str));
3402    }
3403
3404    /**
3405     * Normalize line breaks in a string.
3406     * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
3407     * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
3408     * @param string $text
3409     * @param string $breaktype What kind of line break to use, defaults to CRLF
3410     * @return string
3411     * @access public
3412     * @static
3413     */
3414    public static function normalizeBreaks($text, $breaktype = "\r\n")
3415    {
3416        return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
3417    }
3418
3419
3420    /**
3421     * Set the public and private key files and password for S/MIME signing.
3422     * @access public
3423     * @param string $cert_filename
3424     * @param string $key_filename
3425     * @param string $key_pass Password for private key
3426     * @param string $extracerts_filename Optional path to chain certificate
3427     */
3428    public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
3429    {
3430        $this->sign_cert_file = $cert_filename;
3431        $this->sign_key_file = $key_filename;
3432        $this->sign_key_pass = $key_pass;
3433        $this->sign_extracerts_file = $extracerts_filename;
3434    }
3435
3436    /**
3437     * Quoted-Printable-encode a DKIM header.
3438     * @access public
3439     * @param string $txt
3440     * @return string
3441     */
3442    public function DKIM_QP($txt)
3443    {
3444        $line = '';
3445        for ($i = 0; $i < strlen($txt); $i++) {
3446            $ord = ord($txt[$i]);
3447            if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
3448                $line .= $txt[$i];
3449            } else {
3450                $line .= '=' . sprintf('%02X', $ord);
3451            }
3452        }
3453        return $line;
3454    }
3455
3456    /**
3457     * Generate a DKIM signature.
3458     * @access public
3459     * @param string $signHeader
3460     * @throws phpmailerException
3461     * @return string
3462     */
3463    public function DKIM_Sign($signHeader)
3464    {
3465        if (!defined('PKCS7_TEXT')) {
3466            if ($this->exceptions) {
3467                throw new phpmailerException($this->lang('extension_missing') . 'openssl');
3468            }
3469            return '';
3470        }
3471        $privKeyStr = file_get_contents($this->DKIM_private);
3472        if ($this->DKIM_passphrase != '') {
3473            $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
3474        } else {
3475            $privKey = $privKeyStr;
3476        }
3477        if (openssl_sign($signHeader, $signature, $privKey)) {
3478            return base64_encode($signature);
3479        }
3480        return '';
3481    }
3482
3483    /**
3484     * Generate a DKIM canonicalization header.
3485     * @access public
3486     * @param string $signHeader Header
3487     * @return string
3488     */
3489    public function DKIM_HeaderC($signHeader)
3490    {
3491        $signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader);
3492        $lines = explode("\r\n", $signHeader);
3493        foreach ($lines as $key => $line) {
3494            list($heading, $value) = explode(':', $line, 2);
3495            $heading = strtolower($heading);
3496            $value = preg_replace('/\s+/', ' ', $value); // Compress useless spaces
3497            $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value
3498        }
3499        $signHeader = implode("\r\n", $lines);
3500        return $signHeader;
3501    }
3502
3503    /**
3504     * Generate a DKIM canonicalization body.
3505     * @access public
3506     * @param string $body Message Body
3507     * @return string
3508     */
3509    public function DKIM_BodyC($body)
3510    {
3511        if ($body == '') {
3512            return "\r\n";
3513        }
3514        // stabilize line endings
3515        $body = str_replace("\r\n", "\n", $body);
3516        $body = str_replace("\n", "\r\n", $body);
3517        // END stabilize line endings
3518        while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
3519            $body = substr($body, 0, strlen($body) - 2);
3520        }
3521        return $body;
3522    }
3523
3524    /**
3525     * Create the DKIM header and body in a new message header.
3526     * @access public
3527     * @param string $headers_line Header lines
3528     * @param string $subject Subject
3529     * @param string $body Body
3530     * @return string
3531     */
3532    public function DKIM_Add($headers_line, $subject, $body)
3533    {
3534        $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
3535        $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
3536        $DKIMquery = 'dns/txt'; // Query method
3537        $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
3538        $subject_header = "Subject: $subject";
3539        $headers = explode($this->LE, $headers_line);
3540        $from_header = '';
3541        $to_header = '';
3542        $current = '';
3543        foreach ($headers as $header) {
3544            if (strpos($header, 'From:') === 0) {
3545                $from_header = $header;
3546                $current = 'from_header';
3547            } elseif (strpos($header, 'To:') === 0) {
3548                $to_header = $header;
3549                $current = 'to_header';
3550            } else {
3551                if (!empty($$current) && strpos($header, ' =?') === 0) {
3552                    $$current .= $header;
3553                } else {
3554                    $current = '';
3555                }
3556            }
3557        }
3558        $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
3559        $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
3560        $subject = str_replace(
3561            '|',
3562            '=7C',
3563            $this->DKIM_QP($subject_header)
3564        ); // Copied header fields (dkim-quoted-printable)
3565        $body = $this->DKIM_BodyC($body);
3566        $DKIMlen = strlen($body); // Length of body
3567        $DKIMb64 = base64_encode(pack('H*', sha1($body))); // Base64 of packed binary SHA-1 hash of body
3568        if ('' == $this->DKIM_identity) {
3569            $ident = '';
3570        } else {
3571            $ident = ' i=' . $this->DKIM_identity . ';';
3572        }
3573        $dkimhdrs = 'DKIM-Signature: v=1; a=' .
3574            $DKIMsignatureType . '; q=' .
3575            $DKIMquery . '; l=' .
3576            $DKIMlen . '; s=' .
3577            $this->DKIM_selector .
3578            ";\r\n" .
3579            "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
3580            "\th=From:To:Subject;\r\n" .
3581            "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
3582            "\tz=$from\r\n" .
3583            "\t|$to\r\n" .
3584            "\t|$subject;\r\n" .
3585            "\tbh=" . $DKIMb64 . ";\r\n" .
3586            "\tb=";
3587        $toSign = $this->DKIM_HeaderC(
3588            $from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs
3589        );
3590        $signed = $this->DKIM_Sign($toSign);
3591        return $dkimhdrs . $signed . "\r\n";
3592    }
3593
3594    /**
3595     * Detect if a string contains a line longer than the maximum line length allowed.
3596     * @param string $str
3597     * @return boolean
3598     * @static
3599     */
3600    public static function hasLineLongerThanMax($str)
3601    {
3602        //+2 to include CRLF line break for a 1000 total
3603        return (boolean)preg_match('/^(.{'.(self::MAX_LINE_LENGTH + 2).',})/m', $str);
3604    }
3605
3606    /**
3607     * Allows for public read access to 'to' property.
3608     * @access public
3609     * @return array
3610     */
3611    public function getToAddresses()
3612    {
3613        return $this->to;
3614    }
3615
3616    /**
3617     * Allows for public read access to 'cc' property.
3618     * @access public
3619     * @return array
3620     */
3621    public function getCcAddresses()
3622    {
3623        return $this->cc;
3624    }
3625
3626    /**
3627     * Allows for public read access to 'bcc' property.
3628     * @access public
3629     * @return array
3630     */
3631    public function getBccAddresses()
3632    {
3633        return $this->bcc;
3634    }
3635
3636    /**
3637     * Allows for public read access to 'ReplyTo' property.
3638     * @access public
3639     * @return array
3640     */
3641    public function getReplyToAddresses()
3642    {
3643        return $this->ReplyTo;
3644    }
3645
3646    /**
3647     * Allows for public read access to 'all_recipients' property.
3648     * @access public
3649     * @return array
3650     */
3651    public function getAllRecipientAddresses()
3652    {
3653        return $this->all_recipients;
3654    }
3655
3656    /**
3657     * Perform a callback.
3658     * @param boolean $isSent
3659     * @param array $to
3660     * @param array $cc
3661     * @param array $bcc
3662     * @param string $subject
3663     * @param string $body
3664     * @param string $from
3665     */
3666    protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from)
3667    {
3668        if (!empty($this->action_function) && is_callable($this->action_function)) {
3669            $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
3670            call_user_func_array($this->action_function, $params);
3671        }
3672    }
3673}
3674
3675/**
3676 * PHPMailer exception handler
3677 * @package PHPMailer
3678 */
3679class phpmailerException extends Exception
3680{
3681    /**
3682     * Prettify error message output
3683     * @return string
3684     */
3685    public function errorMessage()
3686    {
3687        $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
3688        return $errorMsg;
3689    }
3690}