Guest User

PHP SMTP Mailer

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