[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

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


Generated : Wed Nov 18 08:20:02 2026 Cross-referenced by PHPXref