<?php
// Author: Mik Foxi admin@mikfoxi.com
// License: GNU GPL v3 - https://www.gnu.org/licenses/gpl-3.0.en.html
// Website: https://antibot.cloud/

$ab_version = '8.020';
$ab_se = array();
$ab_proxy = array();
$ab_rule = array();
$ab_path = array();
$ab_config['colors'] = array('BLACK', 'GRAY', 'RED', 'YELLOW', 'GREEN', 'BLUE');
$ab_config['country'] = 'XX';
$ab_config['hosting'] = 0;

// default conf:
$ab_config['demo'] = 0;
$ab_config['phperror'] = 1;
$ab_config['disable'] = 0;
$ab_config['timezone'] = '';
$ab_config['webdir'] = '/antibot8/';
$ab_config['email'] = '';
$ab_config['pass'] = '';
$ab_config['secondpass'] = '';
$ab_config['salt'] = 'antibot';
$ab_config['timesalt'] = 'Y';
$ab_config['check_url'] = '';
$ab_config['is_bitrix'] = 0;
$ab_config['timer'] = 5;
$ab_config['hits_per_user'] = 1000;
$ab_config['input_button'] = 0;
$ab_config['tpl_lang'] = '';
$ab_config['buttons'] = 1;
$ab_config['time_ban'] = 0;
$ab_config['re_check'] = 0;
$ab_config['recaptcha_key'] = '';
$ab_config['recaptcha_secret'] = '';
$ab_config['utm_referrer'] = 1; 
$ab_config['utm_noindex'] = 1;
$ab_config['check_get_ref'] = 0;
$ab_config['bad_get_ref'] = '';
$ab_config['secret_allow_get'] = '';
$ab_config['antibot_log_tests'] = 1;
$ab_config['antibot_log_local'] = 0;
$ab_config['antibot_log_allow'] = 1;
$ab_config['antibot_log_fake'] = 1;
$ab_config['antibot_log_goodip'] = 0;
$ab_config['antibot_log_block'] = 1;
$ab_config['header_test_code'] = 200;
$ab_config['header_error_code'] = 200;
$ab_config['period_cleaning'] = 'lastmonth';

// CloudFlare:
$ab_proxy['173.245.48.0/20'] = 'HTTP_CF_CONNECTING_IP';
$ab_proxy['103.21.244.0/22'] = 'HTTP_CF_CONNECTING_IP';
$ab_proxy['103.22.200.0/22'] = 'HTTP_CF_CONNECTING_IP';
$ab_proxy['103.31.4.0/22'] = 'HTTP_CF_CONNECTING_IP';
$ab_proxy['141.101.64.0/18'] = 'HTTP_CF_CONNECTING_IP';
$ab_proxy['108.162.192.0/18'] = 'HTTP_CF_CONNECTING_IP';
$ab_proxy['190.93.240.0/20'] = 'HTTP_CF_CONNECTING_IP';
$ab_proxy['188.114.96.0/20'] = 'HTTP_CF_CONNECTING_IP';
$ab_proxy['197.234.240.0/22'] = 'HTTP_CF_CONNECTING_IP';
$ab_proxy['198.41.128.0/17'] = 'HTTP_CF_CONNECTING_IP';
$ab_proxy['162.158.0.0/15'] = 'HTTP_CF_CONNECTING_IP';
$ab_proxy['104.16.0.0/13'] = 'HTTP_CF_CONNECTING_IP';
$ab_proxy['104.24.0.0/14'] = 'HTTP_CF_CONNECTING_IP';
$ab_proxy['172.64.0.0/13'] = 'HTTP_CF_CONNECTING_IP';
$ab_proxy['131.0.72.0/22'] = 'HTTP_CF_CONNECTING_IP';

// server response code for blocking pages:
$ab_config['error_headers'] = array(
200 => '200 OK', 
400 => '400 Bad Request', 
401 => '401 Unauthorized', 
403 => '403 Forbidden', 
404 => '404 Not Found', 
410 => '410 Gone', 
429 => '42 Too Many Requests', 
451 => '451 Unavailable For Legal Reasons', 
500 => '500 Internal Server Error', 
502 => '502 Bad Gateway', 
503 => '503 Service Unavailable', 
504 => '504 Gateway Time-out', 
511 => '511 Network Authentication Required'
);

require_once(__DIR__.'/../data/conf.php');

$ab_start_time = microtime(true);
$ab_config['time'] = time();

include(__DIR__.'/../data/se.php');
include(__DIR__.'/../data/proxy.php');
include(__DIR__.'/../data/path.php');
require_once(__DIR__.'/func.php');

// disabling the antibot in the presence of a secret parameter:
if ($ab_config['secret_allow_get'] != '') {
if (isset($_GET[$ab_config['secret_allow_get']]) OR isset($_COOKIE[$ab_config['secret_allow_get']])) {
header('X-Robots-Tag: noindex');
setcookie($ab_config['secret_allow_get'], 1, $ab_config['time']+2592000, '/'); // for a month
$ab_config['disable'] = 1;
}
}

// do not interfere with access to the admin panel:
if(defined('ANTIBOT_ADMIN')) {
$ab_config['antibot_log_local'] = 0;
$ab_config['antibot_log_allow'] = 0;
$ab_config['disable'] = 0;
$ab_config['hits_per_user'] = 1000;
}

if (php_sapi_name() != 'cli' AND $ab_config['disable'] != 1) {

if (isset($_GET['utm_referrer']) AND $ab_config['utm_noindex'] == 1) {
header('X-Robots-Tag: noindex');
}

$ab_config['date'] = date('Y.m.d', $ab_config['time']);
if ($ab_config['is_bitrix'] == 1) {
$ab_config['host'] = isset($_SERVER['HTTP_HOST']) ? preg_replace("/[^0-9a-z-.:]/","", strstr($_SERVER['HTTP_HOST'], ':', true)) : die('Host Error');
} else {
$ab_config['host'] = isset($_SERVER['HTTP_HOST']) ? preg_replace("/[^0-9a-z-.:]/","", $_SERVER['HTTP_HOST']) : die('Host Error');
}

if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
$ab_config['scheme'] = trim(strip_tags($_SERVER['HTTP_X_FORWARDED_PROTO']));
} elseif (isset($_SERVER['REQUEST_SCHEME'])) {
$ab_config['scheme'] = trim(strip_tags($_SERVER['REQUEST_SCHEME']));
} else {
$ab_config['scheme'] = 'http';
}

$ab_config['ym_uid'] = isset($_COOKIE['_ym_uid']) ? trim(preg_replace("/[^0-9]/","",$_COOKIE['_ym_uid'])) : '';
$ab_config['ga_uid'] = isset($_COOKIE['_ga']) ? trim(preg_replace("/[^a-zA-Z0-9\.]/","",$_COOKIE['_ga'])) : '';
$ab_config['useragent'] = isset($_SERVER['HTTP_USER_AGENT']) ? trim(strip_tags($_SERVER['HTTP_USER_AGENT'])) : '';
$ab_config['uri'] = isset($_SERVER['REQUEST_URI']) ? trim(strip_tags($_SERVER['REQUEST_URI'])) : '/';
$ab_config['ip'] = isset($_SERVER['REMOTE_ADDR']) ? trim(strip_tags($_SERVER['REMOTE_ADDR'])) : die('Remote Addr Error');
$ab_config['referer'] = isset($_SERVER['HTTP_REFERER']) ? trim(strip_tags($_SERVER['HTTP_REFERER'])) : '';
$ab_config['refhost'] = preg_replace("/[^0-9a-z-.:]/","", (string)parse_url($ab_config['referer'], PHP_URL_HOST));
if ($ab_config['referer'] != '' AND $ab_config['refhost'] == '') {
$ab_config['refhost'] = preg_replace("/[^0-9a-z-.]/","", $ab_config['referer']);
}
$ab_config['refhost_scheme'] = preg_replace("/[^a-z]/","", (string)parse_url($ab_config['referer'], PHP_URL_SCHEME));
$ab_config['accept_lang'] = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? trim(strip_tags($_SERVER['HTTP_ACCEPT_LANGUAGE'])) : '';
$ab_config['lang'] = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? mb_substr(mb_strtolower(trim(preg_replace("/[^a-zA-Z]/","",$_SERVER['HTTP_ACCEPT_LANGUAGE'])), 'UTF-8'), 0, 2, 'utf-8') : ''; // 2 первых символа
if ($ab_config['timer'] < 1) {$ab_config['timer'] = 0;}
$ab_config['protocol'] = (isset($_SERVER['SERVER_PROTOCOL']) ? trim(strip_tags($_SERVER['SERVER_PROTOCOL'])) : 'HTTP/1.0');
$ab_config['http_accept'] = isset($_SERVER['HTTP_ACCEPT']) ? trim(strip_tags($_SERVER['HTTP_ACCEPT'])) : '';
$ab_config['request_method'] = isset($_SERVER['REQUEST_METHOD']) ? (string)trim(preg_replace("/[^a-zA-Z]/","",$_SERVER['REQUEST_METHOD'])) : '';

$ab_config['antibot_hits'] = isset($_COOKIE['antibot_hits']) ? (int)trim(preg_replace("/[^0-9]/","",$_COOKIE['antibot_hits'])) : 1;
$ab_config['antibot_score'] = isset($_COOKIE['antibot_score']) ? trim(preg_replace("/[^0-9\.]/","",$_COOKIE['antibot_score'])) : '';

$ab_config['cid'] = $ab_config['time'].rand(1111,9999); // unique click id (hit)

// cloud check address
if ($ab_config['check_url'] == '') {
$ab_config['check_url'] = 'https://antibotcloud.com/antibot8.php';
}

// check for cloudflare and proxy:
if (filter_var($ab_config['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
foreach ($ab_proxy as $proxy_mask => $proxy_attr) {
if (net_match($proxy_mask, $ab_config['ip']) == 1 AND isset($_SERVER[$proxy_attr])) {
$ab_config['ip'] = $_SERVER[$proxy_attr];
break;
}
}
}

// ip validation check:
if (filter_var($ab_config['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$ab_config['ipv'] = 4;
$ab_config_ip_array = explode('.', $ab_config['ip']);
$ab_config['ip_short'] = $ab_config_ip_array[0].'.'.$ab_config_ip_array[1].'.'.$ab_config_ip_array[2].'.0/24';
} elseif (filter_var($ab_config['ip'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$ab_config['ip'] = abExpand($ab_config['ip']);
$ab_config['ipv'] = 6;
$ab_config_ip_array = explode(':', $ab_config['ip']);
$ab_config['ip_short'] = $ab_config_ip_array[0].':'.$ab_config_ip_array[1].':'.$ab_config_ip_array[2].':'.$ab_config_ip_array[3].':0000:0000:0000:0000/64';
} else {
die('Bad IP');
}
$ab_config['ipnum'] = AbIp2num($ab_config['ip']);

// unique user id and main cookie name:
$ab_config['uid'] = md5($ab_config['salt'].$ab_config['ip'].$ab_config['useragent'].$ab_config['accept_lang']);

// main cookie content:
$ab_config['antibot_v'] = isset($_COOKIE['antibot_'.$ab_config['uid']]) ? trim(strip_tags($_COOKIE['antibot_'.$ab_config['uid']])) : '';

$ab_cookie = explode('-', $ab_config['antibot_v']);
$ab_config['cookie_date'] = isset($ab_cookie[1]) ? (int)trim($ab_cookie[1]) : $ab_config['time']-864100;
$ab_config['antibot'] = isset($ab_cookie[0]) ? trim($ab_cookie[0]) : 0;

// the hash (value) from the cookie should be like this:
$ab_config['antibot_ok'] = md5($ab_config['pass'].$ab_config['host'].$ab_config['useragent'].$ab_config['ip'].$ab_config['cookie_date']);

// if this is a person with a cookie older than 10 days:
if ($ab_config['time'] - $ab_config['cookie_date'] > 864000) {
// cookies expired:
//setcookie('antibot_'.$ab_config['uid'], 1, $ab_config['time']-100, '/');
$ab_config['antibot'] = 'delete';
}

// коннект к базе:
$antibot_db = new SQLite3(__DIR__.'/../data/sqlite.db'); 
$antibot_db->busyTimeout(3000);
$antibot_db->exec("PRAGMA journal_mode = WAL;");

$ab_config['useragent'] = $antibot_db->escapeString($ab_config['useragent']);
$ab_config['referer'] = $antibot_db->escapeString($ab_config['referer']);
$ab_config['accept_lang'] = $antibot_db->escapeString($ab_config['accept_lang']);
$ab_config['page'] = $antibot_db->escapeString($ab_config['scheme'].'://'.$ab_config['host'].$ab_config['uri']);
$ab_config['http_accept'] = $antibot_db->escapeString($ab_config['http_accept']);

// connection to the geo base:
$antibot_geo_db = new SQLite3(__DIR__.'/ipv'.$ab_config['ipv'].'.db'); 
$antibot_geo_db->busyTimeout(1000);
@$antibot_geo_db->exec("PRAGMA journal_mode = MEMORY;");
@$antibot_geo_db->exec("PRAGMA synchronous = OFF;");

$ab_ip_info = @$antibot_geo_db->querySingle("SELECT * FROM list WHERE ip1 <= ".$ab_config['ipnum']." AND ip2 >= ".$ab_config['ipnum'].";", true);

// ip parameters from geo base:
if (isset($ab_ip_info['country'])) {
$ab_config['country'] = $ab_ip_info['country'];
$ab_config['cidr'] = $ab_ip_info['cidr'];
$ab_config['asname'] = $ab_ip_info['asname'];
$ab_config['asnum'] = $ab_ip_info['asnum'];
$ab_config['hosting'] = $ab_ip_info['hosting'];
} else {
$ab_config['country'] = 'XX';
$ab_config['cidr'] = '';
$ab_config['asname'] = '';
$ab_config['asnum'] = '';
}

// for China, disable the recaptcha check:
if ($ab_config['country'] == 'CN') {
$ab_config['re_check'] = 0;
}

// check ip by ipv rules:
if (!isset($ab_config['whitebot'])) {
$ab_ip_test = @$antibot_db->querySingle("SELECT rowid, * FROM ipv".$ab_config['ipv']."rules WHERE ip1 <= ".$ab_config['ipnum']." AND ip2 >= ".$ab_config['ipnum']." ORDER by priority ASC;", true);
// create table if not present:
if ($antibot_db->lastErrorMsg() == 'no such table: ipv'.$ab_config['ipv'].'rules') {
require_once(__DIR__.'/install.php');
die();
}

// if ip is found in rules:
if (isset($ab_ip_test['rule'])) {
// deleting an expired rule:
if ($ab_ip_test['expires'] < $ab_config['time']) {
$del = $antibot_db->exec("DELETE FROM ipv".$ab_config['ipv']."rules WHERE rowid=".$ab_ip_test['rowid'].";");
$ab_ip_test['rule'] = 'gray';
}
if ($ab_ip_test['rule'] == 'allow') {
$ab_config['whitebot'] = 1;
// в счетчик записывать в конце скрипта.
} elseif ($ab_ip_test['rule'] == 'block') {
if ($ab_config['antibot_log_block'] == 1) {
$ab_ip_test['search'] = $antibot_db->escapeString($ab_ip_test['search']);
$ab_exec_time = round(microtime(true) - $ab_start_time, 5);
$add = @$antibot_db->exec("INSERT INTO hits (cid, date, ip, ptr, useragent, uid, country, referer, page, lang, generation, passed, recaptcha, js_w, js_h, js_cw, js_ch, js_co, js_pi, refhost, adblock, asnum, asname, result, http_accept, method, ym_uid, ga_uid) VALUES ('".$ab_config['cid']."', '".$ab_config['time']."', '".$ab_config['ip']."', '', '".$ab_config['useragent']."', '".$ab_config['uid']."', '".$ab_config['country']."', '".$ab_config['referer']."', '".$ab_config['page']."', '".$ab_config['accept_lang']."', '".$ab_exec_time."', '6', '', '', '', '', '', '', '', '".$ab_config['refhost']."', '', '".$ab_config['asnum']."', '".$ab_config['asname']."', 'Blocked by rule: ".$ab_ip_test['search']."', '".$ab_config['http_accept']."', '".$ab_config['request_method']."', '".$ab_config['ym_uid']."', '".$ab_config['ga_uid']."');");
}
file_put_contents(__DIR__.'/../data/counters/block_'.date('Ymd', $ab_config['time']), '1', FILE_APPEND | LOCK_EX);
header('X-Robots-Tag: noindex');
header($ab_config['protocol'].' '.$ab_config['error_headers'][$ab_config['header_error_code']]);
header('Status: '.$ab_config['error_headers'][$ab_config['header_error_code']]);
$content = file_get_contents(__DIR__.'/../data/error.txt');
if (is_numeric($ab_ip_test['expires']) AND $ab_ip_test['expires'] - $ab_config['time'] < 86401) {
// перевод заглушки на язык посетителя:
if ($ab_config['tpl_lang'] == '') {$ab_config['tpl_lang'] = $ab_config['lang'];}
if (file_exists(__DIR__.'/../lang/tpl/'.$ab_config['tpl_lang'].'.php')) {
require_once(__DIR__.'/../lang/tpl/'.$ab_config['tpl_lang'].'.php');
}
$content = str_replace('<!--ip_ban_msg-->', '<center>'.abTranslate('Your IP has been blocked. Minutes to unlock:').' '.round(($ab_ip_test['expires'] - $ab_config['time']) / 60).'</center>', $content);

}
echo $content;
die();
} elseif ($ab_ip_test['rule'] == 'gray') {
$ab_config['check_url'] = $ab_config['webdir'].'gray.php';
}
}

}
// конец проверки ip по базе правил.

// проверяем юзерагент на принадлежность к белым ботам по массиву ab_se и ab_rule:
if (!isset($ab_config['whitebot'])) {
// полная PTR запись:
$ab_config['ptr'] = trim(preg_replace("/[^0-9a-z-.:]/","", mb_strtolower(gethostbyaddr($ab_config['ip']), 'UTF-8')));


foreach ($ab_se as $ab_line => $ab_sign) {
// если часть юзерагента в черном списке:
if (stripos($ab_config['useragent'], $ab_line, 0) !== false) {
if ($ab_rule[$ab_line] == 'block') {
if ($ab_config['antibot_log_block'] == 1) {
$ab_ip_test['search'] = $antibot_db->escapeString($ab_line);
$ab_exec_time = round(microtime(true) - $ab_start_time, 5);
$add = @$antibot_db->exec("INSERT INTO hits (cid, date, ip, ptr, useragent, uid, country, referer, page, lang, generation, passed, recaptcha, js_w, js_h, js_cw, js_ch, js_co, js_pi, refhost, adblock, asnum, asname, result, http_accept, method, ym_uid, ga_uid) VALUES ('".$ab_config['cid']."', '".$ab_config['time']."', '".$ab_config['ip']."', '', '".$ab_config['useragent']."', '".$ab_config['uid']."', '".$ab_config['country']."', '".$ab_config['referer']."', '".$ab_config['page']."', '".$ab_config['accept_lang']."', '".$ab_exec_time."', '6', '', '', '', '', '', '', '', '".$ab_config['refhost']."', '', '".$ab_config['asnum']."', '".$ab_config['asname']."', 'Blocked by rule (user-agent part): ".$ab_ip_test['search']."', '".$ab_config['http_accept']."', '".$ab_config['request_method']."', '".$ab_config['ym_uid']."', '".$ab_config['ga_uid']."');");
}
file_put_contents(__DIR__.'/../data/counters/block_'.date('Ymd', $ab_config['time']), '1', FILE_APPEND | LOCK_EX);
header('X-Robots-Tag: noindex');
header($ab_config['protocol'].' '.$ab_config['error_headers'][$ab_config['header_error_code']]);
header('Status: '.$ab_config['error_headers'][$ab_config['header_error_code']]);
echo file_get_contents(__DIR__.'/../data/error.txt');
die();
} elseif ($ab_rule[$ab_line] == 'gray') {
$ab_config['check_url'] = $ab_config['webdir'].'gray.php';
}
}
// если нашли совпадение в имени юзерагента:
if (stripos($ab_config['useragent'], $ab_line, 0) !== false) {
if (TestWhiteBot($ab_config['ip'], $ab_sign) == 1) {
// если это в реале по ptr белый бот:
if (!in_array('.',$ab_se[$ab_line])) {
// сохраняем ip в белый список только тем у кого полноценный идентифицируемый ptr:
$ips = AbIpRange($ab_config['ip_short']);

$add = @$antibot_db->exec("INSERT INTO ipv".$ab_config['ipv']."rules (priority, search, ip1, ip2, rule, comment, expires) VALUES ('10', '".$ab_config['ip_short']."', '".AbIp2num($ips[0])."', '".AbIp2num($ips[1])."', 'allow', '".$ab_config['useragent']." (ip: ".$ab_config['ip'].")', '".($ab_config['time'] + 7776000)."');");
}
$ab_config['whitebot'] = 1; break;
} else {
// фейковый бот:
if ($ab_config['antibot_log_fake'] == 1) {
$ab_exec_time = round(microtime(true) - $ab_start_time, 5);
$add = @$antibot_db->exec("INSERT INTO hits (cid, date, ip, ptr, useragent, uid, country, referer, page, lang, generation, passed, recaptcha, js_w, js_h, js_cw, js_ch, js_co, js_pi, refhost, adblock, asnum, asname, result, http_accept, method, ym_uid, ga_uid) VALUES ('".$ab_config['cid']."', '".$ab_config['time']."', '".$ab_config['ip']."', '".$ab_config['ptr']."', '".$ab_config['useragent']."', '".$ab_config['uid']."', '".$ab_config['country']."', '".$ab_config['referer']."', '".$ab_config['page']."', '".$ab_config['accept_lang']."', '".$ab_exec_time."', '7', '', '', '', '', '', '', '', '".$ab_config['refhost']."', '', '".$ab_config['asnum']."', '".$ab_config['asname']."', '', '".$ab_config['http_accept']."', '".$ab_config['request_method']."', '".$ab_config['ym_uid']."', '".$ab_config['ga_uid']."');");
}
// счетчик фейк ботов:
file_put_contents(__DIR__.'/../data/counters/fakes_'.date('Ymd', $ab_config['time']), '1', FILE_APPEND | LOCK_EX);
header('X-Robots-Tag: noindex');
header($ab_config['protocol'].' '.$ab_config['error_headers'][$ab_config['header_error_code']]);
header('Status: '.$ab_config['error_headers'][$ab_config['header_error_code']]);
echo file_get_contents(__DIR__.'/../data/error.txt');
die();
}
break;
}
}
}
// конец проверки по массиву конфига.

// проверяем URL по вхождению в $ab_path
if (!isset($ab_config['whitebot'])) {

// $ab_path['/api'] = 'allow';
foreach ($ab_path as $ab_line => $ab_sign) {
// если нашли совпадение в имени юзерагента:
if (stripos($ab_config['uri'], $ab_line, 0) !== false) {
// нашли:
if ($ab_sign == 'block') {
if ($ab_config['antibot_log_block'] == 1) {
$ab_exec_time = round(microtime(true) - $ab_start_time, 5);
$add = @$antibot_db->exec("INSERT INTO hits (cid, date, ip, ptr, useragent, uid, country, referer, page, lang, generation, passed, recaptcha, js_w, js_h, js_cw, js_ch, js_co, js_pi, refhost, adblock, asnum, asname, result, http_accept, method, ym_uid, ga_uid) VALUES ('".$ab_config['cid']."', '".$ab_config['time']."', '".$ab_config['ip']."', '', '".$ab_config['useragent']."', '".$ab_config['uid']."', '".$ab_config['country']."', '".$ab_config['referer']."', '".$ab_config['page']."', '".$ab_config['accept_lang']."', '".$ab_exec_time."', '6', '', '', '', '', '', '', '', '".$ab_config['refhost']."', '', '".$ab_config['asnum']."', '".$ab_config['asname']."', 'Blocked by rule (url part): ".$ab_line."', '".$ab_config['http_accept']."', '".$ab_config['request_method']."', '".$ab_config['ym_uid']."', '".$ab_config['ga_uid']."');");
}
file_put_contents(__DIR__.'/../data/counters/block_'.date('Ymd', $ab_config['time']), '1', FILE_APPEND | LOCK_EX);
header('X-Robots-Tag: noindex');
header($ab_config['protocol'].' '.$ab_config['error_headers'][$ab_config['header_error_code']]);
header('Status: '.$ab_config['error_headers'][$ab_config['header_error_code']]);
echo file_get_contents(__DIR__.'/../data/error.txt');
die();
} elseif ($ab_sign == 'gray') {
$ab_config['check_url'] = $ab_config['webdir'].'gray.php';
} elseif ($ab_sign == 'allow') {
$ab_config['antibot_log_local'] = 0; // для исключения дублей в логе
$ab_config['whitebot'] = 0;
if ($ab_config['antibot_log_allow'] == 1) {
// записать в лог посещаемости, если включено логирование, с passed 4
$ab_exec_time = round(microtime(true) - $ab_start_time, 5);
$add = @$antibot_db->exec("INSERT INTO hits (cid, date, ip, ptr, useragent, uid, country, referer, page, lang, generation, passed, recaptcha, js_w, js_h, js_cw, js_ch, js_co, js_pi, refhost, adblock, asnum, asname, result, http_accept, method, ym_uid, ga_uid) VALUES ('".$ab_config['cid']."', '".$ab_config['time']."', '".$ab_config['ip']."', '".$ab_config['ptr']."', '".$ab_config['useragent']."', '".$ab_config['uid']."', '".$ab_config['country']."', '".$ab_config['referer']."', '".$ab_config['page']."', '".$ab_config['accept_lang']."', '".$ab_exec_time."', '4', '', '', '', '', '', '', '', '".$ab_config['refhost']."', '', '".$ab_config['asnum']."', '".$ab_config['asname']."', 'Allow rule (url part): ".$ab_line."', '".$ab_config['http_accept']."', '".$ab_config['request_method']."', '".$ab_config['ym_uid']."', '".$ab_config['ga_uid']."');");
}
file_put_contents(__DIR__.'/../data/counters/allow_'.date('Ymd', $ab_config['time']), '1', FILE_APPEND | LOCK_EX);
break;
}
// конец найденного
}
}
}
// конец проверки по массиву  $ab_path

// проверка по всем остальным параметрам:
if (!isset($ab_config['whitebot'])) {

// проверка GET переменных реферера:
if ($ab_config['check_get_ref'] == 1) {
$ab_query = parse_url($ab_config['referer']);
if (isset($ab_query['query'])) {
mb_parse_str($ab_query['query'], $mb_parse_str);
$ab_config['bad_get_ref'] = explode(' ', $ab_config['bad_get_ref']);
foreach ($ab_config['bad_get_ref'] as $bad_get_ref) {
if (isset($mb_parse_str[$bad_get_ref])) {
$ab_config['check_url'] = $ab_config['webdir'].'gray.php';
break;
}
}
}
}

// проверка по таблице правил № 5:
// формируем через OR кучу всего: useragent, country, lang, referer, ptr, asname, asnum, uri, scriptname, httpaccept
$ab_search = array();
$ab_search[] = $antibot_db->escapeString('useragent='.$ab_config['useragent']);
$ab_search[] = 'country='.$ab_config['country'];
$ab_search[] = 'lang='.$ab_config['lang'];
$ab_search[] = 'referer='.$ab_config['refhost'];

// PTR 2 и 3 уровня если есть:
$ab_config['ptr_arr'] = explode('.', $ab_config['ptr']);
$ab_config['ptr_arr'] = array_reverse($ab_config['ptr_arr'], false);
$ab_config['search'] = array();
if (isset($ab_config['ptr_arr'][1])) {
$ab_search[] = $antibot_db->escapeString('ptr='.$ab_config['ptr_arr'][1].'.'.$ab_config['ptr_arr'][0]);
}
if (isset($ab_config['ptr_arr'][2])) {
$ab_search[] = $antibot_db->escapeString('ptr='.$ab_config['ptr_arr'][2].'.'.$ab_config['ptr_arr'][1].'.'.$ab_config['ptr_arr'][0]);
}
$ab_search[] = $antibot_db->escapeString('asname='.$ab_config['asname']);
$ab_search[] = 'asnum='.$ab_config['asnum'];
$ab_search[] = $antibot_db->escapeString('uri='.$ab_config['uri']);
$ab_search[] = $antibot_db->escapeString('scriptname='.trim(strip_tags($_SERVER['SCRIPT_NAME'])));
$ab_search[] = $antibot_db->escapeString('httpaccept='.trim(strip_tags($ab_config['http_accept'])));

$ab_all_test = $antibot_db->query("SELECT * FROM rules WHERE search='".implode('\' OR search=\'', $ab_search)."' ORDER by priority ASC;");
while ($echo = $ab_all_test->fetchArray(SQLITE3_ASSOC)) {
if ($echo['rule'] == 'allow') {
// куки чтоб далее пускать как LOCAL:
if (version_compare(PHP_VERSION, '7.3.0', '>=')) {
setcookie('antibot_'.$ab_config['uid'], md5($ab_config['pass'].$ab_config['host'].$ab_config['useragent'].$ab_config['ip'].$ab_config['time']).'-'.$ab_config['time'], [
    'expires' => $ab_config['time']+864000,
    'path' => '/',
    'domain' => $ab_config['host'],
    'secure' => false,
    'httponly' => false,
    'samesite' => 'Lax',
]);
} else {
setcookie('antibot_'.$ab_config['uid'], md5($ab_config['pass'].$ab_config['host'].$ab_config['useragent'].$ab_config['ip'].$ab_config['time']).'-'.$ab_config['time'], $ab_config['time']+864000, '/');
}

$ab_config['antibot_log_local'] = 0; // для исключения дублей в логе
$ab_config['whitebot'] = 0;
if ($ab_config['antibot_log_allow'] == 1) {
// записать в лог посещаемости, если включено логирование, с passed 4
$ab_exec_time = round(microtime(true) - $ab_start_time, 5);
$add = @$antibot_db->exec("INSERT INTO hits (cid, date, ip, ptr, useragent, uid, country, referer, page, lang, generation, passed, recaptcha, js_w, js_h, js_cw, js_ch, js_co, js_pi, refhost, adblock, asnum, asname, result, http_accept, method, ym_uid, ga_uid) VALUES ('".$ab_config['cid']."', '".$ab_config['time']."', '".$ab_config['ip']."', '".$ab_config['ptr']."', '".$ab_config['useragent']."', '".$ab_config['uid']."', '".$ab_config['country']."', '".$ab_config['referer']."', '".$ab_config['page']."', '".$ab_config['accept_lang']."', '".$ab_exec_time."', '4', '', '', '', '', '', '', '', '".$ab_config['refhost']."', '', '".$ab_config['asnum']."', '".$ab_config['asname']."', '', '".$ab_config['http_accept']."', '".$ab_config['request_method']."', '".$ab_config['ym_uid']."', '".$ab_config['ga_uid']."');");
}
file_put_contents(__DIR__.'/../data/counters/allow_'.date('Ymd', $ab_config['time']), '1', FILE_APPEND | LOCK_EX);
break;
} elseif ($echo['rule'] == 'block') {
if ($ab_config['antibot_log_block'] == 1) {
$echo['search'] = $antibot_db->escapeString($echo['search']);
$ab_exec_time = round(microtime(true) - $ab_start_time, 5);
$add = @$antibot_db->exec("INSERT INTO hits (cid, date, ip, ptr, useragent, uid, country, referer, page, lang, generation, passed, recaptcha, js_w, js_h, js_cw, js_ch, js_co, js_pi, refhost, adblock, asnum, asname, result, http_accept, method, ym_uid, ga_uid) VALUES ('".$ab_config['cid']."', '".$ab_config['time']."', '".$ab_config['ip']."', '".$ab_config['ptr']."', '".$ab_config['useragent']."', '".$ab_config['uid']."', '".$ab_config['country']."', '".$ab_config['referer']."', '".$ab_config['page']."', '".$ab_config['accept_lang']."', '".$ab_exec_time."', '6', '', '', '', '', '', '', '', '".$ab_config['refhost']."', '', '".$ab_config['asnum']."', '".$ab_config['asname']."', 'Blocked by rule: ".$echo['search']."', '".$ab_config['http_accept']."', '".$ab_config['request_method']."', '".$ab_config['ym_uid']."', '".$ab_config['ga_uid']."');");
}
file_put_contents(__DIR__.'/../data/counters/block_'.date('Ymd', $ab_config['time']), '1', FILE_APPEND | LOCK_EX);
header('X-Robots-Tag: noindex');
header($ab_config['protocol'].' '.$ab_config['error_headers'][$ab_config['header_error_code']]);
header('Status: '.$ab_config['error_headers'][$ab_config['header_error_code']]);
echo file_get_contents(__DIR__.'/../data/error.txt');
die();
} elseif ($echo['rule'] == 'gray') {
$ab_config['check_url'] = $ab_config['webdir'].'gray.php';
}
}
}
// конец проверки по остальным параметрам.

// дальше проверяем только людей:
if (!isset($ab_config['whitebot'])) {
// отдаем юзеру заглушку для проверки:
if ($ab_config['antibot_ok'] != $ab_config['antibot']) {
// если post запрос к заглушке, то все равно он нормально не будет обработан, редиректим на get:
if ($ab_config['request_method'] == 'POST') {
header('Location: '.$ab_config['uri']);
die();
}

// перевод заглушки на язык посетителя:
if ($ab_config['tpl_lang'] == '') {$ab_config['tpl_lang'] = $ab_config['lang'];}
if (file_exists(__DIR__.'/../lang/tpl/'.$ab_config['tpl_lang'].'.php')) {
require_once(__DIR__.'/../lang/tpl/'.$ab_config['tpl_lang'].'.php');
}

// подключение своего php кода:
require_once(__DIR__.'/../data/code.php');

header('Content-Type: text/html; charset=UTF-8');
header('X-Robots-Tag: noindex');
header('X-Powered-By: AntiBot.Cloud (See: https://antibot.cloud/)');
header('Expires: Thu, 18 Aug 1994 05:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Link: <https://antibotcloud.com/>; rel=dns-prefetch');
header($ab_config['protocol'].' '.$ab_config['error_headers'][$ab_config['header_test_code']]);
header('Status: '.$ab_config['error_headers'][$ab_config['header_test_code']]);

// перенос статистики из файлов в базу:
$cron_update_time = (int) trim(@file_get_contents(__DIR__.'/../data/counters/update')) + 0;
if ($ab_config['time'] - $cron_update_time > 600) {
file_put_contents(__DIR__.'/../data/counters/update', $ab_config['time'], LOCK_EX);
require_once(__DIR__.'/cron.php');
}

// счетчик показов заглушки:
file_put_contents(__DIR__.'/../data/counters/test_'.date('Ymd', $ab_config['time']), '1', FILE_APPEND | LOCK_EX);

// показываем заглушку:
$tpl = file_get_contents(__DIR__.'/../data/tpl.txt');
ob_start();
require_once(__DIR__.'/js.php');
$tpl_js = ob_get_clean();
$tpl = str_ireplace('Protected by AntiBot.Cloud', abTranslate('Protected by AntiBot.Cloud'), $tpl);
$tpl = str_ireplace('"https://antibot.cloud/"', '"https://antibot.cloud/'.$ab_config['tpl_lang'].'.html"', $tpl);
$tpl = str_ireplace('<body>', '<body><a href="https://xaxaxa.antibot.cloud/"> <!-- don\'t click here --> </a>', $tpl);
$tpl = str_ireplace('</body>', $tpl_js.'</body>', $tpl);
$tpl = str_ireplace('antibot-btn-success', 's'.md5('antibot-btn-success'.$ab_config['time']), $tpl);
$tpl = str_ireplace('antibot-btn-color', 's'.md5('antibot-btn-color'.$ab_config['time']), $tpl);
echo $tpl;

if ($ab_config['antibot_log_tests'] == 1) {
//запись в лог попавших на заглушку:
$ab_exec_time = round(microtime(true) - $ab_start_time, 5);
$add = @$antibot_db->exec("INSERT INTO hits (cid, date, ip, ptr, useragent, uid, country, referer, page, lang, generation, passed, recaptcha, js_w, js_h, js_cw, js_ch, js_co, js_pi, refhost, adblock, asnum, asname, result, http_accept, method, ym_uid, ga_uid) VALUES ('".$ab_config['cid']."', '".$ab_config['time']."', '".$ab_config['ip']."', '".$ab_config['ptr']."', '".$ab_config['useragent']."', '".$ab_config['uid']."', '".$ab_config['country']."', '".$ab_config['referer']."', '".$ab_config['page']."', '".$ab_config['accept_lang']."', '".$ab_exec_time."', '0', '', '', '', '', '', '', '', '".$ab_config['refhost']."', '', '".$ab_config['asnum']."', '".$ab_config['asname']."', '".(($ab_config['hosting'] == 1) ? 'Data Center or Web Hosting IP' : '')."', '".$ab_config['http_accept']."', '".$ab_config['request_method']."', '".$ab_config['ym_uid']."', '".$ab_config['ga_uid']."');");
}
$ab_exec_time = microtime(true) - $ab_start_time;
$ab_exec_time = round($ab_exec_time, 5);
echo '<!-- Time: '.$ab_exec_time.' Sec. Protected by AntiBot.Cloud -->';
// конец вывод заглушки.
die();
}

// счетчик LOCAL:
file_put_contents(__DIR__.'/../data/counters/local_'.date('Ymd', $ab_config['time']), '1', FILE_APPEND | LOCK_EX);

if ($ab_config['antibot_log_local'] == 1) {
//запись в лог имеющих разрешающие cookie:
$ab_exec_time = round(microtime(true) - $ab_start_time, 5);
$add = @$antibot_db->exec("INSERT INTO hits (cid, date, ip, ptr, useragent, uid, country, referer, page, lang, generation, passed, recaptcha, js_w, js_h, js_cw, js_ch, js_co, js_pi, refhost, adblock, asnum, asname, result, http_accept, method, ym_uid, ga_uid) VALUES ('".$ab_config['cid']."', '".$ab_config['time']."', '".$ab_config['ip']."', '".$ab_config['ptr']."', '".$ab_config['useragent']."', '".$ab_config['uid']."', '".$ab_config['country']."', '".$ab_config['referer']."', '".$ab_config['page']."', '".$ab_config['accept_lang']."', '".$ab_exec_time."', '3', '', '', '', '', '', '', '', '".$ab_config['refhost']."', '', '".$ab_config['asnum']."', '".$ab_config['asname']."', '', '".$ab_config['http_accept']."', '".$ab_config['request_method']."', '".$ab_config['ym_uid']."', '".$ab_config['ga_uid']."');");
}
}

if (isset($ab_config['whitebot']) AND $ab_config['whitebot'] == 1) {
// логирование белых ботов, если включено:
if ($ab_config['antibot_log_goodip'] == 1) {
$ab_exec_time = round(microtime(true) - $ab_start_time, 5);
$add = @$antibot_db->exec("INSERT INTO hits (cid, date, ip, ptr, useragent, uid, country, referer, page, lang, generation, passed, recaptcha, js_w, js_h, js_cw, js_ch, js_co, js_pi, refhost, adblock, asnum, asname, result, http_accept, method, ym_uid, ga_uid) VALUES ('".$ab_config['cid']."', '".$ab_config['time']."', '".$ab_config['ip']."', '".$ab_config['ptr']."', '".$ab_config['useragent']."', '".$ab_config['uid']."', '".$ab_config['country']."', '".$ab_config['referer']."', '".$ab_config['page']."', '".$ab_config['accept_lang']."', '".$ab_exec_time."', '5', '', '', '', '', '', '', '', '".$ab_config['refhost']."', '', '".$ab_config['asnum']."', '".$ab_config['asname']."', '', '".$ab_config['http_accept']."', '".$ab_config['request_method']."', '".$ab_config['ym_uid']."', '".$ab_config['ga_uid']."');");
}
// счетчик белых ботов:
file_put_contents(__DIR__.'/../data/counters/goodip_'.date('Ymd', $ab_config['time']), '1', FILE_APPEND | LOCK_EX);
if (stripos($ab_config['useragent'], 'Googlebot', 0) !== false) {
file_put_contents(__DIR__.'/../data/counters/google_'.date('Ymd', $ab_config['time']), '1', FILE_APPEND | LOCK_EX);
} elseif (stripos($ab_config['useragent'], 'yandex.com', 0) !== false) {
file_put_contents(__DIR__.'/../data/counters/yandex_'.date('Ymd', $ab_config['time']), '1', FILE_APPEND | LOCK_EX);
} elseif (stripos($ab_config['useragent'], 'bingbot', 0) !== false) {
file_put_contents(__DIR__.'/../data/counters/bing_'.date('Ymd', $ab_config['time']), '1', FILE_APPEND | LOCK_EX);
}
} else {
// счетчик хитов в куках:
if ($ab_config['antibot_hits'] > $ab_config['hits_per_user']) {
setcookie('antibot_hits', 0, $ab_config['time']-100, '/');
setcookie('antibot_'.$ab_config['uid'], 0, $ab_config['time']-100, '/');
} else {
setcookie('antibot_hits', ($ab_config['antibot_hits']+1), $ab_config['time']+86400, '/');
}

}

} else {
$ab_config['whitebot'] = 0;
}

if (!isset($ab_config['whitebot'])) {$ab_config['whitebot'] = 0;}


define('ANTIBOT_WHITEBOT', $ab_config['whitebot']);
