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