[ Index ]

PHP Cross Reference of Joomla 4.2.2 documentation

title

Body

[close]

/libraries/vendor/phpmailer/phpmailer/src/ -> 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) <[email protected]>
  10   * @author    Jim Jagielski (jimjag) <[email protected]>
  11   * @author    Andy Prevost (codeworxtech) <[email protected]>
  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) <[email protected]>
  28   * @author Jim Jagielski (jimjag) <[email protected]>
  29   * @author Andy Prevost (codeworxtech) <[email protected]>
  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) {
 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('[email protected]', 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: `[email protected]`
1375                   *  * unbracketed IPv4 literals: `[email protected]`
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                      $punycode = idn_to_ascii($domain, $errorcode, \INTL_IDNA_VARIANT_2003);
1464                  } else {
1465                      //Fall back to a default we don't know about
1466                      $punycode = idn_to_ascii($domain, $errorcode);
1467                  }
1468                  if (false !== $punycode) {
1469                      return substr($address, 0, $pos) . $punycode;
1470                  }
1471              }
1472          }
1473  
1474          return $address;
1475      }
1476  
1477      /**
1478       * Create a message and send it.
1479       * Uses the sending method specified by $Mailer.
1480       *
1481       * @throws Exception
1482       *
1483       * @return bool false on error - See the ErrorInfo property for details of the error
1484       */
1485      public function send()
1486      {
1487          try {
1488              if (!$this->preSend()) {
1489                  return false;
1490              }
1491  
1492              return $this->postSend();
1493          } catch (Exception $exc) {
1494              $this->mailHeader = '';
1495              $this->setError($exc->getMessage());
1496              if ($this->exceptions) {
1497                  throw $exc;
1498              }
1499  
1500              return false;
1501          }
1502      }
1503  
1504      /**
1505       * Prepare a message for sending.
1506       *
1507       * @throws Exception
1508       *
1509       * @return bool
1510       */
1511      public function preSend()
1512      {
1513          if (
1514              'smtp' === $this->Mailer
1515              || ('mail' === $this->Mailer && (\PHP_VERSION_ID >= 80000 || stripos(PHP_OS, 'WIN') === 0))
1516          ) {
1517              //SMTP mandates RFC-compliant line endings
1518              //and it's also used with mail() on Windows
1519              static::setLE(self::CRLF);
1520          } else {
1521              //Maintain backward compatibility with legacy Linux command line mailers
1522              static::setLE(PHP_EOL);
1523          }
1524          //Check for buggy PHP versions that add a header with an incorrect line break
1525          if (
1526              'mail' === $this->Mailer
1527              && ((\PHP_VERSION_ID >= 70000 && \PHP_VERSION_ID < 70017)
1528                  || (\PHP_VERSION_ID >= 70100 && \PHP_VERSION_ID < 70103))
1529              && ini_get('mail.add_x_header') === '1'
1530              && stripos(PHP_OS, 'WIN') === 0
1531          ) {
1532              trigger_error($this->lang('buggy_php'), E_USER_WARNING);
1533          }
1534  
1535          try {
1536              $this->error_count = 0; //Reset errors
1537              $this->mailHeader = '';
1538  
1539              //Dequeue recipient and Reply-To addresses with IDN
1540              foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
1541                  $params[1] = $this->punyencodeAddress($params[1]);
1542                  call_user_func_array([$this, 'addAnAddress'], $params);
1543              }
1544              if (count($this->to) + count($this->cc) + count($this->bcc) < 1) {
1545                  throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL);
1546              }
1547  
1548              //Validate From, Sender, and ConfirmReadingTo addresses
1549              foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) {
1550                  $this->$address_kind = trim($this->$address_kind);
1551                  if (empty($this->$address_kind)) {
1552                      continue;
1553                  }
1554                  $this->$address_kind = $this->punyencodeAddress($this->$address_kind);
1555                  if (!static::validateAddress($this->$address_kind)) {
1556                      $error_message = sprintf(
1557                          '%s (%s): %s',
1558                          $this->lang('invalid_address'),
1559                          $address_kind,
1560                          $this->$address_kind
1561                      );
1562                      $this->setError($error_message);
1563                      $this->edebug($error_message);
1564                      if ($this->exceptions) {
1565                          throw new Exception($error_message);
1566                      }
1567  
1568                      return false;
1569                  }
1570              }
1571  
1572              //Set whether the message is multipart/alternative
1573              if ($this->alternativeExists()) {
1574                  $this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE;
1575              }
1576  
1577              $this->setMessageType();
1578              //Refuse to send an empty message unless we are specifically allowing it
1579              if (!$this->AllowEmpty && empty($this->Body)) {
1580                  throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
1581              }
1582  
1583              //Trim subject consistently
1584              $this->Subject = trim($this->Subject);
1585              //Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
1586              $this->MIMEHeader = '';
1587              $this->MIMEBody = $this->createBody();
1588              //createBody may have added some headers, so retain them
1589              $tempheaders = $this->MIMEHeader;
1590              $this->MIMEHeader = $this->createHeader();
1591              $this->MIMEHeader .= $tempheaders;
1592  
1593              //To capture the complete message when using mail(), create
1594              //an extra header list which createHeader() doesn't fold in
1595              if ('mail' === $this->Mailer) {
1596                  if (count($this->to) > 0) {
1597                      $this->mailHeader .= $this->addrAppend('To', $this->to);
1598                  } else {
1599                      $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
1600                  }
1601                  $this->mailHeader .= $this->headerLine(
1602                      'Subject',
1603                      $this->encodeHeader($this->secureHeader($this->Subject))
1604                  );
1605              }
1606  
1607              //Sign with DKIM if enabled
1608              if (
1609                  !empty($this->DKIM_domain)
1610                  && !empty($this->DKIM_selector)
1611                  && (!empty($this->DKIM_private_string)
1612                      || (!empty($this->DKIM_private)
1613                          && static::isPermittedPath($this->DKIM_private)
1614                          && file_exists($this->DKIM_private)
1615                      )
1616                  )
1617              ) {
1618                  $header_dkim = $this->DKIM_Add(
1619                      $this->MIMEHeader . $this->mailHeader,
1620                      $this->encodeHeader($this->secureHeader($this->Subject)),
1621                      $this->MIMEBody
1622                  );
1623                  $this->MIMEHeader = static::stripTrailingWSP($this->MIMEHeader) . static::$LE .
1624                      static::normalizeBreaks($header_dkim) . static::$LE;
1625              }
1626  
1627              return true;
1628          } catch (Exception $exc) {
1629              $this->setError($exc->getMessage());
1630              if ($this->exceptions) {
1631                  throw $exc;
1632              }
1633  
1634              return false;
1635          }
1636      }
1637  
1638      /**
1639       * Actually send a message via the selected mechanism.
1640       *
1641       * @throws Exception
1642       *
1643       * @return bool
1644       */
1645      public function postSend()
1646      {
1647          try {
1648              //Choose the mailer and send through it
1649              switch ($this->Mailer) {
1650                  case 'sendmail':
1651                  case 'qmail':
1652                      return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
1653                  case 'smtp':
1654                      return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
1655                  case 'mail':
1656                      return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1657                  default:
1658                      $sendMethod = $this->Mailer . 'Send';
1659                      if (method_exists($this, $sendMethod)) {
1660                          return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
1661                      }
1662  
1663                      return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
1664              }
1665          } catch (Exception $exc) {
1666              if ($this->Mailer === 'smtp' && $this->SMTPKeepAlive == true) {
1667                  $this->smtp->reset();
1668              }
1669              $this->setError($exc->getMessage());
1670              $this->edebug($exc->getMessage());
1671              if ($this->exceptions) {
1672                  throw $exc;
1673              }
1674          }
1675  
1676          return false;
1677      }
1678  
1679      /**
1680       * Send mail using the $Sendmail program.
1681       *
1682       * @see PHPMailer::$Sendmail
1683       *
1684       * @param string $header The message headers
1685       * @param string $body   The message body
1686       *
1687       * @throws Exception
1688       *
1689       * @return bool
1690       */
1691      protected function sendmailSend($header, $body)
1692      {
1693          if ($this->Mailer === 'qmail') {
1694              $this->edebug('Sending with qmail');
1695          } else {
1696              $this->edebug('Sending with sendmail');
1697          }
1698          $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
1699          //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
1700          //A space after `-f` is optional, but there is a long history of its presence
1701          //causing problems, so we don't use one
1702          //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
1703          //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
1704          //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
1705          //Example problem: https://www.drupal.org/node/1057954
1706  
1707          //PHP 5.6 workaround
1708          $sendmail_from_value = ini_get('sendmail_from');
1709          if (empty($this->Sender) && !empty($sendmail_from_value)) {
1710              //PHP config has a sender address we can use
1711              $this->Sender = ini_get('sendmail_from');
1712          }
1713          //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1714          if (!empty($this->Sender) && static::validateAddress($this->Sender) && self::isShellSafe($this->Sender)) {
1715              if ($this->Mailer === 'qmail') {
1716                  $sendmailFmt = '%s -f%s';
1717              } else {
1718                  $sendmailFmt = '%s -oi -f%s -t';
1719              }
1720          } else {
1721              //allow sendmail to choose a default envelope sender. It may
1722              //seem preferable to force it to use the From header as with
1723              //SMTP, but that introduces new problems (see
1724              //<https://github.com/PHPMailer/PHPMailer/issues/2298>), and
1725              //it has historically worked this way.
1726              $sendmailFmt = '%s -oi -t';
1727          }
1728  
1729          $sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);
1730          $this->edebug('Sendmail path: ' . $this->Sendmail);
1731          $this->edebug('Sendmail command: ' . $sendmail);
1732          $this->edebug('Envelope sender: ' . $this->Sender);
1733          $this->edebug("Headers: {$header}");
1734  
1735          if ($this->SingleTo) {
1736              foreach ($this->SingleToArray as $toAddr) {
1737                  $mail = @popen($sendmail, 'w');
1738                  if (!$mail) {
1739                      throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1740                  }
1741                  $this->edebug("To: {$toAddr}");
1742                  fwrite($mail, 'To: ' . $toAddr . "\n");
1743                  fwrite($mail, $header);
1744                  fwrite($mail, $body);
1745                  $result = pclose($mail);
1746                  $addrinfo = static::parseAddresses($toAddr, true, $this->CharSet);
1747                  $this->doCallback(
1748                      ($result === 0),
1749                      [[$addrinfo['address'], $addrinfo['name']]],
1750                      $this->cc,
1751                      $this->bcc,
1752                      $this->Subject,
1753                      $body,
1754                      $this->From,
1755                      []
1756                  );
1757                  $this->edebug("Result: " . ($result === 0 ? 'true' : 'false'));
1758                  if (0 !== $result) {
1759                      throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1760                  }
1761              }
1762          } else {
1763              $mail = @popen($sendmail, 'w');
1764              if (!$mail) {
1765                  throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1766              }
1767              fwrite($mail, $header);
1768              fwrite($mail, $body);
1769              $result = pclose($mail);
1770              $this->doCallback(
1771                  ($result === 0),
1772                  $this->to,
1773                  $this->cc,
1774                  $this->bcc,
1775                  $this->Subject,
1776                  $body,
1777                  $this->From,
1778                  []
1779              );
1780              $this->edebug("Result: " . ($result === 0 ? 'true' : 'false'));
1781              if (0 !== $result) {
1782                  throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
1783              }
1784          }
1785  
1786          return true;
1787      }
1788  
1789      /**
1790       * Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.
1791       * Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.
1792       *
1793       * @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report
1794       *
1795       * @param string $string The string to be validated
1796       *
1797       * @return bool
1798       */
1799      protected static function isShellSafe($string)
1800      {
1801          //It's not possible to use shell commands safely (which includes the mail() function) without escapeshellarg,
1802          //but some hosting providers disable it, creating a security problem that we don't want to have to deal with,
1803          //so we don't.
1804          if (!function_exists('escapeshellarg') || !function_exists('escapeshellcmd')) {
1805              return false;
1806          }
1807  
1808          if (
1809              escapeshellcmd($string) !== $string
1810              || !in_array(escapeshellarg($string), ["'$string'", "\"$string\""])
1811          ) {
1812              return false;
1813          }
1814  
1815          $length = strlen($string);
1816  
1817          for ($i = 0; $i < $length; ++$i) {
1818              $c = $string[$i];
1819  
1820              //All other characters have a special meaning in at least one common shell, including = and +.
1821              //Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
1822              //Note that this does permit non-Latin alphanumeric characters based on the current locale.
1823              if (!ctype_alnum($c) && strpos('@_-.', $c) === false) {
1824                  return false;
1825              }
1826          }
1827  
1828          return true;
1829      }
1830  
1831      /**
1832       * Check whether a file path is of a permitted type.
1833       * Used to reject URLs and phar files from functions that access local file paths,
1834       * such as addAttachment.
1835       *
1836       * @param string $path A relative or absolute path to a file
1837       *
1838       * @return bool
1839       */
1840      protected static function isPermittedPath($path)
1841      {
1842          //Matches scheme definition from https://tools.ietf.org/html/rfc3986#section-3.1
1843          return !preg_match('#^[a-z][a-z\d+.-]*://#i', $path);
1844      }
1845  
1846      /**
1847       * Check whether a file path is safe, accessible, and readable.
1848       *
1849       * @param string $path A relative or absolute path to a file
1850       *
1851       * @return bool
1852       */
1853      protected static function fileIsAccessible($path)
1854      {
1855          if (!static::isPermittedPath($path)) {
1856              return false;
1857          }
1858          $readable = file_exists($path);
1859          //If not a UNC path (expected to start with \\), check read permission, see #2069
1860          if (strpos($path, '\\\\') !== 0) {
1861              $readable = $readable && is_readable($path);
1862          }
1863          return  $readable;
1864      }
1865  
1866      /**
1867       * Send mail using the PHP mail() function.
1868       *
1869       * @see http://www.php.net/manual/en/book.mail.php
1870       *
1871       * @param string $header The message headers
1872       * @param string $body   The message body
1873       *
1874       * @throws Exception
1875       *
1876       * @return bool
1877       */
1878      protected function mailSend($header, $body)
1879      {
1880          $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
1881  
1882          $toArr = [];
1883          foreach ($this->to as $toaddr) {
1884              $toArr[] = $this->addrFormat($toaddr);
1885          }
1886          $to = implode(', ', $toArr);
1887  
1888          $params = null;
1889          //This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
1890          //A space after `-f` is optional, but there is a long history of its presence
1891          //causing problems, so we don't use one
1892          //Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
1893          //Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
1894          //Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
1895          //Example problem: https://www.drupal.org/node/1057954
1896          //CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
1897  
1898          //PHP 5.6 workaround
1899          $sendmail_from_value = ini_get('sendmail_from');
1900          if (empty($this->Sender) && !empty($sendmail_from_value)) {
1901              //PHP config has a sender address we can use
1902              $this->Sender = ini_get('sendmail_from');
1903          }
1904          if (!empty($this->Sender) && static::validateAddress($this->Sender)) {
1905              if (self::isShellSafe($this->Sender)) {
1906                  $params = sprintf('-f%s', $this->Sender);
1907              }
1908              $old_from = ini_get('sendmail_from');
1909              ini_set('sendmail_from', $this->Sender);
1910          }
1911          $result = false;
1912          if ($this->SingleTo && count($toArr) > 1) {
1913              foreach ($toArr as $toAddr) {
1914                  $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
1915                  $addrinfo = static::parseAddresses($toAddr, true, $this->CharSet);
1916                  $this->doCallback(
1917                      $result,
1918                      [[$addrinfo['address'], $addrinfo['name']]],
1919                      $this->cc,
1920                      $this->bcc,
1921                      $this->Subject,
1922                      $body,
1923                      $this->From,
1924                      []
1925                  );
1926              }
1927          } else {
1928              $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
1929              $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);
1930          }
1931          if (isset($old_from)) {
1932              ini_set('sendmail_from', $old_from);
1933          }
1934          if (!$result) {
1935              throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL);
1936          }
1937  
1938          return true;
1939      }
1940  
1941      /**
1942       * Get an instance to use for SMTP operations.
1943       * Override this function to load your own SMTP implementation,
1944       * or set one with setSMTPInstance.
1945       *
1946       * @return SMTP
1947       */
1948      public function getSMTPInstance()
1949      {
1950          if (!is_object($this->smtp)) {
1951              $this->smtp = new SMTP();
1952          }
1953  
1954          return $this->smtp;
1955      }
1956  
1957      /**
1958       * Provide an instance to use for SMTP operations.
1959       *
1960       * @return SMTP
1961       */
1962      public function setSMTPInstance(SMTP $smtp)
1963      {
1964          $this->smtp = $smtp;
1965  
1966          return $this->smtp;
1967      }
1968  
1969      /**
1970       * Send mail via SMTP.
1971       * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
1972       *
1973       * @see PHPMailer::setSMTPInstance() to use a different class.
1974       *
1975       * @uses \PHPMailer\PHPMailer\SMTP
1976       *
1977       * @param string $header The message headers
1978       * @param string $body   The message body
1979       *
1980       * @throws Exception
1981       *
1982       * @return bool
1983       */
1984      protected function smtpSend($header, $body)
1985      {
1986          $header = static::stripTrailingWSP($header) . static::$LE . static::$LE;
1987          $bad_rcpt = [];
1988          if (!$this->smtpConnect($this->SMTPOptions)) {
1989              throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
1990          }
1991          //Sender already validated in preSend()
1992          if ('' === $this->Sender) {
1993              $smtp_from = $this->From;
1994          } else {
1995              $smtp_from = $this->Sender;
1996          }
1997          if (!$this->smtp->mail($smtp_from)) {
1998              $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
1999              throw new Exception($this->ErrorInfo, self::STOP_CRITICAL);
2000          }
2001  
2002          $callbacks = [];
2003          //Attempt to send to all recipients
2004          foreach ([$this->to, $this->cc, $this->bcc] as $togroup) {
2005              foreach ($togroup as $to) {
2006                  if (!$this->smtp->recipient($to[0], $this->dsn)) {
2007                      $error = $this->smtp->getError();
2008                      $bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']];
2009                      $isSent = false;
2010                  } else {
2011                      $isSent = true;
2012                  }
2013  
2014                  $callbacks[] = ['issent' => $isSent, 'to' => $to[0], 'name' => $to[1]];
2015              }
2016          }
2017  
2018          //Only send the DATA command if we have viable recipients
2019          if ((count($this->all_recipients) > count($bad_rcpt)) && !$this->smtp->data($header . $body)) {
2020              throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL);
2021          }
2022  
2023          $smtp_transaction_id = $this->smtp->getLastTransactionID();
2024  
2025          if ($this->SMTPKeepAlive) {
2026              $this->smtp->reset();
2027          } else {
2028              $this->smtp->quit();
2029              $this->smtp->close();
2030          }
2031  
2032          foreach ($callbacks as $cb) {
2033              $this->doCallback(
2034                  $cb['issent'],
2035                  [[$cb['to'], $cb['name']]],
2036                  [],
2037                  [],
2038                  $this->Subject,
2039                  $body,
2040                  $this->From,
2041                  ['smtp_transaction_id' => $smtp_transaction_id]
2042              );
2043          }
2044  
2045          //Create error message for any bad addresses
2046          if (count($bad_rcpt) > 0) {
2047              $errstr = '';
2048              foreach ($bad_rcpt as $bad) {
2049                  $errstr .= $bad['to'] . ': ' . $bad['error'];
2050              }
2051              throw new Exception($this->lang('recipients_failed') . $errstr, self::STOP_CONTINUE);
2052          }
2053  
2054          return true;
2055      }
2056  
2057      /**
2058       * Initiate a connection to an SMTP server.
2059       * Returns false if the operation failed.
2060       *
2061       * @param array $options An array of options compatible with stream_context_create()
2062       *
2063       * @throws Exception
2064       *
2065       * @uses \PHPMailer\PHPMailer\SMTP
2066       *
2067       * @return bool
2068       */
2069      public function smtpConnect($options = null)
2070      {
2071          if (null === $this->smtp) {
2072              $this->smtp = $this->getSMTPInstance();
2073          }
2074  
2075          //If no options are provided, use whatever is set in the instance
2076          if (null === $options) {
2077              $options = $this->SMTPOptions;
2078          }
2079  
2080          //Already connected?
2081          if ($this->smtp->connected()) {
2082              return true;
2083          }
2084  
2085          $this->smtp->setTimeout($this->Timeout);
2086          $this->smtp->setDebugLevel($this->SMTPDebug);
2087          $this->smtp->setDebugOutput($this->Debugoutput);
2088          $this->smtp->setVerp($this->do_verp);
2089          $hosts = explode(';', $this->Host);
2090          $lastexception = null;
2091  
2092          foreach ($hosts as $hostentry) {
2093              $hostinfo = [];
2094              if (
2095                  !preg_match(
2096                      '/^(?:(ssl|tls):\/\/)?(.+?)(?::(\d+))?$/',
2097                      trim($hostentry),
2098                      $hostinfo
2099                  )
2100              ) {
2101                  $this->edebug($this->lang('invalid_hostentry') . ' ' . trim($hostentry));
2102                  //Not a valid host entry
2103                  continue;
2104              }
2105              //$hostinfo[1]: optional ssl or tls prefix
2106              //$hostinfo[2]: the hostname
2107              //$hostinfo[3]: optional port number
2108              //The host string prefix can temporarily override the current setting for SMTPSecure
2109              //If it's not specified, the default value is used
2110  
2111              //Check the host name is a valid name or IP address before trying to use it
2112              if (!static::isValidHost($hostinfo[2])) {
2113                  $this->edebug($this->lang('invalid_host') . ' ' . $hostinfo[2]);
2114                  continue;
2115              }
2116              $prefix = '';
2117              $secure = $this->SMTPSecure;
2118              $tls = (static::ENCRYPTION_STARTTLS === $this->SMTPSecure);
2119              if ('ssl' === $hostinfo[1] || ('' === $hostinfo[1] && static::ENCRYPTION_SMTPS === $this->SMTPSecure)) {
2120                  $prefix = 'ssl://';
2121                  $tls = false; //Can't have SSL and TLS at the same time
2122                  $secure = static::ENCRYPTION_SMTPS;
2123              } elseif ('tls' === $hostinfo[1]) {
2124                  $tls = true;
2125                  //TLS doesn't use a prefix
2126                  $secure = static::ENCRYPTION_STARTTLS;
2127              }
2128              //Do we need the OpenSSL extension?
2129              $sslext = defined('OPENSSL_ALGO_SHA256');
2130              if (static::ENCRYPTION_STARTTLS === $secure || static::ENCRYPTION_SMTPS === $secure) {
2131                  //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
2132                  if (!$sslext) {
2133                      throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL);
2134                  }
2135              }
2136              $host = $hostinfo[2];
2137              $port = $this->Port;
2138              if (
2139                  array_key_exists(3, $hostinfo) &&
2140                  is_numeric($hostinfo[3]) &&
2141                  $hostinfo[3] > 0 &&
2142                  $hostinfo[3] < 65536
2143              ) {
2144                  $port = (int) $hostinfo[3];
2145              }
2146              if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
2147                  try {
2148                      if ($this->Helo) {
2149                          $hello = $this->Helo;
2150                      } else {
2151                          $hello = $this->serverHostname();
2152                      }
2153                      $this->smtp->hello($hello);
2154                      //Automatically enable TLS encryption if:
2155                      //* it's not disabled
2156                      //* we have openssl extension
2157                      //* we are not already using SSL
2158                      //* the server offers STARTTLS
2159                      if ($this->SMTPAutoTLS && $sslext && 'ssl' !== $secure && $this->smtp->getServerExt('STARTTLS')) {
2160                          $tls = true;
2161                      }
2162                      if ($tls) {
2163                          if (!$this->smtp->startTLS()) {
2164                              $message = $this->getSmtpErrorMessage('connect_host');
2165                              throw new Exception($message);
2166                          }
2167                          //We must resend EHLO after TLS negotiation
2168                          $this->smtp->hello($hello);
2169                      }
2170                      if (
2171                          $this->SMTPAuth && !$this->smtp->authenticate(
2172                              $this->Username,
2173                              $this->Password,
2174                              $this->AuthType,
2175                              $this->oauth
2176                          )
2177                      ) {
2178                          throw new Exception($this->lang('authenticate'));
2179                      }
2180  
2181                      return true;
2182                  } catch (Exception $exc) {
2183                      $lastexception = $exc;
2184                      $this->edebug($exc->getMessage());
2185                      //We must have connected, but then failed TLS or Auth, so close connection nicely
2186                      $this->smtp->quit();
2187                  }
2188              }
2189          }
2190          //If we get here, all connection attempts have failed, so close connection hard
2191          $this->smtp->close();
2192          //As we've caught all exceptions, just report whatever the last one was
2193          if ($this->exceptions && null !== $lastexception) {
2194              throw $lastexception;
2195          } elseif ($this->exceptions) {
2196              // no exception was thrown, likely $this->smtp->connect() failed
2197              $message = $this->getSmtpErrorMessage('connect_host');
2198              throw new Exception($message);
2199          }
2200  
2201          return false;
2202      }
2203  
2204      /**
2205       * Close the active SMTP session if one exists.
2206       */
2207      public function smtpClose()
2208      {
2209          if ((null !== $this->smtp) && $this->smtp->connected()) {
2210              $this->smtp->quit();
2211              $this->smtp->close();
2212          }
2213      }
2214  
2215      /**
2216       * Set the language for error messages.
2217       * The default language is English.
2218       *
2219       * @param string $langcode  ISO 639-1 2-character language code (e.g. French is "fr")
2220       *                          Optionally, the language code can be enhanced with a 4-character
2221       *                          script annotation and/or a 2-character country annotation.
2222       * @param string $lang_path Path to the language file directory, with trailing separator (slash)
2223       *                          Do not set this from user input!
2224       *
2225       * @return bool Returns true if the requested language was loaded, false otherwise.
2226       */
2227      public function setLanguage($langcode = 'en', $lang_path = '')
2228      {
2229          //Backwards compatibility for renamed language codes
2230          $renamed_langcodes = [
2231              'br' => 'pt_br',
2232              'cz' => 'cs',
2233              'dk' => 'da',
2234              'no' => 'nb',
2235              'se' => 'sv',
2236              'rs' => 'sr',
2237              'tg' => 'tl',
2238              'am' => 'hy',
2239          ];
2240  
2241          if (array_key_exists($langcode, $renamed_langcodes)) {
2242              $langcode = $renamed_langcodes[$langcode];
2243          }
2244  
2245          //Define full set of translatable strings in English
2246          $PHPMAILER_LANG = [
2247              'authenticate' => 'SMTP Error: Could not authenticate.',
2248              'buggy_php' => 'Your version of PHP is affected by a bug that may result in corrupted messages.' .
2249                  ' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' .
2250                  ' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.',
2251              'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
2252              'data_not_accepted' => 'SMTP Error: data not accepted.',
2253              'empty_message' => 'Message body empty',
2254              'encoding' => 'Unknown encoding: ',
2255              'execute' => 'Could not execute: ',
2256              'extension_missing' => 'Extension missing: ',
2257              'file_access' => 'Could not access file: ',
2258              'file_open' => 'File Error: Could not open file: ',
2259              'from_failed' => 'The following From address failed: ',
2260              'instantiate' => 'Could not instantiate mail function.',
2261              'invalid_address' => 'Invalid address: ',
2262              'invalid_header' => 'Invalid header name or value',
2263              'invalid_hostentry' => 'Invalid hostentry: ',
2264              'invalid_host' => 'Invalid host: ',
2265              'mailer_not_supported' => ' mailer is not supported.',
2266              'provide_address' => 'You must provide at least one recipient email address.',
2267              'recipients_failed' => 'SMTP Error: The following recipients failed: ',
2268              'signing' => 'Signing Error: ',
2269              'smtp_code' => 'SMTP code: ',
2270              'smtp_code_ex' => 'Additional SMTP info: ',
2271              'smtp_connect_failed' => 'SMTP connect() failed.',
2272              'smtp_detail' => 'Detail: ',
2273              'smtp_error' => 'SMTP server error: ',
2274              'variable_set' => 'Cannot set or reset variable: ',
2275          ];
2276          if (empty($lang_path)) {
2277              //Calculate an absolute path so it can work if CWD is not here
2278              $lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR;
2279          }
2280  
2281          //Validate $langcode
2282          $foundlang = true;
2283          $langcode  = strtolower($langcode);
2284          if (
2285              !preg_match('/^(?P<lang>[a-z]{2})(?P<script>_[a-z]{4})?(?P<country>_[a-z]{2})?$/', $langcode, $matches)
2286              && $langcode !== 'en'
2287          ) {
2288              $foundlang = false;
2289              $langcode = 'en';
2290          }
2291  
2292          //There is no English translation file
2293          if ('en' !== $langcode) {
2294              $langcodes = [];
2295              if (!empty($matches['script']) && !empty($matches['country'])) {
2296                  $langcodes[] = $matches['lang'] . $matches['script'] . $matches['country'];
2297              }
2298              if (!empty($matches['country'])) {
2299                  $langcodes[] = $matches['lang'] . $matches['country'];
2300              }
2301              if (!empty($matches['script'])) {
2302                  $langcodes[] = $matches['lang'] . $matches['script'];
2303              }
2304              $langcodes[] = $matches['lang'];
2305  
2306              //Try and find a readable language file for the requested language.
2307              $foundFile = false;
2308              foreach ($langcodes as $code) {
2309                  $lang_file = $lang_path . 'phpmailer.lang-' . $code . '.php';
2310                  if (static::fileIsAccessible($lang_file)) {
2311                      $foundFile = true;
2312                      break;
2313                  }
2314              }
2315  
2316              if ($foundFile === false) {
2317                  $foundlang = false;
2318              } else {
2319                  $lines = file($lang_file);
2320                  foreach ($lines as $line) {
2321                      //Translation file lines look like this:
2322                      //$PHPMAILER_LANG['authenticate'] = 'SMTP-Fehler: Authentifizierung fehlgeschlagen.';
2323                      //These files are parsed as text and not PHP so as to avoid the possibility of code injection
2324                      //See https://blog.stevenlevithan.com/archives/match-quoted-string
2325                      $matches = [];
2326                      if (
2327                          preg_match(
2328                              '/^\$PHPMAILER_LANG\[\'([a-z\d_]+)\'\]\s*=\s*(["\'])(.+)*?\2;/',
2329                              $line,
2330                              $matches
2331                          ) &&
2332                          //Ignore unknown translation keys
2333                          array_key_exists($matches[1], $PHPMAILER_LANG)
2334                      ) {
2335                          //Overwrite language-specific strings so we'll never have missing translation keys.
2336                          $PHPMAILER_LANG[$matches[1]] = (string)$matches[3];
2337                      }
2338                  }
2339              }
2340          }
2341          $this->language = $PHPMAILER_LANG;
2342  
2343          return $foundlang; //Returns false if language not found
2344      }
2345  
2346      /**
2347       * Get the array of strings for the current language.
2348       *
2349       * @return array
2350       */
2351      public function getTranslations()
2352      {
2353          if (empty($this->language)) {
2354              $this->setLanguage(); // Set the default language.
2355          }
2356  
2357          return $this->language;
2358      }
2359  
2360      /**
2361       * Create recipient headers.
2362       *
2363       * @param string $type
2364       * @param array  $addr An array of recipients,
2365       *                     where each recipient is a 2-element indexed array with element 0 containing an address
2366       *                     and element 1 containing a name, like:
2367       *                     [['[email protected]', 'Joe User'], ['[email protected]', 'Zoe User']]
2368       *
2369       * @return string
2370       */
2371      public function addrAppend($type, $addr)
2372      {
2373          $addresses = [];
2374          foreach ($addr as $address) {
2375              $addresses[] = $this->addrFormat($address);
2376          }
2377  
2378          return $type . ': ' . implode(', ', $addresses) . static::$LE;
2379      }
2380  
2381      /**
2382       * Format an address for use in a message header.
2383       *
2384       * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like
2385       *                    ['[email protected]', 'Joe User']
2386       *
2387       * @return string
2388       */
2389      public function addrFormat($addr)
2390      {
2391          if (empty($addr[1])) { //No name provided
2392              return $this->secureHeader($addr[0]);
2393          }
2394  
2395          return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') .
2396              ' <' . $this->secureHeader($addr[0]) . '>';
2397      }
2398  
2399      /**
2400       * Word-wrap message.
2401       * For use with mailers that do not automatically perform wrapping
2402       * and for quoted-printable encoded messages.
2403       * Original written by philippe.
2404       *
2405       * @param string $message The message to wrap
2406       * @param int    $length  The line length to wrap to
2407       * @param bool   $qp_mode Whether to run in Quoted-Printable mode
2408       *
2409       * @return string
2410       */
2411      public function wrapText($message, $length, $qp_mode = false)
2412      {
2413          if ($qp_mode) {
2414              $soft_break = sprintf(' =%s', static::$LE);
2415          } else {
2416              $soft_break = static::$LE;
2417          }
2418          //If utf-8 encoding is used, we will need to make sure we don't
2419          //split multibyte characters when we wrap
2420          $is_utf8 = static::CHARSET_UTF8 === strtolower($this->CharSet);
2421          $lelen = strlen(static::$LE);
2422          $crlflen = strlen(static::$LE);
2423  
2424          $message = static::normalizeBreaks($message);
2425          //Remove a trailing line break
2426          if (substr($message, -$lelen) === static::$LE) {
2427              $message = substr($message, 0, -$lelen);
2428          }
2429  
2430          //Split message into lines
2431          $lines = explode(static::$LE, $message);
2432          //Message will be rebuilt in here
2433          $message = '';
2434          foreach ($lines as $line) {
2435              $words = explode(' ', $line);
2436              $buf = '';
2437              $firstword = true;
2438              foreach ($words as $word) {
2439                  if ($qp_mode && (strlen($word) > $length)) {
2440                      $space_left = $length - strlen($buf) - $crlflen;
2441                      if (!$firstword) {
2442                          if ($space_left > 20) {
2443                              $len = $space_left;
2444                              if ($is_utf8) {
2445                                  $len = $this->utf8CharBoundary($word, $len);
2446                              } elseif ('=' === substr($word, $len - 1, 1)) {
2447                                  --$len;
2448                              } elseif ('=' === substr($word, $len - 2, 1)) {
2449                                  $len -= 2;
2450                              }
2451                              $part = substr($word, 0, $len);
2452                              $word = substr($word, $len);
2453                              $buf .= ' ' . $part;
2454                              $message .= $buf . sprintf('=%s', static::$LE);
2455                          } else {
2456                              $message .= $buf . $soft_break;
2457                          }
2458                          $buf = '';
2459                      }
2460                      while ($word !== '') {
2461                          if ($length <= 0) {
2462                              break;
2463                          }
2464                          $len = $length;
2465                          if ($is_utf8) {
2466                              $len = $this->utf8CharBoundary($word, $len);
2467                          } elseif ('=' === substr($word, $len - 1, 1)) {
2468                              --$len;
2469                          } elseif ('=' === substr($word, $len - 2, 1)) {
2470                              $len -= 2;
2471                          }
2472                          $part = substr($word, 0, $len);
2473                          $word = (string) substr($word, $len);
2474  
2475                          if ($word !== '') {
2476                              $message .= $part . sprintf('=%s', static::$LE);
2477                          } else {
2478                              $buf = $part;
2479                          }
2480                      }
2481                  } else {
2482                      $buf_o = $buf;
2483                      if (!$firstword) {
2484                          $buf .= ' ';
2485                      }
2486                      $buf .= $word;
2487  
2488                      if ('' !== $buf_o && strlen($buf) > $length) {
2489                          $message .= $buf_o . $soft_break;
2490                          $buf = $word;
2491                      }
2492                  }
2493                  $firstword = false;
2494              }
2495              $message .= $buf . static::$LE;
2496          }
2497  
2498          return $message;
2499      }
2500  
2501      /**
2502       * Find the last character boundary prior to $maxLength in a utf-8
2503       * quoted-printable encoded string.
2504       * Original written by Colin Brown.
2505       *
2506       * @param string $encodedText utf-8 QP text
2507       * @param int    $maxLength   Find the last character boundary prior to this length
2508       *
2509       * @return int
2510       */
2511      public function utf8CharBoundary($encodedText, $maxLength)
2512      {
2513          $foundSplitPos = false;
2514          $lookBack = 3;
2515          while (!$foundSplitPos) {
2516              $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
2517              $encodedCharPos = strpos($lastChunk, '=');
2518              if (false !== $encodedCharPos) {
2519                  //Found start of encoded character byte within $lookBack block.
2520                  //Check the encoded byte value (the 2 chars after the '=')
2521                  $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
2522                  $dec = hexdec($hex);
2523                  if ($dec < 128) {
2524                      //Single byte character.
2525                      //If the encoded char was found at pos 0, it will fit
2526                      //otherwise reduce maxLength to start of the encoded char
2527                      if ($encodedCharPos > 0) {
2528                          $maxLength -= $lookBack - $encodedCharPos;
2529                      }
2530                      $foundSplitPos = true;
2531                  } elseif ($dec >= 192) {
2532                      //First byte of a multi byte character
2533                      //Reduce maxLength to split at start of character
2534                      $maxLength -= $lookBack - $encodedCharPos;
2535                      $foundSplitPos = true;
2536                  } elseif ($dec < 192) {
2537                      //Middle byte of a multi byte character, look further back
2538                      $lookBack += 3;
2539                  }
2540              } else {
2541                  //No encoded character found
2542                  $foundSplitPos = true;
2543              }
2544          }
2545  
2546          return $maxLength;
2547      }
2548  
2549      /**
2550       * Apply word wrapping to the message body.
2551       * Wraps the message body to the number of chars set in the WordWrap property.
2552       * You should only do this to plain-text bodies as wrapping HTML tags may break them.
2553       * This is called automatically by createBody(), so you don't need to call it yourself.
2554       */
2555      public function setWordWrap()
2556      {
2557          if ($this->WordWrap < 1) {
2558              return;
2559          }
2560  
2561          switch ($this->message_type) {
2562              case 'alt':
2563              case 'alt_inline':
2564              case 'alt_attach':
2565              case 'alt_inline_attach':
2566                  $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
2567                  break;
2568              default:
2569                  $this->Body = $this->wrapText($this->Body, $this->WordWrap);
2570                  break;
2571          }
2572      }
2573  
2574      /**
2575       * Assemble message headers.
2576       *
2577       * @return string The assembled headers
2578       */
2579      public function createHeader()
2580      {
2581          $result = '';
2582  
2583          $result .= $this->headerLine('Date', '' === $this->MessageDate ? self::rfcDate() : $this->MessageDate);
2584  
2585          //The To header is created automatically by mail(), so needs to be omitted here
2586          if ('mail' !== $this->Mailer) {
2587              if ($this->SingleTo) {
2588                  foreach ($this->to as $toaddr) {
2589                      $this->SingleToArray[] = $this->addrFormat($toaddr);
2590                  }
2591              } elseif (count($this->to) > 0) {
2592                  $result .= $this->addrAppend('To', $this->to);
2593              } elseif (count($this->cc) === 0) {
2594                  $result .= $this->headerLine('To', 'undisclosed-recipients:;');
2595              }
2596          }
2597          $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]);
2598  
2599          //sendmail and mail() extract Cc from the header before sending
2600          if (count($this->cc) > 0) {
2601              $result .= $this->addrAppend('Cc', $this->cc);
2602          }
2603  
2604          //sendmail and mail() extract Bcc from the header before sending
2605          if (
2606              (
2607                  'sendmail' === $this->Mailer || 'qmail' === $this->Mailer || 'mail' === $this->Mailer
2608              )
2609              && count($this->bcc) > 0
2610          ) {
2611              $result .= $this->addrAppend('Bcc', $this->bcc);
2612          }
2613  
2614          if (count($this->ReplyTo) > 0) {
2615              $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
2616          }
2617  
2618          //mail() sets the subject itself
2619          if ('mail' !== $this->Mailer) {
2620              $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
2621          }
2622  
2623          //Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
2624          //https://tools.ietf.org/html/rfc5322#section-3.6.4
2625          if (
2626              '' !== $this->MessageID &&
2627              preg_match(
2628                  '/^<((([a-z\d!#$%&\'*+\/=?^_`{|}~-]+(\.[a-z\d!#$%&\'*+\/=?^_`{|}~-]+)*)' .
2629                  '|("(([\x01-\x08\x0B\x0C\x0E-\x1F\x7F]|[\x21\x23-\x5B\x5D-\x7E])' .
2630                  '|(\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*"))@(([a-z\d!#$%&\'*+\/=?^_`{|}~-]+' .
2631                  '(\.[a-z\d!#$%&\'*+\/=?^_`{|}~-]+)*)|(\[(([\x01-\x08\x0B\x0C\x0E-\x1F\x7F]' .
2632                  '|[\x21-\x5A\x5E-\x7E])|(\\[\x01-\x09\x0B\x0C\x0E-\x7F]))*\])))>$/Di',
2633                  $this->MessageID
2634              )
2635          ) {
2636              $this->lastMessageID = $this->MessageID;
2637          } else {
2638              $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
2639          }
2640          $result .= $this->headerLine('Message-ID', $this->lastMessageID);
2641          if (null !== $this->Priority) {
2642              $result .= $this->headerLine('X-Priority', $this->Priority);
2643          }
2644          if ('' === $this->XMailer) {
2645              //Empty string for default X-Mailer header
2646              $result .= $this->headerLine(
2647                  'X-Mailer',
2648                  'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)'
2649              );
2650          } elseif (is_string($this->XMailer) && trim($this->XMailer) !== '') {
2651              //Some string
2652              $result .= $this->headerLine('X-Mailer', trim($this->XMailer));
2653          } //Other values result in no X-Mailer header
2654  
2655          if ('' !== $this->ConfirmReadingTo) {
2656              $result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
2657          }
2658  
2659          //Add custom headers
2660          foreach ($this->CustomHeader as $header) {
2661              $result .= $this->headerLine(
2662                  trim($header[0]),
2663                  $this->encodeHeader(trim($header[1]))
2664              );
2665          }
2666          if (!$this->sign_key_file) {
2667              $result .= $this->headerLine('MIME-Version', '1.0');
2668              $result .= $this->getMailMIME();
2669          }
2670  
2671          return $result;
2672      }
2673  
2674      /**
2675       * Get the message MIME type headers.
2676       *
2677       * @return string
2678       */
2679      public function getMailMIME()
2680      {
2681          $result = '';
2682          $ismultipart = true;
2683          switch ($this->message_type) {
2684              case 'inline':
2685                  $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2686                  $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2687                  break;
2688              case 'attach':
2689              case 'inline_attach':
2690              case 'alt_attach':
2691              case 'alt_inline_attach':
2692                  $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_MIXED . ';');
2693                  $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2694                  break;
2695              case 'alt':
2696              case 'alt_inline':
2697                  $result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
2698                  $result .= $this->textLine(' boundary="' . $this->boundary[1] . '"');
2699                  break;
2700              default:
2701                  //Catches case 'plain': and case '':
2702                  $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
2703                  $ismultipart = false;
2704                  break;
2705          }
2706          //RFC1341 part 5 says 7bit is assumed if not specified
2707          if (static::ENCODING_7BIT !== $this->Encoding) {
2708              //RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
2709              if ($ismultipart) {
2710                  if (static::ENCODING_8BIT === $this->Encoding) {
2711                      $result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT);
2712                  }
2713                  //The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
2714              } else {
2715                  $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
2716              }
2717          }
2718  
2719          return $result;
2720      }
2721  
2722      /**
2723       * Returns the whole MIME message.
2724       * Includes complete headers and body.
2725       * Only valid post preSend().
2726       *
2727       * @see PHPMailer::preSend()
2728       *
2729       * @return string
2730       */
2731      public function getSentMIMEMessage()
2732      {
2733          return static::stripTrailingWSP($this->MIMEHeader . $this->mailHeader) .
2734              static::$LE . static::$LE . $this->MIMEBody;
2735      }
2736  
2737      /**
2738       * Create a unique ID to use for boundaries.
2739       *
2740       * @return string
2741       */
2742      protected function generateId()
2743      {
2744          $len = 32; //32 bytes = 256 bits
2745          $bytes = '';
2746          if (function_exists('random_bytes')) {
2747              try {
2748                  $bytes = random_bytes($len);
2749              } catch (\Exception $e) {
2750                  //Do nothing
2751              }
2752          } elseif (function_exists('openssl_random_pseudo_bytes')) {
2753              /** @noinspection CryptographicallySecureRandomnessInspection */
2754              $bytes = openssl_random_pseudo_bytes($len);
2755          }
2756          if ($bytes === '') {
2757              //We failed to produce a proper random string, so make do.
2758              //Use a hash to force the length to the same as the other methods
2759              $bytes = hash('sha256', uniqid((string) mt_rand(), true), true);
2760          }
2761  
2762          //We don't care about messing up base64 format here, just want a random string
2763          return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true)));
2764      }
2765  
2766      /**
2767       * Assemble the message body.
2768       * Returns an empty string on failure.
2769       *
2770       * @throws Exception
2771       *
2772       * @return string The assembled message body
2773       */
2774      public function createBody()
2775      {
2776          $body = '';
2777          //Create unique IDs and preset boundaries
2778          $this->uniqueid = $this->generateId();
2779          $this->boundary[1] = 'b1_' . $this->uniqueid;
2780          $this->boundary[2] = 'b2_' . $this->uniqueid;
2781          $this->boundary[3] = 'b3_' . $this->uniqueid;
2782  
2783          if ($this->sign_key_file) {
2784              $body .= $this->getMailMIME() . static::$LE;
2785          }
2786  
2787          $this->setWordWrap();
2788  
2789          $bodyEncoding = $this->Encoding;
2790          $bodyCharSet = $this->CharSet;
2791          //Can we do a 7-bit downgrade?
2792          if (static::ENCODING_8BIT === $bodyEncoding && !$this->has8bitChars($this->Body)) {
2793              $bodyEncoding = static::ENCODING_7BIT;
2794              //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2795              $bodyCharSet = static::CHARSET_ASCII;
2796          }
2797          //If lines are too long, and we're not already using an encoding that will shorten them,
2798          //change to quoted-printable transfer encoding for the body part only
2799          if (static::ENCODING_BASE64 !== $this->Encoding && static::hasLineLongerThanMax($this->Body)) {
2800              $bodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
2801          }
2802  
2803          $altBodyEncoding = $this->Encoding;
2804          $altBodyCharSet = $this->CharSet;
2805          //Can we do a 7-bit downgrade?
2806          if (static::ENCODING_8BIT === $altBodyEncoding && !$this->has8bitChars($this->AltBody)) {
2807              $altBodyEncoding = static::ENCODING_7BIT;
2808              //All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
2809              $altBodyCharSet = static::CHARSET_ASCII;
2810          }
2811          //If lines are too long, and we're not already using an encoding that will shorten them,
2812          //change to quoted-printable transfer encoding for the alt body part only
2813          if (static::ENCODING_BASE64 !== $altBodyEncoding && static::hasLineLongerThanMax($this->AltBody)) {
2814              $altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
2815          }
2816          //Use this as a preamble in all multipart message types
2817          $mimepre = 'This is a multi-part message in MIME format.' . static::$LE . static::$LE;
2818          switch ($this->message_type) {
2819              case 'inline':
2820                  $body .= $mimepre;
2821                  $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2822                  $body .= $this->encodeString($this->Body, $bodyEncoding);
2823                  $body .= static::$LE;
2824                  $body .= $this->attachAll('inline', $this->boundary[1]);
2825                  break;
2826              case 'attach':
2827                  $body .= $mimepre;
2828                  $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
2829                  $body .= $this->encodeString($this->Body, $bodyEncoding);
2830                  $body .= static::$LE;
2831                  $body .= $this->attachAll('attachment', $this->boundary[1]);
2832                  break;
2833              case 'inline_attach':
2834                  $body .= $mimepre;
2835                  $body .= $this->textLine('--' . $this->boundary[1]);
2836                  $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2837                  $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";');
2838                  $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
2839                  $body .= static::$LE;
2840                  $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
2841                  $body .= $this->encodeString($this->Body, $bodyEncoding);
2842                  $body .= static::$LE;
2843                  $body .= $this->attachAll('inline', $this->boundary[2]);
2844                  $body .= static::$LE;
2845                  $body .= $this->attachAll('attachment', $this->boundary[1]);
2846                  break;
2847              case 'alt':
2848                  $body .= $mimepre;
2849                  $body .= $this->getBoundary(
2850                      $this->boundary[1],
2851                      $altBodyCharSet,
2852                      static::CONTENT_TYPE_PLAINTEXT,
2853                      $altBodyEncoding
2854                  );
2855                  $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2856                  $body .= static::$LE;
2857                  $body .= $this->getBoundary(
2858                      $this->boundary[1],
2859                      $bodyCharSet,
2860                      static::CONTENT_TYPE_TEXT_HTML,
2861                      $bodyEncoding
2862                  );
2863                  $body .= $this->encodeString($this->Body, $bodyEncoding);
2864                  $body .= static::$LE;
2865                  if (!empty($this->Ical)) {
2866                      $method = static::ICAL_METHOD_REQUEST;
2867                      foreach (static::$IcalMethods as $imethod) {
2868                          if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) {
2869                              $method = $imethod;
2870                              break;
2871                          }
2872                      }
2873                      $body .= $this->getBoundary(
2874                          $this->boundary[1],
2875                          '',
2876                          static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method,
2877                          ''
2878                      );
2879                      $body .= $this->encodeString($this->Ical, $this->Encoding);
2880                      $body .= static::$LE;
2881                  }
2882                  $body .= $this->endBoundary($this->boundary[1]);
2883                  break;
2884              case 'alt_inline':
2885                  $body .= $mimepre;
2886                  $body .= $this->getBoundary(
2887                      $this->boundary[1],
2888                      $altBodyCharSet,
2889                      static::CONTENT_TYPE_PLAINTEXT,
2890                      $altBodyEncoding
2891                  );
2892                  $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2893                  $body .= static::$LE;
2894                  $body .= $this->textLine('--' . $this->boundary[1]);
2895                  $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2896                  $body .= $this->textLine(' boundary="' . $this->boundary[2] . '";');
2897                  $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
2898                  $body .= static::$LE;
2899                  $body .= $this->getBoundary(
2900                      $this->boundary[2],
2901                      $bodyCharSet,
2902                      static::CONTENT_TYPE_TEXT_HTML,
2903                      $bodyEncoding
2904                  );
2905                  $body .= $this->encodeString($this->Body, $bodyEncoding);
2906                  $body .= static::$LE;
2907                  $body .= $this->attachAll('inline', $this->boundary[2]);
2908                  $body .= static::$LE;
2909                  $body .= $this->endBoundary($this->boundary[1]);
2910                  break;
2911              case 'alt_attach':
2912                  $body .= $mimepre;
2913                  $body .= $this->textLine('--' . $this->boundary[1]);
2914                  $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
2915                  $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"');
2916                  $body .= static::$LE;
2917                  $body .= $this->getBoundary(
2918                      $this->boundary[2],
2919                      $altBodyCharSet,
2920                      static::CONTENT_TYPE_PLAINTEXT,
2921                      $altBodyEncoding
2922                  );
2923                  $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2924                  $body .= static::$LE;
2925                  $body .= $this->getBoundary(
2926                      $this->boundary[2],
2927                      $bodyCharSet,
2928                      static::CONTENT_TYPE_TEXT_HTML,
2929                      $bodyEncoding
2930                  );
2931                  $body .= $this->encodeString($this->Body, $bodyEncoding);
2932                  $body .= static::$LE;
2933                  if (!empty($this->Ical)) {
2934                      $method = static::ICAL_METHOD_REQUEST;
2935                      foreach (static::$IcalMethods as $imethod) {
2936                          if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) {
2937                              $method = $imethod;
2938                              break;
2939                          }
2940                      }
2941                      $body .= $this->getBoundary(
2942                          $this->boundary[2],
2943                          '',
2944                          static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method,
2945                          ''
2946                      );
2947                      $body .= $this->encodeString($this->Ical, $this->Encoding);
2948                  }
2949                  $body .= $this->endBoundary($this->boundary[2]);
2950                  $body .= static::$LE;
2951                  $body .= $this->attachAll('attachment', $this->boundary[1]);
2952                  break;
2953              case 'alt_inline_attach':
2954                  $body .= $mimepre;
2955                  $body .= $this->textLine('--' . $this->boundary[1]);
2956                  $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
2957                  $body .= $this->textLine(' boundary="' . $this->boundary[2] . '"');
2958                  $body .= static::$LE;
2959                  $body .= $this->getBoundary(
2960                      $this->boundary[2],
2961                      $altBodyCharSet,
2962                      static::CONTENT_TYPE_PLAINTEXT,
2963                      $altBodyEncoding
2964                  );
2965                  $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
2966                  $body .= static::$LE;
2967                  $body .= $this->textLine('--' . $this->boundary[2]);
2968                  $body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
2969                  $body .= $this->textLine(' boundary="' . $this->boundary[3] . '";');
2970                  $body .= $this->textLine(' type="' . static::CONTENT_TYPE_TEXT_HTML . '"');
2971                  $body .= static::$LE;
2972                  $body .= $this->getBoundary(
2973                      $this->boundary[3],
2974                      $bodyCharSet,
2975                      static::CONTENT_TYPE_TEXT_HTML,
2976                      $bodyEncoding
2977                  );
2978                  $body .= $this->encodeString($this->Body, $bodyEncoding);
2979                  $body .= static::$LE;
2980                  $body .= $this->attachAll('inline', $this->boundary[3]);
2981                  $body .= static::$LE;
2982                  $body .= $this->endBoundary($this->boundary[2]);
2983                  $body .= static::$LE;
2984                  $body .= $this->attachAll('attachment', $this->boundary[1]);
2985                  break;
2986              default:
2987                  //Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
2988                  //Reset the `Encoding` property in case we changed it for line length reasons
2989                  $this->Encoding = $bodyEncoding;
2990                  $body .= $this->encodeString($this->Body, $this->Encoding);
2991                  break;
2992          }
2993  
2994          if ($this->isError()) {
2995              $body = '';
2996              if ($this->exceptions) {
2997                  throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
2998              }
2999          } elseif ($this->sign_key_file) {
3000              try {
3001                  if (!defined('PKCS7_TEXT')) {
3002                      throw new Exception($this->lang('extension_missing') . 'openssl');
3003                  }
3004  
3005                  $file = tempnam(sys_get_temp_dir(), 'srcsign');
3006                  $signed = tempnam(sys_get_temp_dir(), 'mailsign');
3007                  file_put_contents($file, $body);
3008  
3009                  //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
3010                  if (empty($this->sign_extracerts_file)) {
3011                      $sign = @openssl_pkcs7_sign(
3012                          $file,
3013                          $signed,
3014                          'file://' . realpath($this->sign_cert_file),
3015                          ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
3016                          []
3017                      );
3018                  } else {
3019                      $sign = @openssl_pkcs7_sign(
3020                          $file,
3021                          $signed,
3022                          'file://' . realpath($this->sign_cert_file),
3023                          ['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
3024                          [],
3025                          PKCS7_DETACHED,
3026                          $this->sign_extracerts_file
3027                      );
3028                  }
3029  
3030                  @unlink($file);
3031                  if ($sign) {
3032                      $body = file_get_contents($signed);
3033                      @unlink($signed);
3034                      //The message returned by openssl contains both headers and body, so need to split them up
3035                      $parts = explode("\n\n", $body, 2);
3036                      $this->MIMEHeader .= $parts[0] . static::$LE . static::$LE;
3037                      $body = $parts[1];
3038                  } else {
3039                      @unlink($signed);
3040                      throw new Exception($this->lang('signing') . openssl_error_string());
3041                  }
3042              } catch (Exception $exc) {
3043                  $body = '';
3044                  if ($this->exceptions) {
3045                      throw $exc;
3046                  }
3047              }
3048          }
3049  
3050          return $body;
3051      }
3052  
3053      /**
3054       * Return the start of a message boundary.
3055       *
3056       * @param string $boundary
3057       * @param string $charSet
3058       * @param string $contentType
3059       * @param string $encoding
3060       *
3061       * @return string
3062       */
3063      protected function getBoundary($boundary, $charSet, $contentType, $encoding)
3064      {
3065          $result = '';
3066          if ('' === $charSet) {
3067              $charSet = $this->CharSet;
3068          }
3069          if ('' === $contentType) {
3070              $contentType = $this->ContentType;
3071          }
3072          if ('' === $encoding) {
3073              $encoding = $this->Encoding;
3074          }
3075          $result .= $this->textLine('--' . $boundary);
3076          $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
3077          $result .= static::$LE;
3078          //RFC1341 part 5 says 7bit is assumed if not specified
3079          if (static::ENCODING_7BIT !== $encoding) {
3080              $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
3081          }
3082          $result .= static::$LE;
3083  
3084          return $result;
3085      }
3086  
3087      /**
3088       * Return the end of a message boundary.
3089       *
3090       * @param string $boundary
3091       *
3092       * @return string
3093       */
3094      protected function endBoundary($boundary)
3095      {
3096          return static::$LE . '--' . $boundary . '--' . static::$LE;
3097      }
3098  
3099      /**
3100       * Set the message type.
3101       * PHPMailer only supports some preset message types, not arbitrary MIME structures.
3102       */
3103      protected function setMessageType()
3104      {
3105          $type = [];
3106          if ($this->alternativeExists()) {
3107              $type[] = 'alt';
3108          }
3109          if ($this->inlineImageExists()) {
3110              $type[] = 'inline';
3111          }
3112          if ($this->attachmentExists()) {
3113              $type[] = 'attach';
3114          }
3115          $this->message_type = implode('_', $type);
3116          if ('' === $this->message_type) {
3117              //The 'plain' message_type refers to the message having a single body element, not that it is plain-text
3118              $this->message_type = 'plain';
3119          }
3120      }
3121  
3122      /**
3123       * Format a header line.
3124       *
3125       * @param string     $name
3126       * @param string|int $value
3127       *
3128       * @return string
3129       */
3130      public function headerLine($name, $value)
3131      {
3132          return $name . ': ' . $value . static::$LE;
3133      }
3134  
3135      /**
3136       * Return a formatted mail line.
3137       *
3138       * @param string $value
3139       *
3140       * @return string
3141       */
3142      public function textLine($value)
3143      {
3144          return $value . static::$LE;
3145      }
3146  
3147      /**
3148       * Add an attachment from a path on the filesystem.
3149       * Never use a user-supplied path to a file!
3150       * Returns false if the file could not be found or read.
3151       * Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client.
3152       * If you need to do that, fetch the resource yourself and pass it in via a local file or string.
3153       *
3154       * @param string $path        Path to the attachment
3155       * @param string $name        Overrides the attachment name
3156       * @param string $encoding    File encoding (see $Encoding)
3157       * @param string $type        MIME type, e.g. `image/jpeg`; determined automatically from $path if not specified
3158       * @param string $disposition Disposition to use
3159       *
3160       * @throws Exception
3161       *
3162       * @return bool
3163       */
3164      public function addAttachment(
3165          $path,
3166          $name = '',
3167          $encoding = self::ENCODING_BASE64,
3168          $type = '',
3169          $disposition = 'attachment'
3170      ) {
3171          try {
3172              if (!static::fileIsAccessible($path)) {
3173                  throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
3174              }
3175  
3176              //If a MIME type is not specified, try to work it out from the file name
3177              if ('' === $type) {
3178                  $type = static::filenameToType($path);
3179              }
3180  
3181              $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME);
3182              if ('' === $name) {
3183                  $name = $filename;
3184              }
3185              if (!$this->validateEncoding($encoding)) {
3186                  throw new Exception($this->lang('encoding') . $encoding);
3187              }
3188  
3189              $this->attachment[] = [
3190                  0 => $path,
3191                  1 => $filename,
3192                  2 => $name,
3193                  3 => $encoding,
3194                  4 => $type,
3195                  5 => false, //isStringAttachment
3196                  6 => $disposition,
3197                  7 => $name,
3198              ];
3199          } catch (Exception $exc) {
3200              $this->setError($exc->getMessage());
3201              $this->edebug($exc->getMessage());
3202              if ($this->exceptions) {
3203                  throw $exc;
3204              }
3205  
3206              return false;
3207          }
3208  
3209          return true;
3210      }
3211  
3212      /**
3213       * Return the array of attachments.
3214       *
3215       * @return array
3216       */
3217      public function getAttachments()
3218      {
3219          return $this->attachment;
3220      }
3221  
3222      /**
3223       * Attach all file, string, and binary attachments to the message.
3224       * Returns an empty string on failure.
3225       *
3226       * @param string $disposition_type
3227       * @param string $boundary
3228       *
3229       * @throws Exception
3230       *
3231       * @return string
3232       */
3233      protected function attachAll($disposition_type, $boundary)
3234      {
3235          //Return text of body
3236          $mime = [];
3237          $cidUniq = [];
3238          $incl = [];
3239  
3240          //Add all attachments
3241          foreach ($this->attachment as $attachment) {
3242              //Check if it is a valid disposition_filter
3243              if ($attachment[6] === $disposition_type) {
3244                  //Check for string attachment
3245                  $string = '';
3246                  $path = '';
3247                  $bString = $attachment[5];
3248                  if ($bString) {
3249                      $string = $attachment[0];
3250                  } else {
3251                      $path = $attachment[0];
3252                  }
3253  
3254                  $inclhash = hash('sha256', serialize($attachment));
3255                  if (in_array($inclhash, $incl, true)) {
3256                      continue;
3257                  }
3258                  $incl[] = $inclhash;
3259                  $name = $attachment[2];
3260                  $encoding = $attachment[3];
3261                  $type = $attachment[4];
3262                  $disposition = $attachment[6];
3263                  $cid = $attachment[7];
3264                  if ('inline' === $disposition && array_key_exists($cid, $cidUniq)) {
3265                      continue;
3266                  }
3267                  $cidUniq[$cid] = true;
3268  
3269                  $mime[] = sprintf('--%s%s', $boundary, static::$LE);
3270                  //Only include a filename property if we have one
3271                  if (!empty($name)) {
3272                      $mime[] = sprintf(
3273                          'Content-Type: %s; name=%s%s',
3274                          $type,
3275                          static::quotedString($this->encodeHeader($this->secureHeader($name))),
3276                          static::$LE
3277                      );
3278                  } else {
3279                      $mime[] = sprintf(
3280                          'Content-Type: %s%s',
3281                          $type,
3282                          static::$LE
3283                      );
3284                  }
3285                  //RFC1341 part 5 says 7bit is assumed if not specified
3286                  if (static::ENCODING_7BIT !== $encoding) {
3287                      $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE);
3288                  }
3289  
3290                  //Only set Content-IDs on inline attachments
3291                  if ((string) $cid !== '' && $disposition === 'inline') {
3292                      $mime[] = 'Content-ID: <' . $this->encodeHeader($this->secureHeader($cid)) . '>' . static::$LE;
3293                  }
3294  
3295                  //Allow for bypassing the Content-Disposition header
3296                  if (!empty($disposition)) {
3297                      $encoded_name = $this->encodeHeader($this->secureHeader($name));
3298                      if (!empty($encoded_name)) {
3299                          $mime[] = sprintf(
3300                              'Content-Disposition: %s; filename=%s%s',
3301                              $disposition,
3302                              static::quotedString($encoded_name),
3303                              static::$LE . static::$LE
3304                          );
3305                      } else {
3306                          $mime[] = sprintf(
3307                              'Content-Disposition: %s%s',
3308                              $disposition,
3309                              static::$LE . static::$LE
3310                          );
3311                      }
3312                  } else {
3313                      $mime[] = static::$LE;
3314                  }
3315  
3316                  //Encode as string attachment
3317                  if ($bString) {
3318                      $mime[] = $this->encodeString($string, $encoding);
3319                  } else {
3320                      $mime[] = $this->encodeFile($path, $encoding);
3321                  }
3322                  if ($this->isError()) {
3323                      return '';
3324                  }
3325                  $mime[] = static::$LE;
3326              }
3327          }
3328  
3329          $mime[] = sprintf('--%s--%s', $boundary, static::$LE);
3330  
3331          return implode('', $mime);
3332      }
3333  
3334      /**
3335       * Encode a file attachment in requested format.
3336       * Returns an empty string on failure.
3337       *
3338       * @param string $path     The full path to the file
3339       * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
3340       *
3341       * @return string
3342       */
3343      protected function encodeFile($path, $encoding = self::ENCODING_BASE64)
3344      {
3345          try {
3346              if (!static::fileIsAccessible($path)) {
3347                  throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
3348              }
3349              $file_buffer = file_get_contents($path);
3350              if (false === $file_buffer) {
3351                  throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
3352              }
3353              $file_buffer = $this->encodeString($file_buffer, $encoding);
3354  
3355              return $file_buffer;
3356          } catch (Exception $exc) {
3357              $this->setError($exc->getMessage());
3358              $this->edebug($exc->getMessage());
3359              if ($this->exceptions) {
3360                  throw $exc;
3361              }
3362  
3363              return '';
3364          }
3365      }
3366  
3367      /**
3368       * Encode a string in requested format.
3369       * Returns an empty string on failure.
3370       *
3371       * @param string $str      The text to encode
3372       * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
3373       *
3374       * @throws Exception
3375       *
3376       * @return string
3377       */
3378      public function encodeString($str, $encoding = self::ENCODING_BASE64)
3379      {
3380          $encoded = '';
3381          switch (strtolower($encoding)) {
3382              case static::ENCODING_BASE64:
3383                  $encoded = chunk_split(
3384                      base64_encode($str),
3385                      static::STD_LINE_LENGTH,
3386                      static::$LE
3387                  );
3388                  break;
3389              case static::ENCODING_7BIT:
3390              case static::ENCODING_8BIT:
3391                  $encoded = static::normalizeBreaks($str);
3392                  //Make sure it ends with a line break
3393                  if (substr($encoded, -(strlen(static::$LE))) !== static::$LE) {
3394                      $encoded .= static::$LE;
3395                  }
3396                  break;
3397              case static::ENCODING_BINARY:
3398                  $encoded = $str;
3399                  break;
3400              case static::ENCODING_QUOTED_PRINTABLE:
3401                  $encoded = $this->encodeQP($str);
3402                  break;
3403              default:
3404                  $this->setError($this->lang('encoding') . $encoding);
3405                  if ($this->exceptions) {
3406                      throw new Exception($this->lang('encoding') . $encoding);
3407                  }
3408                  break;
3409          }
3410  
3411          return $encoded;
3412      }
3413  
3414      /**
3415       * Encode a header value (not including its label) optimally.
3416       * Picks shortest of Q, B, or none. Result includes folding if needed.
3417       * See RFC822 definitions for phrase, comment and text positions.
3418       *
3419       * @param string $str      The header value to encode
3420       * @param string $position What context the string will be used in
3421       *
3422       * @return string
3423       */
3424      public function encodeHeader($str, $position = 'text')
3425      {
3426          $matchcount = 0;
3427          switch (strtolower($position)) {
3428              case 'phrase':
3429                  if (!preg_match('/[\200-\377]/', $str)) {
3430                      //Can't use addslashes as we don't know the value of magic_quotes_sybase
3431                      $encoded = addcslashes($str, "\0..\37\177\\\"");
3432                      if (($str === $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
3433                          return $encoded;
3434                      }
3435  
3436                      return "\"$encoded\"";
3437                  }
3438                  $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
3439                  break;
3440              /* @noinspection PhpMissingBreakStatementInspection */
3441              case 'comment':
3442                  $matchcount = preg_match_all('/[()"]/', $str, $matches);
3443              //fallthrough
3444              case 'text':
3445              default:
3446                  $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
3447                  break;
3448          }
3449  
3450          if ($this->has8bitChars($str)) {
3451              $charset = $this->CharSet;
3452          } else {
3453              $charset = static::CHARSET_ASCII;
3454          }
3455  
3456          //Q/B encoding adds 8 chars and the charset ("` =?<charset>?[QB]?<content>?=`").
3457          $overhead = 8 + strlen($charset);
3458  
3459          if ('mail' === $this->Mailer) {
3460              $maxlen = static::MAIL_MAX_LINE_LENGTH - $overhead;
3461          } else {
3462              $maxlen = static::MAX_LINE_LENGTH - $overhead;
3463          }
3464  
3465          //Select the encoding that produces the shortest output and/or prevents corruption.
3466          if ($matchcount > strlen($str) / 3) {
3467              //More than 1/3 of the content needs encoding, use B-encode.
3468              $encoding = 'B';
3469          } elseif ($matchcount > 0) {
3470              //Less than 1/3 of the content needs encoding, use Q-encode.
3471              $encoding = 'Q';
3472          } elseif (strlen($str) > $maxlen) {
3473              //No encoding needed, but value exceeds max line length, use Q-encode to prevent corruption.
3474              $encoding = 'Q';
3475          } else {
3476              //No reformatting needed
3477              $encoding = false;
3478          }
3479  
3480          switch ($encoding) {
3481              case 'B':
3482                  if ($this->hasMultiBytes($str)) {
3483                      //Use a custom function which correctly encodes and wraps long
3484                      //multibyte strings without breaking lines within a character
3485                      $encoded = $this->base64EncodeWrapMB($str, "\n");
3486                  } else {
3487                      $encoded = base64_encode($str);
3488                      $maxlen -= $maxlen % 4;
3489                      $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
3490                  }
3491                  $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded);
3492                  break;
3493              case 'Q':
3494                  $encoded = $this->encodeQ($str, $position);
3495                  $encoded = $this->wrapText($encoded, $maxlen, true);
3496                  $encoded = str_replace('=' . static::$LE, "\n", trim($encoded));
3497                  $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded);
3498                  break;
3499              default:
3500                  return $str;
3501          }
3502  
3503          return trim(static::normalizeBreaks($encoded));
3504      }
3505  
3506      /**
3507       * Check if a string contains multi-byte characters.
3508       *
3509       * @param string $str multi-byte text to wrap encode
3510       *
3511       * @return bool
3512       */
3513      public function hasMultiBytes($str)
3514      {
3515          if (function_exists('mb_strlen')) {
3516              return strlen($str) > mb_strlen($str, $this->CharSet);
3517          }
3518  
3519          //Assume no multibytes (we can't handle without mbstring functions anyway)
3520          return false;
3521      }
3522  
3523      /**
3524       * Does a string contain any 8-bit chars (in any charset)?
3525       *
3526       * @param string $text
3527       *
3528       * @return bool
3529       */
3530      public function has8bitChars($text)
3531      {
3532          return (bool) preg_match('/[\x80-\xFF]/', $text);
3533      }
3534  
3535      /**
3536       * Encode and wrap long multibyte strings for mail headers
3537       * without breaking lines within a character.
3538       * Adapted from a function by paravoid.
3539       *
3540       * @see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
3541       *
3542       * @param string $str       multi-byte text to wrap encode
3543       * @param string $linebreak string to use as linefeed/end-of-line
3544       *
3545       * @return string
3546       */
3547      public function base64EncodeWrapMB($str, $linebreak = null)
3548      {
3549          $start = '=?' . $this->CharSet . '?B?';
3550          $end = '?=';
3551          $encoded = '';
3552          if (null === $linebreak) {
3553              $linebreak = static::$LE;
3554          }
3555  
3556          $mb_length = mb_strlen($str, $this->CharSet);
3557          //Each line must have length <= 75, including $start and $end
3558          $length = 75 - strlen($start) - strlen($end);
3559          //Average multi-byte ratio
3560          $ratio = $mb_length / strlen($str);
3561          //Base64 has a 4:3 ratio
3562          $avgLength = floor($length * $ratio * .75);
3563  
3564          $offset = 0;
3565          for ($i = 0; $i < $mb_length; $i += $offset) {
3566              $lookBack = 0;
3567              do {
3568                  $offset = $avgLength - $lookBack;
3569                  $chunk = mb_substr($str, $i, $offset, $this->CharSet);
3570                  $chunk = base64_encode($chunk);
3571                  ++$lookBack;
3572              } while (strlen($chunk) > $length);
3573              $encoded .= $chunk . $linebreak;
3574          }
3575  
3576          //Chomp the last linefeed
3577          return substr($encoded, 0, -strlen($linebreak));
3578      }
3579  
3580      /**
3581       * Encode a string in quoted-printable format.
3582       * According to RFC2045 section 6.7.
3583       *
3584       * @param string $string The text to encode
3585       *
3586       * @return string
3587       */
3588      public function encodeQP($string)
3589      {
3590          return static::normalizeBreaks(quoted_printable_encode($string));
3591      }
3592  
3593      /**
3594       * Encode a string using Q encoding.
3595       *
3596       * @see http://tools.ietf.org/html/rfc2047#section-4.2
3597       *
3598       * @param string $str      the text to encode
3599       * @param string $position Where the text is going to be used, see the RFC for what that means
3600       *
3601       * @return string
3602       */
3603      public function encodeQ($str, $position = 'text')
3604      {
3605          //There should not be any EOL in the string
3606          $pattern = '';
3607          $encoded = str_replace(["\r", "\n"], '', $str);
3608          switch (strtolower($position)) {
3609              case 'phrase':
3610                  //RFC 2047 section 5.3
3611                  $pattern = '^A-Za-z0-9!*+\/ -';
3612                  break;
3613              /*
3614               * RFC 2047 section 5.2.
3615               * Build $pattern without including delimiters and []
3616               */
3617              /* @noinspection PhpMissingBreakStatementInspection */
3618              case 'comment':
3619                  $pattern = '\(\)"';
3620              /* Intentional fall through */
3621              case 'text':
3622              default:
3623                  //RFC 2047 section 5.1
3624                  //Replace every high ascii, control, =, ? and _ characters
3625                  $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
3626                  break;
3627          }
3628          $matches = [];
3629          if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
3630              //If the string contains an '=', make sure it's the first thing we replace
3631              //so as to avoid double-encoding
3632              $eqkey = array_search('=', $matches[0], true);
3633              if (false !== $eqkey) {
3634                  unset($matches[0][$eqkey]);
3635                  array_unshift($matches[0], '=');
3636              }
3637              foreach (array_unique($matches[0]) as $char) {
3638                  $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
3639              }
3640          }
3641          //Replace spaces with _ (more readable than =20)
3642          //RFC 2047 section 4.2(2)
3643          return str_replace(' ', '_', $encoded);
3644      }
3645  
3646      /**
3647       * Add a string or binary attachment (non-filesystem).
3648       * This method can be used to attach ascii or binary data,
3649       * such as a BLOB record from a database.
3650       *
3651       * @param string $string      String attachment data
3652       * @param string $filename    Name of the attachment
3653       * @param string $encoding    File encoding (see $Encoding)
3654       * @param string $type        File extension (MIME) type
3655       * @param string $disposition Disposition to use
3656       *
3657       * @throws Exception
3658       *
3659       * @return bool True on successfully adding an attachment
3660       */
3661      public function addStringAttachment(
3662          $string,
3663          $filename,
3664          $encoding = self::ENCODING_BASE64,
3665          $type = '',
3666          $disposition = 'attachment'
3667      ) {
3668          try {
3669              //If a MIME type is not specified, try to work it out from the file name
3670              if ('' === $type) {
3671                  $type = static::filenameToType($filename);
3672              }
3673  
3674              if (!$this->validateEncoding($encoding)) {
3675                  throw new Exception($this->lang('encoding') . $encoding);
3676              }
3677  
3678              //Append to $attachment array
3679              $this->attachment[] = [
3680                  0 => $string,
3681                  1 => $filename,
3682                  2 => static::mb_pathinfo($filename, PATHINFO_BASENAME),
3683                  3 => $encoding,
3684                  4 => $type,
3685                  5 => true, //isStringAttachment
3686                  6 => $disposition,
3687                  7 => 0,
3688              ];
3689          } catch (Exception $exc) {
3690              $this->setError($exc->getMessage());
3691              $this->edebug($exc->getMessage());
3692              if ($this->exceptions) {
3693                  throw $exc;
3694              }
3695  
3696              return false;
3697          }
3698  
3699          return true;
3700      }
3701  
3702      /**
3703       * Add an embedded (inline) attachment from a file.
3704       * This can include images, sounds, and just about any other document type.
3705       * These differ from 'regular' attachments in that they are intended to be
3706       * displayed inline with the message, not just attached for download.
3707       * This is used in HTML messages that embed the images
3708       * the HTML refers to using the $cid value.
3709       * Never use a user-supplied path to a file!
3710       *
3711       * @param string $path        Path to the attachment
3712       * @param string $cid         Content ID of the attachment; Use this to reference
3713       *                            the content when using an embedded image in HTML
3714       * @param string $name        Overrides the attachment name
3715       * @param string $encoding    File encoding (see $Encoding)
3716       * @param string $type        File MIME type
3717       * @param string $disposition Disposition to use
3718       *
3719       * @throws Exception
3720       *
3721       * @return bool True on successfully adding an attachment
3722       */
3723      public function addEmbeddedImage(
3724          $path,
3725          $cid,
3726          $name = '',
3727          $encoding = self::ENCODING_BASE64,
3728          $type = '',
3729          $disposition = 'inline'
3730      ) {
3731          try {
3732              if (!static::fileIsAccessible($path)) {
3733                  throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
3734              }
3735  
3736              //If a MIME type is not specified, try to work it out from the file name
3737              if ('' === $type) {
3738                  $type = static::filenameToType($path);
3739              }
3740  
3741              if (!$this->validateEncoding($encoding)) {
3742                  throw new Exception($this->lang('encoding') . $encoding);
3743              }
3744  
3745              $filename = (string) static::mb_pathinfo($path, PATHINFO_BASENAME);
3746              if ('' === $name) {
3747                  $name = $filename;
3748              }
3749  
3750              //Append to $attachment array
3751              $this->attachment[] = [
3752                  0 => $path,
3753                  1 => $filename,
3754                  2 => $name,
3755                  3 => $encoding,
3756                  4 => $type,
3757                  5 => false, //isStringAttachment
3758                  6 => $disposition,
3759                  7 => $cid,
3760              ];
3761          } catch (Exception $exc) {
3762              $this->setError($exc->getMessage());
3763              $this->edebug($exc->getMessage());
3764              if ($this->exceptions) {
3765                  throw $exc;
3766              }
3767  
3768              return false;
3769          }
3770  
3771          return true;
3772      }
3773  
3774      /**
3775       * Add an embedded stringified attachment.
3776       * This can include images, sounds, and just about any other document type.
3777       * If your filename doesn't contain an extension, be sure to set the $type to an appropriate MIME type.
3778       *
3779       * @param string $string      The attachment binary data
3780       * @param string $cid         Content ID of the attachment; Use this to reference
3781       *                            the content when using an embedded image in HTML
3782       * @param string $name        A filename for the attachment. If this contains an extension,
3783       *                            PHPMailer will attempt to set a MIME type for the attachment.
3784       *                            For example 'file.jpg' would get an 'image/jpeg' MIME type.
3785       * @param string $encoding    File encoding (see $Encoding), defaults to 'base64'
3786       * @param string $type        MIME type - will be used in preference to any automatically derived type
3787       * @param string $disposition Disposition to use
3788       *
3789       * @throws Exception
3790       *
3791       * @return bool True on successfully adding an attachment
3792       */
3793      public function addStringEmbeddedImage(
3794          $string,
3795          $cid,
3796          $name = '',
3797          $encoding = self::ENCODING_BASE64,
3798          $type = '',
3799          $disposition = 'inline'
3800      ) {
3801          try {
3802              //If a MIME type is not specified, try to work it out from the name
3803              if ('' === $type && !empty($name)) {
3804                  $type = static::filenameToType($name);
3805              }
3806  
3807              if (!$this->validateEncoding($encoding)) {
3808                  throw new Exception($this->lang('encoding') . $encoding);
3809              }
3810  
3811              //Append to $attachment array
3812              $this->attachment[] = [
3813                  0 => $string,
3814                  1 => $name,
3815                  2 => $name,
3816                  3 => $encoding,
3817                  4 => $type,
3818                  5 => true, //isStringAttachment
3819                  6 => $disposition,
3820                  7 => $cid,
3821              ];
3822          } catch (Exception $exc) {
3823              $this->setError($exc->getMessage());
3824              $this->edebug($exc->getMessage());
3825              if ($this->exceptions) {
3826                  throw $exc;
3827              }
3828  
3829              return false;
3830          }
3831  
3832          return true;
3833      }
3834  
3835      /**
3836       * Validate encodings.
3837       *
3838       * @param string $encoding
3839       *
3840       * @return bool
3841       */
3842      protected function validateEncoding($encoding)
3843      {
3844          return in_array(
3845              $encoding,
3846              [
3847                  self::ENCODING_7BIT,
3848                  self::ENCODING_QUOTED_PRINTABLE,
3849                  self::ENCODING_BASE64,
3850                  self::ENCODING_8BIT,
3851                  self::ENCODING_BINARY,
3852              ],
3853              true
3854          );
3855      }
3856  
3857      /**
3858       * Check if an embedded attachment is present with this cid.
3859       *
3860       * @param string $cid
3861       *
3862       * @return bool
3863       */
3864      protected function cidExists($cid)
3865      {
3866          foreach ($this->attachment as $attachment) {
3867              if ('inline' === $attachment[6] && $cid === $attachment[7]) {
3868                  return true;
3869              }
3870          }
3871  
3872          return false;
3873      }
3874  
3875      /**
3876       * Check if an inline attachment is present.
3877       *
3878       * @return bool
3879       */
3880      public function inlineImageExists()
3881      {
3882          foreach ($this->attachment as $attachment) {
3883              if ('inline' === $attachment[6]) {
3884                  return true;
3885              }
3886          }
3887  
3888          return false;
3889      }
3890  
3891      /**
3892       * Check if an attachment (non-inline) is present.
3893       *
3894       * @return bool
3895       */
3896      public function attachmentExists()
3897      {
3898          foreach ($this->attachment as $attachment) {
3899              if ('attachment' === $attachment[6]) {
3900                  return true;
3901              }
3902          }
3903  
3904          return false;
3905      }
3906  
3907      /**
3908       * Check if this message has an alternative body set.
3909       *
3910       * @return bool
3911       */
3912      public function alternativeExists()
3913      {
3914          return !empty($this->AltBody);
3915      }
3916  
3917      /**
3918       * Clear queued addresses of given kind.
3919       *
3920       * @param string $kind 'to', 'cc', or 'bcc'
3921       */
3922      public function clearQueuedAddresses($kind)
3923      {
3924          $this->RecipientsQueue = array_filter(
3925              $this->RecipientsQueue,
3926              static function ($params) use ($kind) {
3927                  return $params[0] !== $kind;
3928              }
3929          );
3930      }
3931  
3932      /**
3933       * Clear all To recipients.
3934       */
3935      public function clearAddresses()
3936      {
3937          foreach ($this->to as $to) {
3938              unset($this->all_recipients[strtolower($to[0])]);
3939          }
3940          $this->to = [];
3941          $this->clearQueuedAddresses('to');
3942      }
3943  
3944      /**
3945       * Clear all CC recipients.
3946       */
3947      public function clearCCs()
3948      {
3949          foreach ($this->cc as $cc) {
3950              unset($this->all_recipients[strtolower($cc[0])]);
3951          }
3952          $this->cc = [];
3953          $this->clearQueuedAddresses('cc');
3954      }
3955  
3956      /**
3957       * Clear all BCC recipients.
3958       */
3959      public function clearBCCs()
3960      {
3961          foreach ($this->bcc as $bcc) {
3962              unset($this->all_recipients[strtolower($bcc[0])]);
3963          }
3964          $this->bcc = [];
3965          $this->clearQueuedAddresses('bcc');
3966      }
3967  
3968      /**
3969       * Clear all ReplyTo recipients.
3970       */
3971      public function clearReplyTos()
3972      {
3973          $this->ReplyTo = [];
3974          $this->ReplyToQueue = [];
3975      }
3976  
3977      /**
3978       * Clear all recipient types.
3979       */
3980      public function clearAllRecipients()
3981      {
3982          $this->to = [];
3983          $this->cc = [];
3984          $this->bcc = [];
3985          $this->all_recipients = [];
3986          $this->RecipientsQueue = [];
3987      }
3988  
3989      /**
3990       * Clear all filesystem, string, and binary attachments.
3991       */
3992      public function clearAttachments()
3993      {
3994          $this->attachment = [];
3995      }
3996  
3997      /**
3998       * Clear all custom headers.
3999       */
4000      public function clearCustomHeaders()
4001      {
4002          $this->CustomHeader = [];
4003      }
4004  
4005      /**
4006       * Add an error message to the error container.
4007       *
4008       * @param string $msg
4009       */
4010      protected function setError($msg)
4011      {
4012          ++$this->error_count;
4013          if ('smtp' === $this->Mailer && null !== $this->smtp) {
4014              $lasterror = $this->smtp->getError();
4015              if (!empty($lasterror['error'])) {
4016                  $msg .= $this->lang('smtp_error') . $lasterror['error'];
4017                  if (!empty($lasterror['detail'])) {
4018                      $msg .= ' ' . $this->lang('smtp_detail') . $lasterror['detail'];
4019                  }
4020                  if (!empty($lasterror['smtp_code'])) {
4021                      $msg .= ' ' . $this->lang('smtp_code') . $lasterror['smtp_code'];
4022                  }
4023                  if (!empty($lasterror['smtp_code_ex'])) {
4024                      $msg .= ' ' . $this->lang('smtp_code_ex') . $lasterror['smtp_code_ex'];
4025                  }
4026              }
4027          }
4028          $this->ErrorInfo = $msg;
4029      }
4030  
4031      /**
4032       * Return an RFC 822 formatted date.
4033       *
4034       * @return string
4035       */
4036      public static function rfcDate()
4037      {
4038          //Set the time zone to whatever the default is to avoid 500 errors
4039          //Will default to UTC if it's not set properly in php.ini
4040          date_default_timezone_set(@date_default_timezone_get());
4041  
4042          return date('D, j M Y H:i:s O');
4043      }
4044  
4045      /**
4046       * Get the server hostname.
4047       * Returns 'localhost.localdomain' if unknown.
4048       *
4049       * @return string
4050       */
4051      protected function serverHostname()
4052      {
4053          $result = '';
4054          if (!empty($this->Hostname)) {
4055              $result = $this->Hostname;
4056          } elseif (isset($_SERVER) && array_key_exists('SERVER_NAME', $_SERVER)) {
4057              $result = $_SERVER['SERVER_NAME'];
4058          } elseif (function_exists('gethostname') && gethostname() !== false) {
4059              $result = gethostname();
4060          } elseif (php_uname('n') !== false) {
4061              $result = php_uname('n');
4062          }
4063          if (!static::isValidHost($result)) {
4064              return 'localhost.localdomain';
4065          }
4066  
4067          return $result;
4068      }
4069  
4070      /**
4071       * Validate whether a string contains a valid value to use as a hostname or IP address.
4072       * IPv6 addresses must include [], e.g. `[::1]`, not just `::1`.
4073       *
4074       * @param string $host The host name or IP address to check
4075       *
4076       * @return bool
4077       */
4078      public static function isValidHost($host)
4079      {
4080          //Simple syntax limits
4081          if (
4082              empty($host)
4083              || !is_string($host)
4084              || strlen($host) > 256
4085              || !preg_match('/^([a-zA-Z\d.-]*|\[[a-fA-F\d:]+\])$/', $host)
4086          ) {
4087              return false;
4088          }
4089          //Looks like a bracketed IPv6 address
4090          if (strlen($host) > 2 && substr($host, 0, 1) === '[' && substr($host, -1, 1) === ']') {
4091              return filter_var(substr($host, 1, -1), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
4092          }
4093          //If removing all the dots results in a numeric string, it must be an IPv4 address.
4094          //Need to check this first because otherwise things like `999.0.0.0` are considered valid host names
4095          if (is_numeric(str_replace('.', '', $host))) {
4096              //Is it a valid IPv4 address?
4097              return filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
4098          }
4099          if (filter_var('http://' . $host, FILTER_VALIDATE_URL) !== false) {
4100              //Is it a syntactically valid hostname?
4101              return true;
4102          }
4103  
4104          return false;
4105      }
4106  
4107      /**
4108       * Get an error message in the current language.
4109       *
4110       * @param string $key
4111       *
4112       * @return string
4113       */
4114      protected function lang($key)
4115      {
4116          if (count($this->language) < 1) {
4117              $this->setLanguage(); //Set the default language
4118          }
4119  
4120          if (array_key_exists($key, $this->language)) {
4121              if ('smtp_connect_failed' === $key) {
4122                  //Include a link to troubleshooting docs on SMTP connection failure.
4123                  //This is by far the biggest cause of support questions
4124                  //but it's usually not PHPMailer's fault.
4125                  return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
4126              }
4127  
4128              return $this->language[$key];
4129          }
4130  
4131          //Return the key as a fallback
4132          return $key;
4133      }
4134  
4135      /**
4136       * Build an error message starting with a generic one and adding details if possible.
4137       *
4138       * @param string $base_key
4139       * @return string
4140       */
4141      private function getSmtpErrorMessage($base_key)
4142      {
4143          $message = $this->lang($base_key);
4144          $error = $this->smtp->getError();
4145          if (!empty($error['error'])) {
4146              $message .= ' ' . $error['error'];
4147              if (!empty($error['detail'])) {
4148                  $message .= ' ' . $error['detail'];
4149              }
4150          }
4151  
4152          return $message;
4153      }
4154  
4155      /**
4156       * Check if an error occurred.
4157       *
4158       * @return bool True if an error did occur
4159       */
4160      public function isError()
4161      {
4162          return $this->error_count > 0;
4163      }
4164  
4165      /**
4166       * Add a custom header.
4167       * $name value can be overloaded to contain
4168       * both header name and value (name:value).
4169       *
4170       * @param string      $name  Custom header name
4171       * @param string|null $value Header value
4172       *
4173       * @throws Exception
4174       */
4175      public function addCustomHeader($name, $value = null)
4176      {
4177          if (null === $value && strpos($name, ':') !== false) {
4178              //Value passed in as name:value
4179              list($name, $value) = explode(':', $name, 2);
4180          }
4181          $name = trim($name);
4182          $value = (null === $value) ? '' : trim($value);
4183          //Ensure name is not empty, and that neither name nor value contain line breaks
4184          if (empty($name) || strpbrk($name . $value, "\r\n") !== false) {
4185              if ($this->exceptions) {
4186                  throw new Exception($this->lang('invalid_header'));
4187              }
4188  
4189              return false;
4190          }
4191          $this->CustomHeader[] = [$name, $value];
4192  
4193          return true;
4194      }
4195  
4196      /**
4197       * Returns all custom headers.
4198       *
4199       * @return array
4200       */
4201      public function getCustomHeaders()
4202      {
4203          return $this->CustomHeader;
4204      }
4205  
4206      /**
4207       * Create a message body from an HTML string.
4208       * Automatically inlines images and creates a plain-text version by converting the HTML,
4209       * overwriting any existing values in Body and AltBody.
4210       * Do not source $message content from user input!
4211       * $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty
4212       * will look for an image file in $basedir/images/a.png and convert it to inline.
4213       * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email)
4214       * Converts data-uri images into embedded attachments.
4215       * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly.
4216       *
4217       * @param string        $message  HTML message string
4218       * @param string        $basedir  Absolute path to a base directory to prepend to relative paths to images
4219       * @param bool|callable $advanced Whether to use the internal HTML to text converter
4220       *                                or your own custom converter
4221       * @return string The transformed message body
4222       *
4223       * @throws Exception
4224       *
4225       * @see PHPMailer::html2text()
4226       */
4227      public function msgHTML($message, $basedir = '', $advanced = false)
4228      {
4229          preg_match_all('/(?<!-)(src|background)=["\'](.*)["\']/Ui', $message, $images);
4230          if (array_key_exists(2, $images)) {
4231              if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {
4232                  //Ensure $basedir has a trailing /
4233                  $basedir .= '/';
4234              }
4235              foreach ($images[2] as $imgindex => $url) {
4236                  //Convert data URIs into embedded images
4237                  //e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
4238                  $match = [];
4239                  if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) {
4240                      if (count($match) === 4 && static::ENCODING_BASE64 === $match[2]) {
4241                          $data = base64_decode($match[3]);
4242                      } elseif ('' === $match[2]) {
4243                          $data = rawurldecode($match[3]);
4244                      } else {
4245                          //Not recognised so leave it alone
4246                          continue;
4247                      }
4248                      //Hash the decoded data, not the URL, so that the same data-URI image used in multiple places
4249                      //will only be embedded once, even if it used a different encoding
4250                      $cid = substr(hash('sha256', $data), 0, 32) . '@phpmailer.0'; //RFC2392 S 2
4251  
4252                      if (!$this->cidExists($cid)) {
4253                          $this->addStringEmbeddedImage(
4254                              $data,
4255                              $cid,
4256                              'embed' . $imgindex,
4257                              static::ENCODING_BASE64,
4258                              $match[1]
4259                          );
4260                      }
4261                      $message = str_replace(
4262                          $images[0][$imgindex],
4263                          $images[1][$imgindex] . '="cid:' . $cid . '"',
4264                          $message
4265                      );
4266                      continue;
4267                  }
4268                  if (
4269                      //Only process relative URLs if a basedir is provided (i.e. no absolute local paths)
4270                      !empty($basedir)
4271                      //Ignore URLs containing parent dir traversal (..)
4272                      && (strpos($url, '..') === false)
4273                      //Do not change urls that are already inline images
4274                      && 0 !== strpos($url, 'cid:')
4275                      //Do not change absolute URLs, including anonymous protocol
4276                      && !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url)
4277                  ) {
4278                      $filename = static::mb_pathinfo($url, PATHINFO_BASENAME);
4279                      $directory = dirname($url);
4280                      if ('.' === $directory) {
4281                          $directory = '';
4282                      }
4283                      //RFC2392 S 2
4284                      $cid = substr(hash('sha256', $url), 0, 32) . '@phpmailer.0';
4285                      if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {
4286                          $basedir .= '/';
4287                      }
4288                      if (strlen($directory) > 1 && '/' !== substr($directory, -1)) {
4289                          $directory .= '/';
4290                      }
4291                      if (
4292                          $this->addEmbeddedImage(
4293                              $basedir . $directory . $filename,
4294                              $cid,
4295                              $filename,
4296                              static::ENCODING_BASE64,
4297                              static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION))
4298                          )
4299                      ) {
4300                          $message = preg_replace(
4301                              '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
4302                              $images[1][$imgindex] . '="cid:' . $cid . '"',
4303                              $message
4304                          );
4305                      }
4306                  }
4307              }
4308          }
4309          $this->isHTML();
4310          //Convert all message body line breaks to LE, makes quoted-printable encoding work much better
4311          $this->Body = static::normalizeBreaks($message);
4312          $this->AltBody = static::normalizeBreaks($this->html2text($message, $advanced));
4313          if (!$this->alternativeExists()) {
4314              $this->AltBody = 'This is an HTML-only message. To view it, activate HTML in your email application.'
4315                  . static::$LE;
4316          }
4317  
4318          return $this->Body;
4319      }
4320  
4321      /**
4322       * Convert an HTML string into plain text.
4323       * This is used by msgHTML().
4324       * Note - older versions of this function used a bundled advanced converter
4325       * which was removed for license reasons in #232.
4326       * Example usage:
4327       *
4328       * ```php
4329       * //Use default conversion
4330       * $plain = $mail->html2text($html);
4331       * //Use your own custom converter
4332       * $plain = $mail->html2text($html, function($html) {
4333       *     $converter = new MyHtml2text($html);
4334       *     return $converter->get_text();
4335       * });
4336       * ```
4337       *
4338       * @param string        $html     The HTML text to convert
4339       * @param bool|callable $advanced Any boolean value to use the internal converter,
4340       *                                or provide your own callable for custom conversion.
4341       *                                *Never* pass user-supplied data into this parameter
4342       *
4343       * @return string
4344       */
4345      public function html2text($html, $advanced = false)
4346      {
4347          if (is_callable($advanced)) {
4348              return call_user_func($advanced, $html);
4349          }
4350  
4351          return html_entity_decode(
4352              trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
4353              ENT_QUOTES,
4354              $this->CharSet
4355          );
4356      }
4357  
4358      /**
4359       * Get the MIME type for a file extension.
4360       *
4361       * @param string $ext File extension
4362       *
4363       * @return string MIME type of file
4364       */
4365      public static function _mime_types($ext = '')
4366      {
4367          $mimes = [
4368              'xl' => 'application/excel',
4369              'js' => 'application/javascript',
4370              'hqx' => 'application/mac-binhex40',
4371              'cpt' => 'application/mac-compactpro',
4372              'bin' => 'application/macbinary',
4373              'doc' => 'application/msword',
4374              'word' => 'application/msword',
4375              'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
4376              'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
4377              'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
4378              'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
4379              'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
4380              'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
4381              'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
4382              'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
4383              'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
4384              'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
4385              'class' => 'application/octet-stream',
4386              'dll' => 'application/octet-stream',
4387              'dms' => 'application/octet-stream',
4388              'exe' => 'application/octet-stream',
4389              'lha' => 'application/octet-stream',
4390              'lzh' => 'application/octet-stream',
4391              'psd' => 'application/octet-stream',
4392              'sea' => 'application/octet-stream',
4393              'so' => 'application/octet-stream',
4394              'oda' => 'application/oda',
4395              'pdf' => 'application/pdf',
4396              'ai' => 'application/postscript',
4397              'eps' => 'application/postscript',
4398              'ps' => 'application/postscript',
4399              'smi' => 'application/smil',
4400              'smil' => 'application/smil',
4401              'mif' => 'application/vnd.mif',
4402              'xls' => 'application/vnd.ms-excel',
4403              'ppt' => 'application/vnd.ms-powerpoint',
4404              'wbxml' => 'application/vnd.wap.wbxml',
4405              'wmlc' => 'application/vnd.wap.wmlc',
4406              'dcr' => 'application/x-director',
4407              'dir' => 'application/x-director',
4408              'dxr' => 'application/x-director',
4409              'dvi' => 'application/x-dvi',
4410              'gtar' => 'application/x-gtar',
4411              'php3' => 'application/x-httpd-php',
4412              'php4' => 'application/x-httpd-php',
4413              'php' => 'application/x-httpd-php',
4414              'phtml' => 'application/x-httpd-php',
4415              'phps' => 'application/x-httpd-php-source',
4416              'swf' => 'application/x-shockwave-flash',
4417              'sit' => 'application/x-stuffit',
4418              'tar' => 'application/x-tar',
4419              'tgz' => 'application/x-tar',
4420              'xht' => 'application/xhtml+xml',
4421              'xhtml' => 'application/xhtml+xml',
4422              'zip' => 'application/zip',
4423              'mid' => 'audio/midi',
4424              'midi' => 'audio/midi',
4425              'mp2' => 'audio/mpeg',
4426              'mp3' => 'audio/mpeg',
4427              'm4a' => 'audio/mp4',
4428              'mpga' => 'audio/mpeg',
4429              'aif' => 'audio/x-aiff',
4430              'aifc' => 'audio/x-aiff',
4431              'aiff' => 'audio/x-aiff',
4432              'ram' => 'audio/x-pn-realaudio',
4433              'rm' => 'audio/x-pn-realaudio',
4434              'rpm' => 'audio/x-pn-realaudio-plugin',
4435              'ra' => 'audio/x-realaudio',
4436              'wav' => 'audio/x-wav',
4437              'mka' => 'audio/x-matroska',
4438              'bmp' => 'image/bmp',
4439              'gif' => 'image/gif',
4440              'jpeg' => 'image/jpeg',
4441              'jpe' => 'image/jpeg',
4442              'jpg' => 'image/jpeg',
4443              'png' => 'image/png',
4444              'tiff' => 'image/tiff',
4445              'tif' => 'image/tiff',
4446              'webp' => 'image/webp',
4447              'avif' => 'image/avif',
4448              'heif' => 'image/heif',
4449              'heifs' => 'image/heif-sequence',
4450              'heic' => 'image/heic',
4451              'heics' => 'image/heic-sequence',
4452              'eml' => 'message/rfc822',
4453              'css' => 'text/css',
4454              'html' => 'text/html',
4455              'htm' => 'text/html',
4456              'shtml' => 'text/html',
4457              'log' => 'text/plain',
4458              'text' => 'text/plain',
4459              'txt' => 'text/plain',
4460              'rtx' => 'text/richtext',
4461              'rtf' => 'text/rtf',
4462              'vcf' => 'text/vcard',
4463              'vcard' => 'text/vcard',
4464              'ics' => 'text/calendar',
4465              'xml' => 'text/xml',
4466              'xsl' => 'text/xml',
4467              'wmv' => 'video/x-ms-wmv',
4468              'mpeg' => 'video/mpeg',
4469              'mpe' => 'video/mpeg',
4470              'mpg' => 'video/mpeg',
4471              'mp4' => 'video/mp4',
4472              'm4v' => 'video/mp4',
4473              'mov' => 'video/quicktime',
4474              'qt' => 'video/quicktime',
4475              'rv' => 'video/vnd.rn-realvideo',
4476              'avi' => 'video/x-msvideo',
4477              'movie' => 'video/x-sgi-movie',
4478              'webm' => 'video/webm',
4479              'mkv' => 'video/x-matroska',
4480          ];
4481          $ext = strtolower($ext);
4482          if (array_key_exists($ext, $mimes)) {
4483              return $mimes[$ext];
4484          }
4485  
4486          return 'application/octet-stream';
4487      }
4488  
4489      /**
4490       * Map a file name to a MIME type.
4491       * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
4492       *
4493       * @param string $filename A file name or full path, does not need to exist as a file
4494       *
4495       * @return string
4496       */
4497      public static function filenameToType($filename)
4498      {
4499          //In case the path is a URL, strip any query string before getting extension
4500          $qpos = strpos($filename, '?');
4501          if (false !== $qpos) {
4502              $filename = substr($filename, 0, $qpos);
4503          }
4504          $ext = static::mb_pathinfo($filename, PATHINFO_EXTENSION);
4505  
4506          return static::_mime_types($ext);
4507      }
4508  
4509      /**
4510       * Multi-byte-safe pathinfo replacement.
4511       * Drop-in replacement for pathinfo(), but multibyte- and cross-platform-safe.
4512       *
4513       * @see http://www.php.net/manual/en/function.pathinfo.php#107461
4514       *
4515       * @param string     $path    A filename or path, does not need to exist as a file
4516       * @param int|string $options Either a PATHINFO_* constant,
4517       *                            or a string name to return only the specified piece
4518       *
4519       * @return string|array
4520       */
4521      public static function mb_pathinfo($path, $options = null)
4522      {
4523          $ret = ['dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''];
4524          $pathinfo = [];
4525          if (preg_match('#^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^.\\\\/]+?)|))[\\\\/.]*$#m', $path, $pathinfo)) {
4526              if (array_key_exists(1, $pathinfo)) {
4527                  $ret['dirname'] = $pathinfo[1];
4528              }
4529              if (array_key_exists(2, $pathinfo)) {
4530                  $ret['basename'] = $pathinfo[2];
4531              }
4532              if (array_key_exists(5, $pathinfo)) {
4533                  $ret['extension'] = $pathinfo[5];
4534              }
4535              if (array_key_exists(3, $pathinfo)) {
4536                  $ret['filename'] = $pathinfo[3];
4537              }
4538          }
4539          switch ($options) {
4540              case PATHINFO_DIRNAME:
4541              case 'dirname':
4542                  return $ret['dirname'];
4543              case PATHINFO_BASENAME:
4544              case 'basename':
4545                  return $ret['basename'];
4546              case PATHINFO_EXTENSION:
4547              case 'extension':
4548                  return $ret['extension'];
4549              case PATHINFO_FILENAME:
4550              case 'filename':
4551                  return $ret['filename'];
4552              default:
4553                  return $ret;
4554          }
4555      }
4556  
4557      /**
4558       * Set or reset instance properties.
4559       * You should avoid this function - it's more verbose, less efficient, more error-prone and
4560       * harder to debug than setting properties directly.
4561       * Usage Example:
4562       * `$mail->set('SMTPSecure', static::ENCRYPTION_STARTTLS);`
4563       *   is the same as:
4564       * `$mail->SMTPSecure = static::ENCRYPTION_STARTTLS;`.
4565       *
4566       * @param string $name  The property name to set
4567       * @param mixed  $value The value to set the property to
4568       *
4569       * @return bool
4570       */
4571      public function set($name, $value = '')
4572      {
4573          if (property_exists($this, $name)) {
4574              $this->$name = $value;
4575  
4576              return true;
4577          }
4578          $this->setError($this->lang('variable_set') . $name);
4579  
4580          return false;
4581      }
4582  
4583      /**
4584       * Strip newlines to prevent header injection.
4585       *
4586       * @param string $str
4587       *
4588       * @return string
4589       */
4590      public function secureHeader($str)
4591      {
4592          return trim(str_replace(["\r", "\n"], '', $str));
4593      }
4594  
4595      /**
4596       * Normalize line breaks in a string.
4597       * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
4598       * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
4599       *
4600       * @param string $text
4601       * @param string $breaktype What kind of line break to use; defaults to static::$LE
4602       *
4603       * @return string
4604       */
4605      public static function normalizeBreaks($text, $breaktype = null)
4606      {
4607          if (null === $breaktype) {
4608              $breaktype = static::$LE;
4609          }
4610          //Normalise to \n
4611          $text = str_replace([self::CRLF, "\r"], "\n", $text);
4612          //Now convert LE as needed
4613          if ("\n" !== $breaktype) {
4614              $text = str_replace("\n", $breaktype, $text);
4615          }
4616  
4617          return $text;
4618      }
4619  
4620      /**
4621       * Remove trailing breaks from a string.
4622       *
4623       * @param string $text
4624       *
4625       * @return string The text to remove breaks from
4626       */
4627      public static function stripTrailingWSP($text)
4628      {
4629          return rtrim($text, " \r\n\t");
4630      }
4631  
4632      /**
4633       * Return the current line break format string.
4634       *
4635       * @return string
4636       */
4637      public static function getLE()
4638      {
4639          return static::$LE;
4640      }
4641  
4642      /**
4643       * Set the line break format string, e.g. "\r\n".
4644       *
4645       * @param string $le
4646       */
4647      protected static function setLE($le)
4648      {
4649          static::$LE = $le;
4650      }
4651  
4652      /**
4653       * Set the public and private key files and password for S/MIME signing.
4654       *
4655       * @param string $cert_filename
4656       * @param string $key_filename
4657       * @param string $key_pass            Password for private key
4658       * @param string $extracerts_filename Optional path to chain certificate
4659       */
4660      public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
4661      {
4662          $this->sign_cert_file = $cert_filename;
4663          $this->sign_key_file = $key_filename;
4664          $this->sign_key_pass = $key_pass;
4665          $this->sign_extracerts_file = $extracerts_filename;
4666      }
4667  
4668      /**
4669       * Quoted-Printable-encode a DKIM header.
4670       *
4671       * @param string $txt
4672       *
4673       * @return string
4674       */
4675      public function DKIM_QP($txt)
4676      {
4677          $line = '';
4678          $len = strlen($txt);
4679          for ($i = 0; $i < $len; ++$i) {
4680              $ord = ord($txt[$i]);
4681              if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord === 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
4682                  $line .= $txt[$i];
4683              } else {
4684                  $line .= '=' . sprintf('%02X', $ord);
4685              }
4686          }
4687  
4688          return $line;
4689      }
4690  
4691      /**
4692       * Generate a DKIM signature.
4693       *
4694       * @param string $signHeader
4695       *
4696       * @throws Exception
4697       *
4698       * @return string The DKIM signature value
4699       */
4700      public function DKIM_Sign($signHeader)
4701      {
4702          if (!defined('PKCS7_TEXT')) {
4703              if ($this->exceptions) {
4704                  throw new Exception($this->lang('extension_missing') . 'openssl');
4705              }
4706  
4707              return '';
4708          }
4709          $privKeyStr = !empty($this->DKIM_private_string) ?
4710              $this->DKIM_private_string :
4711              file_get_contents($this->DKIM_private);
4712          if ('' !== $this->DKIM_passphrase) {
4713              $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
4714          } else {
4715              $privKey = openssl_pkey_get_private($privKeyStr);
4716          }
4717          if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
4718              if (\PHP_MAJOR_VERSION < 8) {
4719                  openssl_pkey_free($privKey);
4720              }
4721  
4722              return base64_encode($signature);
4723          }
4724          if (\PHP_MAJOR_VERSION < 8) {
4725              openssl_pkey_free($privKey);
4726          }
4727  
4728          return '';
4729      }
4730  
4731      /**
4732       * Generate a DKIM canonicalization header.
4733       * Uses the 'relaxed' algorithm from RFC6376 section 3.4.2.
4734       * Canonicalized headers should *always* use CRLF, regardless of mailer setting.
4735       *
4736       * @see https://tools.ietf.org/html/rfc6376#section-3.4.2
4737       *
4738       * @param string $signHeader Header
4739       *
4740       * @return string
4741       */
4742      public function DKIM_HeaderC($signHeader)
4743      {
4744          //Normalize breaks to CRLF (regardless of the mailer)
4745          $signHeader = static::normalizeBreaks($signHeader, self::CRLF);
4746          //Unfold header lines
4747          //Note PCRE \s is too broad a definition of whitespace; RFC5322 defines it as `[ \t]`
4748          //@see https://tools.ietf.org/html/rfc5322#section-2.2
4749          //That means this may break if you do something daft like put vertical tabs in your headers.
4750          $signHeader = preg_replace('/\r\n[ \t]+/', ' ', $signHeader);
4751          //Break headers out into an array
4752          $lines = explode(self::CRLF, $signHeader);
4753          foreach ($lines as $key => $line) {
4754              //If the header is missing a :, skip it as it's invalid
4755              //This is likely to happen because the explode() above will also split
4756              //on the trailing LE, leaving an empty line
4757              if (strpos($line, ':') === false) {
4758                  continue;
4759              }
4760              list($heading, $value) = explode(':', $line, 2);
4761              //Lower-case header name
4762              $heading = strtolower($heading);
4763              //Collapse white space within the value, also convert WSP to space
4764              $value = preg_replace('/[ \t]+/', ' ', $value);
4765              //RFC6376 is slightly unclear here - it says to delete space at the *end* of each value
4766              //But then says to delete space before and after the colon.
4767              //Net result is the same as trimming both ends of the value.
4768              //By elimination, the same applies to the field name
4769              $lines[$key] = trim($heading, " \t") . ':' . trim($value, " \t");
4770          }
4771  
4772          return implode(self::CRLF, $lines);
4773      }
4774  
4775      /**
4776       * Generate a DKIM canonicalization body.
4777       * Uses the 'simple' algorithm from RFC6376 section 3.4.3.
4778       * Canonicalized bodies should *always* use CRLF, regardless of mailer setting.
4779       *
4780       * @see https://tools.ietf.org/html/rfc6376#section-3.4.3
4781       *
4782       * @param string $body Message Body
4783       *
4784       * @return string
4785       */
4786      public function DKIM_BodyC($body)
4787      {
4788          if (empty($body)) {
4789              return self::CRLF;
4790          }
4791          //Normalize line endings to CRLF
4792          $body = static::normalizeBreaks($body, self::CRLF);
4793  
4794          //Reduce multiple trailing line breaks to a single one
4795          return static::stripTrailingWSP($body) . self::CRLF;
4796      }
4797  
4798      /**
4799       * Create the DKIM header and body in a new message header.
4800       *
4801       * @param string $headers_line Header lines
4802       * @param string $subject      Subject
4803       * @param string $body         Body
4804       *
4805       * @throws Exception
4806       *
4807       * @return string
4808       */
4809      public function DKIM_Add($headers_line, $subject, $body)
4810      {
4811          $DKIMsignatureType = 'rsa-sha256'; //Signature & hash algorithms
4812          $DKIMcanonicalization = 'relaxed/simple'; //Canonicalization methods of header & body
4813          $DKIMquery = 'dns/txt'; //Query method
4814          $DKIMtime = time();
4815          //Always sign these headers without being asked
4816          //Recommended list from https://tools.ietf.org/html/rfc6376#section-5.4.1
4817          $autoSignHeaders = [
4818              'from',
4819              'to',
4820              'cc',
4821              'date',
4822              'subject',
4823              'reply-to',
4824              'message-id',
4825              'content-type',
4826              'mime-version',
4827              'x-mailer',
4828          ];
4829          if (stripos($headers_line, 'Subject') === false) {
4830              $headers_line .= 'Subject: ' . $subject . static::$LE;
4831          }
4832          $headerLines = explode(static::$LE, $headers_line);
4833          $currentHeaderLabel = '';
4834          $currentHeaderValue = '';
4835          $parsedHeaders = [];
4836          $headerLineIndex = 0;
4837          $headerLineCount = count($headerLines);
4838          foreach ($headerLines as $headerLine) {
4839              $matches = [];
4840              if (preg_match('/^([^ \t]*?)(?::[ \t]*)(.*)$/', $headerLine, $matches)) {
4841                  if ($currentHeaderLabel !== '') {
4842                      //We were previously in another header; This is the start of a new header, so save the previous one
4843                      $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue];
4844                  }
4845                  $currentHeaderLabel = $matches[1];
4846                  $currentHeaderValue = $matches[2];
4847              } elseif (preg_match('/^[ \t]+(.*)$/', $headerLine, $matches)) {
4848                  //This is a folded continuation of the current header, so unfold it
4849                  $currentHeaderValue .= ' ' . $matches[1];
4850              }
4851              ++$headerLineIndex;
4852              if ($headerLineIndex >= $headerLineCount) {
4853                  //This was the last line, so finish off this header
4854                  $parsedHeaders[] = ['label' => $currentHeaderLabel, 'value' => $currentHeaderValue];
4855              }
4856          }
4857          $copiedHeaders = [];
4858          $headersToSignKeys = [];
4859          $headersToSign = [];
4860          foreach ($parsedHeaders as $header) {
4861              //Is this header one that must be included in the DKIM signature?
4862              if (in_array(strtolower($header['label']), $autoSignHeaders, true)) {
4863                  $headersToSignKeys[] = $header['label'];
4864                  $headersToSign[] = $header['label'] . ': ' . $header['value'];
4865                  if ($this->DKIM_copyHeaderFields) {
4866                      $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC
4867                          str_replace('|', '=7C', $this->DKIM_QP($header['value']));
4868                  }
4869                  continue;
4870              }
4871              //Is this an extra custom header we've been asked to sign?
4872              if (in_array($header['label'], $this->DKIM_extraHeaders, true)) {
4873                  //Find its value in custom headers
4874                  foreach ($this->CustomHeader as $customHeader) {
4875                      if ($customHeader[0] === $header['label']) {
4876                          $headersToSignKeys[] = $header['label'];
4877                          $headersToSign[] = $header['label'] . ': ' . $header['value'];
4878                          if ($this->DKIM_copyHeaderFields) {
4879                              $copiedHeaders[] = $header['label'] . ':' . //Note no space after this, as per RFC
4880                                  str_replace('|', '=7C', $this->DKIM_QP($header['value']));
4881                          }
4882                          //Skip straight to the next header
4883                          continue 2;
4884                      }
4885                  }
4886              }
4887          }
4888          $copiedHeaderFields = '';
4889          if ($this->DKIM_copyHeaderFields && count($copiedHeaders) > 0) {
4890              //Assemble a DKIM 'z' tag
4891              $copiedHeaderFields = ' z=';
4892              $first = true;
4893              foreach ($copiedHeaders as $copiedHeader) {
4894                  if (!$first) {
4895                      $copiedHeaderFields .= static::$LE . ' |';
4896                  }
4897                  //Fold long values
4898                  if (strlen($copiedHeader) > self::STD_LINE_LENGTH - 3) {
4899                      $copiedHeaderFields .= substr(
4900                          chunk_split($copiedHeader, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS),
4901                          0,
4902                          -strlen(static::$LE . self::FWS)
4903                      );
4904                  } else {
4905                      $copiedHeaderFields .= $copiedHeader;
4906                  }
4907                  $first = false;
4908              }
4909              $copiedHeaderFields .= ';' . static::$LE;
4910          }
4911          $headerKeys = ' h=' . implode(':', $headersToSignKeys) . ';' . static::$LE;
4912          $headerValues = implode(static::$LE, $headersToSign);
4913          $body = $this->DKIM_BodyC($body);
4914          //Base64 of packed binary SHA-256 hash of body
4915          $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body)));
4916          $ident = '';
4917          if ('' !== $this->DKIM_identity) {
4918              $ident = ' i=' . $this->DKIM_identity . ';' . static::$LE;
4919          }
4920          //The DKIM-Signature header is included in the signature *except for* the value of the `b` tag
4921          //which is appended after calculating the signature
4922          //https://tools.ietf.org/html/rfc6376#section-3.5
4923          $dkimSignatureHeader = 'DKIM-Signature: v=1;' .
4924              ' d=' . $this->DKIM_domain . ';' .
4925              ' s=' . $this->DKIM_selector . ';' . static::$LE .
4926              ' a=' . $DKIMsignatureType . ';' .
4927              ' q=' . $DKIMquery . ';' .
4928              ' t=' . $DKIMtime . ';' .
4929              ' c=' . $DKIMcanonicalization . ';' . static::$LE .
4930              $headerKeys .
4931              $ident .
4932              $copiedHeaderFields .
4933              ' bh=' . $DKIMb64 . ';' . static::$LE .
4934              ' b=';
4935          //Canonicalize the set of headers
4936          $canonicalizedHeaders = $this->DKIM_HeaderC(
4937              $headerValues . static::$LE . $dkimSignatureHeader
4938          );
4939          $signature = $this->DKIM_Sign($canonicalizedHeaders);
4940          $signature = trim(chunk_split($signature, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS));
4941  
4942          return static::normalizeBreaks($dkimSignatureHeader . $signature);
4943      }
4944  
4945      /**
4946       * Detect if a string contains a line longer than the maximum line length
4947       * allowed by RFC 2822 section 2.1.1.
4948       *
4949       * @param string $str
4950       *
4951       * @return bool
4952       */
4953      public static function hasLineLongerThanMax($str)
4954      {
4955          return (bool) preg_match('/^(.{' . (self::MAX_LINE_LENGTH + strlen(static::$LE)) . ',})/m', $str);
4956      }
4957  
4958      /**
4959       * If a string contains any "special" characters, double-quote the name,
4960       * and escape any double quotes with a backslash.
4961       *
4962       * @param string $str
4963       *
4964       * @return string
4965       *
4966       * @see RFC822 3.4.1
4967       */
4968      public static function quotedString($str)
4969      {
4970          if (preg_match('/[ ()<>@,;:"\/\[\]?=]/', $str)) {
4971              //If the string contains any of these chars, it must be double-quoted
4972              //and any double quotes must be escaped with a backslash
4973              return '"' . str_replace('"', '\\"', $str) . '"';
4974          }
4975  
4976          //Return the string untouched, it doesn't need quoting
4977          return $str;
4978      }
4979  
4980      /**
4981       * Allows for public read access to 'to' property.
4982       * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4983       *
4984       * @return array
4985       */
4986      public function getToAddresses()
4987      {
4988          return $this->to;
4989      }
4990  
4991      /**
4992       * Allows for public read access to 'cc' property.
4993       * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
4994       *
4995       * @return array
4996       */
4997      public function getCcAddresses()
4998      {
4999          return $this->cc;
5000      }
5001  
5002      /**
5003       * Allows for public read access to 'bcc' property.
5004       * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
5005       *
5006       * @return array
5007       */
5008      public function getBccAddresses()
5009      {
5010          return $this->bcc;
5011      }
5012  
5013      /**
5014       * Allows for public read access to 'ReplyTo' property.
5015       * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
5016       *
5017       * @return array
5018       */
5019      public function getReplyToAddresses()
5020      {
5021          return $this->ReplyTo;
5022      }
5023  
5024      /**
5025       * Allows for public read access to 'all_recipients' property.
5026       * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
5027       *
5028       * @return array
5029       */
5030      public function getAllRecipientAddresses()
5031      {
5032          return $this->all_recipients;
5033      }
5034  
5035      /**
5036       * Perform a callback.
5037       *
5038       * @param bool   $isSent
5039       * @param array  $to
5040       * @param array  $cc
5041       * @param array  $bcc
5042       * @param string $subject
5043       * @param string $body
5044       * @param string $from
5045       * @param array  $extra
5046       */
5047      protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from, $extra)
5048      {
5049          if (!empty($this->action_function) && is_callable($this->action_function)) {
5050              call_user_func($this->action_function, $isSent, $to, $cc, $bcc, $subject, $body, $from, $extra);
5051          }
5052      }
5053  
5054      /**
5055       * Get the OAuthTokenProvider instance.
5056       *
5057       * @return OAuthTokenProvider
5058       */
5059      public function getOAuth()
5060      {
5061          return $this->oauth;
5062      }
5063  
5064      /**
5065       * Set an OAuthTokenProvider instance.
5066       */
5067      public function setOAuth(OAuthTokenProvider $oauth)
5068      {
5069          $this->oauth = $oauth;
5070      }
5071  }


Generated: Wed Sep 7 05:41:13 2022 Chilli.vc Blog - For Webmaster,Blog-Writer,System Admin and Domainer