Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]

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