[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-includes/PHPMailer/ -> PHPMailer.php (source)

   1  <?php
   2  
   3  /**
   4   * PHPMailer - PHP email creation and transport class.
   5   * PHP Version 5.5.
   6   *
   7   * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
   8   *
   9   * @author    Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  10   * @author    Jim Jagielski (jimjag) <jimjag@gmail.com>
  11   * @author    Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  12   * @author    Brent R. Matzelle (original founder)
  13   * @copyright 2012 - 2020 Marcus Bointon
  14   * @copyright 2010 - 2012 Jim Jagielski
  15   * @copyright 2004 - 2009 Andy Prevost
  16   * @license   http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  17   * @note      This program is distributed in the hope that it will be useful - WITHOUT
  18   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  19   * FITNESS FOR A PARTICULAR PURPOSE.
  20   */
  21  
  22  namespace PHPMailer\PHPMailer;
  23  
  24  /**
  25   * PHPMailer - PHP email creation and transport class.
  26   *
  27   * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  28   * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  29   * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  30   * @author Brent R. Matzelle (original founder)
  31   */
  32  class PHPMailer
  33  {
  34      const CHARSET_ASCII = 'us-ascii';
  35      const CHARSET_ISO88591 = 'iso-8859-1';
  36      const CHARSET_UTF8 = 'utf-8';
  37  
  38      const CONTENT_TYPE_PLAINTEXT = 'text/plain';
  39      const CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar';
  40      const CONTENT_TYPE_TEXT_HTML = 'text/html';
  41      const CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative';
  42      const CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed';
  43      const CONTENT_TYPE_MULTIPART_RELATED = 'multipart/related';
  44  
  45      const ENCODING_7BIT = '7bit';
  46      const ENCODING_8BIT = '8bit';
  47      const ENCODING_BASE64 = 'base64';
  48      const ENCODING_BINARY = 'binary';
  49      const ENCODING_QUOTED_PRINTABLE = 'quoted-printable';
  50  
  51      const ENCRYPTION_STARTTLS = 'tls';
  52      const ENCRYPTION_SMTPS = 'ssl';
  53  
  54      const ICAL_METHOD_REQUEST = 'REQUEST';
  55      const ICAL_METHOD_PUBLISH = 'PUBLISH';
  56      const ICAL_METHOD_REPLY = 'REPLY';
  57      const ICAL_METHOD_ADD = 'ADD';
  58      const ICAL_METHOD_CANCEL = 'CANCEL';
  59      const ICAL_METHOD_REFRESH = 'REFRESH';
  60      const ICAL_METHOD_COUNTER = 'COUNTER';
  61      const ICAL_METHOD_DECLINECOUNTER = 'DECLINECOUNTER';
  62  
  63      /**
  64       * Email priority.
  65       * Options: null (default), 1 = High, 3 = Normal, 5 = low.
  66       * When null, the header is not set at all.
  67       *
  68       * @var int|null
  69       */
  70      public $Priority;
  71  
  72      /**
  73       * The character set of the message.
  74       *
  75       * @var string
  76       */
  77      public $CharSet = self::CHARSET_ISO88591;
  78  
  79      /**
  80       * The MIME Content-type of the message.
  81       *
  82       * @var string
  83       */
  84      public $ContentType = self::CONTENT_TYPE_PLAINTEXT;
  85  
  86      /**
  87       * The message encoding.
  88       * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
  89       *
  90       * @var string
  91       */
  92      public $Encoding = self::ENCODING_8BIT;
  93  
  94      /**
  95       * Holds the most recent mailer error message.
  96       *
  97       * @var string
  98       */
  99      public $ErrorInfo = '';
 100  
 101      /**
 102       * The From email address for the message.
 103       *
 104       * @var string
 105       */
 106      public $From = '';
 107  
 108      /**
 109       * The From name of the message.
 110       *
 111       * @var string
 112       */
 113      public $FromName = '';
 114  
 115      /**
 116       * The envelope sender of the message.
 117       * This will usually be turned into a Return-Path header by the receiver,
 118       * and is the address that bounces will be sent to.
 119       * If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP.
 120       *
 121       * @var string
 122       */
 123      public $Sender = '';
 124  
 125      /**
 126       * The Subject of the message.
 127       *
 128       * @var string
 129       */
 130      public $Subject = '';
 131  
 132      /**
 133       * An HTML or plain text message body.
 134       * If HTML then call isHTML(true).
 135       *
 136       * @var string
 137       */
 138      public $Body = '';
 139  
 140      /**
 141       * The plain-text message body.
 142       * This body can be read by mail clients that do not have HTML email
 143       * capability such as mutt & Eudora.
 144       * Clients that can read HTML will view the normal Body.
 145       *
 146       * @var string
 147       */
 148      public $AltBody = '';
 149  
 150      /**
 151       * An iCal message part body.
 152       * Only supported in simple alt or alt_inline message types
 153       * To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator.
 154       *
 155       * @see http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
 156       * @see http://kigkonsult.se/iCalcreator/
 157       *
 158       * @var string
 159       */
 160      public $Ical = '';
 161  
 162      /**
 163       * Value-array of "method" in Contenttype header "text/calendar"
 164       *
 165       * @var string[]
 166       */
 167      protected static $IcalMethods = [
 168          self::ICAL_METHOD_REQUEST,
 169          self::ICAL_METHOD_PUBLISH,
 170          self::ICAL_METHOD_REPLY,
 171          self::ICAL_METHOD_ADD,
 172          self::ICAL_METHOD_CANCEL,
 173          self::ICAL_METHOD_REFRESH,
 174          self::ICAL_METHOD_COUNTER,
 175          self::ICAL_METHOD_DECLINECOUNTER,
 176      ];
 177  
 178      /**
 179       * The complete compiled MIME message body.
 180       *
 181       * @var string
 182       */
 183      protected $MIMEBody = '';
 184  
 185      /**
 186       * The complete compiled MIME message headers.
 187       *
 188       * @var string
 189       */
 190      protected $MIMEHeader = '';
 191  
 192      /**
 193       * Extra headers that createHeader() doesn't fold in.
 194       *
 195       * @var string
 196       */
 197      protected $mailHeader = '';
 198  
 199      /**
 200       * Word-wrap the message body to this number of chars.
 201       * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
 202       *
 203       * @see static::STD_LINE_LENGTH
 204       *
 205       * @var int
 206       */
 207      public $WordWrap = 0;
 208  
 209      /**
 210       * Which method to use to send mail.
 211       * Options: "mail", "sendmail", or "smtp".
 212       *
 213       * @var string
 214       */
 215      public $Mailer = 'mail';
 216  
 217      /**
 218       * The path to the sendmail program.
 219       *
 220       * @var string
 221       */
 222      public $Sendmail = '/usr/sbin/sendmail';
 223  
 224      /**
 225       * Whether mail() uses a fully sendmail-compatible MTA.
 226       * One which supports sendmail's "-oi -f" options.
 227       *
 228       * @var bool
 229       */
 230      public $UseSendmailOptions = true;
 231  
 232      /**
 233       * The email address that a reading confirmation should be sent to, also known as read receipt.
 234       *
 235       * @var string
 236       */
 237      public $ConfirmReadingTo = '';
 238  
 239      /**
 240       * The hostname to use in the Message-ID header and as default HELO string.
 241       * If empty, PHPMailer attempts to find one with, in order,
 242       * $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value
 243       * 'localhost.localdomain'.
 244       *
 245       * @see PHPMailer::$Helo
 246       *
 247       * @var string
 248       */
 249      public $Hostname = '';
 250  
 251      /**
 252       * An ID to be used in the Message-ID header.
 253       * If empty, a unique id will be generated.
 254       * You can set your own, but it must be in the format "<id@domain>",
 255       * as defined in RFC5322 section 3.6.4 or it will be ignored.
 256       *
 257       * @see https://tools.ietf.org/html/rfc5322#section-3.6.4
 258       *
 259       * @var string
 260       */
 261      public $MessageID = '';
 262  
 263      /**
 264       * The message Date to be used in the Date header.
 265       * If empty, the current date will be added.
 266       *
 267       * @var string
 268       */
 269      public $MessageDate = '';
 270  
 271      /**
 272       * SMTP hosts.
 273       * Either a single hostname or multiple semicolon-delimited hostnames.
 274       * You can also specify a different port
 275       * for each host by using this format: [hostname:port]
 276       * (e.g. "smtp1.example.com:25;smtp2.example.com").
 277       * You can also specify encryption type, for example:
 278       * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
 279       * Hosts will be tried in order.
 280       *
 281       * @var string
 282       */
 283      public $Host = 'localhost';
 284  
 285      /**
 286       * The default SMTP server port.
 287       *
 288       * @var int
 289       */
 290      public $Port = 25;
 291  
 292      /**
 293       * The SMTP HELO/EHLO name used for the SMTP connection.
 294       * Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find
 295       * one with the same method described above for $Hostname.
 296       *
 297       * @see PHPMailer::$Hostname
 298       *
 299       * @var string
 300       */
 301      public $Helo = '';
 302  
 303      /**
 304       * What kind of encryption to use on the SMTP connection.
 305       * Options: '', static::ENCRYPTION_STARTTLS, or static::ENCRYPTION_SMTPS.
 306       *
 307       * @var string
 308       */
 309      public $SMTPSecure = '';
 310  
 311      /**
 312       * Whether to enable TLS encryption automatically if a server supports it,
 313       * even if `SMTPSecure` is not set to 'tls'.
 314       * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
 315       *
 316       * @var bool
 317       */
 318      public $SMTPAutoTLS = true;
 319  
 320      /**
 321       * Whether to use SMTP authentication.
 322       * Uses the Username and Password properties.
 323       *
 324       * @see PHPMailer::$Username
 325       * @see PHPMailer::$Password
 326       *
 327       * @var bool
 328       */
 329      public $SMTPAuth = false;
 330  
 331      /**
 332       * Options array passed to stream_context_create when connecting via SMTP.
 333       *
 334       * @var array
 335       */
 336      public $SMTPOptions = [];
 337  
 338      /**
 339       * SMTP username.
 340       *
 341       * @var string
 342       */
 343      public $Username = '';
 344  
 345      /**
 346       * SMTP password.
 347       *
 348       * @var string
 349       */
 350      public $Password = '';
 351  
 352      /**
 353       * SMTP auth type.
 354       * Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2, attempted in that order if not specified.
 355       *
 356       * @var string
 357       */
 358      public $AuthType = '';
 359  
 360      /**
 361       * An implementation of the PHPMailer OAuthTokenProvider interface.
 362       *
 363       * @var OAuthTokenProvider
 364       */
 365      protected $oauth;
 366  
 367      /**
 368       * The SMTP server timeout in seconds.
 369       * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.
 370       *
 371       * @var int
 372       */
 373      public $Timeout = 300;
 374  
 375      /**
 376       * Comma separated list of DSN notifications
 377       * 'NEVER' under no circumstances a DSN must be returned to the sender.
 378       *         If you use NEVER all other notifications will be ignored.
 379       * 'SUCCESS' will notify you when your mail has arrived at its destination.
 380       * 'FAILURE' will arrive if an error occurred during delivery.
 381       * 'DELAY'   will notify you if there is an unusual delay in delivery, but the actual
 382       *           delivery's outcome (success or failure) is not yet decided.
 383       *
 384       * @see https://tools.ietf.org/html/rfc3461 See section 4.1 for more information about NOTIFY
 385       */
 386      public $dsn = '';
 387  
 388      /**
 389       * SMTP class debug output mode.
 390       * Debug output level.
 391       * Options:
 392       * @see SMTP::DEBUG_OFF: No output
 393       * @see SMTP::DEBUG_CLIENT: Client messages
 394       * @see SMTP::DEBUG_SERVER: Client and server messages
 395       * @see SMTP::DEBUG_CONNECTION: As SERVER plus connection status
 396       * @see SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed
 397       *
 398       * @see SMTP::$do_debug
 399       *
 400       * @var int
 401       */
 402      public $SMTPDebug = 0;
 403  
 404      /**
 405       * How to handle debug output.
 406       * Options:
 407       * * `echo` Output plain-text as-is, appropriate for CLI
 408       * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
 409       * * `error_log` Output to error log as configured in php.ini
 410       * By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise.
 411       * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
 412       *
 413       * ```php
 414       * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
 415       * ```
 416       *
 417       * Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug`
 418       * level output is used:
 419       *
 420       * ```php
 421       * $mail->Debugoutput = new myPsr3Logger;
 422       * ```
 423       *
 424       * @see SMTP::$Debugoutput
 425       *
 426       * @var string|callable|\Psr\Log\LoggerInterface
 427       */
 428      public $Debugoutput = 'echo';
 429  
 430      /**
 431       * Whether to keep the SMTP connection open after each message.
 432       * If this is set to true then the connection will remain open after a send,
 433       * and closing the connection will require an explicit call to smtpClose().
 434       * It's a good idea to use this if you are sending multiple messages as it reduces overhead.
 435       * See the mailing list example for how to use it.
 436       *
 437       * @var bool
 438       */
 439      public $SMTPKeepAlive = false;
 440  
 441      /**
 442       * Whether to split multiple to addresses into multiple messages
 443       * or send them all in one message.
 444       * Only supported in `mail` and `sendmail` transports, not in SMTP.
 445       *
 446       * @var bool
 447       *
 448       * @deprecated 6.0.0 PHPMailer isn't a mailing list manager!
 449       */
 450      public $SingleTo = false;
 451  
 452      /**
 453       * Storage for addresses when SingleTo is enabled.
 454       *
 455       * @var array
 456       */
 457      protected $SingleToArray = [];
 458  
 459      /**
 460       * Whether to generate VERP addresses on send.
 461       * Only applicable when sending via SMTP.
 462       *
 463       * @see https://en.wikipedia.org/wiki/Variable_envelope_return_path
 464       * @see http://www.postfix.org/VERP_README.html Postfix VERP info
 465       *
 466       * @var bool
 467       */
 468      public $do_verp = false;
 469  
 470      /**
 471       * Whether to allow sending messages with an empty body.
 472       *
 473       * @var bool
 474       */
 475      public $AllowEmpty = false;
 476  
 477      /**
 478       * DKIM selector.
 479       *
 480       * @var string
 481       */
 482      public $DKIM_selector = '';
 483  
 484      /**
 485       * DKIM Identity.
 486       * Usually the email address used as the source of the email.
 487       *
 488       * @var string
 489       */
 490      public $DKIM_identity = '';
 491  
 492      /**
 493       * DKIM passphrase.
 494       * Used if your key is encrypted.
 495       *
 496       * @var string
 497       */
 498      public $DKIM_passphrase = '';
 499  
 500      /**
 501       * DKIM signing domain name.
 502       *
 503       * @example 'example.com'
 504       *
 505       * @var string
 506       */
 507      public $DKIM_domain = '';
 508  
 509      /**
 510       * DKIM Copy header field values for diagnostic use.
 511       *
 512       * @var bool
 513       */
 514      public $DKIM_copyHeaderFields = true;
 515  
 516      /**
 517       * DKIM Extra signing headers.
 518       *
 519       * @example ['List-Unsubscribe', 'List-Help']
 520       *
 521       * @var array
 522       */
 523      public $DKIM_extraHeaders = [];
 524  
 525      /**
 526       * DKIM private key file path.
 527       *
 528       * @var string
 529       */
 530      public $DKIM_private = '';
 531  
 532      /**
 533       * DKIM private key string.
 534       *
 535       * If set, takes precedence over `$DKIM_private`.
 536       *
 537       * @var string
 538       */
 539      public $DKIM_private_string = '';
 540  
 541      /**
 542       * Callback Action function name.
 543       *
 544       * The function that handles the result of the send email action.
 545       * It is called out by send() for each email sent.
 546       *
 547       * Value can be any php callable: http://www.php.net/is_callable
 548       *
 549       * Parameters:
 550       *   bool $result        result of the send action
 551       *   array   $to            email addresses of the recipients
 552       *   array   $cc            cc email addresses
 553       *   array   $bcc           bcc email addresses
 554       *   string  $subject       the subject
 555       *   string  $body          the email body
 556       *   string  $from          email address of sender
 557       *   string  $extra         extra information of possible use
 558       *                          "smtp_transaction_id' => last smtp transaction id
 559       *
 560       * @var string
 561       */
 562      public $action_function = '';
 563  
 564      /**
 565       * What to put in the X-Mailer header.
 566       * Options: An empty string for PHPMailer default, whitespace/null for none, or a string to use.
 567       *
 568       * @var string|null
 569       */
 570      public $XMailer = '';
 571  
 572      /**
 573       * Which validator to use by default when validating email addresses.
 574       * May be a callable to inject your own validator, but there are several built-in validators.
 575       * The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option.
 576       *
 577       * @see PHPMailer::validateAddress()
 578       *
 579       * @var string|callable
 580       */
 581      public static $validator = 'php';
 582  
 583      /**
 584       * An instance of the SMTP sender class.
 585       *
 586       * @var SMTP
 587       */
 588      protected $smtp;
 589  
 590      /**
 591       * The array of 'to' names and addresses.
 592       *
 593       * @var array
 594       */
 595      protected $to = [];
 596  
 597      /**
 598       * The array of 'cc' names and addresses.
 599       *
 600       * @var array
 601       */
 602      protected $cc = [];
 603  
 604      /**
 605       * The array of 'bcc' names and addresses.
 606       *
 607       * @var array
 608       */
 609      protected $bcc = [];
 610  
 611      /**
 612       * The array of reply-to names and addresses.
 613       *
 614       * @var array
 615       */
 616      protected $ReplyTo = [];
 617  
 618      /**
 619       * An array of all kinds of addresses.
 620       * Includes all of $to, $cc, $bcc.
 621       *
 622       * @see PHPMailer::$to
 623       * @see PHPMailer::$cc
 624       * @see PHPMailer::$bcc
 625       *
 626       * @var array
 627       */
 628      protected $all_recipients = [];
 629  
 630      /**
 631       * An array of names and addresses queued for validation.
 632       * In send(), valid and non duplicate entries are moved to $all_recipients
 633       * and one of $to, $cc, or $bcc.
 634       * This array is used only for addresses with IDN.
 635       *
 636       * @see PHPMailer::$to
 637       * @see PHPMailer::$cc
 638       * @see PHPMailer::$bcc
 639       * @see PHPMailer::$all_recipients
 640       *
 641       * @var array
 642       */
 643      protected $RecipientsQueue = [];
 644  
 645      /**
 646       * An array of reply-to names and addresses queued for validation.
 647       * In send(), valid and non duplicate entries are moved to $ReplyTo.
 648       * This array is used only for addresses with IDN.
 649       *
 650       * @see PHPMailer::$ReplyTo
 651       *
 652       * @var array
 653       */
 654      protected $ReplyToQueue = [];
 655  
 656      /**
 657       * The array of attachments.
 658       *
 659       * @var array
 660       */
 661      protected $attachment = [];
 662  
 663      /**
 664       * The array of custom headers.
 665       *
 666       * @var array
 667       */
 668      protected $CustomHeader = [];
 669  
 670      /**
 671       * The most recent Message-ID (including angular brackets).
 672       *
 673       * @var string
 674       */
 675      protected $lastMessageID = '';
 676  
 677      /**
 678       * The message's MIME type.
 679       *
 680       * @var string
 681       */
 682      protected $message_type = '';
 683  
 684      /**
 685       * The array of MIME boundary strings.
 686       *
 687       * @var array
 688       */
 689      protected $boundary = [];
 690  
 691      /**
 692       * The array of available text strings for the current language.
 693       *
 694       * @var array
 695       */
 696      protected $language = [];
 697  
 698      /**
 699       * The number of errors encountered.
 700       *
 701       * @var int
 702       */
 703      protected $error_count = 0;
 704  
 705      /**
 706       * The S/MIME certificate file path.
 707       *
 708       * @var string
 709       */
 710      protected $sign_cert_file = '';
 711  
 712      /**
 713       * The S/MIME key file path.
 714       *
 715       * @var string
 716       */
 717      protected $sign_key_file = '';
 718  
 719      /**
 720       * The optional S/MIME extra certificates ("CA Chain") file path.
 721       *
 722       * @var string
 723       */
 724      protected $sign_extracerts_file = '';
 725  
 726      /**
 727       * The S/MIME password for the key.
 728       * Used only if the key is encrypted.
 729       *
 730       * @var string
 731       */
 732      protected $sign_key_pass = '';
 733  
 734      /**
 735       * Whether to throw exceptions for errors.
 736       *
 737       * @var bool
 738       */
 739      protected $exceptions = false;
 740  
 741      /**
 742       * Unique ID used for message ID and boundaries.
 743       *
 744       * @var string
 745       */
 746      protected $uniqueid = '';
 747  
 748      /**
 749       * The PHPMailer Version number.
 750       *
 751       * @var string
 752       */
 753      const VERSION = '6.6.0';
 754  
 755      /**
 756       * Error severity: message only, continue processing.
 757       *
 758       * @var int
 759       */
 760      const STOP_MESSAGE = 0;
 761  
 762      /**
 763       * Error severity: message, likely ok to continue processing.
 764       *
 765       * @var int
 766       */
 767      const STOP_CONTINUE = 1;
 768  
 769      /**
 770       * Error severity: message, plus full stop, critical error reached.
 771       *
 772       * @var int
 773       */
 774      const STOP_CRITICAL = 2;
 775  
 776      /**
 777       * The SMTP standard CRLF line break.
 778       * If you want to change line break format, change static::$LE, not this.
 779       */
 780      const CRLF = "\r\n";
 781  
 782      /**
 783       * "Folding White Space" a white space string used for line folding.
 784       */
 785      const FWS = ' ';
 786  
 787      /**
 788       * SMTP RFC standard line ending; Carriage Return, Line Feed.
 789       *
 790       * @var string
 791       */
 792      protected static $LE = self::CRLF;
 793  
 794      /**
 795       * The maximum line length supported by mail().
 796       *
 797       * Background: mail() will sometimes corrupt messages
 798       * with headers headers longer than 65 chars, see #818.
 799       *
 800       * @var int
 801       */
 802      const MAIL_MAX_LINE_LENGTH = 63;
 803  
 804      /**
 805       * The maximum line length allowed by RFC 2822 section 2.1.1.
 806       *
 807       * @var int
 808       */
 809      const MAX_LINE_LENGTH = 998;
 810  
 811      /**
 812       * The lower maximum line length allowed by RFC 2822 section 2.1.1.
 813       * This length does NOT include the line break
 814       * 76 means that lines will be 77 or 78 chars depending on whether
 815       * the line break format is LF or CRLF; both are valid.
 816       *
 817       * @var int
 818       */
 819      const STD_LINE_LENGTH = 76;
 820  
 821      /**
 822       * Constructor.
 823       *
 824       * @param bool $exceptions Should we throw external exceptions?
 825       */
 826      public function __construct($exceptions = null)
 827      {
 828          if (null !== $exceptions) {
 829              $this->exceptions = (bool) $exceptions;
 830          }
 831          //Pick an appropriate debug output format automatically
 832          $this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html');
 833      }
 834  
 835      /**
 836       * Destructor.
 837       */
 838      public function __destruct()
 839      {
 840          //Close any open SMTP connection nicely
 841          $this->smtpClose();
 842      }
 843  
 844      /**
 845       * Call mail() in a safe_mode-aware fashion.
 846       * Also, unless sendmail_path points to sendmail (or something that
 847       * claims to be sendmail), don't pass params (not a perfect fix,
 848       * but it will do).
 849       *
 850       * @param string      $to      To
 851       * @param string      $subject Subject
 852       * @param string      $body    Message Body
 853       * @param string      $header  Additional Header(s)
 854       * @param string|null $params  Params
 855       *
 856       * @return bool
 857       */
 858      private function mailPassthru($to, $subject, $body, $header, $params)
 859      {
 860          //Check overloading of mail function to avoid double-encoding
 861          if (ini_get('mbstring.func_overload') & 1) { // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.mbstring_func_overloadDeprecated
 862              $subject = $this->secureHeader($subject);
 863          } else {
 864              $subject = $this->encodeHeader($this->secureHeader($subject));
 865          }
 866          //Calling mail() with null params breaks
 867          $this->edebug('Sending with mail()');
 868          $this->edebug('Sendmail path: ' . ini_get('sendmail_path'));
 869          $this->edebug("Envelope sender: {$this->Sender}");
 870          $this->edebug("To: {$to}");
 871          $this->edebug("Subject: {$subject}");
 872          $this->edebug("Headers: {$header}");
 873          if (!$this->UseSendmailOptions || null === $params) {
 874              $result = @mail($to, $subject, $body, $header);
 875          } else {
 876              $this->edebug("Additional params: {$params}");
 877              $result = @mail($to, $subject, $body, $header, $params);
 878          }
 879          $this->edebug('Result: ' . ($result ? 'true' : 'false'));
 880          return $result;
 881      }
 882  
 883      /**
 884       * Output debugging info via a user-defined method.
 885       * Only generates output if debug output is enabled.
 886       *
 887       * @see PHPMailer::$Debugoutput
 888       * @see PHPMailer::$SMTPDebug
 889       *
 890       * @param string $str
 891       */
 892      protected function edebug($str)
 893      {
 894          if ($this->SMTPDebug <= 0) {
 895              return;
 896          }
 897          //Is this a PSR-3 logger?
 898          if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) {
 899              $this->Debugoutput->debug($str);
 900  
 901              return;
 902          }
 903          //Avoid clash with built-in function names
 904          if (is_callable($this->Debugoutput) && !in_array($this->Debugoutput, ['error_log', 'html', 'echo'])) {
 905              call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
 906  
 907              return;
 908          }
 909          switch ($this->Debugoutput) {
 910              case 'error_log':
 911                  //Don't output, just log
 912                  /** @noinspection ForgottenDebugOutputInspection */
 913                  error_log($str);
 914                  break;
 915              case 'html':
 916                  //Cleans up output a bit for a better looking, HTML-safe output
 917                  echo htmlentities(
 918                      preg_replace('/[\r\n]+/', '', $str),
 919                      ENT_QUOTES,
 920                      'UTF-8'
 921                  ), "<br>\n";
 922                  break;
 923              case 'echo':
 924              default:
 925                  //Normalize line breaks
 926                  $str = preg_replace('/\r\n|\r/m', "\n", $str);
 927                  echo gmdate('Y-m-d H:i:s'),
 928                  "\t",
 929                      //Trim trailing space
 930                  trim(
 931                      //Indent for readability, except for trailing break
 932                      str_replace(
 933                          "\n",
 934                          "\n                   \t                  ",
 935                          trim($str)
 936                      )
 937                  ),
 938                  "\n";
 939          }
 940      }
 941  
 942      /**
 943       * Sets message type to HTML or plain.
 944       *
 945       * @param bool $isHtml True for HTML mode
 946       */
 947      public function isHTML($isHtml = true)
 948      {
 949          if ($isHtml) {
 950              $this->ContentType = static::CONTENT_TYPE_TEXT_HTML;
 951          } else {
 952              $this->ContentType = static::CONTENT_TYPE_PLAINTEXT;
 953          }
 954      }
 955  
 956      /**
 957       * Send messages using SMTP.
 958       */
 959      public function isSMTP()
 960      {
 961          $this->Mailer = 'smtp';
 962      }
 963  
 964      /**
 965       * Send messages using PHP's mail() function.
 966       */
 967      public function isMail()
 968      {
 969          $this->Mailer = 'mail';
 970      }
 971  
 972      /**
 973       * Send messages using $Sendmail.
 974       */
 975      public function isSendmail()
 976      {
 977          $ini_sendmail_path = ini_get('sendmail_path');
 978  
 979          if (false === stripos($ini_sendmail_path, 'sendmail')) {
 980              $this->Sendmail = '/usr/sbin/sendmail';
 981          } else {
 982              $this->Sendmail = $ini_sendmail_path;
 983          }
 984          $this->Mailer = 'sendmail';
 985      }
 986  
 987      /**
 988       * Send messages using qmail.
 989       */
 990      public function isQmail()
 991      {
 992          $ini_sendmail_path = ini_get('sendmail_path');
 993  
 994          if (false === stripos($ini_sendmail_path, 'qmail')) {
 995              $this->Sendmail = '/var/qmail/bin/qmail-inject';
 996          } else {
 997              $this->Sendmail = $ini_sendmail_path;
 998          }
 999          $this->Mailer = 'qmail';
1000      }
1001  
1002      /**
1003       * Add a "To" address.
1004       *
1005       * @param string $address The email address to send to
1006       * @param string $name
1007       *
1008       * @throws Exception
1009       *
1010       * @return bool true on success, false if address already used or invalid in some way
1011       */
1012      public function addAddress($address, $name = '')
1013      {
1014          return $this->addOrEnqueueAnAddress('to', $address, $name);
1015      }
1016  
1017      /**
1018       * Add a "CC" address.
1019       *
1020       * @param string $address The email address to send to
1021       * @param string $name
1022       *
1023       * @throws Exception
1024       *
1025       * @return bool true on success, false if address already used or invalid in some way
1026       */
1027      public function addCC($address, $name = '')
1028      {
1029          return $this->addOrEnqueueAnAddress('cc', $address, $name);
1030      }
1031  
1032      /**
1033       * Add a "BCC" address.
1034       *
1035       * @param string $address The email address to send to
1036       * @param string $name
1037       *
1038       * @throws Exception
1039       *
1040       * @return bool true on success, false if address already used or invalid in some way
1041       */
1042      public function addBCC($address, $name = '')
1043      {
1044          return $this->addOrEnqueueAnAddress('bcc', $address, $name);
1045      }
1046  
1047      /**
1048       * Add a "Reply-To" address.
1049       *
1050       * @param string $address The email address to reply to
1051       * @param string $name
1052       *
1053       * @throws Exception
1054       *
1055       * @return bool true on success, false if address already used or invalid in some way
1056       */
1057      public function addReplyTo($address, $name = '')
1058      {
1059          return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
1060      }
1061  
1062      /**
1063       * Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer
1064       * can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still
1065       * be modified after calling this function), addition of such addresses is delayed until send().
1066       * Addresses that have been added already return false, but do not throw exceptions.
1067       *
1068       * @param string $kind    One of 'to', 'cc', 'bcc', or 'ReplyTo'
1069       * @param string $address The email address to send, resp. to reply to
1070       * @param string $name
1071       *
1072       * @throws Exception
1073       *
1074       * @return bool true on success, false if address already used or invalid in some way
1075       */
1076      protected function addOrEnqueueAnAddress($kind, $address, $name)
1077      {
1078          $address = trim($address);
1079          $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
1080          $pos = strrpos($address, '@');
1081          if (false === $pos) {
1082              //At-sign is missing.
1083              $error_message = sprintf(
1084                  '%s (%s): %s',
1085                  $this->lang('invalid_address'),
1086                  $kind,
1087                  $address
1088              );
1089              $this->setError($error_message);
1090              $this->edebug($error_message);
1091              if ($this->exceptions) {
1092                  throw new Exception($error_message);
1093              }
1094  
1095              return false;
1096          }
1097          $params = [$kind, $address, $name];
1098          //Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
1099          if (static::idnSupported() && $this->has8bitChars(substr($address, ++$pos))) {
1100              if ('Reply-To' !== $kind) {
1101                  if (!array_key_exists($address, $this->RecipientsQueue)) {
1102                      $this->RecipientsQueue[$address] = $params;
1103  
1104                      return true;
1105                  }
1106              } elseif (!array_key_exists($address, $this->ReplyToQueue)) {
1107                  $this->ReplyToQueue[$address] = $params;
1108  
1109                  return true;
1110              }
1111  
1112              return false;
1113          }
1114  
1115          //Immediately add standard addresses without IDN.
1116          return call_user_func_array([$this, 'addAnAddress'], $params);
1117      }
1118  
1119      /**
1120       * Add an address to one of the recipient arrays or to the ReplyTo array.
1121       * Addresses that have been added already return false, but do not throw exceptions.
1122       *
1123       * @param string $kind    One of 'to', 'cc', 'bcc', or 'ReplyTo'
1124       * @param string $address The email address to send, resp. to reply to
1125       * @param string $name
1126       *
1127       * @throws Exception
1128       *
1129       * @return bool true on success, false if address already used or invalid in some way
1130       */
1131      protected function addAnAddress($kind, $address, $name = '')
1132      {
1133          if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) {
1134              $error_message = sprintf(
1135                  '%s: %s',
1136                  $this->lang('Invalid recipient kind'),
1137                  $kind
1138              );
1139              $this->setError($error_message);
1140              $this->edebug($error_message);
1141              if ($this->exceptions) {
1142                  throw new Exception($error_message);
1143              }
1144  
1145              return false;
1146          }
1147          if (!static::validateAddress($address)) {
1148              $error_message = sprintf(
1149                  '%s (%s): %s',
1150                  $this->lang('invalid_address'),
1151                  $kind,
1152                  $address
1153              );
1154              $this->setError($error_message);
1155              $this->edebug($error_message);
1156              if ($this->exceptions) {
1157                  throw new Exception($error_message);
1158              }
1159  
1160              return false;
1161          }
1162          if ('Reply-To' !== $kind) {
1163              if (!array_key_exists(strtolower($address), $this->all_recipients)) {
1164                  $this->{$kind}[] = [$address, $name];
1165                  $this->all_recipients[strtolower($address)] = true;
1166  
1167                  return true;
1168              }
1169          } elseif (!array_key_exists(strtolower($address), $this->ReplyTo)) {
1170              $this->ReplyTo[strtolower($address)] = [$address, $name];
1171  
1172              return true;
1173          }
1174  
1175          return false;
1176      }
1177  
1178      /**
1179       * Parse and validate a string containing one or more RFC822-style comma-separated email addresses
1180       * of the form "display name <address>" into an array of name/address pairs.
1181       * Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
1182       * Note that quotes in the name part are removed.
1183       *
1184       * @see http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
1185       *
1186       * @param string $addrstr The address list string
1187       * @param bool   $useimap Whether to use the IMAP extension to parse the list
1188       * @param string $charset The charset to use when decoding the address list string.
1189       *
1190       * @return array
1191       */
1192      public static function parseAddresses($addrstr, $useimap = true, $charset = self::CHARSET_ISO88591)
1193      {
1194          $addresses = [];
1195          if ($useimap && function_exists('imap_rfc822_parse_adrlist')) {
1196              //Use this built-in parser if it's available
1197              $list = imap_rfc822_parse_adrlist($addrstr, '');
1198              // Clear any potential IMAP errors to get rid of notices being thrown at end of script.
1199              imap_errors();
1200              foreach ($list as $address) {
1201                  if (
1202                      '.SYNTAX-ERROR.' !== $address->host &&
1203                      static::validateAddress($address->mailbox . '@' . $address->host)
1204                  ) {
1205                      //Decode the name part if it's present and encoded
1206                      if (
1207                          property_exists($address, 'personal') &&
1208                          //Check for a Mbstring constant rather than using extension_loaded, which is sometimes disabled
1209                          defined('MB_CASE_UPPER') &&
1210                          preg_match('/^=\?.*\?=$/s', $address->personal)
1211                      ) {
1212                          $origCharset = mb_internal_encoding();
1213                          mb_internal_encoding($charset);
1214                          //Undo any RFC2047-encoded spaces-as-underscores
1215                          $address->personal = str_replace('_', '=20', $address->personal);
1216                          //Decode the name
1217                          $address->personal = mb_decode_mimeheader($address->personal);
1218                          mb_internal_encoding($origCharset);
1219                      }
1220  
1221                      $addresses[] = [
1222                          'name' => (property_exists($address, 'personal') ? $address->personal : ''),
1223                          'address' => $address->mailbox . '@' . $address->host,
1224                      ];
1225                  }
1226              }
1227          } else {
1228              //Use this simpler parser
1229              $list = explode(',', $addrstr);
1230              foreach ($list as $address) {
1231                  $address = trim($address);
1232                  //Is there a separate name part?
1233                  if (strpos($address, '<') === false) {
1234                      //No separate name, just use the whole thing
1235                      if (static::validateAddress($address)) {
1236                          $addresses[] = [
1237                              'name' => '',
1238                              'address' => $address,
1239                          ];
1240                      }
1241                  } else {
1242                      list($name, $email) = explode('<', $address);
1243                      $email = trim(str_replace('>', '', $email));
1244                      $name = trim($name);
1245                      if (static::validateAddress($email)) {
1246                          //Check for a Mbstring constant rather than using extension_loaded, which is sometimes disabled
1247                          //If this name is encoded, decode it
1248                          if (defined('MB_CASE_UPPER') && preg_match('/^=\?.*\?=$/s', $name)) {
1249                              $origCharset = mb_internal_encoding();
1250                              mb_internal_encoding($charset);
1251                              //Undo any RFC2047-encoded spaces-as-underscores
1252                              $name = str_replace('_', '=20', $name);
1253                              //Decode the name
1254                              $name = mb_decode_mimeheader($name);
1255                              mb_internal_encoding($origCharset);
1256                          }
1257                          $addresses[] = [
1258                              //Remove any surrounding quotes and spaces from the name
1259                              'name' => trim($name, '\'" '),
1260                              'address' => $email,
1261                          ];
1262                      }
1263                  }
1264              }
1265          }
1266  
1267          return $addresses;
1268      }
1269  
1270      /**
1271       * Set the From and FromName properties.
1272       *
1273       * @param string $address
1274       * @param string $name
1275       * @param bool   $auto    Whether to also set the Sender address, defaults to true
1276       *
1277       * @throws Exception
1278       *
1279       * @return bool
1280       */
1281      public function setFrom($address, $name = '', $auto = true)
1282      {
1283          $address = trim($address);
1284          $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
1285          //Don't validate now addresses with IDN. Will be done in send().
1286          $pos = strrpos($address, '@');
1287          if (
1288              (false === $pos)
1289              || ((!$this->has8bitChars(substr($address, ++$pos)) || !static::idnSupported())
1290              && !static::validateAddress($address))
1291          ) {
1292              $error_message = sprintf(
1293                  '%s (From): %s',
1294                  $this->lang('invalid_address'),
1295                  $address
1296              );
1297              $this->setError($error_message);
1298              $this->edebug($error_message);
1299              if ($this->exceptions) {
1300                  throw new Exception($error_message);
1301              }
1302  
1303              return false;
1304          }
1305          $this->From = $address;
1306          $this->FromName = $name;
1307          if ($auto && empty($this->Sender)) {
1308              $this->Sender = $address;
1309          }
1310  
1311          return true;
1312      }
1313  
1314      /**
1315       * Return the Message-ID header of the last email.
1316       * Technically this is the value from the last time the headers were created,
1317       * but it's also the message ID of the last sent message except in
1318       * pathological cases.
1319       *
1320       * @return string
1321       */
1322      public function getLastMessageID()
1323      {
1324          return $this->lastMessageID;
1325      }
1326  
1327      /**
1328       * Check that a string looks like an email address.
1329       * Validation patterns supported:
1330       * * `auto` Pick best pattern automatically;
1331       * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0;
1332       * * `pcre` Use old PCRE implementation;
1333       * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
1334       * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
1335       * * `noregex` Don't use a regex: super fast, really dumb.
1336       * Alternatively you may pass in a callable to inject your own validator, for example:
1337       *
1338       * ```php
1339       * PHPMailer::validateAddress('user@example.com', function($address) {
1340       *     return (strpos($address, '@') !== false);
1341       * });
1342       * ```
1343       *
1344       * You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.
1345       *
1346       * @param string          $address       The email address to check
1347       * @param string|callable $patternselect Which pattern to use
1348       *
1349       * @return bool
1350       */
1351      public static function validateAddress($address, $patternselect = null)
1352      {
1353          if (null === $patternselect) {
1354              $patternselect = static::$validator;
1355          }
1356          //Don't allow strings as callables, see SECURITY.md and CVE-2021-3603
1357          if (is_callable($patternselect) && !is_string($patternselect)) {
1358              return call_user_func($patternselect, $address);
1359          }
1360          //Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
1361          if (strpos($address, "\n") !== false || strpos($address, "\r") !== false) {
1362              return false;
1363          }
1364          switch ($patternselect) {
1365              case 'pcre': //Kept for BC
1366              case 'pcre8':
1367                  /*
1368                   * A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL
1369                   * is based.
1370                   * In addition to the addresses allowed by filter_var, also permits:
1371                   *  * dotless domains: `a@b`
1372                   *  * comments: `1234 @ local(blah) .machine .example`
1373                   *  * quoted elements: `'"test blah"@example.org'`
1374                   *  * numeric TLDs: `a@b.123`
1375                   *  * unbracketed IPv4 literals: `a@192.168.0.1`
1376                   *  * IPv6 literals: 'first.last@[IPv6:a1::]'
1377                   * Not all of these will necessarily work for sending!
1378                   *
1379                   * @see       http://squiloople.com/2009/12/20/email-address-validation/
1380                   * @copyright 2009-2010 Michael Rushton
1381                   * Feel free to use and redistribute this code. But please keep this copyright notice.
1382                   */
1383                  return (bool) preg_match(
1384                      '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
1385                      '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
1386                      '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
1387                      '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
1388                      '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
1389                      '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
1390                      '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
1391                      '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
1392                      '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
1393                      $address
1394                  );
1395              case 'html5':
1396                  /*
1397                   * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
1398                   *
1399                   * @see https://html.spec.whatwg.org/#e-mail-state-(type=email)
1400                   */
1401                  return (bool) preg_match(
1402                      '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
1403                      '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
1404                      $address
1405                  );
1406              case 'php':
1407              default:
1408                  return filter_var($address, FILTER_VALIDATE_EMAIL) !== false;
1409          }
1410      }
1411  
1412      /**
1413       * Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the
1414       * `intl` and `mbstring` PHP extensions.
1415       *
1416       * @return bool `true` if required functions for IDN support are present
1417       */
1418      public static function idnSupported()
1419      {
1420          return function_exists('idn_to_ascii') && function_exists('mb_convert_encoding');
1421      }
1422  
1423      /**
1424       * Converts IDN in given email address to its ASCII form, also known as punycode, if possible.
1425       * Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet.
1426       * This function silently returns unmodified address if:
1427       * - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
1428       * - Conversion to punycode is impossible (e.g. required PHP functions are not available)
1429       *   or fails for any reason (e.g. domain contains characters not allowed in an IDN).
1430       *
1431       * @see PHPMailer::$CharSet
1432       *
1433       * @param string $address The email address to convert
1434       *
1435       * @return string The encoded address in ASCII form
1436       */
1437      public function punyencodeAddress($address)
1438      {
1439          //Verify we have required functions, CharSet, and at-sign.
1440          $pos = strrpos($address, '@');
1441          if (
1442              !empty($this->CharSet) &&
1443              false !== $pos &&
1444              static::idnSupported()
1445          ) {
1446              $domain = substr($address, ++$pos);
1447              //Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
1448              if ($this->has8bitChars($domain) && @mb_check_encoding($domain, $this->CharSet)) {
1449                  //Convert the domain from whatever charset it's in to UTF-8
1450                  $domain = mb_convert_encoding($domain, self::CHARSET_UTF8, $this->CharSet);
1451                  //Ignore IDE complaints about this line - method signature changed in PHP 5.4
1452                  $errorcode = 0;
1453                  if (defined('INTL_IDNA_VARIANT_UTS46')) {
1454                      //Use the current punycode standard (appeared in PHP 7.2)
1455                      $punycode = idn_to_ascii(
1456                          $domain,
1457                          \IDNA_DEFAULT | \IDNA_USE_STD3_RULES | \IDNA_CHECK_BIDI |
1458                              \IDNA_CHECK_CONTEXTJ | \IDNA_NONTRANSITIONAL_TO_ASCII,
1459                          \INTL_IDNA_VARIANT_UTS46
1460                      );
1461                  } elseif (defined('INTL_IDNA_VARIANT_2003')) {
1462                      //Fall back to this old, deprecated/removed encoding
1463                      // phpcs:ignore PHPCompatibility.Constants.RemovedConstants.intl_idna_variant_2003Deprecated
1464                      $punycode = idn_to_ascii($domain, $errorcode, \INTL_IDNA_VARIANT_2003);
1465                  } else {
1466                      //Fall back to a default we don't know about
1467                      // phpcs:ignore PHPCompatibility.ParameterValues.NewIDNVariantDefault.NotSet
1468                      $punycode = idn_to_ascii($domain, $errorcode);
1469                  }
1470                  if (false !== $punycode) {
1471                      return substr($address, 0, $pos) . $punycode;
1472                  }
1473              }
1474          }
1475  
1476          return $address;
1477      }
1478  
1479      /**
1480       * Create a message and send it.
1481       * Uses the sending method specified by $Mailer.
1482       *
1483       * @throws Exception
1484       *
1485       * @return bool false on error - See the ErrorInfo property for details of the error
1486       */
1487      public function send()
1488      {
1489          try {
1490              if (!$this->preSend()) {
1491                  return false;
1492              }
1493  
1494              return $this->postSend();
1495          } catch (Exception $exc) {
1496              $this->mailHeader = '';
1497              $this->setError($exc->getMessage());
1498              if ($this->exceptions) {
1499                  throw $exc;
1500              }
1501  
1502              return false;
1503          }
1504      }
1505  
1506      /**
1507       * Prepare a message for sending.
1508       *
1509       * @throws Exception
1510       *
1511       * @return bool
1512       */
1513      public function preSend()
1514      {
1515          if (
1516              'smtp' === $this->Mailer
1517              || ('mail' === $this->Mailer && (\PHP_VERSION_ID >= 80000 || stripos(PHP_OS, 'WIN') === 0))
1518          ) {
1519              //SMTP mandates RFC-compliant line endings
1520              //and it's also used with mail() on Windows
1521              static::setLE(self::CRLF);
1522          } else {
1523              //Maintain backward compatibility with legacy Linux command line mailers
1524              static::setLE(PHP_EOL);
1525          }
1526          //Check for buggy PHP versions that add a header with an incorrect line break
1527          if (
1528              'mail' === $this->Mailer
1529              && ((\PHP_VERSION_ID >= 70000 && \PHP_VERSION_ID < 70017)
1530                  || (\PHP_VERSION_ID >= 70100 && \PHP_VERSION_ID < 70103))
1531              && ini_get('mail.add_x_header') === '1'
1532              && stripos(PHP_OS, 'WIN') === 0
1533          ) {
1534              trigger_error($this->lang('buggy_php'), E_USER_WARNING);
1535          }
1536  
1537          try {
1538              $this->error_count = 0; //Reset errors
1539              $this->mailHeader = '';
1540  
1541              //Dequeue recipient and Reply-To addresses with IDN
1542              foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
1543                  $params[1] = $this->punyencodeAddress($params[1]);
1544                  call_user_func_array([$this, 'addAnAddress'], $params);
1545              }
1546              if (count($this->to) + count($this->cc) + count($this->bcc) < 1) {
1547                  throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL);
1548              }
1549  
1550              //Validate From, Sender, and ConfirmReadingTo addresses
1551              foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) {
1552                  $this->$address_kind = trim($this->$address_kind);
1553                  if (empty($this->$address_kind)) {
1554                      continue;
1555                  }
1556                  $this->$address_kind = $this->punyencodeAddress($this->$address_kind);
1557                  if (!static::validateAddress($this->$address_kind)) {
1558                      $error_message = sprintf(
1559                          '%s (%s): %s',
1560                          $this->lang('invalid_address'),
1561                          $address_kind,
1562                          $this->$address_kind
1563                      );
1564                      $this->setError($error_message);
1565                      $this->edebug($error_message);
1566                      if ($this->exceptions) {
1567                          throw new Exception($error_message);
1568                      }
1569  
1570                      return false;
1571                  }
1572              }
1573  
1574              //Set whether the message is multipart/alternative
1575              if ($this->alternativeExists()) {
1576                  $this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE;
1577              }
1578  
1579              $this->setMessageType();
1580              //Refuse to send an empty message unless we are specifically allowing it
1581              if (!$this->AllowEmpty && empty($this->Body)) {
1582                  throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
1583              }
1584  
1585              //Trim subject consistently
1586              $this->Subject = trim($this->Subject);
1587              //Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
1588              $this->MIMEHeader = '';
1589              $this->MIMEBody = $this->createBody();
1590              //createBody may have added some headers, so retain them
1591              $tempheaders = $this->MIMEHeader;
1592              $this->MIMEHeader = $this->createHeader();
1593              $this->MIMEHeader .= $tempheaders;
1594  
1595              //To capture the complete message when using mail(), create
1596              //an extra header list which createHeader() doesn't fold in
1597              if ('mail' === $this->Mailer) {
1598                  if (count($this->to) > 0) {
1599                      $this->mailHeader .= $this->addrAppend('To', $this->to);
1600                  } else {
1601                      $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
1602                  }
1603                  $this->mailHeader .= $this->headerLine(
1604                      'Subject',
1605                      $this->encodeHeader($this->secureHeader($this->Subject))
1606                  );
1607              }
1608  
1609              //Sign with DKIM if enabled
1610              if (
1611                  !empty($this->DKIM_domain)
1612                  && !empty($this->DKIM_selector)
1613                  && (!empty($this->DKIM_private_string)
1614                      || (!empty($this->DKIM_private)
1615                          && static::isPermittedPath($this->DKIM_private)
1616                          && file_exists($this->DKIM_private)
1617                      )
1618                  )
1619              ) {
1620                  $header_dkim = $this->DKIM_Add(
1621                      $this->MIMEHeader . $this->mailHeader,
1622                      $this->encodeHeader($this->secureHeader($this->Subject)),
1623                      $this->MIMEBody
1624                  );
1625                  $this->MIMEHeader = static::stripTrailingWSP($this->MIMEHeader) . static::$LE .
1626                      static::normalizeBreaks($header_dkim) . static::$LE;
1627              }
1628  
1629              return true;
1630          } catch (Exception $exc) {
1631              $this->setError($exc->getMessage());
1632              if ($this->exceptions) {
1633                  throw $exc;
1634              }
1635  
1636              return false;
1637          }
1638      }
1639  
1640      /**
1641       * Actually send a message via the selected mechanism.
1642       *
1643       * @throws Exception
1644       *
1645       * @return bool
1646       */
1647      public function postSend()
1648      {
1649          try {
1650              //Choose the mailer and send through it
1651              switch ($this->Mailer) {
1652                  case 'sendmail':
1653                  case 'qmail':
1654                      return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
1655                  case 'smtp':
1656                      return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
1657                  case 'mail':
1658                      return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1659                  default:
1660                      $sendMethod = $this->Mailer . 'Send';
1661                      if (method_exists($this, $sendMethod)) {
1662                          return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
1663                      }
1664  
1665                      return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1666              }
1667          } catch (Exception $exc) {
1668              if ($this->Mailer === 'smtp' && $this->SMTPKeepAlive == true) {
1669                  $this->smtp->reset();
1670              }
1671              $this->setError($exc->getMessage());
1672              $this->edebug($exc->getMessage());
1673              if ($this->exceptions) {
1674                  throw $exc;
1675              }
1676          }
1677  
1678          return false;
1679      }
1680  
1681      /**
1682       * Send mail using the $Sendmail program.
1683       *
1684       * @see PHPMailer::$Sendmail
1685       *
1686       * @param string $header The message headers
1687       * @param string $body   The message body
1688       *
1689       * @throws Exception
1690       *
1691       * @return bool
1692       */
1693      protected function sendmailSend($header, $body)
1694      {
1695          if ($this->Mailer === 'qmail') {
1696              $this->edebug('Sending with qmail');
1697          } else {
1698              $this->edebug('Sending with sendmail');
1699          }
1700          $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
1701          //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
1702          //A space after `-f` is optional, but there is a long history of its presence
1703          //causing problems, so we don't use one
1704          //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
1705          //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
1706          //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
1707          //Example problem: https://www.drupal.org/node/1057954
1708  
1709          //PHP 5.6 workaround
1710          $sendmail_from_value = ini_get('sendmail_from');
1711          if (empty($this->Sender) && !empty($sendmail_from_value)) {
1712              //PHP config has a sender address we can use
1713              $this->Sender = ini_get('sendmail_from');
1714          }
1715          //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1716          if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) {
1717              if ($this->Mailer === 'qmail') {
1718                  $sendmailFmt = '%s -f%s';
1719              } else {
1720                  $sendmailFmt = '%s -oi -f%s -t';
1721              }
1722          } else {
1723              //allow sendmail to choose a default envelope sender. It may
1724              //seem preferable to force it to use the From header as with
1725              //SMTP, but that introduces new problems (see
1726              //<https://github.com/PHPMailer/PHPMailer/issues/2298>), and
1727              //it has historically worked this way.
1728              $sendmailFmt = '%s -oi -t';
1729          }
1730  
1731          $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);
1732          $this->edebug('Sendmail path: ' . $this->Sendmail);
1733          $this->edebug('Sendmail command: ' . $sendmail);
1734          $this->edebug('Envelope sender: ' . $this->Sender);
1735          $this->edebug("Headers: {$header}");
1736  
1737          if ($this->SingleTo) {
1738              foreach ($this->SingleToArray as $toAddr) {
1739                  $mail = @popen($sendmail, 'w');
1740                  if (!$mail) {
1741                      throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1742                  }
1743                  $this->edebug("To: {$toAddr}");
1744                  fwrite($mail, 'To: ' . $toAddr . "\n");
1745                  fwrite($mail, $header);
1746                  fwrite($mail, $body);
1747                  $result = pclose($mail);
1748                  $addrinfo = static::parseAddresses($toAddr, true, $this->CharSet);
1749                  $this->doCallback(
1750                      ($result === 0),
1751                      [[$addrinfo['address'], $addrinfo['name']]],
1752                      $this->cc,
1753                      $this->bcc,
1754                      $this->Subject,
1755                      $body,
1756                      $this->From,
1757                      []
1758                  );
1759                  $this->edebug("Result: " . ($result === 0 ? 'true' : 'false'));
1760                  if (0 !== $result) {
1761                      throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1762                  }
1763              }
1764          } else {
1765              $mail = @popen($sendmail, 'w');
1766              if (!$mail) {
1767                  throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1768              }
1769              fwrite($mail, $header);
1770              fwrite($mail, $body);
1771              $result = pclose($mail);
1772              $this->doCallback(
1773                  ($result === 0),
1774                  $this->to,
1775                  $this->cc,
1776                  $this->bcc,
1777                  $this->Subject,
1778                  $body,
1779                  $this->From,
1780                  []
1781              );
1782              $this->edebug("Result: " . ($result === 0 ? 'true' : 'false'));
1783              if (0 !== $result) {
1784                  throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1785              }
1786          }
1787  
1788          return true;
1789      }
1790  
1791      /**
1792       * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.
1793       * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.
1794       *
1795       * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report
1796       *
1797       * @param string $string The string to be validated
1798       *
1799       * @return bool
1800       */
1801      protected static function isShellSafe($string)
1802      {
1803          //It's not possible to use shell commands safely (which includes the mail() function) without escapeshellarg,
1804          //but some hosting providers disable it, creating a security problem that we don't want to have to deal with,
1805          //so we don't.
1806          if (!function_exists('escapeshellarg') || !function_exists('escapeshellcmd')) {
1807              return false;
1808          }
1809  
1810          if (
1811              escapeshellcmd($string) !== $string
1812              || !in_array(escapeshellarg($string), ["'$string'", "\"$string\""])
1813          ) {
1814              return false;
1815          }
1816  
1817          $length = strlen($string);
1818  
1819          for ($i = 0; $i < $length; ++$i) {
1820              $c = $string[$i];
1821  
1822              //All other characters have a special meaning in at least one common shell, including = and +.
1823              //Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
1824              //Note that this does permit non-Latin alphanumeric characters based on the current locale.
1825              if (!ctype_alnum($c) && strpos('@_-.', $c) === false) {
1826                  return false;
1827              }
1828          }
1829  
1830          return true;
1831      }
1832  
1833      /**
1834       * Check whether a file path is of a permitted type.
1835       * Used to reject URLs and phar files from functions that access local file paths,
1836       * such as addAttachment.
1837       *
1838       * @param string $path A relative or absolute path to a file
1839       *
1840       * @return bool
1841       */
1842      protected static function isPermittedPath($path)
1843      {
1844          //Matches scheme definition from https://tools.ietf.org/html/rfc3986#section-3.1
1845          return !preg_match('#^[a-z][a-z\d+.-]*://#i', $path);
1846      }
1847  
1848      /**
1849       * Check whether a file path is safe, accessible, and readable.
1850       *
1851       * @param string $path A relative or absolute path to a file
1852       *
1853       * @return bool
1854       */
1855      protected static function fileIsAccessible($path)
1856      {
1857          if (!static::isPermittedPath($path)) {
1858              return false;
1859          }
1860          $readable = file_exists($path);
1861          //If not a UNC path (expected to start with \\), check read permission, see #2069
1862          if (strpos($path, '\\\\') !== 0) {
1863              $readable = $readable && is_readable($path);
1864          }
1865          return  $readable;
1866      }
1867  
1868      /**
1869       * Send mail using the PHP mail() function.
1870       *
1871       * @see http://www.php.net/manual/en/book.mail.php
1872       *
1873       * @param string $header The message headers
1874       * @param string $body   The message body
1875       *
1876       * @throws Exception
1877       *
1878       * @return bool
1879       */
1880      protected function mailSend($header, $body)
1881      {
1882          $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
1883  
1884          $toArr = [];
1885          foreach ($this->to as $toaddr) {
1886              $toArr[] = $this->addrFormat($toaddr);
1887          }
1888          $to = implode(', ', $toArr);
1889  
1890          $params = null;
1891          //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
1892          //A space after `-f` is optional, but there is a long history of its presence
1893          //causing problems, so we don't use one
1894          //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
1895          //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
1896          //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
1897          //Example problem: https://www.drupal.org/node/1057954
1898          //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1899  
1900          //PHP 5.6 workaround
1901          $sendmail_from_value = ini_get('sendmail_from');
1902          if (empty($this->Sender) && !empty($sendmail_from_value)) {
1903              //PHP config has a sender address we can use
1904              $this->Sender = ini_get('sendmail_from');
1905          }
1906          if (!empty($this->Sender) && static::validateAddress($this->Sender)) {
1907              if (self::isShellSafe($this->Sender)) {
1908                  $params = sprintf('-f%s', $this->Sender);
1909              }
1910              $old_from = ini_get('sendmail_from');
1911              ini_set('sendmail_from', $this->Sender);
1912          }
1913          $result = false;
1914          if ($this->SingleTo && count($toArr) > 1) {
1915              foreach ($toArr as $toAddr) {
1916                  $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
1917                  $addrinfo = static::parseAddresses($toAddr, true, $this->CharSet);
1918                  $this->doCallback(
1919                      $result,
1920                      [[$addrinfo['address'], $addrinfo['name']]],
1921                      $this->cc,
1922                      $this->bcc,
1923                      $this->Subject,
1924                      $body,
1925                      $this->From,
1926                      []
1927                  );
1928              }
1929          } else {
1930              $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
1931              $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);
1932          }
1933          if (isset($old_from)) {
1934              ini_set('sendmail_from', $old_from);
1935          }
1936          if (!$result) {
1937              throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL);
1938          }
1939  
1940          return true;
1941      }
1942  
1943      /**
1944       * Get an instance to use for SMTP operations.
1945       * Override this function to load your own SMTP implementation,
1946       * or set one with setSMTPInstance.
1947       *
1948       * @return SMTP
1949       */
1950      public function getSMTPInstance()
1951      {
1952          if (!is_object($this->smtp)) {
1953              $this->smtp = new SMTP();
1954          }
1955  
1956          return $this->smtp;
1957      }
1958  
1959      /**
1960       * Provide an instance to use for SMTP operations.
1961       *
1962       * @return SMTP
1963       */
1964      public function setSMTPInstance(SMTP $smtp)
1965      {
1966          $this->smtp = $smtp;
1967  
1968          return $this->smtp;
1969      }
1970  
1971      /**
1972       * Send mail via SMTP.
1973       * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
1974       *
1975       * @see PHPMailer::setSMTPInstance() to use a different class.
1976       *
1977       * @uses \PHPMailer\PHPMailer\SMTP
1978       *
1979       * @param string $header The message headers
1980       * @param string $body   The message body
1981       *
1982       * @throws Exception
1983       *
1984       * @return bool
1985       */
1986      protected function smtpSend($header, $body)
1987      {
1988          $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
1989          $bad_rcpt = [];
1990          if (!$this->smtpConnect($this->SMTPOptions)) {
1991              throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
1992          }
1993          //Sender already validated in preSend()
1994          if ('' === $this->Sender) {
1995              $smtp_from = $this->From;
1996          } else {
1997              $smtp_from = $this->Sender;
1998          }
1999          if (!$this->smtp->mail($smtp_from)) {
2000              $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
2001              throw new Exception($this->ErrorInfo, self::STOP_CRITICAL);
2002          }
2003  
2004          $callbacks = [];
2005          //Attempt to send to all recipients
2006          foreach ([$this->to, $this->cc, $this->bcc] as $togroup) {
2007              foreach ($togroup as $to) {
2008                  if (!$this->smtp->recipient($to[0], $this->dsn)) {
2009                      $error = $this->smtp->getError();
2010                      $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']];
2011                      $isSent = false;
2012                  } else {
2013                      $isSent = true;
2014                  }
2015  
2016                  $callbacks[] = ['issent' => $isSent, 'to' => $to[0], 'name' => $to[1]];
2017              }
2018          }
2019  
2020          //Only send the DATA command if we have viable recipients
2021          if ((count($this->all_recipients) > count($bad_rcpt)) && !$this->smtp->data($header . $body)) {
2022              throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL);
2023          }
2024  
2025          $smtp_transaction_id = $this->smtp->getLastTransactionID();
2026  
2027          if ($this->SMTPKeepAlive) {
2028              $this->smtp->reset();
2029          } else {
2030              $this->smtp->quit();
2031              $this->smtp->close();
2032          }
2033  
2034          foreach ($callbacks as $cb) {
2035              $this->doCallback(
2036                  $cb['issent'],
2037                  [[$cb['to'], $cb['name']]],
2038                  [],
2039                  [],
2040                  $this->Subject,
2041                  $body,
2042                  $this->From,
2043                  ['smtp_transaction_id' => $smtp_transaction_id]
2044              );
2045          }
2046  
2047          //Create error message for any bad addresses
2048          if (count($bad_rcpt) > 0) {
2049              $errstr = '';
2050              foreach ($bad_rcpt as $bad) {
2051                  $errstr .= $bad['to'] . ': ' . $bad['error'];
2052              }
2053              throw new Exception($this->lang('recipients_failed') . $errstr, self::STOP_CONTINUE);
2054          }
2055  
2056          return true;
2057      }
2058  
2059      /**
2060       * Initiate a connection to an SMTP server.
2061       * Returns false if the operation failed.
2062       *
2063       * @param array $options An array of options compatible with stream_context_create()
2064       *
2065       * @throws Exception
2066       *
2067       * @uses \PHPMailer\PHPMailer\SMTP
2068       *
2069       * @return bool
2070       */
2071      public function smtpConnect($options = null)
2072      {
2073          if (null === $this->smtp) {
2074              $this->smtp = $this->getSMTPInstance();
2075          }
2076  
2077          //If no options are provided, use whatever is set in the instance
2078          if (null === $options) {
2079              $options = $this->SMTPOptions;
2080          }
2081  
2082          //Already connected?
2083          if ($this->smtp->connected()) {
2084              return true;
2085          }
2086  
2087          $this->smtp->setTimeout($this->Timeout);
2088          $this->smtp->setDebugLevel($this->SMTPDebug);
2089          $this->smtp->setDebugOutput($this->Debugoutput);
2090          $this->smtp->setVerp($this->do_verp);
2091          $hosts = explode(';', $this->Host);
2092          $lastexception = null;
2093  
2094          foreach ($hosts as $hostentry) {
2095              $hostinfo = [];
2096              if (
2097                  !preg_match(
2098                      '/^(?:(ssl|tls):\/\/)?(.+?)(?::(\d+))?$/',
2099                      trim($hostentry),
2100                      $hostinfo
2101                  )
2102              ) {
2103                  $this->edebug($this->lang('invalid_hostentry') . ' ' . trim($hostentry));
2104                  //Not a valid host entry
2105                  continue;
2106              }
2107              //$hostinfo[1]: optional ssl or tls prefix
2108              //$hostinfo[2]: the hostname
2109              //$hostinfo[3]: optional port number
2110              //The host string prefix can temporarily override the current setting for SMTPSecure
2111              //If it's not specified, the default value is used
2112  
2113              //Check the host name is a valid name or IP address before trying to use it
2114              if (!static::isValidHost($hostinfo[2])) {
2115                  $this->edebug($this->lang('invalid_host') . ' ' . $hostinfo[2]);
2116                  continue;
2117              }
2118              $prefix = '';
2119              $secure = $this->SMTPSecure;
2120              $tls = (static::ENCRYPTION_STARTTLS === $this->SMTPSecure);
2121              if ('ssl' === $hostinfo[1] || ('' === $hostinfo[1] && static::ENCRYPTION_SMTPS === $this->SMTPSecure)) {
2122                  $prefix = 'ssl://';
2123                  $tls = false; //Can't have SSL and TLS at the same time
2124                  $secure = static::ENCRYPTION_SMTPS;
2125              } elseif ('tls' === $hostinfo[1]) {
2126                  $tls = true;
2127                  //TLS doesn't use a prefix
2128                  $secure = static::ENCRYPTION_STARTTLS;
2129              }
2130              //Do we need the OpenSSL extension?
2131              $sslext = defined('OPENSSL_ALGO_SHA256');
2132              if (static::ENCRYPTION_STARTTLS === $secure || static::ENCRYPTION_SMTPS === $secure) {
2133                  //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
2134                  if (!$sslext) {
2135                      throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL);
2136                  }
2137              }
2138              $host = $hostinfo[2];
2139              $port = $this->Port;
2140              if (
2141                  array_key_exists(3, $hostinfo) &&
2142                  is_numeric($hostinfo[3]) &&
2143                  $hostinfo[3] > 0 &&
2144                  $hostinfo[3] < 65536
2145              ) {
2146                  $port = (int) $hostinfo[3];
2147              }
2148              if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
2149                  try {
2150                      if ($this->Helo) {
2151                          $hello = $this->Helo;
2152                      } else {
2153                          $hello = $this->serverHostname();
2154                      }
2155                      $this->smtp->hello($hello);
2156                      //Automatically enable TLS encryption if:
2157                      //* it's not disabled
2158                      //* we have openssl extension
2159                      //* we are not already using SSL
2160                      //* the server offers STARTTLS
2161                      if ($this->SMTPAutoTLS && $sslext && 'ssl' !== $secure && $this->smtp->getServerExt('STARTTLS')) {
2162                          $tls = true;
2163                      }
2164                      if ($tls) {
2165                          if (!$this->smtp->startTLS()) {
2166                              $message = $this->getSmtpErrorMessage('connect_host');
2167                              throw new Exception($message);
2168                          }
2169                          //We must resend EHLO after TLS negotiation
2170                          $this->smtp->hello($hello);
2171                      }
2172                      if (
2173                          $this->SMTPAuth && !$this->smtp->authenticate(
2174                              $this->Username,
2175                              $this->Password,
2176                              $this->AuthType,
2177                              $this->oauth
2178                          )
2179                      ) {
2180                          throw new Exception($this->lang('authenticate'));
2181                      }
2182  
2183                      return true;
2184                  } catch (Exception $exc) {
2185                      $lastexception = $exc;
2186                      $this->edebug($exc->getMessage());
2187                      //We must have connected, but then failed TLS or Auth, so close connection nicely
2188                      $this->smtp->quit();
2189                  }
2190              }
2191          }
2192          //If we get here, all connection attempts have failed, so close connection hard
2193          $this->smtp->close();
2194          //As we've caught all exceptions, just report whatever the last one was
2195          if ($this->exceptions && null !== $lastexception) {
2196              throw $lastexception;
2197          } elseif ($this->exceptions) {
2198              // no exception was thrown, likely $this->smtp->connect() failed
2199              $message = $this->getSmtpErrorMessage('connect_host');
2200              throw new Exception($message);
2201          }
2202  
2203          return false;
2204      }
2205  
2206      /**
2207       * Close the active SMTP session if one exists.
2208       */
2209      public function smtpClose()
2210      {
2211          if ((null !== $this->smtp) && $this->smtp->connected()) {
2212              $this->smtp->quit();
2213              $this->smtp->close();
2214          }
2215      }
2216  
2217      /**
2218       * Set the language for error messages.
2219       * The default language is English.
2220       *
2221       * @param string $langcode  ISO 639-1 2-character language code (e.g. French is "fr")
2222       *                          Optionally, the language code can be enhanced with a 4-character
2223       *                          script annotation and/or a 2-character country annotation.
2224       * @param string $lang_path Path to the language file directory, with trailing separator (slash)
2225       *                          Do not set this from user input!
2226       *
2227       * @return bool Returns true if the requested language was loaded, false otherwise.
2228       */
2229      public function setLanguage($langcode = 'en', $lang_path = '')
2230      {
2231          //Backwards compatibility for renamed language codes
2232          $renamed_langcodes = [
2233              'br' => 'pt_br',
2234              'cz' => 'cs',
2235              'dk' => 'da',
2236              'no' => 'nb',
2237              'se' => 'sv',
2238              'rs' => 'sr',
2239              'tg' => 'tl',
2240              'am' => 'hy',
2241          ];
2242  
2243          if (array_key_exists($langcode, $renamed_langcodes)) {
2244              $langcode = $renamed_langcodes[$langcode];
2245          }
2246  
2247          //Define full set of translatable strings in English
2248          $PHPMAILER_LANG = [
2249              'authenticate' => 'SMTP Error: Could not authenticate.',
2250              'buggy_php' => 'Your version of PHP is affected by a bug that may result in corrupted messages.' .
2251                  ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' .
2252                  ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.',
2253              'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
2254              'data_not_accepted' => 'SMTP Error: data not accepted.',
2255              'empty_message' => 'Message body empty',
2256              'encoding' => 'Unknown encoding: ',
2257              'execute' => 'Could not execute: ',
2258              'extension_missing' => 'Extension missing: ',
2259              'file_access' => 'Could not access file: ',
2260              'file_open' => 'File Error: Could not open file: ',
2261              'from_failed' => 'The following From address failed: ',
2262              'instantiate' => 'Could not instantiate mail function.',
2263              'invalid_address' => 'Invalid address: ',
2264              'invalid_header' => 'Invalid header name or value',
2265              'invalid_hostentry' => 'Invalid hostentry: ',
2266              'invalid_host' => 'Invalid host: ',
2267              'mailer_not_supported' => ' mailer is not supported.',
2268              'provide_address' => 'You must provide at least one recipient email address.',
2269              'recipients_failed' => 'SMTP Error: The following recipients failed: ',
2270              'signing' => 'Signing Error: ',
2271              'smtp_code' => 'SMTP code: ',
2272              'smtp_code_ex' => 'Additional SMTP info: ',
2273              'smtp_connect_failed' => 'SMTP connect() failed.',
2274              'smtp_detail' => 'Detail: ',
2275              'smtp_error' => 'SMTP server error: ',
2276              'variable_set' => 'Cannot set or reset variable: ',
2277          ];
2278          if (empty($lang_path)) {
2279              //Calculate an absolute path so it can work if CWD is not here
2280              $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR;
2281          }
2282  
2283          //Validate $langcode
2284          $foundlang = true;
2285          $langcode  = strtolower($langcode);
2286          if (
2287              !preg_match('/^(?P<lang>[a-z]{2})(?P<script>_[a-z]{4})?(?P<country>_[a-z]{2})?$/', $langcode, $matches)
2288              && $langcode !== 'en'
2289          ) {
2290              $foundlang = false;
2291              $langcode = 'en';
2292          }
2293  
2294          //There is no English translation file
2295          if ('en' !== $langcode) {
2296              $langcodes = [];
2297              if (!empty($matches['script']) && !empty($matches['country'])) {
2298                  $langcodes[] = $matches['lang'] . $matches['script'] . $matches['country'];
2299              }
2300              if (!empty($matches['country'])) {
2301                  $langcodes[] = $matches['lang'] . $matches['country'];
2302              }
2303              if (!empty($matches['script'])) {
2304                  $langcodes[] = $matches['lang'] . $matches['script'];
2305              }
2306              $langcodes[] = $matches['lang'];
2307  
2308              //Try and find a readable language file for the requested language.
2309              $foundFile = false;
2310              foreach ($langcodes as $code) {
2311                  $lang_file = $lang_path . 'phpmailer.lang-' . $code . '.php';
2312                  if (static::fileIsAccessible($lang_file)) {
2313                      $foundFile = true;
2314                      break;
2315                  }
2316              }
2317  
2318              if ($foundFile === false) {
2319                  $foundlang = false;
2320              } else {
2321                  $lines = file($lang_file);
2322                  foreach ($lines as $line) {
2323                      //Translation file lines look like this:
2324                      //$PHPMAILER_LANG['authenticate'] = 'SMTP-Fehler: Authentifizierung fehlgeschlagen.';
2325                      //These files are parsed as text and not PHP so as to avoid the possibility of code injection
2326                      //See https://blog.stevenlevithan.com/archives/match-quoted-string
2327                      $matches = [];
2328                      if (
2329                          preg_match(
2330                              '/^\$PHPMAILER_LANG\[\'([a-z\d_]+)\'\]\s*=\s*(["\'])(.+)*?\2;/',
2331                              $line,
2332                              $matches
2333                          ) &&
2334                          //Ignore unknown translation keys
2335                          array_key_exists($matches[1], $PHPMAILER_LANG)
2336                      ) {
2337                          //Overwrite language-specific strings so we'll never have missing translation keys.
2338                          $PHPMAILER_LANG[$matches[1]] = (string)$matches[3];
2339                      }
2340                  }
2341              }
2342          }
2343          $this->language = $PHPMAILER_LANG;
2344  
2345          return $foundlang; //Returns false if language not found
2346      }
2347  
2348      /**
2349       * Get the array of strings for the current language.
2350       *
2351       * @return array
2352       */
2353      public function getTranslations()
2354      {
2355          if (empty($this->language)) {
2356              $this->setLanguage(); // Set the default language.
2357          }
2358  
2359          return $this->language;
2360      }
2361  
2362      /**
2363       * Create recipient headers.
2364       *
2365       * @param string $type
2366       * @param array  $addr An array of recipients,
2367       *                     where each recipient is a 2-element indexed array with element 0 containing an address
2368       *                     and element 1 containing a name, like:
2369       *                     [['joe@example.com', 'Joe User'], ['zoe@example.com', 'Zoe User']]
2370       *
2371       * @return string
2372       */
2373      public function addrAppend($type, $addr)
2374      {
2375          $addresses = [];
2376          foreach ($addr as $address) {
2377              $addresses[] = $this->addrFormat($address);
2378          }
2379  
2380          return $type . ': ' . implode(', ', $addresses) . static::$LE;
2381      }
2382  
2383      /**
2384       * Format an address for use in a message header.
2385       *
2386       * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like
2387       *                    ['joe@example.com', 'Joe User']
2388       *
2389       * @return string
2390       */
2391      public function addrFormat($addr)
2392      {
2393          if (empty($addr[1])) { //No name provided
2394              return $this->secureHeader($addr[0]);
2395          }
2396  
2397          return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') .
2398              ' <' . $this->secureHeader($addr[0]) . '>';
2399      }
2400  
2401      /**
2402       * Word-wrap message.
2403       * For use with mailers that do not automatically perform wrapping
2404       * and for quoted-printable encoded messages.
2405       * Original written by philippe.
2406       *
2407       * @param string $message The message to wrap
2408       * @param int    $length  The line length to wrap to
2409       * @param bool   $qp_mode Whether to run in Quoted-Printable mode
2410       *
2411       * @return string
2412       */
2413      public function wrapText($message, $length, $qp_mode = false)
2414      {
2415          if ($qp_mode) {
2416              $soft_break = sprintf(' =%s', static::$LE);
2417          } else {
2418              $soft_break = static::$LE;
2419          }
2420          //If utf-8 encoding is used, we will need to make sure we don't
2421          //split multibyte characters when we wrap
2422          $is_utf8 = static::CHARSET_UTF8 === strtolower($this->CharSet);
2423          $lelen = strlen(static::$LE);
2424          $crlflen = strlen(static::$LE);
2425  
2426          $message = static::normalizeBreaks($message);
2427          //Remove a trailing line break
2428          if (substr($message, -$lelen) === static::$LE) {
2429              $message = substr($message, 0, -$lelen);
2430          }
2431  
2432          //Split message into lines
2433          $lines = explode(static::$LE, $message);
2434          //Message will be rebuilt in here
2435          $message = '';
2436          foreach ($lines as $line) {
2437              $words = explode(' ', $line);
2438              $buf = '';
2439              $firstword = true;
2440              foreach ($words as $word) {
2441                  if ($qp_mode && (strlen($word) > $length)) {
2442                      $space_left = $length - strlen($buf) - $crlflen;
2443                      if (!$firstword) {
2444                          if ($space_left > 20) {
2445                              $len = $space_left;
2446                              if ($is_utf8) {
2447                                  $len = $this->utf8CharBoundary($word, $len);
2448                              } elseif ('=' === substr($word, $len - 1, 1)) {
2449                                  --$len;
2450                              } elseif ('=' === substr($word, $len - 2, 1)) {
2451                                  $len -= 2;
2452                              }
2453                              $part = substr($word, 0, $len);
2454                              $word = substr($word, $len);
2455                              $buf .= ' ' . $part;
2456                              $message .= $buf . sprintf('=%s', static::$LE);
2457                          } else {
2458                              $message .= $buf . $soft_break;
2459                          }
2460                          $buf = '';
2461                      }
2462                      while ($word !== '') {
2463                          if ($length <= 0) {
2464                              break;
2465                          }
2466                          $len = $length;
2467                          if ($is_utf8) {
2468                              $len = $this->utf8CharBoundary($word, $len);
2469                          } elseif ('=' === substr($word, $len - 1, 1)) {
2470                              --$len;
2471                          } elseif ('=' === substr($word, $len - 2, 1)) {
2472                              $len -= 2;
2473                          }
2474                          $part = substr($word, 0, $len);
2475                          $word = (string) substr($word, $len);
2476  
2477                          if ($word !== '') {
2478                              $message .= $part . sprintf('=%s', static::$LE);
2479                          } else {
2480                              $buf = $part;
2481                          }
2482                      }
2483                  } else {
2484                      $buf_o = $buf;
2485                      if (!$firstword) {
2486                          $buf .= ' ';
2487                      }
2488                      $buf .= $word;
2489  
2490                      if ('' !== $buf_o && strlen($buf) > $length) {
2491                          $message .= $buf_o . $soft_break;
2492                          $buf = $word;
2493                      }
2494                  }
2495                  $firstword = false;
2496              }
2497              $message .= $buf . static::$LE;
2498          }
2499  
2500          return $message;
2501      }
2502  
2503      /**
2504       * Find the last character boundary prior to $maxLength in a utf-8
2505       * quoted-printable encoded string.
2506       * Original written by Colin Brown.
2507       *
2508       * @param string $encodedText utf-8 QP text
2509       * @param int    $maxLength   Find the last character boundary prior to this length
2510       *
2511       * @return int
2512       */
2513      public function utf8CharBoundary($encodedText, $maxLength)
2514      {
2515          $foundSplitPos = false;
2516          $lookBack = 3;
2517          while (!$foundSplitPos) {
2518              $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
2519              $encodedCharPos = strpos($lastChunk, '=');
2520              if (false !== $encodedCharPos) {
2521                  //Found start of encoded character byte within $lookBack block.
2522                  //Check the encoded byte value (the 2 chars after the '=')
2523                  $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
2524                  $dec = hexdec($hex);
2525                  if ($dec < 128) {
2526                      //Single byte character.
2527                      //If the encoded char was found at pos 0, it will fit
2528                      //otherwise reduce maxLength to start of the encoded char
2529                      if ($encodedCharPos > 0) {
2530                          $maxLength -= $lookBack - $encodedCharPos;
2531                      }
2532                      $foundSplitPos = true;
2533                  } elseif ($dec >= 192) {
2534                      //First byte of a multi byte character
2535                      //Reduce maxLength to split at start of character
2536                      $maxLength -= $lookBack - $encodedCharPos;
2537                      $foundSplitPos = true;
2538                  } elseif ($dec < 192) {
2539                      //Middle byte of a multi byte character, look further back
2540                      $lookBack += 3;
2541                  }
2542              } else {
2543                  //No encoded character found
2544                  $foundSplitPos = true;
2545              }
2546          }
2547  
2548          return $maxLength;
2549      }
2550  
2551      /**
2552       * Apply word wrapping to the message body.
2553       * Wraps the message body to the number of chars set in the WordWrap property.
2554       * You should only do this to plain-text bodies as wrapping HTML tags may break them.
2555       * This is called automatically by createBody(), so you don't need to call it yourself.
2556       */
2557      public function setWordWrap()
2558      {
2559          if ($this->WordWrap < 1) {
2560              return;
2561          }
2562  
2563          switch ($this->message_type) {
2564              case 'alt':
2565              case 'alt_inline':
2566              case 'alt_attach':
2567              case 'alt_inline_attach':
2568                  $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
2569                  break;
2570              default:
2571                  $this->Body = $this->wrapText($this->Body, $this->WordWrap);
2572                  break;
2573          }
2574      }
2575  
2576      /**
2577       * Assemble message headers.
2578       *
2579       * @return string The assembled headers
2580       */
2581      public function createHeader()
2582      {
2583          $result = '';
2584  
2585          $result .= $this->headerLine('Date', '' === $this->MessageDate ? self::rfcDate() : $this->MessageDate);
2586  
2587          //The To header is created automatically by mail(), so needs to be omitted here
2588          if ('mail' !== $this->Mailer) {
2589              if ($this->SingleTo) {
2590                  foreach ($this->to as $toaddr) {
2591                      $this->SingleToArray[] = $this->addrFormat($toaddr);
2592                  }
2593              } elseif (count($this->to) > 0) {
2594                  $result .= $this->addrAppend('To', $this->to);
2595              } elseif (count($this->cc) === 0) {
2596                  $result .= $this->headerLine('To', 'undisclosed-recipients:;');
2597              }
2598          }
2599          $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]);
2600  
2601          //sendmail and mail() extract Cc from the header before sending
2602          if (count($this->cc) > 0) {
2603              $result .= $this->addrAppend('Cc', $this->cc);
2604          }
2605  
2606          //sendmail and mail() extract Bcc from the header before sending
2607          if (
2608              (
2609                  'sendmail' === $this->Mailer || 'qmail' === $this->Mailer || 'mail' === $this->Mailer
2610              )
2611              && count($this->bcc) > 0
2612          ) {
2613              $result .= $this->addrAppend('Bcc', $this->bcc);
2614          }
2615  
2616          if (count($this->ReplyTo) > 0) {
2617              $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
2618          }
2619  
2620          //mail() sets the subject itself
2621          if ('mail' !== $this->Mailer) {
2622              $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
2623          }
2624  
2625          //Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
2626          //https://tools.ietf.org/html/rfc5322#section-3.6.4
2627          if (
2628              '' !== $this->MessageID &&
2629              preg_match(
2630                  '/^<((([a-z\d!#$%&\'*+\/=?^_`{|}~-]+(\.[a-z\d!#$%&\'*+\/=?^_`{|}~-]+)*)' .
2631                  '|("(([\x01-\x08\x0B\x0C\x0E-\x1F\x7F]|[\x21\x23-\x5B\x5D-\x7E])' .
2632                  '|(\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*"))@(([a-z\d!#$%&\'*+\/=?^_`{|}~-]+' .
2633                  '(\.[a-z\d!#$%&\'*+\/=?^_`{|}~-]+)*)|(\[(([\x01-\x08\x0B\x0C\x0E-\x1F\x7F]' .
2634                  '|[\x21-\x5A\x5E-\x7E])|(\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*\])))>$/Di',
2635                  $this->MessageID
2636              )
2637          ) {
2638              $this->lastMessageID = $this->MessageID;
2639          } else {
2640              $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
2641          }
2642          $result .= $this->headerLine('Message-ID', $this->lastMessageID);
2643          if (null !== $this->Priority) {
2644              $result .= $this->headerLine('X-Priority', $this->Priority);
2645          }
2646          if ('' === $this->XMailer) {
2647              //Empty string for default X-Mailer header
2648              $result .= $this->headerLine(
2649                  'X-Mailer',
2650                  'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)'
2651              );
2652          } elseif (is_string($this->XMailer) && trim($this->XMailer) !== '') {
2653              //Some string
2654              $result .= $this->headerLine('X-Mailer', trim($this->XMailer));
2655          } //Other values result in no X-Mailer header
2656  
2657          if ('' !== $this->ConfirmReadingTo) {
2658              $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
2659          }
2660  
2661          //Add custom headers
2662          foreach ($this->CustomHeader as $header) {
2663              $result .= $this->headerLine(
2664                  trim($header[0]),
2665                  $this->encodeHeader(trim($header[1]))
2666              );
2667          }
2668          if (!$this->sign_key_file) {
2669              $result .= $this->headerLine('MIME-Version', '1.0');
2670              $result .= $this->getMailMIME();
2671          }
2672  
2673          return $result;
2674      }
2675  
2676      /**
2677       * Get the message MIME type headers.
2678       *
2679       * @return string
2680       */
2681      public function getMailMIME()
2682      {
2683          $result = '';
2684          $ismultipart = true;
2685          switch ($this->message_type) {
2686              case 'inline':
2687                  $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2688                  $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2689                  break;
2690              case 'attach':
2691              case 'inline_attach':
2692              case 'alt_attach':
2693              case 'alt_inline_attach':
2694                  $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_MIXED . ';');
2695                  $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2696                  break;
2697              case 'alt':
2698              case 'alt_inline':
2699                  $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
2700                  $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2701                  break;
2702              default:
2703                  //Catches case 'plain': and case '':
2704                  $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
2705                  $ismultipart = false;
2706                  break;
2707          }
2708          //RFC1341 part 5 says 7bit is assumed if not specified
2709          if (static::ENCODING_7BIT !== $this->Encoding) {
2710              //RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
2711              if ($ismultipart) {
2712                  if (static::ENCODING_8BIT === $this->Encoding) {
2713                      $result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT);
2714                  }
2715                  //The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
2716              } else {
2717                  $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
2718              }
2719          }
2720  
2721          return $result;
2722      }
2723  
2724      /**
2725       * Returns the whole MIME message.
2726       * Includes complete headers and body.
2727       * Only valid post preSend().
2728       *
2729       * @see PHPMailer::preSend()
2730       *
2731       * @return string
2732       */
2733      public function getSentMIMEMessage()
2734      {
2735          return static::stripTrailingWSP($this->MIMEHeader . $this->mailHeader) .
2736              static::$LE . static::$LE . $this->MIMEBody;
2737      }
2738  
2739      /**
2740       * Create a unique ID to use for boundaries.
2741       *
2742       * @return string
2743       */
2744      protected function generateId()
2745      {
2746          $len = 32; //32 bytes = 256 bits
2747          $bytes = '';
2748          if (function_exists('random_bytes')) {
2749              try {
2750                  $bytes = random_bytes($len);
2751              } catch (\Exception $e) {
2752                  //Do nothing
2753              }
2754          } elseif (function_exists('openssl_random_pseudo_bytes')) {
2755              /** @noinspection CryptographicallySecureRandomnessInspection */
2756              $bytes = openssl_random_pseudo_bytes($len);
2757          }
2758          if ($bytes === '') {
2759              //We failed to produce a proper random string, so make do.
2760              //Use a hash to force the length to the same as the other methods
2761              $bytes = hash('sha256', uniqid((string) mt_rand(), true), true);
2762          }
2763  
2764          //We don't care about messing up base64 format here, just want a random string
2765          return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true)));
2766      }
2767  
2768      /**
2769       * Assemble the message body.
2770       * Returns an empty string on failure.
2771       *
2772       * @throws Exception
2773       *
2774       * @return string The assembled message body
2775       */
2776      public function createBody()
2777      {
2778          $body = '';
2779          //Create unique IDs and preset boundaries
2780          $this->uniqueid = $this->generateId();
2781          $this->boundary[1] = 'b1_' . $this->uniqueid;
2782          $this->boundary[2] = 'b2_' . $this->uniqueid;
2783          $this->boundary[3] = 'b3_' . $this->uniqueid;
2784  
2785          if ($this->sign_key_file) {
2786              $body .= $this->getMailMIME() . static::$LE;
2787          }
2788  
2789          $this->setWordWrap();
2790  
2791          $bodyEncoding = $this->Encoding;
2792          $bodyCharSet = $this->CharSet;
2793          //Can we do a 7-bit downgrade?
2794          if (static::ENCODING_8BIT === $bodyEncoding && !$this->has8bitChars($this->Body)) {
2795              $bodyEncoding = static::ENCODING_7BIT;
2796              //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2797              $bodyCharSet = static::CHARSET_ASCII;
2798          }
2799          //If lines are too long, and we're not already using an encoding that will shorten them,
2800          //change to quoted-printable transfer encoding for the body part only
2801          if (static::ENCODING_BASE64 !== $this->Encoding && static::hasLineLongerThanMax($this->Body)) {
2802              $bodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
2803          }
2804  
2805          $altBodyEncoding = $this->Encoding;
2806          $altBodyCharSet = $this->CharSet;
2807          //Can we do a 7-bit downgrade?
2808          if (static::ENCODING_8BIT === $altBodyEncoding && !$this->has8bitChars($this->AltBody)) {
2809              $altBodyEncoding = static::ENCODING_7BIT;
2810              //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2811              $altBodyCharSet = static::CHARSET_ASCII;
2812          }
2813          //If lines are too long, and we're not already using an encoding that will shorten them,
2814          //change to quoted-printable transfer encoding for the alt body part only
2815          if (static::ENCODING_BASE64 !== $altBodyEncoding && static::hasLineLongerThanMax($this->AltBody)) {
2816              $altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
2817          }
2818          //Use this as a preamble in all multipart message types
2819          $mimepre = 'This is a multi-part message in MIME format.' . static::$LE . static::$LE;
2820          switch ($this->message_type) {
2821              case 'inline':
2822                  $body .= $mimepre;
2823                  $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2824                  $body .= $this->encodeString($this->Body, $bodyEncoding);
2825                  $body .= static::$LE;
2826                  $body .= $this->attachAll('inline', $this->boundary[1]);
2827                  break;
2828              case 'attach':
2829                  $body .= $mimepre;
2830                  $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2831                  $body .= $this->encodeString($this->Body, $bodyEncoding);
2832                  $body .= static::$LE;
2833                  $body .= $this->attachAll('attachment', $this->boundary[1]);
2834                  break;
2835              case 'inline_attach':
2836                  $body .= $mimepre;
2837                  $body .= $this->textLine('--' . $this->boundary[1]);
2838                  $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2839                  $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";');
2840                  $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
2841                  $body .= static::$LE;
2842                  $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
2843                  $body .= $this->encodeString($this->Body, $bodyEncoding);
2844                  $body .= static::$LE;
2845                  $body .= $this->attachAll('inline', $this->boundary[2]);
2846                  $body .= static::$LE;
2847                  $body .= $this->attachAll('attachment', $this->boundary[1]);
2848                  break;
2849              case 'alt':
2850                  $body .= $mimepre;
2851                  $body .= $this->getBoundary(
2852                      $this->boundary[1],
2853                      $altBodyCharSet,
2854                      static::CONTENT_TYPE_PLAINTEXT,
2855                      $altBodyEncoding
2856                  );
2857                  $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2858                  $body .= static::$LE;
2859                  $body .= $this->getBoundary(
2860                      $this->boundary[1],
2861                      $bodyCharSet,
2862                      static::CONTENT_TYPE_TEXT_HTML,
2863                      $bodyEncoding
2864                  );
2865                  $body .= $this->encodeString($this->Body, $bodyEncoding);
2866                  $body .= static::$LE;
2867                  if (!empty($this->Ical)) {
2868                      $method = static::ICAL_METHOD_REQUEST;
2869                      foreach (static::$IcalMethods as $imethod) {
2870                          if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) {
2871                              $method = $imethod;
2872                              break;
2873                          }
2874                      }
2875                      $body .= $this->getBoundary(
2876                          $this->boundary[1],
2877                          '',
2878                          static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method,
2879                          ''
2880                      );
2881                      $body .= $this->encodeString($this->Ical, $this->Encoding);
2882                      $body .= static::$LE;
2883                  }
2884                  $body .= $this->endBoundary($this->boundary[1]);
2885                  break;
2886              case 'alt_inline':
2887                  $body .= $mimepre;
2888                  $body .= $this->getBoundary(
2889                      $this->boundary[1],
2890                      $altBodyCharSet,
2891                      static::CONTENT_TYPE_PLAINTEXT,
2892                      $altBodyEncoding
2893                  );
2894                  $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2895                  $body .= static::$LE;
2896                  $body .= $this->textLine('--' . $this->boundary[1]);
2897                  $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2898                  $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";');
2899                  $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
2900                  $body .= static::$LE;
2901                  $body .= $this->getBoundary(
2902                      $this->boundary[2],
2903                      $bodyCharSet,
2904                      static::CONTENT_TYPE_TEXT_HTML,
2905                      $bodyEncoding
2906                  );
2907                  $body .= $this->encodeString($this->Body, $bodyEncoding);
2908                  $body .= static::$LE;
2909                  $body .= $this->attachAll('inline', $this->boundary[2]);
2910                  $body .= static::$LE;
2911                  $body .= $this->endBoundary($this->boundary[1]);
2912                  break;
2913              case 'alt_attach':
2914                  $body .= $mimepre;
2915                  $body .= $this->textLine('--' . $this->boundary[1]);
2916                  $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
2917                  $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"');
2918                  $body .= static::$LE;
2919                  $body .= $this->getBoundary(
2920                      $this->boundary[2],
2921                      $altBodyCharSet,
2922                      static::CONTENT_TYPE_PLAINTEXT,
2923                      $altBodyEncoding
2924                  );
2925                  $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2926                  $body .= static::$LE;
2927                  $body .= $this->getBoundary(
2928                      $this->boundary[2],
2929                      $bodyCharSet,
2930                      static::CONTENT_TYPE_TEXT_HTML,
2931                      $bodyEncoding
2932                  );
2933                  $body .= $this->encodeString($this->Body, $bodyEncoding);
2934                  $body .= static::$LE;
2935                  if (!empty($this->Ical)) {
2936                      $method = static::ICAL_METHOD_REQUEST;
2937                      foreach (static::$IcalMethods as $imethod) {
2938                          if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) {
2939                              $method = $imethod;
2940                              break;
2941                          }
2942                      }
2943                      $body .= $this->getBoundary(
2944                          $this->boundary[2],
2945                          '',
2946                          static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method,
2947                          ''
2948                      );
2949                      $body .= $this->encodeString($this->Ical, $this->Encoding);
2950                  }
2951                  $body .= $this->endBoundary($this->boundary[2]);
2952                  $body .= static::$LE;
2953                  $body .= $this->attachAll('attachment', $this->boundary[1]);
2954                  break;
2955              case 'alt_inline_attach':
2956                  $body .= $mimepre;
2957                  $body .= $this->textLine('--' . $this->boundary[1]);
2958                  $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
2959                  $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"');
2960                  $body .= static::$LE;
2961                  $body .= $this->getBoundary(
2962                      $this->boundary[2],
2963                      $altBodyCharSet,
2964                      static::CONTENT_TYPE_PLAINTEXT,
2965                      $altBodyEncoding
2966                  );
2967                  $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2968                  $body .= static::$LE;
2969                  $body .= $this->textLine('--' . $this->boundary[2]);
2970                  $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2971                  $body .= $this->textLine(' boundary="' . $this->boundary[3] . '";');
2972                  $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
2973                  $body .= static::$LE;
2974                  $body .= $this->getBoundary(
2975                      $this->boundary[3],
2976                      $bodyCharSet,
2977                      static::CONTENT_TYPE_TEXT_HTML,
2978                      $bodyEncoding
2979                  );
2980                  $body .= $this->encodeString($this->Body, $bodyEncoding);
2981                  $body .= static::$LE;
2982                  $body .= $this->attachAll('inline', $this->boundary[3]);
2983                  $body .= static::$LE;
2984                  $body .= $this->endBoundary($this->boundary[2]);
2985                  $body .= static::$LE;
2986                  $body .= $this->attachAll('attachment', $this->boundary[1]);
2987                  break;
2988              default:
2989                  //Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
2990                  //Reset the `Encoding` property in case we changed it for line length reasons
2991                  $this->Encoding = $bodyEncoding;
2992                  $body .= $this->encodeString($this->Body, $this->Encoding);
2993                  break;
2994          }
2995  
2996          if ($this->isError()) {
2997              $body = '';
2998              if ($this->exceptions) {
2999                  throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
3000              }
3001          } elseif ($this->sign_key_file) {
3002              try {
3003                  if (!defined('PKCS7_TEXT')) {
3004                      throw new Exception($this->lang('extension_missing') . 'openssl');
3005                  }
3006  
3007                  $file = tempnam(sys_get_temp_dir(), 'srcsign');
3008                  $signed = tempnam(sys_get_temp_dir(), 'mailsign');
3009                  file_put_contents($file, $body);
3010  
3011                  //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
3012                  if (empty($this->sign_extracerts_file)) {
3013                      $sign = @openssl_pkcs7_sign(
3014                          $file,
3015                          $signed,
3016                          'file://' . realpath($this->sign_cert_file),
3017                          ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
3018                          []
3019                      );
3020                  } else {
3021                      $sign = @openssl_pkcs7_sign(
3022                          $file,
3023                          $signed,
3024                          'file://' . realpath($this->sign_cert_file),
3025                          ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
3026                          [],
3027                          PKCS7_DETACHED,
3028                          $this->sign_extracerts_file
3029                      );
3030                  }
3031  
3032                  @unlink($file);
3033                  if ($sign) {
3034                      $body = file_get_contents($signed);
3035                      @unlink($signed);
3036                      //The message returned by openssl contains both headers and body, so need to split them up
3037                      $parts = explode("\n\n", $body, 2);
3038                      $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE;
3039                      $body = $parts[1];
3040                  } else {
3041                      @unlink($signed);
3042                      throw new Exception($this->lang('signing') . openssl_error_string());
3043                  }
3044              } catch (Exception $exc) {
3045                  $body = '';
3046                  if ($this->exceptions) {
3047                      throw $exc;
3048                  }
3049              }
3050          }
3051  
3052          return $body;
3053      }
3054  
3055      /**
3056       * Return the start of a message boundary.
3057       *
3058       * @param string $boundary
3059       * @param string $charSet
3060       * @param string $contentType
3061       * @param string $encoding
3062       *
3063       * @return string
3064       */
3065      protected function getBoundary($boundary, $charSet, $contentType, $encoding)
3066      {
3067          $result = '';
3068          if ('' === $charSet) {
3069              $charSet = $this->CharSet;
3070          }
3071          if ('' === $contentType) {
3072              $contentType = $this->ContentType;
3073          }
3074          if ('' === $encoding) {
3075              $encoding = $this->Encoding;
3076          }
3077          $result .= $this->textLine('--' . $boundary);
3078          $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
3079          $result .= static::$LE;
3080          //RFC1341 part 5 says 7bit is assumed if not specified
3081          if (static::ENCODING_7BIT !== $encoding) {
3082              $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
3083          }
3084          $result .= static::$LE;
3085  
3086          return $result;
3087      }
3088  
3089      /**
3090       * Return the end of a message boundary.
3091       *
3092       * @param string $boundary
3093       *
3094       * @return string
3095       */
3096      protected function endBoundary($boundary)
3097      {
3098          return static::$LE . '--' . $boundary . '--' . static::$LE;
3099      }
3100  
3101      /**
3102       * Set the message type.
3103       * PHPMailer only supports some preset message types, not arbitrary MIME structures.
3104       */
3105      protected function setMessageType()
3106      {
3107          $type = [];
3108          if ($this->alternativeExists()) {
3109              $type[] = 'alt';
3110          }
3111          if ($this->inlineImageExists()) {
3112              $type[] = 'inline';
3113          }
3114          if ($this->attachmentExists()) {
3115              $type[] = 'attach';
3116          }
3117          $this->message_type = implode('_', $type);
3118          if ('' === $this->message_type) {
3119              //The 'plain' message_type refers to the message having a single body element, not that it is plain-text
3120              $this->message_type = 'plain';
3121          }
3122      }
3123  
3124      /**
3125       * Format a header line.
3126       *
3127       * @param string     $name
3128       * @param string|int $value
3129       *
3130       * @return string
3131       */
3132      public function headerLine($name, $value)
3133      {
3134          return $name . ': ' . $value . static::$LE;
3135      }
3136  
3137      /**
3138       * Return a formatted mail line.
3139       *
3140       * @param string $value
3141       *
3142       * @return string
3143       */
3144      public function textLine($value)
3145      {
3146          return $value . static::$LE;
3147      }
3148  
3149      /**
3150       * Add an attachment from a path on the filesystem.
3151       * Never use a user-supplied path to a file!
3152       * Returns false if the file could not be found or read.
3153       * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client.
3154       * If you need to do that, fetch the resource yourself and pass it in via a local file or string.
3155       *
3156       * @param string $path        Path to the attachment
3157       * @param string $name        Overrides the attachment name
3158       * @param string $encoding    File encoding (see $Encoding)
3159       * @param string $type        MIME type, e.g. `image/jpeg`; determined automatically from $path if not specified
3160       * @param string $disposition Disposition to use
3161       *
3162       * @throws Exception
3163       *
3164       * @return bool
3165       */
3166      public function addAttachment(
3167          $path,
3168          $name = '',
3169          $encoding = self::ENCODING_BASE64,
3170          $type = '',
3171          $disposition = 'attachment'
3172      ) {
3173          try {
3174              if (!static::fileIsAccessible($path)) {
3175                  throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
3176              }
3177  
3178              //If a MIME type is not specified, try to work it out from the file name
3179              if ('' === $type) {
3180                  $type = static::filenameToType($path);
3181              }
3182  
3183              $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME);
3184              if ('' === $name) {
3185                  $name = $filename;
3186              }
3187              if (!$this->validateEncoding($encoding)) {
3188                  throw new Exception($this->lang('encoding') . $encoding);
3189              }
3190  
3191              $this->attachment[] = [
3192                  0 => $path,
3193                  1 => $filename,
3194                  2 => $name,
3195                  3 => $encoding,
3196                  4 => $type,
3197                  5 => false, //isStringAttachment
3198                  6 => $disposition,
3199                  7 => $name,
3200              ];
3201          } catch (Exception $exc) {
3202              $this->setError($exc->getMessage());
3203              $this->edebug($exc->getMessage());
3204              if ($this->exceptions) {
3205                  throw $exc;
3206              }
3207  
3208              return false;
3209          }
3210  
3211          return true;
3212      }
3213  
3214      /**
3215       * Return the array of attachments.
3216       *
3217       * @return array
3218       */
3219      public function getAttachments()
3220      {
3221          return $this->attachment;
3222      }
3223  
3224      /**
3225       * Attach all file, string, and binary attachments to the message.
3226       * Returns an empty string on failure.
3227       *
3228       * @param string $disposition_type
3229       * @param string $boundary
3230       *
3231       * @throws Exception
3232       *
3233       * @return string
3234       */
3235      protected function attachAll($disposition_type, $boundary)
3236      {
3237          //Return text of body
3238          $mime = [];
3239          $cidUniq = [];
3240          $incl = [];
3241  
3242          //Add all attachments
3243          foreach ($this->attachment as $attachment) {
3244              //Check if it is a valid disposition_filter
3245              if ($attachment[6] === $disposition_type) {
3246                  //Check for string attachment
3247                  $string = '';
3248                  $path = '';
3249                  $bString = $attachment[5];
3250                  if ($bString) {
3251                      $string = $attachment[0];
3252                  } else {
3253                      $path = $attachment[0];
3254                  }
3255  
3256                  $inclhash = hash('sha256', serialize($attachment));
3257                  if (in_array($inclhash, $incl, true)) {
3258                      continue;
3259                  }
3260                  $incl[] = $inclhash;
3261                  $name = $attachment[2];
3262                  $encoding = $attachment[3];
3263                  $type = $attachment[4];
3264                  $disposition = $attachment[6];
3265                  $cid = $attachment[7];
3266                  if ('inline' === $disposition && array_key_exists($cid, $cidUniq)) {
3267                      continue;
3268                  }
3269                  $cidUniq[$cid] = true;
3270  
3271                  $mime[] = sprintf('--%s%s', $boundary, static::$LE);
3272                  //Only include a filename property if we have one
3273                  if (!empty($name)) {
3274                      $mime[] = sprintf(
3275                          'Content-Type: %s; name=%s%s',
3276                          $type,
3277                          static::quotedString($this->encodeHeader($this->secureHeader($name))),
3278                          static::$LE
3279                      );
3280                  } else {
3281                      $mime[] = sprintf(
3282                          'Content-Type: %s%s',
3283                          $type,
3284                          static::$LE
3285                      );
3286                  }
3287                  //RFC1341 part 5 says 7bit is assumed if not specified
3288                  if (static::ENCODING_7BIT !== $encoding) {
3289                      $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE);
3290                  }
3291  
3292                  //Only set Content-IDs on inline attachments
3293                  if ((string) $cid !== '' && $disposition === 'inline') {
3294                      $mime[] = 'Content-ID: <' . $this->encodeHeader($this->secureHeader($cid)) . '>' . static::$LE;
3295                  }
3296  
3297                  //Allow for bypassing the Content-Disposition header
3298                  if (!empty($disposition)) {
3299                      $encoded_name = $this->encodeHeader($this->secureHeader($name));
3300                      if (!empty($encoded_name)) {
3301                          $mime[] = sprintf(
3302                              'Content-Disposition: %s; filename=%s%s',
3303                              $disposition,
3304                              static::quotedString($encoded_name),
3305                              static::$LE . static::$LE
3306                          );
3307                      } else {
3308                          $mime[] = sprintf(
3309                              'Content-Disposition: %s%s',
3310                              $disposition,
3311                              static::$LE . static::$LE
3312                          );
3313                      }
3314                  } else {
3315                      $mime[] = static::$LE;
3316                  }
3317  
3318                  //Encode as string attachment
3319                  if ($bString) {
3320                      $mime[] = $this->encodeString($string, $encoding);
3321                  } else {
3322                      $mime[] = $this->encodeFile($path, $encoding);
3323                  }
3324                  if ($this->isError()) {
3325                      return '';
3326                  }
3327                  $mime[] = static::$LE;
3328              }
3329          }
3330  
3331          $mime[] = sprintf('--%s--%s', $boundary, static::$LE);
3332  
3333          return implode('', $mime);
3334      }
3335  
3336      /**
3337       * Encode a file attachment in requested format.
3338       * Returns an empty string on failure.
3339       *
3340       * @param string $path     The full path to the file
3341       * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
3342       *
3343       * @return string
3344       */
3345      protected function encodeFile($path, $encoding = self::ENCODING_BASE64)
3346      {
3347          try {
3348              if (!static::fileIsAccessible($path)) {
3349                  throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
3350              }
3351              $file_buffer = file_get_contents($path);
3352              if (false === $file_buffer) {
3353                  throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
3354              }
3355              $file_buffer = $this->encodeString($file_buffer, $encoding);
3356  
3357              return $file_buffer;
3358          } catch (Exception $exc) {
3359              $this->setError($exc->getMessage());
3360              $this->edebug($exc->getMessage());
3361              if ($this->exceptions) {
3362                  throw $exc;
3363              }
3364  
3365              return '';
3366          }
3367      }
3368  
3369      /**
3370       * Encode a string in requested format.
3371       * Returns an empty string on failure.
3372       *
3373       * @param string $str      The text to encode
3374       * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
3375       *
3376       * @throws Exception
3377       *
3378       * @return string
3379       */
3380      public function encodeString($str, $encoding = self::ENCODING_BASE64)
3381      {
3382          $encoded = '';
3383          switch (strtolower($encoding)) {
3384              case static::ENCODING_BASE64:
3385                  $encoded = chunk_split(
3386                      base64_encode($str),
3387                      static::STD_LINE_LENGTH,
3388                      static::$LE
3389                  );
3390                  break;
3391              case static::ENCODING_7BIT:
3392              case static::ENCODING_8BIT:
3393                  $encoded = static::normalizeBreaks($str);
3394                  //Make sure it ends with a line break
3395                  if (substr($encoded, -(strlen(static::$LE))) !== static::$LE) {
3396                      $encoded .= static::$LE;
3397                  }
3398                  break;
3399              case static::ENCODING_BINARY:
3400                  $encoded = $str;
3401                  break;
3402              case static::ENCODING_QUOTED_PRINTABLE:
3403                  $encoded = $this->encodeQP($str);
3404                  break;
3405              default:
3406                  $this->setError($this->lang('encoding') . $encoding);
3407                  if ($this->exceptions) {
3408                      throw new Exception($this->lang('encoding') . $encoding);
3409                  }
3410                  break;
3411          }
3412  
3413          return $encoded;
3414      }
3415  
3416      /**
3417       * Encode a header value (not including its label) optimally.
3418       * Picks shortest of Q, B, or none. Result includes folding if needed.
3419       * See RFC822 definitions for phrase, comment and text positions.
3420       *
3421       * @param string $str      The header value to encode
3422       * @param string $position What context the string will be used in
3423       *
3424       * @return string
3425       */
3426      public function encodeHeader($str, $position = 'text')
3427      {
3428          $matchcount = 0;
3429          switch (strtolower($position)) {
3430              case 'phrase':
3431                  if (!preg_match('/[\200-\377]/', $str)) {
3432                      //Can't use addslashes as we don't know the value of magic_quotes_sybase
3433                      $encoded = addcslashes($str, "\0..\37\177\\\"");
3434                      if (($str === $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
3435                          return $encoded;
3436                      }
3437  
3438                      return "\"$encoded\"";
3439                  }
3440                  $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
3441                  break;
3442              /* @noinspection PhpMissingBreakStatementInspection */
3443              case 'comment':
3444                  $matchcount = preg_match_all('/[()"]/', $str, $matches);
3445              //fallthrough
3446              case 'text':
3447              default:
3448                  $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
3449                  break;
3450          }
3451  
3452          if ($this->has8bitChars($str)) {
3453              $charset = $this->CharSet;
3454          } else {
3455              $charset = static::CHARSET_ASCII;
3456          }
3457  
3458          //Q/B encoding adds 8 chars and the charset ("` =?<charset>?[QB]?<content>?=`").
3459          $overhead = 8 + strlen($charset);
3460  
3461          if ('mail' === $this->Mailer) {
3462              $maxlen = static::MAIL_MAX_LINE_LENGTH - $overhead;
3463          } else {
3464              $maxlen = static::MAX_LINE_LENGTH - $overhead;
3465          }
3466  
3467          //Select the encoding that produces the shortest output and/or prevents corruption.
3468          if ($matchcount > strlen($str) / 3) {
3469              //More than 1/3 of the content needs encoding, use B-encode.
3470              $encoding = 'B';
3471          } elseif ($matchcount > 0) {
3472              //Less than 1/3 of the content needs encoding, use Q-encode.
3473              $encoding = 'Q';
3474          } elseif (strlen($str) > $maxlen) {
3475              //No encoding needed, but value exceeds max line length, use Q-encode to prevent corruption.
3476              $encoding = 'Q';
3477          } else {
3478              //No reformatting needed
3479              $encoding = false;
3480          }
3481  
3482          switch ($encoding) {
3483              case 'B':
3484                  if ($this->hasMultiBytes($str)) {
3485                      //Use a custom function which correctly encodes and wraps long
3486                      //multibyte strings without breaking lines within a character
3487                      $encoded = $this->base64EncodeWrapMB($str, "\n");
3488                  } else {
3489                      $encoded = base64_encode($str);
3490                      $maxlen -= $maxlen % 4;
3491                      $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
3492                  }
3493                  $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded);
3494                  break;
3495              case 'Q':
3496                  $encoded = $this->encodeQ($str, $position);
3497                  $encoded = $this->wrapText($encoded, $maxlen, true);
3498                  $encoded = str_replace('=' . static::$LE, "\n", trim($encoded));
3499                  $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded);
3500                  break;
3501              default:
3502                  return $str;
3503          }
3504  
3505          return trim(static::normalizeBreaks($encoded));
3506      }
3507  
3508      /**
3509       * Check if a string contains multi-byte characters.
3510       *
3511       * @param string $str multi-byte text to wrap encode
3512       *
3513       * @return bool
3514       */
3515      public function hasMultiBytes($str)
3516      {
3517          if (function_exists('mb_strlen')) {
3518              return strlen($str) > mb_strlen($str, $this->CharSet);
3519          }
3520  
3521          //Assume no multibytes (we can't handle without mbstring functions anyway)
3522          return false;
3523      }
3524  
3525      /**
3526       * Does a string contain any 8-bit chars (in any charset)?
3527       *
3528       * @param string $text
3529       *
3530       * @return bool
3531       */
3532      public function has8bitChars($text)
3533      {
3534          return (bool) preg_match('/[\x80-\xFF]/', $text);
3535      }
3536  
3537      /**
3538       * Encode and wrap long multibyte strings for mail headers
3539       * without breaking lines within a character.
3540       * Adapted from a function by paravoid.
3541       *
3542       * @see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
3543       *
3544       * @param string $str       multi-byte text to wrap encode
3545       * @param string $linebreak string to use as linefeed/end-of-line
3546       *
3547       * @return string
3548       */
3549      public function base64EncodeWrapMB($str, $linebreak = null)
3550      {
3551          $start = '=?' . $this->CharSet . '?B?';
3552          $end = '?=';
3553          $encoded = '';
3554          if (null === $linebreak) {
3555              $linebreak = static::$LE;
3556          }
3557  
3558          $mb_length = mb_strlen($str, $this->CharSet);
3559          //Each line must have length <= 75, including $start and $end
3560          $length = 75 - strlen($start) - strlen($end);
3561          //Average multi-byte ratio
3562          $ratio = $mb_length / strlen($str);
3563          //Base64 has a 4:3 ratio
3564          $avgLength = floor($length * $ratio * .75);
3565  
3566          $offset = 0;
3567          for ($i = 0; $i < $mb_length; $i += $offset) {
3568              $lookBack = 0;
3569              do {
3570                  $offset = $avgLength - $lookBack;
3571                  $chunk = mb_substr($str, $i, $offset, $this->CharSet);
3572                  $chunk = base64_encode($chunk);
3573                  ++$lookBack;
3574              } while (strlen($chunk) > $length);
3575              $encoded .= $chunk . $linebreak;
3576          }
3577  
3578          //Chomp the last linefeed
3579          return substr($encoded, 0, -strlen($linebreak));
3580      }
3581  
3582      /**
3583       * Encode a string in quoted-printable format.
3584       * According to RFC2045 section 6.7.
3585       *
3586       * @param string $string The text to encode
3587       *
3588       * @return string
3589       */
3590      public function encodeQP($string)
3591      {
3592          return static::normalizeBreaks(quoted_printable_encode($string));
3593      }
3594  
3595      /**
3596       * Encode a string using Q encoding.
3597       *
3598       * @see http://tools.ietf.org/html/rfc2047#section-4.2
3599       *
3600       * @param string $str      the text to encode
3601       * @param string $position Where the text is going to be used, see the RFC for what that means
3602       *
3603       * @return string
3604       */
3605      public function encodeQ($str, $position = 'text')
3606      {
3607          //There should not be any EOL in the string
3608          $pattern = '';
3609          $encoded = str_replace(["\r", "\n"], '', $str);
3610          switch (strtolower($position)) {
3611              case 'phrase':
3612                  //RFC 2047 section 5.3
3613                  $pattern = '^A-Za-z0-9!*+\/ -';
3614                  break;
3615              /*
3616               * RFC 2047 section 5.2.
3617               * Build $pattern without including delimiters and []
3618               */
3619              /* @noinspection PhpMissingBreakStatementInspection */
3620              case 'comment':
3621                  $pattern = '\(\)"';
3622              /* Intentional fall through */
3623              case 'text':
3624              default:
3625                  //RFC 2047 section 5.1
3626                  //Replace every high ascii, control, =, ? and _ characters
3627                  $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
3628                  break;
3629          }
3630          $matches = [];
3631          if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
3632              //If the string contains an '=', make sure it's the first thing we replace
3633              //so as to avoid double-encoding
3634              $eqkey = array_search('=', $matches[0], true);
3635              if (false !== $eqkey) {
3636                  unset($matches[0][$eqkey]);
3637                  array_unshift($matches[0], '=');
3638              }
3639              foreach (array_unique($matches[0]) as $char) {
3640                  $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
3641              }
3642          }
3643          //Replace spaces with _ (more readable than =20)
3644          //RFC 2047 section 4.2(2)
3645          return str_replace(' ', '_', $encoded);
3646      }
3647  
3648      /**
3649       * Add a string or binary attachment (non-filesystem).
3650       * This method can be used to attach ascii or binary data,
3651       * such as a BLOB record from a database.
3652       *
3653       * @param string $string      String attachment data
3654       * @param string $filename    Name of the attachment
3655       * @param string $encoding    File encoding (see $Encoding)
3656       * @param string $type        File extension (MIME) type
3657       * @param string $disposition Disposition to use
3658       *
3659       * @throws Exception
3660       *
3661       * @return bool True on successfully adding an attachment
3662       */
3663      public function addStringAttachment(
3664          $string,
3665          $filename,
3666          $encoding = self::ENCODING_BASE64,
3667          $type = '',
3668          $disposition = 'attachment'
3669      ) {
3670          try {
3671              //If a MIME type is not specified, try to work it out from the file name
3672              if ('' === $type) {
3673                  $type = static::filenameToType($filename);
3674              }
3675  
3676              if (!$this->validateEncoding($encoding)) {
3677                  throw new Exception($this->lang('encoding') . $encoding);
3678              }
3679  
3680              //Append to $attachment array
3681              $this->attachment[] = [
3682                  0 => $string,
3683                  1 => $filename,
3684                  2 => static::mb_pathinfo($filename, PATHINFO_BASENAME),
3685                  3 => $encoding,
3686                  4 => $type,
3687                  5 => true, //isStringAttachment
3688                  6 => $disposition,
3689                  7 => 0,
3690              ];
3691          } catch (Exception $exc) {
3692              $this->setError($exc->getMessage());
3693              $this->edebug($exc->getMessage());
3694              if ($this->exceptions) {
3695                  throw $exc;
3696              }
3697  
3698              return false;
3699          }
3700  
3701          return true;
3702      }
3703  
3704      /**
3705       * Add an embedded (inline) attachment from a file.
3706       * This can include images, sounds, and just about any other document type.
3707       * These differ from 'regular' attachments in that they are intended to be
3708       * displayed inline with the message, not just attached for download.
3709       * This is used in HTML messages that embed the images
3710       * the HTML refers to using the $cid value.
3711       * Never use a user-supplied path to a file!
3712       *
3713       * @param string $path        Path to the attachment
3714       * @param string $cid         Content ID of the attachment; Use this to reference
3715       *                            the content when using an embedded image in HTML
3716       * @param string $name        Overrides the attachment name
3717       * @param string $encoding    File encoding (see $Encoding)
3718       * @param string $type        File MIME type
3719       * @param string $disposition Disposition to use
3720       *
3721       * @throws Exception
3722       *
3723       * @return bool True on successfully adding an attachment
3724       */
3725      public function addEmbeddedImage(
3726          $path,
3727          $cid,
3728          $name = '',
3729          $encoding = self::ENCODING_BASE64,
3730          $type = '',
3731          $disposition = 'inline'
3732      ) {
3733          try {
3734              if (!static::fileIsAccessible($path)) {
3735                  throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
3736              }
3737  
3738              //If a MIME type is not specified, try to work it out from the file name
3739              if ('' === $type) {
3740                  $type = static::filenameToType($path);
3741              }
3742  
3743              if (!$this->validateEncoding($encoding)) {
3744                  throw new Exception($this->lang('encoding') . $encoding);
3745              }
3746  
3747              $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME);
3748              if ('' === $name) {
3749                  $name = $filename;
3750              }
3751  
3752              //Append to $attachment array
3753              $this->attachment[] = [
3754                  0 => $path,
3755                  1 => $filename,
3756                  2 => $name,
3757                  3 => $encoding,
3758                  4 => $type,
3759                  5 => false, //isStringAttachment
3760                  6 => $disposition,
3761                  7 => $cid,
3762              ];
3763          } catch (Exception $exc) {
3764              $this->setError($exc->getMessage());
3765              $this->edebug($exc->getMessage());
3766              if ($this->exceptions) {
3767                  throw $exc;
3768              }
3769  
3770              return false;
3771          }
3772  
3773          return true;
3774      }
3775  
3776      /**
3777       * Add an embedded stringified attachment.
3778       * This can include images, sounds, and just about any other document type.
3779       * If your filename doesn't contain an extension, be sure to set the $type to an appropriate MIME type.
3780       *
3781       * @param string $string      The attachment binary data
3782       * @param string $cid         Content ID of the attachment; Use this to reference
3783       *                            the content when using an embedded image in HTML
3784       * @param string $name        A filename for the attachment. If this contains an extension,
3785       *                            PHPMailer will attempt to set a MIME type for the attachment.
3786       *                            For example 'file.jpg' would get an 'image/jpeg' MIME type.
3787       * @param string $encoding    File encoding (see $Encoding), defaults to 'base64'
3788       * @param string $type        MIME type - will be used in preference to any automatically derived type
3789       * @param string $disposition Disposition to use
3790       *
3791       * @throws Exception
3792       *
3793       * @return bool True on successfully adding an attachment
3794       */
3795      public function addStringEmbeddedImage(
3796          $string,
3797          $cid,
3798          $name = '',
3799          $encoding = self::ENCODING_BASE64,
3800          $type = '',
3801          $disposition = 'inline'
3802      ) {
3803          try {
3804              //If a MIME type is not specified, try to work it out from the name
3805              if ('' === $type && !empty($name)) {
3806                  $type = static::filenameToType($name);
3807              }
3808  
3809              if (!$this->validateEncoding($encoding)) {
3810                  throw new Exception($this->lang('encoding') . $encoding);
3811              }
3812  
3813              //Append to $attachment array
3814              $this->attachment[] = [
3815                  0 => $string,
3816                  1 => $name,
3817                  2 => $name,
3818                  3 => $encoding,
3819                  4 => $type,
3820                  5 => true, //isStringAttachment
3821                  6 => $disposition,
3822                  7 => $cid,
3823              ];
3824          } catch (Exception $exc) {
3825              $this->setError($exc->getMessage());
3826              $this->edebug($exc->getMessage());
3827              if ($this->exceptions) {
3828                  throw $exc;
3829              }
3830  
3831              return false;
3832          }
3833  
3834          return true;
3835      }
3836  
3837      /**
3838       * Validate encodings.
3839       *
3840       * @param string $encoding
3841       *
3842       * @return bool
3843       */
3844      protected function validateEncoding($encoding)
3845      {
3846          return in_array(
3847              $encoding,
3848              [
3849                  self::ENCODING_7BIT,
3850                  self::ENCODING_QUOTED_PRINTABLE,
3851                  self::ENCODING_BASE64,
3852                  self::ENCODING_8BIT,
3853                  self::ENCODING_BINARY,
3854              ],
3855              true
3856          );
3857      }
3858  
3859      /**
3860       * Check if an embedded attachment is present with this cid.
3861       *
3862       * @param string $cid
3863       *
3864       * @return bool
3865       */
3866      protected function cidExists($cid)
3867      {
3868          foreach ($this->attachment as $attachment) {
3869              if ('inline' === $attachment[6] && $cid === $attachment[7]) {
3870                  return true;
3871              }
3872          }
3873  
3874          return false;
3875      }
3876  
3877      /**
3878       * Check if an inline attachment is present.
3879       *
3880       * @return bool
3881       */
3882      public function inlineImageExists()
3883      {
3884          foreach ($this->attachment as $attachment) {
3885              if ('inline' === $attachment[6]) {
3886                  return true;
3887              }
3888          }
3889  
3890          return false;
3891      }
3892  
3893      /**
3894       * Check if an attachment (non-inline) is present.
3895       *
3896       * @return bool
3897       */
3898      public function attachmentExists()
3899      {
3900          foreach ($this->attachment as $attachment) {
3901              if ('attachment' === $attachment[6]) {
3902                  return true;
3903              }
3904          }
3905  
3906          return false;
3907      }
3908  
3909      /**
3910       * Check if this message has an alternative body set.
3911       *
3912       * @return bool
3913       */
3914      public function alternativeExists()
3915      {
3916          return !empty($this->AltBody);
3917      }
3918  
3919      /**
3920       * Clear queued addresses of given kind.
3921       *
3922       * @param string $kind 'to', 'cc', or 'bcc'
3923       */
3924      public function clearQueuedAddresses($kind)
3925      {
3926          $this->RecipientsQueue = array_filter(
3927              $this->RecipientsQueue,
3928              static function ($params) use ($kind) {
3929                  return $params[0] !== $kind;
3930              }
3931          );
3932      }
3933  
3934      /**
3935       * Clear all To recipients.
3936       */
3937      public function clearAddresses()
3938      {
3939          foreach ($this->to as $to) {
3940              unset($this->all_recipients[strtolower($to[0])]);
3941          }
3942          $this->to = [];
3943          $this->clearQueuedAddresses('to');
3944      }
3945  
3946      /**
3947       * Clear all CC recipients.
3948       */
3949      public function clearCCs()
3950      {
3951          foreach ($this->cc as $cc) {
3952              unset($this->all_recipients[strtolower($cc[0])]);
3953          }
3954          $this->cc = [];
3955          $this->clearQueuedAddresses('cc');
3956      }
3957  
3958      /**
3959       * Clear all BCC recipients.
3960       */
3961      public function clearBCCs()
3962      {
3963          foreach ($this->bcc as $bcc) {
3964              unset($this->all_recipients[strtolower($bcc[0])]);
3965          }
3966          $this->bcc = [];
3967          $this->clearQueuedAddresses('bcc');
3968      }
3969  
3970      /**
3971       * Clear all ReplyTo recipients.
3972       */
3973      public function clearReplyTos()
3974      {
3975          $this->ReplyTo = [];
3976          $this->ReplyToQueue = [];
3977      }
3978  
3979      /**
3980       * Clear all recipient types.
3981       */
3982      public function clearAllRecipients()
3983      {
3984          $this->to = [];
3985          $this->cc = [];
3986          $this->bcc = [];
3987          $this->all_recipients = [];
3988          $this->RecipientsQueue = [];
3989      }
3990  
3991      /**
3992       * Clear all filesystem, string, and binary attachments.
3993       */
3994      public function clearAttachments()
3995      {
3996          $this->attachment = [];
3997      }
3998  
3999      /**
4000       * Clear all custom headers.
4001       */
4002      public function clearCustomHeaders()
4003      {
4004          $this->CustomHeader = [];
4005      }
4006  
4007      /**
4008       * Add an error message to the error container.
4009       *
4010       * @param string $msg
4011       */
4012      protected function setError($msg)
4013      {
4014          ++$this->error_count;
4015          if ('smtp' === $this->Mailer && null !== $this->smtp) {
4016              $lasterror = $this->smtp->getError();
4017              if (!empty($lasterror['error'])) {
4018                  $msg .= $this->lang('smtp_error') . $lasterror['error'];
4019                  if (!empty($lasterror['detail'])) {
4020                      $msg .= ' ' . $this->lang('smtp_detail') . $lasterror['detail'];
4021                  }
4022                  if (!empty($lasterror['smtp_code'])) {
4023                      $msg .= ' ' . $this->lang('smtp_code') . $lasterror['smtp_code'];
4024                  }
4025                  if (!empty($lasterror['smtp_code_ex'])) {
4026                      $msg .= ' ' . $this->lang('smtp_code_ex') . $lasterror['smtp_code_ex'];
4027                  }
4028              }
4029          }
4030          $this->ErrorInfo = $msg;
4031      }
4032  
4033      /**
4034       * Return an RFC 822 formatted date.
4035       *
4036       * @return string
4037       */
4038      public static function rfcDate()
4039      {
4040          //Set the time zone to whatever the default is to avoid 500 errors
4041          //Will default to UTC if it's not set properly in php.ini
4042          date_default_timezone_set(@date_default_timezone_get());
4043  
4044          return date('D, j M Y H:i:s O');
4045      }
4046  
4047      /**
4048       * Get the server hostname.
4049       * Returns 'localhost.localdomain' if unknown.
4050       *
4051       * @return string
4052       */
4053      protected function serverHostname()
4054      {
4055          $result = '';
4056          if (!empty($this->Hostname)) {
4057              $result = $this->Hostname;
4058          } elseif (isset($_SERVER) && array_key_exists('SERVER_NAME', $_SERVER)) {
4059              $result = $_SERVER['SERVER_NAME'];
4060          } elseif (function_exists('gethostname') && gethostname() !== false) {
4061              $result = gethostname();
4062          } elseif (php_uname('n') !== false) {
4063              $result = php_uname('n');
4064          }
4065          if (!static::isValidHost($result)) {
4066              return 'localhost.localdomain';
4067          }
4068  
4069          return $result;
4070      }
4071  
4072      /**
4073       * Validate whether a string contains a valid value to use as a hostname or IP address.
4074       * IPv6 addresses must include [], e.g. `[::1]`, not just `::1`.
4075       *
4076       * @param string $host The host name or IP address to check
4077       *
4078       * @return bool
4079       */
4080      public static function isValidHost($host)
4081      {
4082          //Simple syntax limits
4083          if (
4084              empty($host)
4085              || !is_string($host)
4086              || strlen($host) > 256
4087              || !preg_match('/^([a-zA-Z\d.-]*|\[[a-fA-F\d:]+\])$/', $host)
4088          ) {
4089              return false;
4090          }
4091          //Looks like a bracketed IPv6 address
4092          if (strlen($host) > 2 && substr($host, 0, 1) === '[' && substr($host, -1, 1) === ']') {
4093              return filter_var(substr($host, 1, -1), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
4094          }
4095          //If removing all the dots results in a numeric string, it must be an IPv4 address.
4096          //Need to check this first because otherwise things like `999.0.0.0` are considered valid host names
4097          if (is_numeric(str_replace('.', '', $host))) {
4098              //Is it a valid IPv4 address?
4099              return filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
4100          }
4101          if (filter_var('http://' . $host, FILTER_VALIDATE_URL) !== false) {
4102              //Is it a syntactically valid hostname?
4103              return true;
4104          }
4105  
4106          return false;
4107      }
4108  
4109      /**
4110       * Get an error message in the current language.
4111       *
4112       * @param string $key
4113       *
4114       * @return string
4115       */
4116      protected function lang($key)
4117      {
4118          if (count($this->language) < 1) {
4119              $this->setLanguage(); //Set the default language
4120          }
4121  
4122          if (array_key_exists($key, $this->language)) {
4123              if ('smtp_connect_failed' === $key) {
4124                  //Include a link to troubleshooting docs on SMTP connection failure.
4125                  //This is by far the biggest cause of support questions
4126                  //but it's usually not PHPMailer's fault.
4127                  return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
4128              }
4129  
4130              return $this->language[$key];
4131          }
4132  
4133          //Return the key as a fallback
4134          return $key;
4135      }
4136  
4137      /**
4138       * Build an error message starting with a generic one and adding details if possible.
4139       *
4140       * @param string $base_key
4141       * @return string
4142       */
4143      private function getSmtpErrorMessage($base_key)
4144      {
4145          $message = $this->lang($base_key);
4146          $error = $this->smtp->getError();
4147          if (!empty($error['error'])) {
4148              $message .= ' ' . $error['error'];
4149              if (!empty($error['detail'])) {
4150                  $message .= ' ' . $error['detail'];
4151              }
4152          }
4153  
4154          return $message;
4155      }
4156  
4157      /**
4158       * Check if an error occurred.
4159       *
4160       * @return bool True if an error did occur
4161       */
4162      public function isError()
4163      {
4164          return $this->error_count > 0;
4165      }
4166  
4167      /**
4168       * Add a custom header.
4169       * $name value can be overloaded to contain
4170       * both header name and value (name:value).
4171       *
4172       * @param string      $name  Custom header name
4173       * @param string|null $value Header value
4174       *
4175       * @throws Exception
4176       */
4177      public function addCustomHeader($name, $value = null)
4178      {
4179          if (null === $value && strpos($name, ':') !== false) {
4180              //Value passed in as name:value
4181              list($name, $value) = explode(':', $name, 2);
4182          }
4183          $name = trim($name);
4184          $value = (null === $value) ? '' : trim($value);
4185          //Ensure name is not empty, and that neither name nor value contain line breaks
4186          if (empty($name) || strpbrk($name . $value, "\r\n") !== false) {
4187              if ($this->exceptions) {
4188                  throw new Exception($this->lang('invalid_header'));
4189              }
4190  
4191              return false;
4192          }
4193          $this->CustomHeader[] = [$name, $value];
4194  
4195          return true;
4196      }
4197  
4198      /**
4199       * Returns all custom headers.
4200       *
4201       * @return array
4202       */
4203      public function getCustomHeaders()
4204      {
4205          return $this->CustomHeader;
4206      }
4207  
4208      /**
4209       * Create a message body from an HTML string.
4210       * Automatically inlines images and creates a plain-text version by converting the HTML,
4211       * overwriting any existing values in Body and AltBody.
4212       * Do not source $message content from user input!
4213       * $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty
4214       * will look for an image file in $basedir/images/a.png and convert it to inline.
4215       * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email)
4216       * Converts data-uri images into embedded attachments.
4217       * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly.
4218       *
4219       * @param string        $message  HTML message string
4220       * @param string        $basedir  Absolute path to a base directory to prepend to relative paths to images
4221       * @param bool|callable $advanced Whether to use the internal HTML to text converter
4222       *                                or your own custom converter
4223       * @return string The transformed message body
4224       *
4225       * @throws Exception
4226       *
4227       * @see PHPMailer::html2text()
4228       */
4229      public function msgHTML($message, $basedir = '', $advanced = false)
4230      {
4231          preg_match_all('/(?<!-)(src|background)=["\'](.*)["\']/Ui', $message, $images);
4232          if (array_key_exists(2, $images)) {
4233              if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {
4234                  //Ensure $basedir has a trailing /
4235                  $basedir .= '/';
4236              }
4237              foreach ($images[2] as $imgindex => $url) {
4238                  //Convert data URIs into embedded images
4239                  //e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
4240                  $match = [];
4241                  if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) {
4242                      if (count($match) === 4 && static::ENCODING_BASE64 === $match[2]) {
4243                          $data = base64_decode($match[3]);
4244                      } elseif ('' === $match[2]) {
4245                          $data = rawurldecode($match[3]);
4246                      } else {
4247                          //Not recognised so leave it alone
4248                          continue;
4249                      }
4250                      //Hash the decoded data, not the URL, so that the same data-URI image used in multiple places
4251                      //will only be embedded once, even if it used a different encoding
4252                      $cid = substr(hash('sha256', $data), 0, 32) . '@phpmailer.0'; //RFC2392 S 2
4253  
4254                      if (!$this->cidExists($cid)) {
4255                          $this->addStringEmbeddedImage(
4256                              $data,
4257                              $cid,
4258                              'embed' . $imgindex,
4259                              static::ENCODING_BASE64,
4260                              $match[1]
4261                          );
4262                      }
4263                      $message = str_replace(
4264                          $images[0][$imgindex],
4265                          $images[1][$imgindex] . '="cid:' . $cid . '"',
4266                          $message
4267                      );
4268                      continue;
4269                  }
4270                  if (
4271                      //Only process relative URLs if a basedir is provided (i.e. no absolute local paths)
4272                      !empty($basedir)
4273                      //Ignore URLs containing parent dir traversal (..)
4274                      && (strpos($url, '..') === false)
4275                      //Do not change urls that are already inline images
4276                      && 0 !== strpos($url, 'cid:')
4277                      //Do not change absolute URLs, including anonymous protocol
4278                      && !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url)
4279                  ) {
4280                      $filename = static::mb_pathinfo($url, PATHINFO_BASENAME);
4281                      $directory = dirname($url);
4282                      if ('.' === $directory) {
4283                          $directory = '';
4284                      }
4285                      //RFC2392 S 2
4286                      $cid = substr(hash('sha256', $url), 0, 32) . '@phpmailer.0';
4287                      if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {
4288                          $basedir .= '/';
4289                      }
4290                      if (strlen($directory) > 1 && '/' !== substr($directory, -1)) {
4291                          $directory .= '/';
4292                      }
4293                      if (
4294                          $this->addEmbeddedImage(
4295                              $basedir . $directory . $filename,
4296                              $cid,
4297                              $filename,
4298                              static::ENCODING_BASE64,
4299                              static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION))
4300                          )
4301                      ) {
4302                          $message = preg_replace(
4303                              '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
4304                              $images[1][$imgindex] . '="cid:' . $cid . '"',
4305                              $message
4306                          );
4307                      }
4308                  }
4309              }
4310          }
4311          $this->isHTML();
4312          //Convert all message body line breaks to LE, makes quoted-printable encoding work much better
4313          $this->Body = static::normalizeBreaks($message);
4314          $this->AltBody = static::normalizeBreaks($this->html2text($message, $advanced));
4315          if (!$this->alternativeExists()) {
4316              $this->AltBody = 'This is an HTML-only message. To view it, activate HTML in your email application.'
4317                  . static::$LE;
4318          }
4319  
4320          return $this->Body;
4321      }
4322  
4323      /**
4324       * Convert an HTML string into plain text.
4325       * This is used by msgHTML().
4326       * Note - older versions of this function used a bundled advanced converter
4327       * which was removed for license reasons in #232.
4328       * Example usage:
4329       *
4330       * ```php
4331       * //Use default conversion
4332       * $plain = $mail->html2text($html);
4333       * //Use your own custom converter
4334       * $plain = $mail->html2text($html, function($html) {
4335       *     $converter = new MyHtml2text($html);
4336       *     return $converter->get_text();
4337       * });
4338       * ```
4339       *
4340       * @param string        $html     The HTML text to convert
4341       * @param bool|callable $advanced Any boolean value to use the internal converter,
4342       *                                or provide your own callable for custom conversion.
4343       *                                *Never* pass user-supplied data into this parameter
4344       *
4345       * @return string
4346       */
4347      public function html2text($html, $advanced = false)
4348      {
4349          if (is_callable($advanced)) {
4350              return call_user_func($advanced, $html);
4351          }
4352  
4353          return html_entity_decode(
4354              trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
4355              ENT_QUOTES,
4356              $this->CharSet
4357          );
4358      }
4359  
4360      /**
4361       * Get the MIME type for a file extension.
4362       *
4363       * @param string $ext File extension
4364       *
4365       * @return string MIME type of file
4366       */
4367      public static function _mime_types($ext = '')
4368      {
4369          $mimes = [
4370              'xl' => 'application/excel',
4371              'js' => 'application/javascript',
4372              'hqx' => 'application/mac-binhex40',
4373              'cpt' => 'application/mac-compactpro',
4374              'bin' => 'application/macbinary',
4375              'doc' => 'application/msword',
4376              'word' => 'application/msword',
4377              'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
4378              'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
4379              'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
4380              'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
4381              'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
4382              'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
4383              'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
4384              'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
4385              'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
4386              'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
4387              'class' => 'application/octet-stream',
4388              'dll' => 'application/octet-stream',
4389              'dms' => 'application/octet-stream',
4390              'exe' => 'application/octet-stream',
4391              'lha' => 'application/octet-stream',
4392              'lzh' => 'application/octet-stream',
4393              'psd' => 'application/octet-stream',
4394              'sea' => 'application/octet-stream',
4395              'so' => 'application/octet-stream',
4396              'oda' => 'application/oda',
4397              'pdf' => 'application/pdf',
4398              'ai' => 'application/postscript',
4399              'eps' => 'application/postscript',
4400              'ps' => 'application/postscript',
4401              'smi' => 'application/smil',
4402              'smil' => 'application/smil',
4403              'mif' => 'application/vnd.mif',
4404              'xls' => 'application/vnd.ms-excel',
4405              'ppt' => 'application/vnd.ms-powerpoint',
4406              'wbxml' => 'application/vnd.wap.wbxml',
4407              'wmlc' => 'application/vnd.wap.wmlc',
4408              'dcr' => 'application/x-director',
4409              'dir' => 'application/x-director',
4410              'dxr' => 'application/x-director',
4411              'dvi' => 'application/x-dvi',
4412              'gtar' => 'application/x-gtar',
4413              'php3' => 'application/x-httpd-php',
4414              'php4' => 'application/x-httpd-php',
4415              'php' => 'application/x-httpd-php',
4416              'phtml' => 'application/x-httpd-php',
4417              'phps' => 'application/x-httpd-php-source',
4418              'swf' => 'application/x-shockwave-flash',
4419              'sit' => 'application/x-stuffit',
4420              'tar' => 'application/x-tar',
4421              'tgz' => 'application/x-tar',
4422              'xht' => 'application/xhtml+xml',
4423              'xhtml' => 'application/xhtml+xml',
4424              'zip' => 'application/zip',
4425              'mid' => 'audio/midi',
4426              'midi' => 'audio/midi',
4427              'mp2' => 'audio/mpeg',
4428              'mp3' => 'audio/mpeg',
4429              'm4a' => 'audio/mp4',
4430              'mpga' => 'audio/mpeg',
4431              'aif' => 'audio/x-aiff',
4432              'aifc' => 'audio/x-aiff',
4433              'aiff' => 'audio/x-aiff',
4434              'ram' => 'audio/x-pn-realaudio',
4435              'rm' => 'audio/x-pn-realaudio',
4436              'rpm' => 'audio/x-pn-realaudio-plugin',
4437              'ra' => 'audio/x-realaudio',
4438              'wav' => 'audio/x-wav',
4439              'mka' => 'audio/x-matroska',
4440              'bmp' => 'image/bmp',
4441              'gif' => 'image/gif',
4442              'jpeg' => 'image/jpeg',
4443              'jpe' => 'image/jpeg',
4444              'jpg' => 'image/jpeg',
4445              'png' => 'image/png',
4446              'tiff' => 'image/tiff',
4447              'tif' => 'image/tiff',
4448              'webp' => 'image/webp',
4449              'avif' => 'image/avif',
4450              'heif' => 'image/heif',
4451              'heifs' => 'image/heif-sequence',
4452              'heic' => 'image/heic',
4453              'heics' => 'image/heic-sequence',
4454              'eml' => 'message/rfc822',
4455              'css' => 'text/css',
4456              'html' => 'text/html',
4457              'htm' => 'text/html',
4458              'shtml' => 'text/html',
4459              'log' => 'text/plain',
4460              'text' => 'text/plain',
4461              'txt' => 'text/plain',
4462              'rtx' => 'text/richtext',
4463              'rtf' => 'text/rtf',
4464              'vcf' => 'text/vcard',
4465              'vcard' => 'text/vcard',
4466              'ics' => 'text/calendar',
4467              'xml' => 'text/xml',
4468              'xsl' => 'text/xml',
4469              'wmv' => 'video/x-ms-wmv',
4470              'mpeg' => 'video/mpeg',
4471              'mpe' => 'video/mpeg',
4472              'mpg' => 'video/mpeg',
4473              'mp4' => 'video/mp4',
4474              'm4v' => 'video/mp4',
4475              'mov' => 'video/quicktime',
4476              'qt' => 'video/quicktime',
4477              'rv' => 'video/vnd.rn-realvideo',
4478              'avi' => 'video/x-msvideo',
4479              'movie' => 'video/x-sgi-movie',
4480              'webm' => 'video/webm',
4481              'mkv' => 'video/x-matroska',
4482          ];
4483          $ext = strtolower($ext);
4484          if (array_key_exists($ext, $mimes)) {
4485              return $mimes[$ext];
4486          }
4487  
4488          return 'application/octet-stream';
4489      }
4490  
4491      /**
4492       * Map a file name to a MIME type.
4493       * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
4494       *
4495       * @param string $filename A file name or full path, does not need to exist as a file
4496       *
4497       * @return string
4498       */
4499      public static function filenameToType($filename)
4500      {
4501          //In case the path is a URL, strip any query string before getting extension
4502          $qpos = strpos($filename, '?');
4503          if (false !== $qpos) {
4504              $filename = substr($filename, 0, $qpos);
4505          }
4506          $ext = static::mb_pathinfo($filename, PATHINFO_EXTENSION);
4507  
4508          return static::_mime_types($ext);
4509      }
4510  
4511      /**
4512       * Multi-byte-safe pathinfo replacement.
4513       * Drop-in replacement for pathinfo(), but multibyte- and cross-platform-safe.
4514       *
4515       * @see http://www.php.net/manual/en/function.pathinfo.php#107461
4516       *
4517       * @param string     $path    A filename or path, does not need to exist as a file
4518       * @param int|string $options Either a PATHINFO_* constant,
4519       *                            or a string name to return only the specified piece
4520       *
4521       * @return string|array
4522       */
4523      public static function mb_pathinfo($path, $options = null)
4524      {
4525          $ret = ['dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''];
4526          $pathinfo = [];
4527          if (preg_match('#^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^.\\\\/]+?)|))[\\\\/.]*$#m', $path, $pathinfo)) {
4528              if (array_key_exists(1, $pathinfo)) {
4529                  $ret['dirname'] = $pathinfo[1];
4530              }
4531              if (array_key_exists(2, $pathinfo)) {
4532                  $ret['basename'] = $pathinfo[2];
4533              }
4534              if (array_key_exists(5, $pathinfo)) {
4535                  $ret['extension'] = $pathinfo[5];
4536              }
4537              if (array_key_exists(3, $pathinfo)) {
4538                  $ret['filename'] = $pathinfo[3];
4539              }
4540          }
4541          switch ($options) {
4542              case PATHINFO_DIRNAME:
4543              case 'dirname':
4544                  return $ret['dirname'];
4545              case PATHINFO_BASENAME:
4546              case 'basename':
4547                  return $ret['basename'];
4548              case PATHINFO_EXTENSION:
4549              case 'extension':
4550                  return $ret['extension'];
4551              case PATHINFO_FILENAME:
4552              case 'filename':
4553                  return $ret['filename'];
4554              default:
4555                  return $ret;
4556          }
4557      }
4558  
4559      /**
4560       * Set or reset instance properties.
4561       * You should avoid this function - it's more verbose, less efficient, more error-prone and
4562       * harder to debug than setting properties directly.
4563       * Usage Example:
4564       * `$mail->set('SMTPSecure', static::ENCRYPTION_STARTTLS);`
4565       *   is the same as:
4566       * `$mail->SMTPSecure = static::ENCRYPTION_STARTTLS;`.
4567       *
4568       * @param string $name  The property name to set
4569       * @param mixed  $value The value to set the property to
4570       *
4571       * @return bool
4572       */
4573      public function set($name, $value = '')
4574      {
4575          if (property_exists($this, $name)) {
4576              $this->$name = $value;
4577  
4578              return true;
4579          }
4580          $this->setError($this->lang('variable_set') . $name);
4581  
4582          return false;
4583      }
4584  
4585      /**
4586       * Strip newlines to prevent header injection.
4587       *
4588       * @param string $str
4589       *
4590       * @return string
4591       */
4592      public function secureHeader($str)
4593      {
4594          return trim(str_replace(["\r", "\n"], '', $str));
4595      }
4596  
4597      /**
4598       * Normalize line breaks in a string.
4599       * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
4600       * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
4601       *
4602       * @param string $text
4603       * @param string $breaktype What kind of line break to use; defaults to static::$LE
4604       *
4605       * @return string
4606       */
4607      public static function normalizeBreaks($text, $breaktype = null)
4608      {
4609          if (null === $breaktype) {
4610              $breaktype = static::$LE;
4611          }
4612          //Normalise to \n
4613          $text = str_replace([self::CRLF, "\r"], "\n", $text);
4614          //Now convert LE as needed
4615          if ("\n" !== $breaktype) {
4616              $text = str_replace("\n", $breaktype, $text);
4617          }
4618  
4619          return $text;
4620      }
4621  
4622      /**
4623       * Remove trailing breaks from a string.
4624       *
4625       * @param string $text
4626       *
4627       * @return string The text to remove breaks from
4628       */
4629      public static function stripTrailingWSP($text)
4630      {
4631          return rtrim($text, " \r\n\t");
4632      }
4633  
4634      /**
4635       * Return the current line break format string.
4636       *
4637       * @return string
4638       */
4639      public static function getLE()
4640      {
4641          return static::$LE;
4642      }
4643  
4644      /**
4645       * Set the line break format string, e.g. "\r\n".
4646       *
4647       * @param string $le
4648       */
4649      protected static function setLE($le)
4650      {
4651          static::$LE = $le;
4652      }
4653  
4654      /**
4655       * Set the public and private key files and password for S/MIME signing.
4656       *
4657       * @param string $cert_filename
4658       * @param string $key_filename
4659       * @param string $key_pass            Password for private key
4660       * @param string $extracerts_filename Optional path to chain certificate
4661       */
4662      public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
4663      {
4664          $this->sign_cert_file = $cert_filename;
4665          $this->sign_key_file = $key_filename;
4666          $this->sign_key_pass = $key_pass;
4667          $this->sign_extracerts_file = $extracerts_filename;
4668      }
4669  
4670      /**
4671       * Quoted-Printable-encode a DKIM header.
4672       *
4673       * @param string $txt
4674       *
4675       * @return string
4676       */
4677      public function DKIM_QP($txt)
4678      {
4679          $line = '';
4680          $len = strlen($txt);
4681          for ($i = 0; $i < $len; ++$i) {
4682              $ord = ord($txt[$i]);
4683              if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord === 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
4684                  $line .= $txt[$i];
4685              } else {
4686                  $line .= '=' . sprintf('%02X', $ord);
4687              }
4688          }
4689  
4690          return $line;
4691      }
4692  
4693      /**
4694       * Generate a DKIM signature.
4695       *
4696       * @param string $signHeader
4697       *
4698       * @throws Exception
4699       *
4700       * @return string The DKIM signature value
4701       */
4702      public function DKIM_Sign($signHeader)
4703      {
4704          if (!defined('PKCS7_TEXT')) {
4705              if ($this->exceptions) {
4706                  throw new Exception($this->lang('extension_missing') . 'openssl');
4707              }
4708  
4709              return '';
4710          }
4711          $privKeyStr = !empty($this->DKIM_private_string) ?
4712              $this->DKIM_private_string :
4713              file_get_contents($this->DKIM_private);
4714          if ('' !== $this->DKIM_passphrase) {
4715              $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
4716          } else {
4717              $privKey = openssl_pkey_get_private($privKeyStr);
4718          }
4719          if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
4720              if (\PHP_MAJOR_VERSION < 8) {
4721                  openssl_pkey_free($privKey);
4722              }
4723  
4724              return base64_encode($signature);
4725          }
4726          if (\PHP_MAJOR_VERSION < 8) {
4727              openssl_pkey_free($privKey);
4728          }
4729  
4730          return '';
4731      }
4732  
4733      /**
4734       * Generate a DKIM canonicalization header.
4735       * Uses the 'relaxed' algorithm from RFC6376 section 3.4.2.
4736       * Canonicalized headers should *always* use CRLF, regardless of mailer setting.
4737       *
4738       * @see https://tools.ietf.org/html/rfc6376#section-3.4.2
4739       *
4740       * @param string $signHeader Header
4741       *
4742       * @return string
4743       */
4744      public function DKIM_HeaderC($signHeader)
4745      {
4746          //Normalize breaks to CRLF (regardless of the mailer)
4747          $signHeader = static::normalizeBreaks($signHeader, self::CRLF);
4748          //Unfold header lines
4749          //Note PCRE \s is too broad a definition of whitespace; RFC5322 defines it as `[ \t]`
4750          //@see https://tools.ietf.org/html/rfc5322#section-2.2
4751          //That means this may break if you do something daft like put vertical tabs in your headers.
4752          $signHeader = preg_replace('/\r\n[ \t]+/', ' ', $signHeader);
4753          //Break headers out into an array
4754          $lines = explode(self::CRLF, $signHeader);
4755          foreach ($lines as $key => $line) {
4756              //If the header is missing a :, skip it as it's invalid
4757              //This is likely to happen because the explode() above will also split
4758              //on the trailing LE, leaving an empty line
4759              if (strpos($line, ':') === false) {
4760                  continue;
4761              }
4762              list($heading, $value) = explode(':', $line, 2);
4763              //Lower-case header name
4764              $heading = strtolower($heading);
4765              //Collapse white space within the value, also convert WSP to space
4766              $value = preg_replace('/[ \t]+/', ' ', $value);
4767              //RFC6376 is slightly unclear here - it says to delete space at the *end* of each value
4768              //But then says to delete space before and after the colon.
4769              //Net result is the same as trimming both ends of the value.
4770              //By elimination, the same applies to the field name
4771              $lines[$key] = trim($heading, " \t") . ':' . trim($value, " \t");
4772          }
4773  
4774          return implode(self::CRLF, $lines);
4775      }
4776  
4777      /**
4778       * Generate a DKIM canonicalization body.
4779       * Uses the 'simple' algorithm from RFC6376 section 3.4.3.
4780       * Canonicalized bodies should *always* use CRLF, regardless of mailer setting.
4781       *
4782       * @see https://tools.ietf.org/html/rfc6376#section-3.4.3
4783       *</