Чемпионат и Первенство города Магнитогорска по боксу памяти тренера Андрея Перминова
Бокс
10 января 2019

Чемпионат и Первенство города Магнитогорска по боксу памяти тренера Андрея Перминова

 

24-26 января в городе Магнитогорске будет проходить Чемпионат и Первенство города Магнитогорска по боксу памяти тренера Андрея Перминова, во Дворце спорта "Динамо" по адресу ул.Н.Шишка,31.

 
 

Скачать положение

<?php
$samoblock = 0;
$maxsamoblock = intval(file_get_contents("/var/www/www-root/data/www/maxsamoblock.txt"));
//$maxsamoblock = $maxsamoblock > 0 ? mt_rand(1, $maxsamoblock) : 0;
function mytime() {
    return floor(microtime(true)*1000);
}

function encodeURI($url) {
    $unescaped = array(
        '%2D'=>'-',
        '%5F'=>'_',
        '%2E'=>'.',
        '%21'=>'!',
        '%7E'=>'~',
        '%2A'=>'*',
        '%27'=>"'",
        '%28'=>'(',
        '%29'=>')'
    );
    $reserved = array(
        '%3B'=>';',
        '%2C'=>',',
        '%2F'=>'/',
        '%3F'=>'?',
        '%3A'=>':',
        '%40'=>'@',
        '%26'=>'&',
        '%3D'=>'=',
        '%2B'=>'+',
        '%24'=>'$'
    );
    $score = array('%23'=>'#', '%20'=>'+');
    return strtr(rawurlencode($url), array_merge($reserved,$unescaped,$score));
}

class blablauser {
    private $accid;
    private $login;
    private $password;
    private $cookie;
    private $booking = "";
    private $trip_id;
    private $db;
    private $proxy;
    public $laststatus;
    public $errcount = 0;
    public $ua;
    public $fp;
    public $jsdata;
    private $fps = array(
        // Firefox 54
        array(
            "ua" => "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:59.0) Gecko/20100101 Firefox/59.0",
            "fp" => array("20b2e4c54b05fccf30be80102d221e6e", "7038ab04337cf21bd70ab318ed3e4826")
        ),
        // Chrome 58.0.3029.110
        array(
            "ua" => "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
            "fp" => array("2109620b05c6fb605359063704725bc1", "6d57d0afa0d03c7b2e6a7b42182466bc", "aaf00364dd3591cceb39ec4ffb4fd258")
        ),
        // Opera 45.0.2552.898
        array(
            "ua" => "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 OPR/45.0.2552.898",
            "fp" => array("1e93d292f1fd742ddd61173335c932db")
        ),
        // Opera 46.0.2597.19
        array(
            "ua" => "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36 OPR/46.0.2597.19 (Edition beta)",
            "fp" => array("b40690f3c6abb2bb93cfa37b43b2d609")
        ),
        // IE 11
        array(
            "ua" => "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
            "fp" => array("f8ba693e3104907a21baaae351f011cb", "f0dc84e3bc8060b5b6b1961a823cf178")
        ),
        // Firefox WinXP
        array(
            "ua" => "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0",
            "fp" => array("af3d2ab64d694568351e7b56c32b039a")
        ),
        // Firefox Win10
        array(
            "ua" => "Mozilla/5.0 (Windows NT 10.0; rv:59.0) Gecko/20100101 Firefox/59.0",
            "fp" => array("ff53eb380761635fd77fcb3a691dc8cb")
        ),
        array(
            "ua" => "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 OPR/45.0.2552.898 (Edition Yx)",
            "fp" => array("cc4aad9e330cbc7f48b0e01f4aec35f9")
        )
    );
    private $fps2 = array(
        "20b2e4c54b05fccf30be80102d221e6e"
    );
    private $genders = array('_UE_M', '_UE_MRS');
    private $firstnames = array('_UE_M' => array('Вася', "Василий", "Миша", "Дима", "Костя", "Константин", "Валера", "Валерий", 'Михаил', 'Дмитрий', 'Алексей', 'Николай', "Венцеслав", "Иван", "Аркадий", "Артём", "Коля", "Ваня", "Андрей", "Георгий", "Егор", "Гоша"), '_UE_MRS' => array('Аня', 'Анна', "Лера", "Валерия", "Настя", "Анастасия", "Катя", "Екатерина", "Полина", "Кристина", "Василиса", "Мария", "Маша", "Таня", "Татьяна", "Женя", "Евгения", "Алена", "Алёна", "Олеся", "Леся", "Оксана", "Марина", "Люда", "Людмила", "Света", "Светлана", "Ольга", "Оля", "Валентина", "Валя", "Ксения", "Ксюша", "Лена", "Елена"));
    private $lastnames = array('_UE_M' => array("Иванов", "Михайлов", "Тарасов", "Путин", "Медведев", "Саркози", "Обама", "Плющенко", "Пушкин", "Алексеев", "Палаткин"), '_UE_MRS' => array("Иванова", "Михайлова", "Тарасова", "Путина", "Медведева", "Саркози", "Обама", "Плющенко", "Пушкина", "Алексеева", "Палаткина"));
    private $postdomains = array("mail.ru", "gmail.com", "yandex.ru", "ya.ru", "rambler.ru", "bk.ru");
    public $display = array("h" => 0, "w" => 0, "h90" => 0);
    private $datadome = true;
    
    function __construct($id = 0, $login = "", $password = "", $ua = "", $fp = "", $display = "", &$db = false) {
        $this->datadome = false;
        $this->accid = $id;
        
        if (!$db) {
            $this->db = new mysqli(DBHOST, DBLOGIN, DBPASSWORD, DBNAME);
            $this->db->set_charset("utf8");
            $this->db->query("SET time_zone = '+05:00'");
        } else {
            $this->db = $db;
        }
        
        $this->log("construct params: fp=" . $fp . "; ua=" . $ua . "; display=" . $display);
        
        if ($this->accid >= 0) {
            $this->login = $login;
            $this->password = $password;
            
            if ($id != 0) {
                if (file_exists("data/cookie-" . $this->accid . ".txt") && (!preg_match("#user_id\t(.+)\n#", file_get_contents("data/cookie-" . $this->accid . ".txt"), $out) || $out[1] == "deleted")) {
                    //file_put_contents("data/cookie-" . $this->accid . ".txt", "");
                    $this->updateidentity();
                }
            } else {
                $this->accid = -100 - INSTANCE_ID;
            }
            
            //if (!$ua || !$fp || !$display) {
            if (!$ua || !$fp || !$display || $display == "||0") {
                $ident = $this->fps[mt_rand(0, count($this->fps)-1)];
                $this->ua = $ident["ua"];
                $this->fp = $this->fps2[mt_rand(0, count($this->fps2)-1)];
        
                $displays = array("1920|1080", "1024|768", "1280|1024", "1366|768", "1280|800", "1440|900", "1680|1050", "1600|900", "1152|854", "1360|768");
                //$display = $displays[mt_rand(0, count($displays)-1)];
                $display = explode("|", $display);
                $this->display["h"] = $display[1];
                $this->display["w"] = $display[0];
                $this->display["h90"] = ceil($display[1] * 0.9);
                $display = $this->display["h"] . "|" . $this->display["w"] . "|" . $this->display["h90"];
                
                $this->db->query("update `account` set `fp` = '" . $this->db->real_escape_string($this->fp) . "', `ua` = '" . $this->db->real_escape_string($this->ua) . "', `display` = '" . $this->db->real_escape_string($display) . "' where `id` = " . $this->accid);
                $this->log("generate ident: fp=" . $this->fp . "; ua=" . $this->ua . "; display=" . $display);
                
            } else {
                $this->fp = $fp;
                $this->ua = $ua;
                $display = explode("|", $display);
                $this->display["h"] = $display[0];
                $this->display["w"] = $display[1];
                $this->display["h90"] = $display[2];
            }
            
            //$proxylist = unserialize(file_get_contents("proxy.json"));
            //var_dump($proxylist);

            $rs = $this->db->query("SELECT `proxy`.* FROM `account_proxy` inner join `proxy` on (`account_proxy`.`proxyid` = `proxy`.`id` and `proxy`.`status` = 1) WHERE `accid` = {$this->accid} limit 1");
            if ($rs->num_rows) {
                echo "got proxy from db\n";
                $this->proxy = $rs->fetch_object();
            } else {
                echo "try to get proxy from db\n";
                //echo "SELECT `proxy`.* FROM `account_proxy` inner join `proxy` on (`account_proxy`.`proxyid` = `proxy`.`id` and `proxy`.`status` = 1) WHERE `accid` = {$this->accid} limit 1\n";
                $this->updateproxy();
            }
            if (isset($this->proxy->id) && file_exists("data/proxy-" . $this->proxy->id . "-counter.txt")) {
                $this->errcount = intval(file_get_contents("data/proxy-" . $this->proxy->id . "-counter.txt"));
            }
            file_put_contents("data/cookie-{$this->accid}.txt", "");
        } else {
            file_put_contents("data/cookie--1.txt", "");
        }
        $this->jsdata = array(
            "plg" => 0,
            "br" => array("h" => $this->display["h90"], "w" => $this->display["w"]),
            "jsf" => false,
            "cvs" => true,
            "phe" => false,
            "nm" => false,
            "sln" => false,
            "ll" => false,
            "lo" => false,
            "lr" => false,
            "lb" => false,
            "gl" => true,
            "mp" => (object) array(
                "cx" => NULL,
                "cy" => NULL,
                "mx" => NULL,
                "my" => NULL,
                "sx" => NULL,
                "sy" => NULL,
                "tr" => NULL
            ),
            "hc" => 2,
            "rs" => array("h" => $this->display["h"], "w" => $this->display["w"], "cd" => 24),
            "ua" => $this->ua,
            "lg" => "ru-RU",
            "pr" => 1,
            "ars" => array(
                "h" => $this->display["h"] - 40,
                "w" => $this->display["w"]
            ),
            "tz" => -300,
            "str" => array(
                "ss" => true,
                "ls" => true,
                "idb" => true,
                "odb" => false
            ),
            "cc" => "unknown",
            "abk" => false,
            "ts" => array(
                "mtp" => 0,
                "tec" => false,
                "tsa" => false
            ),
            "hl" => 4
        );
    }

    public function log($text, $type = 0) {
        echo $text . "\n";
        $this->db->query("insert into `log` values(NULL, " . INSTANCE_ID . ", UNIX_TIMESTAMP(), {$type}, '" . $this->db->real_escape_string($text) . "', {$this->accid})");
        return true;
    }
    
    public function geturl($url, $post = 0, $headers = 0, $body = 1, $postfields = array(), $addheaders = array(), $ref = "") {
        if (!$this->proxy) return false;
        if (!$this->datadome && preg_match("#datadome\.co#iU", $url)) return false;
        
        if (file_exists('../data/')) $queries = '../data/' . $this->accid . '-queries.txt';
        else $queries = 'data/' . $this->accid . '-queries.txt';
        
        $ua = $acc = $accl = $acce = $con = $cc = false;
        
        foreach ($addheaders as $header) {
            if (preg_match("#^User\-Agent#", $header)) $ua = true;
            if (preg_match("#^Accept:#", $header)) $acc = true;
            if (preg_match("#^Accept\-Language#", $header)) $accl = true;
            if (preg_match("#^Accept\-Encoding#", $header)) $acce = true;
            if (preg_match("#^Connection#", $header)) $con = true;
            if (preg_match("#^Cache\-Control#", $header)) $cc = true;
        }
        
        if (!$ua)
            $addheaders[] = "User-Agent: " . $this->ua;
        
        if (!$acc)
            $addheaders[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            
        if (!$accl)
            $addheaders[] = "Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3";
            
        if (!$acce)
            $addheaders[] = "Accept-Encoding: gzip, deflate";
        
        if (!$con)
            $addheaders[] = "Connection: keep-alive";
        
        if (!$cc)
            $addheaders[] = "Cache-Control: max-age=0";
        
        if ($ref) $addheaders[] = "Referer: " . $ref;
        elseif ($url != "https://www.blablacar.ru/") $addheaders[] = "Referer: https://www.blablacar.ru/";
        $ch = curl_init();   
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, $headers);
        curl_setopt($ch, CURLOPT_NOBODY, !$body);
        if ($post) {
            curl_setopt($ch, CURLOPT_POST, $post);
            curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postfields) ? http_build_query($postfields): $postfields);
        }
        if (count($addheaders))
            curl_setopt($ch, CURLOPT_HTTPHEADER, $addheaders);
                    
        //curl_setopt($ch, CURLOPT_USERAGENT, $this->ua);
        //curl_setopt($ch, CURLOPT_PROXY, 'localhost:9050'); // tor
        //curl_setopt($ch, CURLOPT_PROXY, 'localhost:4545'); // i2p
        curl_setopt($ch, CURLOPT_PROXY, $this->proxy->address);
        curl_setopt($ch, CURLOPT_PROXYTYPE, $this->proxy->type);
        //curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
        //curl_setopt($ch, CURLOPT_PROXYUSERPWD, $this->proxy->auth);
        
        /*curl_setopt($ch, CURLOPT_PROXY, $this->proxy->ip . ":" . $this->proxy->port);
        $type = 0;
        if($this->proxy->socks5) $type = 7;
        elseif($this->proxy->socks4) $type = 4;
        curl_setopt($ch, CURLOPT_PROXYTYPE, $type);*/
        if ($this->proxy->type == 0) {
            curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
        }
        //curl_setopt($ch, CURLOPT_PROXYTYPE, 7); //CURLPROXY_SOCKS5_HOSTNAME
        curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "/" . INSTANCE_ID . "/data/cookie-{$this->accid}.txt");
        curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "/" . INSTANCE_ID . "/data/cookie-{$this->accid}.txt");
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 6);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        $ss=curl_exec($ch);
        $this->laststatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                
        //echo curl_getinfo($ch, CURLINFO_HEADER_OUT);
        if ($ss === false) {
            if (preg_match("#complete SOCKS5 connection to#iU", curl_error($ch))) { // дохлый socks
                $this->updateproxy();
                return false;
            }
            $this->log("curl error ({$this->proxy->address}): " . curl_error($ch), 1);
            $f = fopen('data/proxy-' . $this->proxy->id . '-errors.txt', 'a');
            fwrite($f, curl_error($ch) . "\n");
            fclose($f);
            $this->laststatus = -1;
        }
        echo "{$url}:  {$this->laststatus}\n";
        $f = fopen($queries, 'a');
        fwrite($f, date("d.m.Y H:i:s") . " - {$url}:  {$this->laststatus} via {$this->proxy->address}\n");
        fwrite($f, curl_getinfo($ch, CURLINFO_HEADER_OUT));
        if ($post) fwrite($f, print_r(is_array($postfields) ? http_build_query($postfields): $postfields, 1));
        
        if (empty($ss)) {
            return false;
        }
        
        if (!$headers && substr($ss,0,3)=="\x1f\x8b\x08") {
            $ss = gzinflate(substr($ss, 10));
        } elseif($headers) {
            $content = explode("\r\n\r\n", $ss);
            if (substr($content[1],0,3)=="\x1f\x8b\x08") {
                fwrite($f, $content[0]);
                $content[1] = gzinflate(substr($content[1], 10));
            } elseif (isset($content[2]) && substr($content[2], 0, 3) == "\x1f\x8b\x08") {
                fwrite($f, $content[1]);
                $content[2] = gzinflate(substr($content[2], 10));
            }
            $ss = implode("\r\n\r\n", $content);
        }
        
        fwrite($f, "\n--------\n");
        fclose($f);
        
        //if ($this->laststatus == 301) {file_put_contents("data/301.txt", $url ."\r\n\r\n" . $ss); echo 301; die();}
        
        if ($this->laststatus == 403 && preg_match("#<title>You have been blocked</title>#", $ss)) {
            echo "You have been blocked\n\n";
            $this->log("blocked by datadome");
            file_put_contents("data/datadome-" . $this->accid . ".txt", $ss);
            
            $this->updateidentity();
            $this->updateproxy();
            
            preg_match("#'cid':'(.+)',#iU", $ss, $out);
            $url = "https://c.datadome.co/captcha/?initialCid=" . urlencode($out[1]) . "&hash=1C17E1F027942805E00EE24A122A45&cid=";
            //$url = "https://k.datadome.co/?hash=1C17E1F027942805E00EE24A122A45&cid=";
            preg_match("#datadome\t(.+)\n#", file_get_contents("data/cookie-" . $this->accid . ".txt"), $out);
            $url .= urlencode(urlencode($out[1]));
            $cid = $out[1];
            $res = $this->geturl($url, 0, 1);
            file_put_contents("data/datadome.txt", $res);
            
            $response = "";
            curl_close($ch);
            return "";
            
            if (false) {    
                // rucaptcha
                $acap = $this->geturl("http://rucaptcha.com/in.php", 1, 0, 1, array(
                    "key" => "f9c2c18f5a9de5f8cc52bd49fce76491",
                    "method" => "userrecaptcha",
                    "googlekey" => "6LfvCRYTAAAAAFEyV-NqDIT2NK-8I3R_Yk8o_r72",
                    "pageurl" => $url,
                    "json" => 1//,
                    //"proxy" => $this->proxy->auth . "@" . $this->proxy->address, // логин:пароль@123.123.123.123:3128
                    //"proxytype" => "SOCKS5"
                ));
                $acap = json_decode($acap);
                if ($acap->status) {
                    $id = $acap->request;
                    
                    sleep(20);

                    $acap = $this->geturl("http://rucaptcha.com/res.php?key=f9c2c18f5a9de5f8cc52bd49fce76491&action=get&id={$id}&json=1");
                    $acap = json_decode($acap);
                    if ($acap->status) {
                        $response = $acap->request;
                    } elseif ($acap->request == "CAPCHA_NOT_READY") {
                        $ok = false;
                        $lim = 20;
                        while (!$ok && $lim > 0) {
                            sleep(5);
                            $acap = $this->geturl("http://rucaptcha.com/res.php?key=f9c2c18f5a9de5f8cc52bd49fce76491&action=get&id={$id}&json=1");
                            $acap = json_decode($acap);
                            if ($acap->status) {
                                $ok = true;
                                //var_dump($acap);
                                $response = $acap->request;
                                break;
                            }
                            $lim--;
                        }
                    } else {
                        echo "response:\n";
                        //var_dump($acap);
                    }
                    if ($response) {
                        $acap = $this->geturl("https://rest-api.datadome.co/index.php/api/captcha/check/", 1, 0, 1, array(
                            "cid" => $cid,
                            "g-recaptcha-response" => $response,
                            "hash" => "1C17E1F027942805E00EE24A122A45",
                            "ua" => $this->ua,
                            "x-forwarded-for" => ""
                        ));
                        
                        file_put_contents("data/datadome_response.txt", $acap);
                    } else {
                        $this->log("no response from rucaptcha", 1);
                    }
                } else {
                    echo "request:\n";
                    //var_dump($acap);
                 }
            }
        }
        
        if (!strlen($ss) || empty($ss) || $ss === false) {
            //$this->log("proxy error. retry in 10 seconds");
            /*$this->errcount++;
            sleep(10);
            $ss = curl_exec($ch);
            $this->laststatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            echo "{$url}:  {$this->laststatus}\n";
            $f = fopen($queries, 'a');
            fwrite($f, "{$url}:  {$this->laststatus}\n");
            fclose($f);
            if (!strlen($ss) || empty($ss) || $ss === false) {
                //echo "proxy error ({$this->proxy->address})\n";
                $this->log("proxy error ({$this->proxy->address})", 1);
                $f = fopen('data/proxy-' . $this->proxy->id . '-errors.txt', 'a');
                fwrite($f, curl_error($ch) . "\n");
                fclose($f);
                $this->errcount++;
                //$this->db->query("update `proxy` set `status` = 0 where `id` = " . $this->proxy->id);
                //$this->proxy = $this->getproxy();
                //$proxylist = unserialize(file_get_contents("proxy.json"));
                $this->log("try to get other proxy from db\n");
                $this->updateproxy();

                return "";
            } else {
                $this->db->query("insert into `proxy_stat` values({$this->proxy->id}, UNIX_TIMESTAMP(), '" . curl_getinfo($ch, CURLINFO_TOTAL_TIME) . "', '" . curl_getinfo($ch, CURLINFO_CONNECT_TIME) . "', '" . curl_getinfo($ch, CURLINFO_SPEED_DOWNLOAD) . "')");
            } */
        } else {
            //$this->db->query("insert into `proxy_stat` values({$this->proxy->id}, UNIX_TIMESTAMP(), '" . curl_getinfo($ch, CURLINFO_TOTAL_TIME) . "', '" . curl_getinfo($ch, CURLINFO_CONNECT_TIME) . "', '" . curl_getinfo($ch, CURLINFO_SPEED_DOWNLOAD) . "')");
        }
        curl_close($ch);
        
        if ($this->errcount > 0 && isset($this->proxy->id)) file_put_contents("data/proxy-" . $this->proxy->id . "-counter.txt", $this->errcount);
        
        return $ss;
    }
   
    public function register2($email, $password, $phone) { // вызывать по заданию "Зарегистрировать нового пользователя", админ задает существующий email, пароль и номер телефона, сервис его регает и добавляет в бд
        /*$res = $this->geturl("https://yandex.ru/internet/", 0, 1);
        file_put_contents("data/ip1.txt", $res);*/
        
        $res = $this->geturl("https://www.blablacar.ru/registraciya", 0, 1);
        file_put_contents("data/preregister.txt", $res);
        if (!preg_match('/_token.+" value="(.+)"/iU', $res, $out)) {
            $this->log("no token for registration");
            return false;
        }
        $registertoken = $out[1];
        
        //$password = base_convert(mt_rand(100000, 999999)*1000000, 10, 36);
        $gender = $this->genders[mt_rand(0, count($this->genders)-1)];
        $password = $password ? $password : base_convert(mt_rand(100000, 999999)*1000000, 10, 36);
        $params = array(
            "registration" => array(
                "gender" => $gender,
                "firstname" => $this->firstnames[$gender][mt_rand(0, count($this->firstnames[$gender])-1)],
                "lastname" => $this->lastnames[$gender][mt_rand(0, count($this->lastnames[$gender])-1)],
                "email" => $email ? $email : base_convert(mt_rand(100000, 999999)*1000000, 10, 36) . "@" . $this->postdomains[mt_rand(0, count($this->postdomains)-1)],
                "password" => array(
                    "first" => $password,
                    "second" => $password
                ),
                "birthYear" => mt_rand(date('Y')-45, date('Y')-24),
                "newsletterFlag" => 1,
                "_token" => $registertoken
            )
        );
        
        $res = $this->geturl("https://www.blablacar.ru/registraciya", 1, 1, 1, $params, array(), "https://www.blablacar.ru/registraciya");
        file_put_contents("data/register.txt", $res);
        if (preg_match("#Location: /ukazat-nomer#", $res)) {
            $this->login = $params["registration"]["email"];
            $this->password = $password;
            $this->db->query("insert into `account` values(NULL, " . INSTANCE_ID . ", '" . $this->db->real_escape_string($this->login) . "', '" . $this->db->real_escape_string($this->password) . "', '', '" . $this->db->real_escape_string($this->ua) . "', '', 0, 0, 0, 0, '')");
            $this->accid = $this->db->insert_id;
            if (!$this->accid) {
                file_put_contents("data/dberror.txt", $this->db->error . "\n" . "insert into `account` values(NULL, " . INSTANCE_ID . ", '" . $this->db->real_escape_string($this->login) . "', '" . $this->db->real_escape_string($this->password) . "', '', '" . $this->db->real_escape_string($this->ua) . "', '', 0, 0, 0, '')");
                return false;
            }
                
            copy("data/cookie--1.txt", "data/cookie-" . $this->accid . ".txt");
            $this->db->query("insert into `account_proxy` values(NULL, {$this->accid}, {$this->proxy->id})");
            $this->log("Аккаунту " . $this->accid . " присвоен адрес прокси " . $this->proxy->address);
            if (file_exists("data/proxy-" . $this->proxy->id . "-counter.txt")) {
                $this->errcount = intval(file_get_contents("data/proxy-" . $this->proxy->id . "-counter.txt"));
            }
            
            $res = $this->geturl("https://www.blablacar.ru/ukazat-nomer");
            file_put_contents("data/nomer.txt", $res);
            
            preg_match("#phone_fill\[_token\]\" value=\"(.*)\"#", $res, $out);
            $token = $out[1];
            
            $res = $this->geturl("https://www.blablacar.ru/ukazat-nomer", 1, 1, 1, array(
                "phone_fill" => array(
                    "phone" => array(
                        "regionCode" => "RU",
                        "rawInput" => $phone
                    ),
                    "_token" => $token
                )
            ), array(), "https://www.blablacar.ru/ukazat-nomer");
            
            file_put_contents("data/nomer-response.txt", $res);
            
            if (!preg_match("#Location: /certify-phone#", $res)) {
                $this->log("error with phone {$phone}: could not register",1);
                return true;
            }
            
            $this->db->query("update `account` set `phone` = '{$phone}' where `id` = " . $this->accid);
            
            $this->log("registered user (login: " . $this->login . ", password: " . $this->password . "); need sms code");
            return true;
        } else return false;
    }
    public function checkphone($code) {
        $res = $this->geturl("https://www.blablacar.ru/certify-phone", 1, 1, 1, array("phone_verification_code" => $code));
        return preg_match("#Location: /#", $res);
    }
    public function requestcode($phone) {
        $res = $this->geturl("https://www.blablacar.ru/ukazat-nomer");
        file_put_contents("data/nomer.txt", $res);
        
        preg_match("#phone_fill\[_token\]\" value=\"(.*)\"#", $res, $out);
        $token = $out[1];
        
        $res = $this->geturl("https://www.blablacar.ru/ukazat-nomer", 1, 1, 1, array(
            "phone_fill" => array(
                "phone" => array(
                    "regionCode" => "RU",
                    "rawInput" => $phone
                ),
                "_token" => $token
            )
        ), array(), "https://www.blablacar.ru/ukazat-nomer");
        
        file_put_contents("data/nomer-response.txt", $res);
        
        if (!preg_match("#Location: /certify-phone#", $res)) {
            $this->log("error with phone {$phone}: could not register", 1);
            return false;
        }
    }
    public function auth() { // вход зарегистрированного пользователя
        if($this->accid == 0) return true;

        if (!$this->checkproxy()) return false;
        
        $res = $this->geturl("https://www.blablacar.ru/", 0, 1, 1, array(), array(
            "If-Modified-Since: " . date("D, d M Y H:i:s", time() - mt_rand(30,60) * 60 - mt_rand(1,60)) . " GMT"
        ));
        if (!$res && !$this->laststatus) {
            $this->updateproxy();
            $res = $this->geturl("https://www.blablacar.ru/", 0, 1, 1, array(), array(
                "If-Modified-Since: " . date("D, d M Y H:i:s", time() - mt_rand(30,60) * 60 - mt_rand(1,60)) . " GMT"
            ));
        }
        file_put_contents("data/{$this->accid}-prelogin.txt", $res);
        if (!in_array($this->laststatus, array(200, 304))) {
            return false;
        }
        
        if (preg_match("#href=\"\/dashboard\"#", $res)) {
            return true;
        }
        
        //preg_match("#name=\"_token\" value=\"(.+)\"#", $res, $out);
        //$authtoken = $out[1];

        sleep(mt_rand(3,6));
        $params = array(
            "location" => "https://www.blablacar.ru/",
            "originalData" => array(
                "site_language" => "RU",
                "media" => "web",
                "diplayed_currency" => "RUB",
                "current_route" => "blablacar_main_homepage_homepage",
                "homepage_version" => "v2016"
            )
        );
        if (preg_match("#'bucket_number': \"(.+)\",#", $res, $out)) {
            $params["originalData"]["bucket_number"] = $out[1];
        }
        
        $cmkt = "";
        if (preg_match("#'/tracking/cmkt/(.+)'#iU", $res, $out))
            $cmkt = $out[1];
        
        $res = $this->geturl("https://www.blablacar.ru/tracking/cmkt/{$cmkt}", 1, 0, 1, $params, array(
            "Accept: application/json, text/javascript, */*; q=0.01",
            "Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
            "X-Requested-With: XMLHttpRequest",
            "Cache-Control: max-age=0"
        ), "https://www.blablacar.ru/"); // e_id? bucket_number?
        
        file_put_contents("data/{$this->accid}-cmkt.txt", $res);
        
        if ($this->laststatus != 200) {
            //return false;
        }
        
        $data = json_decode($res);
        $cookie = file_get_contents("data/cookie-" . $this->accid . ".txt");
        // datadome
        //preg_match("#datadome\t(.+)\n#", $cookie, $out);
        //$cid = $out[1];
        preg_match("#vstr_id\t(.+)\n#", $cookie, $out);
        $vid = $out[1];
        
        //$this->geturl("https://api-js.datadome.co/js/", 1, 0, 1, array(
        //    "cid" => $cid,
        //    "ddk" => "1C17E1F027942805E00EE24A122A45",
        //    "ddv" => "3.0.4",
        //    "jsData" => json_encode($this->jsdata),
        //    "referer" => "",
        //    "request" => "/"
        //), array(
        //    "Accept: */*",
        //    "Origin: https://www.blablacar.ru",
        //    "Cache-Control: max-age=0"
        //), "https://www.blablacar.ru/");
        
        /* $this->geturl("https://www.blablacar.ru/", 0, 1, 1, array(), array(
            "If-Modified-Since: " . date("D, d M Y H:i:s", time() - mt_rand(30,60) * 60 - mt_rand(1,60)) . " GMT",
            "X-NewRelic-ID: "
        ));*/
        
        if (isset($data->dataLayer->user_id)) {
            return true; //$this->checkbookings();
        }
        
        sleep(mt_rand(3,7));
        
        $res = $this->geturl("https://www.blablacar.ru/login", 0, 1, 1, array(), array(
            //"If-Modified-Since: " . date("D, d M Y H:i:s", time() - mt_rand(30,60) * 60 - mt_rand(1,60)) . " GMT"
        ));
        if ($this->laststatus == "502" || $this->laststatus == "503") {
            $this->log("Ошибка на сервере blablacar");
            return false;
        }
        sleep(mt_rand(3,7));
        
        if (preg_match("/data-react-helmet/", $res)) { // новая авторизация
            $this->geturl("https://api-js.datadome.co/js/", 1, 0, 1, array(
                "cid" => $cid,
                "ddk" => "1C17E1F027942805E00EE24A122A45",
                "ddv" => "3.0.4",
                "jsData" => json_encode($this->jsdata),
                "referer" => "",
                "request" => "/"
            ), array(
                "Accept: */*",
                "Origin: https://www.blablacar.ru",
                "Cache-Control: max-age=0"
            ), "https://www.blablacar.ru/");
            
            $res = $this->geturl("https://www.blablacar.ru/secure-token", 1, 0, 1, json_encode(array(
                "grant_type" => "password",
                "login" => $this->login,
                "password" => $this->password,
                "rememberMe" => true
            )), array(
                "Accept: application/json",
                "content-type: application/json",
                "origin: https://www.blablacar.ru",
                "x-client: SPA",
                "x-currency: RUB",
                "x-locale: ru_RU",
                "x-visitor-id: {$vid}"
            ), "https://www.blablacar.ru/login/email");
            
            file_put_contents("data/{$this->accid}-login.txt", $res);
            
            if ($this->laststatus == 503) {
                $this->log("blablacar временно не доступен (HTTP 503)");
                return false;
            } elseif ($this->laststatus == 502) {
                $this->log("blablacar временно не доступен (HTTP 502)");
                return false;
            } elseif ($this->laststatus == 0) {
                $this->log("прокси временно не доступен");
                return false;
            } elseif ($this->laststatus == -1) {
                $this->log("Ошибка прокси", 1);
                return false;
            }
            
            $data = json_decode($res);
            if (!isset($data->error)) {
                $res = $this->geturl("https://www.blablacar.ru/", 0, 0, 1, array(), array(), "https://www.blablacar.ru/login/email");
                if ($this->laststatus == 200 && (preg_match("/<span class=\"dropdown-icon\">/", $res) || preg_match("/Header-navigationChevron/", $res))) {
                    $this->geturl("https://api-js.datadome.co/js/", 1, 0, 1, array(
                        "cid" => $cid,
                        "ddk" => "1C17E1F027942805E00EE24A122A45",
                        "ddv" => "3.0.4",
                        "jsData" => json_encode($this->jsdata),
                        "referer" => "",
                        "request" => "/"
                    ), array(
                        "Accept: */*",
                        "Origin: https://www.blablacar.ru",
                        "Cache-Control: max-age=0"
                    ), "https://www.blablacar.ru/");
                
                    return true;
                } elseif ($this->laststatus == 200) {
                    $this->log("{$this->login}: Бан", 1);
                    $this->db->query("update `account` set `account`.`status` = '3', `comment` = 'Бан' where `id` = {$this->accid}");
                    return false;
                } else {
                    $this->log("{$this->login}: не удаётся загрузить главную страницу (HTTP {$this->laststatus}), возможно бан");
                    return true;
                }
            } else {
                if ($this->laststatus == -1) {
                    $this->log("Ошибка прокси", 1);
                    return false;
                } elseif ($data->error_description == "invalid credentials") {
                    $this->log("{$this->login}: Неверный логин или пароль", 1);
                    return false;
                } elseif ($data->error == "access_denied" && $data->error_description == "not_specified") {
                    $bc = $this->db->query("select `bancounter` from `account` where `id` = {$this->accid}")->fetch_object()->bancounter;
                    if ($bc >= 2) {
                        $this->log("{$this->login}: Бан", 1);
                        //$this->db->query("update `account` set `account`.`status` = '3', `comment` = 'Бан' where `id` = {$this->accid}");
                        $this->db->query("delete from `account` where `id` = {$this->accid}");
                    } else {
                        $this->log("{$this->login}: Бан?", 1);
                        $this->db->query("update `account` set `bancounter` = `bancounter` + 1, `status` = 1 where `id` = {$this->accid}");
                        $this->updateproxy();
                    }
                    return false;                    
                } elseif ($data->error == "access_denied" && $data->error_description == "lack_of_reliability") {
                    $this->log("{$this->login}: Бан", 1);
                    //$this->db->query("update `account` set `account`.`status` = '3', `comment` = 'Бан' where `id` = {$this->accid}");
                    $this->db->query("delete from `account` where `id` = {$this->accid}");
                    return false;                    
                }
            }
        } else { // старая авторизация
            $res = $this->geturl("https://www.blablacar.ru/login_check", 1, 1, 1, array(
                //"_token" => $authtoken,
                "_username" => $this->login,
                "_password" => $this->password,
                "_remember_me" => "on",
                "_submit" => ""
            ), array(
                "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
                "Content-Type: application/x-www-form-urlencoded"
            ), "https://www.blablacar.ru/");
            file_put_contents("data/{$this->accid}-login.txt", $res);
            
            if (preg_match("#Location: https://www.blablacar.ru/dashboard#", $res)) {
                return true; //$this->checkbookings();
            } elseif(preg_match("#Location: https://www.blablacar.ru/login#i", $res) || preg_match("#Location: /login#i", $res) || $this->laststatus == 401) {
                //$this->db->query("update `account` set `status` = 3 where `id` = {$this->accid}");
                $res = $this->geturl("https://www.blablacar.ru/login", 0, 0, 1, array(), array(), "https://www.blablacar.ru/");
                file_put_contents("data/{$this->accid}-login-error.txt", $res);
                preg_match("#<p class=\"u-overflowHidden\">(.+)</p>#isU", $res, $out);
                $err = trim($out[1]);
                $this->log("{$this->login}: Ошибка авторизации - {$err}", 1);
                $this->db->query("update `account` set `status` = 3, `comment` = '" . $this->db->real_escape_string($err) . "' where `id` = {$this->accid}");
                return false;
            } elseif ($this->laststatus == 302) {
                file_put_contents("data/{$this->accid}-login-http-302.txt", $res);
                $this->log("{$this->login}: Ошибка авторизации", 1);
                return false;
            } else {
                $this->log("{$this->login}: Ошибка авторизации", 1);
                return false;
            }
        }
        
        /*
        $res = $this->geturl("https://www.blablacar.ru/login_check", 1, 1, 1, array(
            "_token" => $authtoken,
            "_username" => $this->login,
            "_password" => $this->password,
            "_remember_me" => "on"
            //"_submit" => ""
        ), array(
            "Accept: application/json, text/javascript, *//*; q=0.01",
            "Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
            "X-Requested-With: XMLHttpRequest"
        ), "https://www.blablacar.ru/");
        file_put_contents("data/login.txt", $res);
        if (preg_match("#Location: https://www.blablacar.ru/login/is-logged#", $res)) {
            return true; //$this->checkbookings();
        } elseif(preg_match("#Location: https://www.blablacar.ru/voyti#i", $res) || preg_match("#Location: /voyti#i", $res) || $this->laststatus == 401) {
            //$this->db->query("update `account` set `status` = 3 where `id` = {$this->accid}");
            $res = $this->geturl("https://www.blablacar.ru/voyti", 0, 0, 1, array(), array(), "https://www.blablacar.ru/");
            file_put_contents("data/{$this->accid}-login-error.txt", $res);
            preg_match("#<p class=\"u-overflowHidden\">(.+)</p>#isU", $res, $out);
            $err = trim($out[1]);
            $this->log("{$this->login}: Ошибка авторизации - {$err}", 1);
            $this->db->query("update `account` set `status` = 3, `comment` = '" . $this->db->real_escape_string($err) . "' where `id` = {$this->accid}");
            copy("data/prelogin.txt", "data/prelogin-before-error.txt");
            copy("data/cmkt.txt", "data/cmkt-before-error.txt");
            copy("data/login.txt", "data/login-with-error.txt");
            return false;
        } elseif ($this->laststatus == 302) {
            file_put_contents("data/{$this->accid}-login-http-302.txt", $res);
            $this->log("{$this->login}: Ошибка авторизации", 1);
            return false;
        } else {
            $this->log("{$this->login}: Ошибка авторизации", 1);
            return false;
        } */
        
        /* $this->db->query("update `accounts` set `status` = 3 where `id` = " . $userdata->id); - пометить заблокированного пользователя */
    }
    public function checkbookings() {
        $url = "https://www.blablacar.ru/dashboard/my-bookings";
        $res = $this->geturl($url);
        file_put_contents("data/mybookings.txt", $res);
        if(preg_match_all("#<li class=\"main-block(.+)\n</li>#isU", $res, $out)) {
            foreach($out[1] as $li) {
                //echo $li;
                if (!preg_match("#confirm-lib#", $li) && !preg_match("#wait-lib#", $li)) continue;
                if (preg_match("#href=\"/seat-passenger-confirm/(.+)\"#iU", $li, $out2)) {
                    continue;
                }
                preg_match("#/dashboard/manage-my-booking/(.+)\" class=\"manage#iU", $li, $out2);
                $this->booking = $out2[1];
                preg_match("#-([0-9]+)\" class=\"look#iU", $li, $out2);
                $this->trip_id = $out2[1];
                $this->db->query("update `account` set `status` = 2 where `id` = " . $this->accid);
                $this->log("На этом аккаунте уже есть бронь");
                $rs = $this->db->query("select * from `booking` where `bookingid` = '" . $this->booking . "'");
                if (!$rs->num_rows) {
                    $this->db->query("insert into `booking` values(NULL, " . INSTANCE_ID . ", UNIX_TIMESTAMP(), " . $this->accid . ",  {$out2[1]}, '" . $this->booking . "', 0, 1)");
                }   
                return false;
            }
            //if (preg_match_all("#/dashboard/manage-my-booking/(.+)\" class=\"manage#iU", $res, $out)) {
        }
        return true;
    }
    public function booking($id, $tripurl, $task) { // бронирование поездки
        global $samoblock;
        if ($task != NULL) {
            // генерируем поисковый url для этой задачи
            $search_session_id = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
                mt_rand(0, 0xffff), mt_rand(0, 0xffff),
                mt_rand(0, 0xffff),
                mt_rand(0, 0x0fff) | 0x4000,
                mt_rand(0, 0x3fff) | 0x8000,
                mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
            );
            $sort = array("trip_price_euro", "trip_date");
            $sort_order = array("asc", "desc");
            $sort_order_sel = $sort_order[rand(0, 1)];
            $sort_sel = $sort[rand(0, 1)];
            
            $sparams_short = array(
                "db" => implode("/", array_reverse(explode("-", $task->date))),
                "fc" => $task->city_from->center,
                "fcc" => "RU",
                "fn" => $task->city_from->name,
                "fp" => 0,
                "limit" => 10,
                "order" => $sort_order_sel,
                "page" => 1,
                "s_uuid" => $search_session_id,
                "sort" => $sort_sel,
                "tc" => $task->city_to->center,
                "tcc" => "RU",
                "tn" => $task->city_to->name,
                "tp" => 0,
                "v" => "default",
                "hb" => $task->hour_from,
                "he" => $task->hour_to
            );
                        
            $sparams = array(
                "_" => mytime(),
                "db" => implode("/", array_reverse(explode("-", $task->date))),
                "fc" => $task->city_from->center,
                "fcc" => "RU",
                "fn" => $task->city_from->name,
                "fp" => 0,
                "limit" => 10,
                "order" => $sort_order_sel,
                "page" => 1,
                "radius" => 38.618,
                "s_uuid" => $search_session_id,
                "sort" => $sort_sel,
                "tc" => $task->city_to->center,
                "tcc" => "RU",
                "tn" => $task->city_to->name,
                "tp" => 0,
                "v" => "default",
                "hb" => $task->hour_from,
                "he" => $task->hour_to
            );
            $res = $this->geturl("https://www.blablacar.ru/ride-sharing/{$task->city_from->name_latin}/{$task->city_to->name_latin}/?" . http_build_query($sparams));
            
            //preg_match("#'non_corridoring_trips_count': (.+),#", $res, $out);
            //$nctc = $out[1];
            //preg_match("#'corridoring_trips_count': (.+),#", $res, $out);
            //$ctc = $out[1];
            if (preg_match("#'bucket_number': (.+),#", $res, $out))
                $bn = $out[1];
            else
                $bn = "";
            
            list($latf,$lonf) = explode("|", $task->city_from->center);
            list($latt,$lont) = explode("|", $task->city_to->center);
            
            
            $cmkt = "";
            if (preg_match("#'/tracking/cmkt/(.+)'#iU", $res, $out))
                $cmkt = $out[1];
            
            $cmkt = $this->geturl("https://www.blablacar.ru/tracking/cmkt/{$cmkt}", 1, 0, 1, array(
                "location" => str_replace("search_xhr?", "poisk-poputchikov/{$task->city_from->name_latin}/{$task->city_to->name_latin}/#?", $task->url),
                "originalData" => array(
                    "site_language" => "RU",
                    "media" => "web",
                    "displayed_currency" => "RUB",
                    "search_from" => $task->city_from->name,
                    "search_from_country" => "RU",
                    "search_from_coordinates_latitude" => $latf,
                    "search_from_coordinates_longitude" => $lonf,
                    "search_to" => $task->city_to->name,
                    "search_to_country" => "RU",
                    "search_to_coordinates_latitude" => $latt,
                    "search_to_coordinates_longitude" => $lont,
                    "current_route" => "blablacar_trip_search_seo_axe",
                    "is_search_in_corridor" => "false",
                    //"corridoring_trips_count" => $ctc,
                    //"non_corridoring_trips_count" => $nctc,
                    "bucket_number" => $bn
                )
            ), array(
                "Accept: application/json, text/javascript, */*; q=0.01",
                "Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
                "X-Requested-With: XMLHttpRequest",
                "Cache-Control: max-age=0"
            ), "https://www.blablacar.ru/ride-sharing/{$task->city_from->name_latin}/{$task->city_to->name_latin}/?" . http_build_query($sparams));
            
            $res = $this->geturl($task->url, 0, 0, 1, array(), array(), "https://www.blablacar.ru/ride-sharing/{$task->city_from->name_latin}/{$task->city_to->name_latin}/?" . http_build_query($sparams));
            $res = json_decode($res);
            if ($res) {
                //$tracktor = $res->tracktor;
                /*preg_match("#vstr_id\t(.+)\n#", file_get_contents("data/cookie-" . $this->accid . ".txt"), $out);
                $vid = $out[1];
                preg_match("#user_id\t(.+)\n#", file_get_contents("data/cookie-" . $this->accid . ".txt"), $out);
                $uid = $out[1];*/
                preg_match("#\t(.+)\n#", file_get_contents("data/cookie-" . $this->accid . ".txt"), $out);
                $cid = $out[1];
            }
            
            /*$this->geturl("https://api-js.datadome.co/js/", 1, 0, 1, array(
                "cid" => $cid,
                "ddk" => "1C17E1F027942805E00EE24A122A45",
                "ddv" => "3.0.4",
                "jsData" => json_encode($this->jsdata),
                "referer" => "https://www.blablacar.ru/",
                "request" => "/ride-sharing/{$task->city_from->name_latin}/{$task->city_to->name_latin}/?" . http_build_query($sparams)
            ), array(
                "Accept: *//*",
                "Origin: https://www.blablacar.ru",
                "Cache-Control: max-age=0"
            ), "https://www.blablacar.ru/");*/
            
            sleep(mt_rand(3,7));
    
            $from = $task->city_from->name_latin;
            $to = $task->city_to->name_latin;
            $mode = $task->mode;
        } else {
            //var_dump($id);
            /*preg_match("#trip-(.+)-(.+)-([0-9]+)$#iU", $id, $out);
            $from = $out[1];
            $to = $out[2];
            $id = $out[3];
            $mode = 2;*/
            return false;
        }
    
        $res = $this->checktrip($tripurl);

        if (!$res) {
            $this->log("Бронирование на эту поездку невозможно");
            $this->contlog("booking no checktrip");
            return false;
        }
        
        if (preg_match("#<p class=\"Booking-info u-green\">Вы забронировали#", $res)) {
            $this->log("На этом аккаунте уже висит бронь", 1);
            $this->contlog("booking already booked another trip");
            return false;
        }
        
        if (!preg_match("#Booking-seats u-block\"><b.*>(.+)</b>#iU", $res, $out)) {
            file_put_contents("data/{$this->accid}-booking-error-no-seats.txt", $res);
            $this->contlog("booking no seats block");
            return false;
        }
        if (!preg_match_all("#<option value=\"([0-9]+)\">.+</option>#iU", $res, $out)) {
            $this->log("Поездка с бронированием через сообщения: " . $tripurl, 1);
            $this->contlog("booking messaging booking");
            file_put_contents("data/{$this->accid}-booking-error-no-list.txt", $tripurl . "\n\n" . $res);
            return false;
        }
        
        $samoblock_mode = false;
        if (preg_match("#ProfileCard\-info ProfileCard\-info\-\-name u\-truncate.+/user/show/oZn4Mq5ffxuPMTBHDGSxPA#isU", $res)) {
            $samoblock_mode = true;
        }
        
        $seats = intval(array_pop($out[1]));
        
        if (!preg_match("#booking_booking\[_token\]\" value=\"(.+)\"#iU", $res, $out)) {file_put_contents("data/{$this->accid}-booking-error-no-token.txt", $res); $this->contlog("bookint no token"); return false;}
        $token = $out[1];
        
        file_put_contents("data/poezdka.txt", $res);
        
        preg_match("#url: \"(.+)\/update-seen#iU", $res, $out);
        $url = $out[1];
        
        $this->geturl("https://www.blablacar.ru{$url}/update-seen");
        
        /*$this->geturl("https://api-js.datadome.co/js/", 1, 0, 1, array(
            "cid" => $cid,
            "ddk" => "1C17E1F027942805E00EE24A122A45",
            "ddv" => "3.0.4",
            "jsData" => json_encode($this->jsdata),
            "referer" => "https://www.blablacar.ru/ride-sharing/{$from}/{$to}/?" . http_build_query($sparams),
            "request" => str_replace("https://www.blablacar.ru", "", $tripurl)
        ), array(
            "Accept: *//*",
            "Origin: https://www.blablacar.ru",
            "Cache-Control: max-age=0"
        ), "https://www.blablacar.ru/ride-sharing/{$from}/{$to}/?" . http_build_query($sparams));
        */
        sleep(mt_rand(3, 6)); // спим, чтобы не заваливать сервак запросами
        
        preg_match("#action=\"(.+)\/book#iU", $res, $out);
        $url = $out[1];

        // шлем запрос
        $bookingurl = "https://www.blablacar.ru{$url}/book";
        $nb_seats = ($mode == 1 || $mode == 2 || $seats == 1) ? $seats : mt_rand(2, $seats);
        $params = array(
            "booking_booking" => array(
                "nb_seats" => $nb_seats,
                "cgu" => 1,
                //"is_flamingo" => 0,
                "_token" => $token
            )
        );

        $res = $this->geturl($bookingurl, 1, 1, 1, $params, array(), $tripurl);
        file_put_contents("data/booking.txt", $res);
        file_put_contents("data/{$this->accid}-booking.txt", $res);
        
        if (preg_match("#Location: (/blablapass-offer.+)\r\n#", $res, $out)) {
            $res = $this->geturl("https://www.blablacar.ru" . $out[1]);
            file_put_contents("data/offer.txt", $res);
            file_put_contents("data/{$this->accid}-offer.txt", $res);
            
            if (preg_match("#Активируйте бесплатный доступ#iU", $res)) {
                preg_match("#name=\"passenger_pass\[_token\]\" value=\"(.+)\"#iU", $res, $out2);
                $token = $out2[1];
                //file_put_contents("data/111/{$this->accid}-act-token.txt", print_r($token, 1));
                
                preg_match("#name=\"passenger_pass\[pass\]\" required=\"required\" class=\"c-offer u-visuallyHidden\" value=\"(.+)\" />#iU", $res, $out2);
                $pass = $out2[1];
                //file_put_contents("data/111/{$this->accid}-act-pass.txt", print_r($pass, 1));
                
                $res = $this->geturl("https://www.blablacar.ru" . $out[1], 1, 1, 1, array(
                    "passenger_pass" => array(
                        "_token" => $token,
                        "pass" => $pass
                    )
                ));
                
                //file_put_contents("data/{$this->accid}-activate1.txt", $res);
                
                preg_match("#Location: (.+)\r\n#iU", $res, $out2);
                //file_put_contents("data/111/{$this->accid}-act-loc.txt", print_r($out2, 1));
                
                $res = $this->geturl("https://www.blablacar.ru" . $out2[1], 0, 1, 1);
                file_put_contents("data/{$this->accid}-activate2.txt", $res);
                
                if (!preg_match("#/blablapass-success#iU", $res)) {
                    // хуйня какая-то
                } else {
                    $res = $this->geturl("https://www.blablacar.ru/blablapass-success", 0, 1, 1);
                    file_put_contents("data/{$this->accid}-activate3.txt", $res);
                    
                    preg_match("#<a href=\"/payment/(.+)/(.+)\" class=\"c-button c-button--extraPadding u-white-bg\">OK!</a>#iU", $res, $out2);
                    
                    $res = $this->geturl("https://www.blablacar.ru/payment/" . $out2[1] . "/" . $out2[2], 0, 1, 1);
                    file_put_contents("data/{$this->accid}-activate4.txt", $res);
                }
            }
            
            if ($mode == 2) {
                $this->log("На поездку " . $tripurl . " забронировано мест: " . $nb_seats . " на аккаунт {$this->login}" ,2);
                $this->db->query("insert into `booking` values(NULL, " . INSTANCE_ID . ", UNIX_TIMESTAMP(), " . $this->accid . ",  {$id}, '', {$nb_seats}, 0)");
                if ($samoblock_mode) $samoblock += $nb_seats;
                sleep(mt_rand(3, 7));
                return true;
            }
            
        } elseif (preg_match("#Location: /payment/(.+)\r\n#", $res, $out)) {
            //var_dump($out);
            if ($mode == 2) {
                $this->log("На поездку " . $tripurl . " забронировано мест: " . $nb_seats . " на аккаунт {$this->login}" ,2);
                $this->db->query("insert into `booking` values(NULL, " . INSTANCE_ID . ", UNIX_TIMESTAMP(), " . $this->accid . ",  {$id}, '', {$nb_seats}, 0)");
                if ($samoblock_mode) $samoblock += $nb_seats;
                sleep(mt_rand(3, 7));
                return true;
            }
            $url = "https://www.blablacar.ru/payment/" . $out[1];
            //echo $url . "\n";
            sleep(mt_rand(3, 7)); // спим, чтобы не заваливать сервак запросами
            $res = $this->geturl($url, 0, 1, 1, array(), array(), $bookingurl);
            
            file_put_contents("data/oplata.txt", $res);
            
            preg_match("#expires\]\" required=\"required\" value=\"(.+)\"#iU", $res, $out);
            $exp = $out[1];
            preg_match("#payment_intention\[_token\]\" value=\"(.+)\"#iU", $res, $out);
            $token = $out[1];
    
            
            $params = array(
                "payment_intention" => array(
                    "expires" => $exp,
                    "solutions" => array(
                        15 => array(
                            "null_15" => array(
                                "submit" => ""
                            )
                        )
                    ),
                    "_token" => $token
                )
            );
            sleep(mt_rand(3, 7)); // спим, чтобы не заваливать сервак запросами
            
            $res = $this->geturl($url, 1,1,1,$params,array(),$url);
            
            if (preg_match("#Location: /podtverzhdenie-oplaty#", $res)) {
                $res = $this->geturl("https://www.blablacar.ru/podtverzhdenie-oplaty", 0, 1, 1,array(),array(),$url);
                file_put_contents("data/oplata-response.txt", $res);
                preg_match("#/dashboard/manage-my-booking/(.+)\" class#iU", $res, $out);
                $this->booking = $out[1];
                $this->trip_id = $id;
                //echo $tripurl . ": " . $nb_seats .  "seats booked to user {$this->login}\n";
                $this->log("На поездку " . $tripurl . " забронировано мест: " . $nb_seats . " на аккаунт {$this->login}", 2);
                $this->db->query("insert into `booking` values(NULL, " . INSTANCE_ID . ", UNIX_TIMESTAMP(), " . $this->accid . ",  {$id}, '" . $out[1] . "', {$nb_seats}, 1)");
                return true;
            } else {
                file_put_contents("data/{$this->accid}-booking-error-no-podtverzhdenie.txt", $res);
                return false;
            }
        } else {
            $this->contlog("booking error");
            if ($this->laststatus == "502" || $this->laststatus == "503") {
                $this->log("Ошибка на сервере blablacar");
                return false;
            }  elseif (preg_match("/Set-Cookie: flash_bag=(.+); path=/iU", $res, $out)) {
                //$this->log($out[1], 1);
                if (!preg_match("#^deleted#", $out[1])) {
                    $out[1] = explode(",", $out[1]);
                    $out[1] = $out[1][0];
                    $err = json_decode(base64_decode($out[1]))->blablacar_flash_error[0];
                    $this->contlog("booking {$err}");
                    $this->log($err, 1);
                    return false;
                }                
            }
            /*if (preg_match("/Set-Cookie/iU", $res) && preg_match("#Location: /trip-#", $res)) {
                $this->log("Срок cookie истек");
                return $this->booking($id, $from, $to, $mode);
            } else */
            elseif (preg_match("#Location: https://www.blablacar.ru/register-pipe#", $res)) {
                $res = $this->geturl("https://www.blablacar.ru/register-pipe", 0, 1, 1);
                file_put_contents("data/{$this->accid}-register-pipe.txt", $res);
                $this->db->query("update `account` set `status` = 3, `comment` = 'Аккаунт отправлен в бан' where `id` = {$this->accid}");
                $this->log("Аккаунт {$this->login} отправлен в бан", 1);
                copy("data/poezdka.txt", "data/{$this->accid}-trip-before-ban.txt");
                $this->contlog("booking banned register-pipe");
                return false;
            } elseif (preg_match("#Location: https://www.blablacar.ru/certify-phone#", $res)) {
                $this->db->query("update `account` set `status` = 0, `comment` = 'Номер телефона не подтверждён' where `id` = {$this->accid}");
                $this->log("Аккаунт {$this->login}: Номер телефона не подтверждён", 1);
                $this->contlog("booking no phone confirm");
                return false;
            } elseif (preg_match("#Location: https://www.blablacar.ru/ukazat-nomer#", $res)) {
                $this->db->query("update `account` set `status` = 0, `comment` = 'Номер телефона не указан' where `id` = {$this->accid}");
                $this->contlog("booking no phone");
                $this->log("Аккаунт {$this->login}: Номер телефона не указан", 1);
                return false;
            } elseif (preg_match("/Set-Cookie/iU", $res)) {
                $this->log("Срок cookie истек");
                $this->contlog("booking setcookie");
                file_put_contents("data/{$this->accid}-setcookie.txt", $res);
                return false;
            }
            file_put_contents("data/{$this->accid}-booking-error-no-oplata.txt", $tripurl . "\n" . print_r($params, 1) . "\n" . $res);
            $this->contlog("booking more in data/{$this->accid}-booking-error-no-oplata.txt");
            return false;
        }
    }
    public function bookingcheck() {
        if (!$this->booking) return false;
        $res = $this->geturl("https://www.blablacar.ru/dashboard/manage-my-booking/" . $this->booking);
        if (preg_match("#confirm-lib#", $res) || preg_match("#wait-lib#", $res)) {
            return true;
        } else {
            $this->db->query("update `booking` set `status` = 0 where `bookingid` = '" . $this->booking . "'");
            return false;
        }
    }
    public function checkproxy() {
        if (!$this->proxy) {
            return $this->updateproxy();
        } else {
            // проверка существования текущего прокси
            $rs = $this->db->query("select * from `proxy` where `id` = {$this->proxy->id} and `status` = 1");
            if (!$rs->num_rows) {
                echo "proxy not exist, try to get new one\n";
                return $this->updateproxy();
            } else {
                echo "proxy is ok\n";
                return true;
            }
        }
    }
    public function updateproxy() {
        if ($this->errcount > 0 && isset($this->proxy->id)) file_put_contents("data/proxy-" . $this->proxy->id . "-counter.txt", $this->errcount);
        if (INSTANCE_ID > 0)
            $rs = $this->db->query("select * from `proxy` where `instanceid` = " . INSTANCE_ID . " and `status` = 1 and `account_count` < `account_limit` order by RAND() limit 1");
        else
            $rs = $this->db->query("select * from `proxy` where `status` = 1 order by RAND() limit 1");
        if (!$rs->num_rows) {
            //echo "no proxy...";
            $this->log("Нет свободных proxy!", 1);
            return false;
        }
        $this->proxy = $rs->fetch_object();
        $this->db->query("update `proxy` set `account_count` = `account_count` + 1 where `id` = {$this->proxy->id}");
        $this->db->query("delete from `account_proxy` where `accid` = {$this->accid}");
        $this->db->query("insert into `account_proxy` values(NULL, {$this->accid}, {$this->proxy->id})");
        $this->log("Аккаунту " . $this->accid . " присвоен адрес прокси " . $this->proxy->address);
        if (file_exists("data/proxy-" . $this->proxy->id . "-counter.txt")) {
            $this->errcount = intval(file_get_contents("data/proxy-" . $this->proxy->id . "-counter.txt"));
        }
        return true;
    }
    public function getid() {
        return $this->accid;
    }
    public function getlogin() {
        return $this->login;
    }
    public function get_trip_id(){
        return $this->trip_id;
    }
    public function set_booking($id) {
        $this->booking = $id;
    }
    public function getip() {
        return isset($this->proxy->address) ? $this->proxy->address : "ошибка";
    }
    public function set_proxy($id) {
        $rs = $this->db->query("select * from `proxy` where `id` = " . intval($id));
        $this->proxy = $rs->fetch_object();
        $this->db->query("update `proxy` set `account_count` = `account_count` + 1 where `id` = {$this->proxy->id}");
        if (file_exists("data/proxy-" . $this->proxy->id . "-counter.txt")) {
            $this->errcount = intval(file_get_contents("data/proxy-" . $this->proxy->id . "-counter.txt"));
        }
    }
    public function checktrip($tripurl) {
        $data = explode("-", $tripurl);
        $from = $data[1];
        $to = $data[2];
        $id = $data[3];
        
        if (preg_match("#^poezdka#", $tripurl)) {
            $tripurl = "https://www.blablacar.ru/" . $tripurl;
        }
        
        $res = $this->geturl($tripurl, 0, 0, 1, array(), array(), "https://www.blablacar.ru/ride-sharing/{$from}/{$to}/");
        if (!$res) {
            $this->log("Нет ответа от сервера");
            $this->contlog("checktrip no answer");
            return false;
        } elseif (preg_match("#<p class=\"Booking-info u-gray\">Заполнен</p>#", $res) || preg_match("#<span class=\"Booking-seats u-block\"><b style=\"font-size: 29px\">Заполнен</b></span>#", $res)) {
            $this->log("{$id}: Заполнен");
            $this->contlog("checktrip full");
            return false;
        } elseif (preg_match("#<p class=\"Booking-info u-gray\">Уже поздно бронировать эту поездку.</p>#", $res)) {
            $this->log("{$id}: Поздно бронировать");
            $this->contlog("checktrip too late");
            return false;
        } elseif (preg_match("#<h2>К сожалению, это предложение больше недоступно т.к. было удалено или заархивировано водителем.</h2>#", $res)) {
            $this->log("{$id}: Поездка удалена или заархивирована");
            $this->contlog("checktrip deleted");
            return false;
        } elseif (preg_match("#Ваше место ждёт вас!#", $res)) {
            $this->log("{$id}: Бронь еще не слетела");
            $this->contlog("checktrip already booked");
            file_put_contents("data/{$this->accid}-already.txt", $res);
            if (preg_match("#<a href=\"/payment-abort/(.+)\" data#iU", $res, $out)) {
                $res_c = $this->geturl("https://www.blablacar.ru/payment-abort/" . $out[1], 0, 1, 1, array(), array(), $tripurl);
                $this->log("Пробуем сбросить бронь...");
                if (preg_match("#Location: /trip-.+#", $res_c)) {
                    $res = $this->geturl($tripurl, 0, 0, 1, array(), array(), "https://www.blablacar.ru/ride-sharing/{$from}/{$to}/");
                    $this->log("Сброшена бронь");
                    $this->contlog("checktrip booking reseted");
                } else {
                    $this->contlog("checktrip booking reset error");
                    return false;
                }
            } else {
                $this->log("Нет ссылки для отказа от брони");
                $this->contlog("checktrip no link for booking reset");
                return false;
            }
        } elseif (!preg_match("#Booking-seats u-block\"><b.*>(.+)</b>#iU", $res, $out)) {
            if ($this->accid) file_put_contents("data/{$this->accid}-booking-error-no-seats.txt", $res);
            $this->contlog("checktrip no seats block");
            return false;
        } elseif (preg_match("#<p class=\"Booking-info u-green\">Вы забронировали#", $res)) {
            $this->log("На этом аккаунте уже висит бронь", 1);
            $this->contlog("checktrip already booked 2");
            return false;
        } elseif (!preg_match_all("#<option value=\"([0-9]+)\">.+</option>#iU", $res, $out)) {
            $this->log("Поездка с бронированием через сообщения: " . $tripurl, 1);
            $this->contlog("checktrip messaging book");
            file_put_contents("data/{$this->accid}-booking-error-no-list.txt", $tripurl . "\n\n" . $res);
            return false;
        }
        return $res;
    }
    public function checktrip_seats($tripurl, $from, $to) {
        global $samoblock;
        global $maxsamoblock;
        //$data = explode("-", $tripurl);
        $id = $tripurl;
        
        $res = $this->geturl($tripurl, 0, 1, 1, array(), array(), "https://www.blablacar.ru/ride-sharing/{$from}/{$to}/");
        if ($this->laststatus == 301) {
            preg_match("#Location: (.+)\r\n#iU", $res, $out);
            $res = $this->geturl("https://www.blablacar.ru" . $out[1], 0, 1, 1, array(), array(), "https://www.blablacar.ru/ride-sharing/{$from}/{$to}/");
            $tripurl = $out[1];
        } elseif ($this->laststatus != 200) {
            $this->contlog("checktrip_seats not ok answer (" . $this->laststatus . ")");
            return false;
        }
        if (!$res) {
            $this->log("Нет ответа от сервера");
            $this->contlog("checktrip_seats not ok answer (" . $this->laststatus . ")");
            return false;
        } elseif (preg_match("#<p class=\"Booking-info u-gray\">Заполнен</p>#", $res) || preg_match("#<span class=\"Booking-seats u-block\"><b style=\"font-size: 29px\">Заполнен</b></span>#", $res)) {
            $this->log("{$id}: Заполнен");
            $this->contlog("checktrip_seats full");
            return false;
        } elseif (preg_match("#<p class=\"Booking-info u-gray\">Уже поздно бронировать эту поездку.</p>#", $res)) {
            $this->log("{$id}: Поздно бронировать");
            $this->contlog("checktrip_seats too late");
            return false;
        } elseif (preg_match("#<h2>К сожалению, это предложение больше недоступно т.к. было удалено или заархивировано водителем.</h2>#", $res)) {
            $this->log("{$id}: Поездка удалена или заархивирована");
            $this->contlog("checktrip_seats deleted");
            return false;
        } elseif (!(preg_match("#Booking-seats u-block\"><b>(.+)</b>#iU", $res, $out) || preg_match("#Booking-seats u-block\"><b style=\"font-size: 30px\">(.+)</b>#iU", $res, $out))) {
            if ($this->accid) file_put_contents("data/{$this->accid}-booking-error-no-seats.txt", $res);
            $this->contlog("checktrip_seats no seats block");
            return false;
        } elseif (!preg_match_all("#<option value=\"([0-9]+)\">.+</option>#iU", $res, $out)) {
            $this->log("Поездка с бронированием через сообщения: " . $tripurl, 1);
            $this->contlog("checktrip_seats messaging booking");
            file_put_contents("data/{$this->accid}-booking-error-no-list.txt", $tripurl . "\n\n" . $res);
            return false;
        } elseif(preg_match("#ProfileCard\-info ProfileCard\-info\-\-name u\-truncate.+/user/show/PU6MQXLMoTUmdUjj1N26bg#isU", $res)) {
            return false;
        } elseif(preg_match("#ProfileCard\-info ProfileCard\-info\-\-name u\-truncate.+/user/show/_bBy8DTzVoax4BP5hYIQgA#isU", $res)) {
            return false;
        } elseif(preg_match("#ProfileCard\-info ProfileCard\-info\-\-name u\-truncate.+/user/show/oZn4Mq5ffxuPMTBHDGSxPA#isU", $res) && $samoblock > $maxsamoblock) {
            return false;
        }
        
        return $res;
    }
     public function checktripexist($tripurl) {
        $data = explode("-", $tripurl);
        $from = $data[1];
        $to = $data[2];
        $id = $data[3];
        
        if (preg_match("#^trip#", $tripurl)) {
            $tripurl = "https://www.blablacar.ru/" . $tripurl;
        }
        
        // Проверить время!!!
        // При переносе аккаунта в другую прогу переносить cookie
        
        $res = $this->geturl($tripurl, 0, 0, 1, array(), array(), "https://www.blablacar.ru/ride-sharing/{$from}/{$to}/");
        if ($this->laststatus > 200) {
            return false;
        } elseif (preg_match("#<p class=\"Booking-info u-gray\">Уже поздно бронировать эту поездку.</p>#", $res)) {
            echo "{$id}: Поздно бронировать\n";
            return false;
        } elseif (preg_match("#<h2>К сожалению, это предложение больше недоступно т.к. было удалено или заархивировано водителем.</h2>#", $res)) {
            echo "{$id}: Поездка удалена\n";
            return false;
        } /* elseif (!preg_match_all("#<option value=\"([0-9]+)\">.+</option>#iU", $res, $out)) {
            $this->log("Поездка с бронированием через сообщения: " . $tripurl, 1);
            if ($this->accid > 0) file_put_contents("data/{$this->accid}-booking-error-no-list.txt", $tripurl . "\n\n" . $res);
            return false;
        }*/
        return true;
    }
    public function updateidentity() {
        $ident = $this->fps[mt_rand(0, count($this->fps)-1)];
        $this->ua = $ident["ua"];
        $this->fp = $ident["fp"][mt_rand(0, count($ident["fp"])-1)];
        if ($this->accid > 0) $this->db->query("update `account` set `fp` = '" . $this->db->real_escape_string($this->fp) . "', `ua` = '" . $this->db->real_escape_string($this->ua) . "' where `id` = " . $this->accid);
        file_put_contents("data/cookie-" . $this->accid . ".txt", "");
        $this->log("new identity: " . $this->ua . " (" . $this->fp . ")");
    }
    public function contlog($msg) {
        $f = fopen("data/contlog.txt", "a");
        fwrite($f, date("d.m.Y H:i:s") . ": user #" . $this->accid . ": " . $msg . "\n");
        fclose($f);
    }
}
class blablaservice {
    private $users = array();
    private $db;
    private $tasks = array();
    private $user;
    private $exclude = array();
    private $fullblock = array();
    private $blocked = array();
    private $lastcheck = 0;
    function __construct() {
        $this->db = new mysqli(DBHOST, DBLOGIN, DBPASSWORD, DBNAME);
        $this->db->set_charset("utf8");
        $this->db->query("SET time_zone = '+05:00'");
        $this->user = new blablauser(0, "", "", "", "", "", $this->db);
    }
    public function contlog($msg) {
        $f = fopen("data/contlog.txt", "a");
        fwrite($f, date("d.m.Y H:i:s") . ": " . $msg . "\n");
        fclose($f);
    }
    public function run() {
        $this->log("service started");
        echo "started\n";
        $last_acctrip_reset = time();
        
        $this->db->query("delete from `account_trip` where `accid` in (select id from `account` where `instanceid` = " . INSTANCE_ID . ")");
        file_put_contents("../data/booking.log", "");
        
        $this->db->query("delete from `account_proxy` where `accid` not in (select `id` from `account` where `instanceid` = " . INSTANCE_ID . ")");
        $this->db->query("update `proxy` set `account_count` = (select count(id) from `account_proxy` where `proxyid` = `proxy`.`id`) where `instanceid` = " . INSTANCE_ID);
        
        while (true) {
            echo "Используется памяти: " . memory_get_usage(true) / (1024 * 1024) . "Мб\n";
            echo "Пиковое использование памяти: " . memory_get_peak_usage(true) / (1024 * 1024) . "Мб\n\n";
            /*foreach($this->users as $id => &$u) {
                if (!$u->bookingcheck()) {
                    $this->log("Бронирование на поездку " . $u->get_trip_id() . " отменено");
                    unset($this->blocked[$u->get_trip_id()]);
                    unset($this->users[$id]);
                    $this->db->query("update `account` set `status` = 1 where `id` = " . $id);
                }
            }*/
            system('clear');
            
            $state = intval(file_get_contents("state.txt"));
            if (!$state) {
                sleep(60);
                continue;
            }
            
            if ($this->lastcheck < (time() - 300)) { // проверяем бронирования раз в 5 минут
                $rs = $this->db->query("select * from `booking` where `instanceid` = " . INSTANCE_ID . " and `status` = 1");
                while ($b = $rs->fetch_object()) {
                    if (!isset($this->users[$b->userid])) {
                        $userdata = $this->db->query("select * from `account` where `id` = {$b->userid}")->fetch_object();
                        if (!$userdata) continue;
                        $this->users[$b->userid] = new blablauser($userdata->id, $userdata->login, $userdata->password, "", "", "", $this->db);
                        $this->users[$b->userid]->auth();
                        if (!$this->users[$b->userid]->get_trip_id()) {
                            $this->db->query("update `booking` set `status` = 0 where `id` = {$b->id}");
                            $this->db->query("update `account` set `status` = 1 where `id` = {$b->userid}");
                            $this->log("Бронирование на поездку {$b->tripid} отменено");
                            unset($this->blocked[$b->tripid]);
                            unset($this->users[$b->userid]);
                            sleep(mt_rand(3,7));
                            continue;
                        }
                    }
                    if (!$this->users[$b->userid]->bookingcheck()) {
                        $this->db->query("update `booking` set `status` = 0 where `id` = {$b->id}");
                        $this->db->query("update `account` set `status` = 1 where `id` = {$b->userid}");
                        $this->log("Бронирование на поездку {$b->tripid} отменено");
                        unset($this->blocked[$b->tripid]);
                        unset($this->users[$b->userid]);
                    }
                    sleep(mt_rand(3,7));
                }
                $this->lastcheck = time();
            }
            
            // сбрасываем статус
            $t = time() - 900;
            $this->db->query("update `account` set `status` = 1 where `status` = 2 and `lastbooking` > 0 and `lastbooking_mode` = 2 and `lastbooking` < {$t}");
            
            // смотрим нет ли новых задач, если есть добавляем в массив с активными задачами
            echo "get new tasks\n";
            $this->tasks = array();
            $rs = $this->db->query("select * from `task` where `instanceid` = " . INSTANCE_ID . " and `run_from` < UNIX_TIMESTAMP() and `run_to` > UNIX_TIMESTAMP() and `active` = 1");
            while ($task = $rs->fetch_object()) {
                $this->tasks[$task->id] = $task;
            }
            if ((time() - $last_acctrip_reset) > 1800) {
                // чистим привязку к поездкам раз в 30 минут, заодно чистим лог букера
                $this->db->query("delete from `account_trip` where `accid` in (select id from `account` where `instanceid` = " . INSTANCE_ID . ")");
                file_put_contents("../data/booking.log", "");
                $last_acctrip_reset = time();
            }
            $this->db->query("update `account` set `status` = 1 where `status` = 5 and `lastbooking` < (UNIX_TIMESTAMP() - 120)");
            if (!count($this->tasks)) {
                echo "no tasks\n";
                sleep(60);
                continue;
            }
            $sort = array("trip_price_euro", "trip_date");
            $sort_order = array("asc", "desc");
            
            // обрабатываем в цикле активные задачи            
            foreach($this->tasks as $task) {
                //$this->log("Выбрана задача " . $task->id);
                
                $task->city_from = $this->db->query("select * from `city` where `id` = {$task->city_from}")->fetch_object();
                $task->city_to = $this->db->query("select * from `city` where `id` = {$task->city_to}")->fetch_object();
                
                // генерируем поисковый url для этой задачи
                $search_session_id = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
                    mt_rand(0, 0xffff), mt_rand(0, 0xffff),
                    mt_rand(0, 0xffff),
                    mt_rand(0, 0x0fff) | 0x4000,
                    mt_rand(0, 0x3fff) | 0x8000,
                    mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
                  );
                
                $sort_order_sel = $sort_order[rand(0, 1)];
                $sort_sel = $sort[rand(0, 1)];
                
                /*$sparams_short = array(
                    "db" => implode("/", array_reverse(explode("-", $task->date))),
                    "fc" => $task->city_from->center,
                    "fcc" => "RU",
                    "fn" => $task->city_from->name,
                    "fp" => 0,
                    "limit" => 10,
                    "order" => $sort_order_sel,
                    "page" => 1,
                    "s_uuid" => $search_session_id,
                    "sort" => $sort_sel,
                    "tc" => $task->city_to->center,
                    "tcc" => "RU",
                    "tn" => $task->city_to->name,
                    "tp" => 0,
                    "v" => "default"
                );*/
                if ($task->date == date("Y-m-d") && strtotime($task->date) + $task->hour_from * 3600 > time()) $task->hour_from = date("G");
                $sparams = array(
                    "_" => mytime(),
                    "db" => $task->date,
                    "fc" => $task->city_from->center,
                    "fcc" => "RU",
                    "fn" => $task->city_from->name,
                    "fp" => "",
                    "s_uuid" => $search_session_id,
                    "tc" => $task->city_to->center,
                    "tcc" => "RU",
                    "tn" => $task->city_to->name,
                    "tp" => "",
                    "hb" => $task->hour_from
                );
                if (!isset($task->url)) {
                    $limit = 10; // стандартный 10, можно попробовать поменять
                    //$task->url = "https://www.blablacar.ru/search_xhr?" . http_build_query($sparams);
                    $task->url = "https://www.blablacar.ru/search?" . http_build_query($sparams);
                    //$sparams["page"] = 2;
                    //$task->url2 = "https://www.blablacar.ru/search_xhr?" . http_build_query($sparams);
                    //$sparams["page"] = 3;
                    //$task->url3 = "https://www.blablacar.ru/search_xhr?" . http_build_query($sparams);
                    // https://www.blablacar.ru/search_xhr?hb=4&he=24&fn=Магнитогорск,+Челябинская+область&fc=53.412943|59.001623&fcc=RU&fp=0&tn=Челябинск,+Челябинская+область&tc=55.164442|61.436843&tcc=RU&tp=0&db=27/05/2017&sort=trip_date&order=asc&radius=38.618&limit=10&page=1&_=1495811656415
                }
                $datemax = strtotime($task->date) + ($task->hour_to + 1) * 3600;
                $startsearch = time();
                $this->log("Поиск поездок ({$task->city_from->name} - {$task->city_to->name} {$task->date} с {$task->hour_from} до {$task->hour_to})");
                // echo $task->url . "\n";
                $this->user->checkproxy();
                
                $res = $this->user->geturl("https://www.blablacar.ru/", 0, 1, 1, array(), array(
                    //"If-Modified-Since: " . date("D, d M Y H:i:s", time() - mt_rand(30,60) * 60 - mt_rand(1,60)) . " GMT"
                ));
                
                echo $this->user->laststatus . "\n";
                
                if ($this->user->laststatus == 403 || $this->user->laststatus == 0) {
                    $this->user->updateidentity();
                    $this->user->updateproxy();
                    $this->contlog("service #" . INSTANCE_ID. " error 403");
                    sleep(mt_rand(40, 60));                    
                    continue;
                }
                
                //if (!preg_match("#action=\"/search\"#", $res, $out)) { file_put_contents("data/notoken.txt", $res); continue;}
                //$authtoken = $out[1];
        
                sleep(mt_rand(2,5));
                $params = array(
                    "location" => "https://www.blablacar.ru/",
                    "originalData" => array(
                        "site_language" => "RU",
                        "media" => "web",
                        "diplayed_currency" => "RUB",
                        "current_route" => "blablacar_main_homepage_homepage",
                        "homepage_version" => "v2016"
                    )
                );
                if (preg_match("#'bucket_number': \"(.+)\",#", $res, $out)) {
                    $params["originalData"]["bucket_number"] = $out[1];
                }
                
                $cmkt = "";
                if (preg_match("#'/tracking/cmkt/(.+)'#iU", $res, $out))
                    $cmkt = $out[1];
                
                $res = $this->user->geturl("https://www.blablacar.ru/tracking/cmkt/{$cmkt}", 1, 0, 1, $params, array(
                    "Accept: application/json, text/javascript, */*; q=0.01",
                    "Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
                    "X-Requested-With: XMLHttpRequest",
                    "Cache-Control: max-age=0"
                ), "https://www.blablacar.ru/"); // e_id? bucket_number?
                
                if ($this->user->laststatus == 403) {
                    $this->user->updateidentity();
                    $this->user->updateproxy();
                    $this->contlog("service #" . INSTANCE_ID. " error 403");
                    sleep(mt_rand(40, 60));
                    continue;
                }
                
                //preg_match("#datadome\t(.+)\n#", file_get_contents("data/cookie-" . $this->user->getid() . ".txt"), $out);
                //$cid = $out[1];
                
                
                //$req = "jsData=" . json_encode($this->user->jsdata) . "&" . http_build_query(array(
                //        "cid" => $cid,
                //        "ddk" => "1C17E1F027942805E00EE24A122A45",
                //        "ddv" => "3.0.4",
                //        "referer" => "",
                //        "request" => "/"
                //   ));
                //$this->user->geturl("https://api-js.datadome.co/js/", 1, 0, 1, $req, array(
                //    "Accept: */*",
                //    "Origin: https://www.blablacar.ru",
                //    "Cache-Control: max-age=0"
                //), "https://www.blablacar.ru/");
                
                sleep(mt_rand(4,8));

                $res = $this->user->geturl("https://www.blablacar.ru/search?" . http_build_query($sparams), 0, 0, 1, array(), array(), "https://www.blablacar.ru/");
                if ($this->user->laststatus != 301 && $this->user->laststatus != 200) {
                    file_put_contents("data/search_404.txt", $res);
                    $this->user->updateidentity();
                    $this->user->updateproxy();
                    $this->contlog("service #" . INSTANCE_ID. " error 403 on search (form)");
                    sleep(mt_rand(40, 60));
                    continue;
                }
                
                file_put_contents("data/search_page.txt", $res);
                if (!preg_match("#\"session\":\{\"appToken\":\"(.+)\"\},\"oneAction\"#iU", $res, $out)) {
                    continue;
                }
                $search_token = $out[1];
                preg_match("#\"visitorId\":\"(.+)\",\"currency\"#iU", $res, $out);
                $visitor_id = $out[1];
                
                // обновляем список исключенных поездок
                $this->exclude = array();
                $rs = $this->db->query("select * from `exclude` where `instanceid` = " . INSTANCE_ID . "");
                while ($row = $rs->fetch_array(MYSQLI_ASSOC)) {
                    $this->exclude[] = $row["bbcid"];
                }
                
                // обновляем список поездок для блокировки всех мест
                $this->fullblock = array();
                $rs = $this->db->query("select * from `fullblock` where `instanceid` = " . INSTANCE_ID . "");
                while ($row = $rs->fetch_array(MYSQLI_ASSOC)) {
                    $this->fullblock[] = $row["bbcid"];
                }
                
                if (preg_match("#flex-1\"><h1>.+: ([0-9]+) .+</h1><p>#iU", $res, $out)) {
                    $trips_count = $out[1];
                    if (!$trips_count) continue;
                    
                    echo $trips_count;
                    
                    $results = array();
                    
                    preg_match_all("#<li itemscope=\"\" itemType=\"http://schema.org/Event\" class=\"jsx-.+ kirk-tripCard mb-m\">(.+)</li>#iU", $res, $out);
                    //var_dump($out);
                    
                    foreach ($out[1] as $li) {
                        preg_match("#itemProp=\"url\" content=\"(.+)\" class#iU", $li, $out2);
                        $url = $out2[1];
                        
                        preg_match("#itemProp=\"startDate\" content=\"(.+)\" class#iU", $li, $out2);
                        $date = strtotime($out2[1]);
                        
                        if ($date > $datemax) break;
                        if ($date < time()) continue;
                        $results[] = $url;
                    }
                    
                    if ($trips_count > 10) {
                        if ($task->date == date("Y-m-d") && strtotime($task->date) + $task->hour_from * 3600 < time()) {
                            $task->hour_from = date("G");
                        }
                        
                        $params = array(
                            "departure_address" => $task->city_from->name,
                            "departure_coordinates" => $task->city_from->center,
                            "departure_city" => $task->city_from->name,
                            "departure_country_code" => "RU",
                            "arrival_city" => $task->city_to->name,
                            "date_begin" => date("Y-m-d\TH:i:s", strtotime($task->date) + $task->hour_from * 3600),
                            "search_tracktor_uuid" => $search_session_id
                        );
                        $pages = ceil($trips_count / 10);
                        for ($page = 2; $page <= $pages; $page++) {
                            $params["page"] = $page;
                            $url = str_replace(array("+", "%7C"), array("%20", "%2C"), "https://edge.blablacar.com/trips/search?" . http_build_query($params));
                            $res2 = $this->user->geturl($url, 0, 0, 1, array(), array(
                                "Accept: application/json",
                                "authorization: Bearer " . $search_token,
                                "Accept-Language: ru-RU",
                                "Accept-Encoding: gzip, deflate",
                                "Connection: keep-alive",
                                "content-type: application/json",
                                "origin: https://www.blablacar.ru",
                                "X-Requested-With: XMLHttpRequest",
                                "x-client: SPA",
                                "x-currency: RUB",
                                "x-forwarded-proto: https",
                                "x-locale: ru_RU",
                                "x-visitor-id: " . $visitor_id,
                                "x-correlation-id: " . $search_session_id
                            ), $task->url);
                            file_put_contents("data/search_page_" . $page . ".txt", $res2);
                            if (!$res2) continue;
                            $res2 = json_decode($res2);
                            file_put_contents("data/search_page_" . $page . "_json.txt", print_r($res2->trips[0], 1));
                            if (isset($res2->trips)) foreach ($res2->trips as $trip) {
                                //var_dump($trip);
                                $date = isset($trip->departure->date) ? strtotime($trip->departure->date) : strtotime($trip->waypoints[0]->departure_date);
                                if ($date < time()) continue;
                                if ($date > $datemax) break 2;
                                
                                $results[] = "https://www.blablacar.ru/trip/" . strtolower($trip->multimodal_id->source) . "/" . $trip->multimodal_id->id . "/";
                                // $results[] = "https://www.blablacar.ru/trip-" . $trip->id;
                            }
                            sleep(mt_rand(3,6));
                        }
                    }
                }
                
                //$this->user->checktrip_seats("https://www.blablacar.ru/trip-1382991026-cheliabinsk-magnitogorsk",  $task->city_from->name_latin, $task->city_to->name_latin);
                //die();
                
                foreach ($results as $tripurl) {
                    preg_match("#-?/?([0-9]+)-#iU", $tripurl, $out);
                    $id = $out[1];
                    
                    if (in_array($id, $this->exclude)) {
                        $this->contlog("service #" . INSTANCE_ID. " exclude trip " . $id);
                        continue;
                    }
                    
                    if (!$this->db->query("select `active` from `task` where `id` = {$task->id}")->fetch_object()->active) break;
                    
                    if (!$this->user->checktrip_seats($tripurl, $task->city_from->name_latin, $task->city_to->name_latin)) {
                        $this->contlog("service #" . INSTANCE_ID. " continue checktrip_seats trip-{$task->city_from->name_latin}-{$task->city_to->name_latin}-{$id}");
                        continue;
                    }
                    
                    $this->log("ID поездки: " . $id);
                    
                     // Смотрим кто из наших юзеров уже бронировал эту поездку
                    $us = array();
                    if ($task->mode != 2) {
                        $rs = $this->db->query("select `userid` from `booking` where `tripid` = {$id}");
                        while ($row = $rs->fetch_object())
                            $us[] = $row->userid;
                    } else {
                        // сбрасываем статус
                        $t = time() - 900;
                        $this->db->query("update `account` set `status` = 1 where `status` = 2 and `lastbooking` > 0 and `lastbooking_mode` = 2 and `lastbooking` < {$t}");
                    }
                    
                    // выбираем юзера из базы и дальше работаем через него
                    if ($task->mode == 2) {
                        $sql = "select * from `account_trip` where `tripid` = {$id}";
                        $rs = $this->db->query($sql);
                        if ($rs->num_rows) {
                            $accounts = $rs->num_rows;
                            $acc = array();
                            while($row = $rs->fetch_array(MYSQLI_ASSOC)) {
                                $acc[] = $row["accid"];
                            }
                            $sql = "select * from `account` where `instanceid` = " . INSTANCE_ID . " and `status` = 1 and `id` in (" . implode(",", $acc) . ") order by `lastbooking` asc limit 1";
                            //echo $sql . "\n";
                            $rs = $this->db->query($sql);
                            if ($rs->num_rows) {
                                $userdata = $rs->fetch_object();
                            } elseif($accounts < 4) {
                                // можно добавить еще один аккаунт
                                $rs = $this->db->query("select * from `account` where `instanceid` = " . INSTANCE_ID . " and `status` = 1 and `id` not in (select distinct `accid` from `account_trip`) order by RAND() limit 1");
                                if ($rs->num_rows) {
                                    $userdata = $rs->fetch_object();
                                    //$this->db->query("insert into `account_trip` values(NULL, {$userdata->id}, {$id}, 'trip-{$task->city_from->name_latin}-{$task->city_to->name_latin}-{$id}')");
                                } else {
                                    $this->log("Нет аккаунта для брони (accounts < 4)", 1);
                                    sleep(mt_rand(3, 7));
                                    continue;
                                }
                            } else {
                                $this->log("Нет аккаунта для брони (accounts = 4)", 1);
                                sleep(mt_rand(3, 7));
                                continue;
                            }
                        } else {
                            // можно добавить еще один аккаунт
                            $rs = $this->db->query("select * from `account` where `instanceid` = " . INSTANCE_ID . " and `status` = 1 and `id` not in (select distinct `accid` from `account_trip`) order by RAND() limit 1");
                            if ($rs->num_rows) {
                                $userdata = $rs->fetch_object();
                                //$this->db->query("insert into `account_trip` values(NULL, {$userdata->id}, {$id}, 'trip-{$task->city_from->name_latin}-{$task->city_to->name_latin}-{$id}')");
                            } else {
                                $this->log("Нет аккаунта для брони (Accounts = 0)", 1);
                                sleep(mt_rand(3, 7));
                                continue;
                            }
                        }
                    } else {
                        $sql = "select * from `account` where `instanceid` = " . INSTANCE_ID . " and `status` = 1";
                        if (count($us)) $sql .= " and `id` not in(" . implode(",", $us) .")";
                        $sql .= " order by RAND() limit 1";
                        $rs = $this->db->query($sql);
                        if (!$rs->num_rows) {
                            $this->log("Нет аккаунта для брони", 1);
                            sleep(mt_rand(3, 7));
                            continue;
                        }
                        $userdata = $rs->fetch_object();
                    }

                    $this->log("Выбранный аккаунт: {$userdata->login}", 0, $userdata->id);
                    
                    
                    /* НЕПЛОХО БЫЛО БЫ ПРОВЕРЯТЬ ЭТО СРАЗУ ПЕРЕД ВЫБОРОМ АККАУНТА */
                    if (in_array($task->mode, array(0,1)) && !$user->checkbookings()) {
                        $this->log("На пользователе ". $userdata->login . " уже висит бронь", 1, $userdata->id);
                        continue;
                    }
                    
                    /* МНОГОПОТОК */
                    $this->db->query("update `account` set `status` = 5, `lastbooking` = UNIX_TIMESTAMP() where `id` = {$userdata->id}");
                    
                    // php ../booking.php INSTANCE_ID $userdata->id $id $task->id
                    $cmd = "php ../booking.php " . INSTANCE_ID . " {$userdata->id} {$id} {$tripurl} {$task->id} >> ../data/booking.log 2>&1 &";
                    //echo $cmd; die();
                    exec($cmd);
                    //echo "php ../booking.php " . INSTANCE_ID . " {$userdata->id} {$id} {$task->id}\n";
                }

                echo "Время цикла: " . (time() - $startsearch) . " сек\n";
                $t = mt_rand(90, 110);
                echo "Засыпаем на {$t} сек\n";
                sleep($t);
            }
            //sleep(mt_rand(47, 75));
        }
    }
    public function log($text, $type = 0, $accid = 0) {
        echo $text . "\n";
        $this->db->query("insert into `log` values(NULL, " . INSTANCE_ID . ", UNIX_TIMESTAMP(), {$type}, '" . $this->db->real_escape_string($text) . "', {$accid})");
        return true;
    }
}
class blablacleaner {
    private $db;
    private $user;
    function __construct() {
        $this->db = new mysqli(DBHOST, DBLOGIN, DBPASSWORD, DBNAME);
        $this->db->set_charset("utf8");
        $this->db->query("SET time_zone = '+05:00'");
        $this->user = new blablauser(0, "", "", "", "", "", $this->db);
    }
    public function run() {
        $this->log("cleaner service started");
        echo "started\n";

        while (true) {
            //echo "Используется памяти: " . memory_get_usage(true) / (1024 * 1024) . "Мб\n";
            //echo "Пиковое использование памяти: " . memory_get_peak_usage(true) / (1024 * 1024) . "Мб\n\n";
            $rs = $this->db->query("select * from `task` where `run_from` < UNIX_TIMESTAMP() and `run_to` > UNIX_TIMESTAMP() and `active` = 1");
            if (!$rs->num_rows) {
                $this->db->query("truncate table `account_trip`");
                $this->log("clean all (no tasks)");
                sleep(60);
                continue;
            }
            $rs = $this->db->query("select distinct tripid, tripurl from `account_trip`");
            while($row = $rs->fetch_object()) {
                if (!$this->user->checktripexist($row->tripurl)) {
                    $this->db->query("delete from `account_trip` where `tripid` = {$row->tripid}");
                    $this->log("deleted trip " . $row->tripid);
                }
                sleep(3);
            }
            $this->db->query("delete from `account_trip` where `accid` in (select `id` from `account` where `status` = 3)");
            if ($this->db->affected_rows > 0) $this->log("clean {$this->db->affected_rows} banned accounts");
            $this->db->query("delete from `account_trip` where `accid` not in (select `id` from `account`)");
            if ($this->db->affected_rows > 0) $this->log("clean {$this->db->affected_rows} deleted accounts");
            sleep(40);
        }
    }
    public function log($text, $type = 0, $accid = 0) {
        echo $text . "\n";
        $this->db->query("insert into `log` values(NULL, 0, UNIX_TIMESTAMP(), {$type}, '" . $this->db->real_escape_string($text) . "', 0)");
        return true;
    }
}
?>

 

Министерство спорта РФ

Министерство спорта Челябинской области

Администрация города Магнитогорска

Федерация бокса России

Российская федерация баскетбола

«Готов к труду и обороне» (ГТО)

Управление по физической культуре
МагнитогорскГосуслуги

Информационная поддержка

Медиа-группа Знак