Guest User

Untitled

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