<?php
// обновление
if(!defined('ANTIBOT')) die('access denied');

$link = glob(__DIR__."/../data/counters/*");
foreach ($link as $line) {
if (filemtime($line) < $ab_config['time'] - 259200) {
unlink($line);
}
}

clearstatcache(true); // Clears file status cache
if(function_exists('opcache_reset')) {
opcache_reset();
}

$content = '';

if (isset($_POST['update_submit']) AND isset($_POST['upd'])) {
// список изменений и хэши:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://antibot.cloud/static/update/update8.json');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 600);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_USERAGENT, 'AntiBot');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
curl_setopt($ch, CURLOPT_FTP_SSL, CURLFTPSSL_TRY);
$actual = @json_decode(trim(curl_exec($ch)), true);
curl_close($ch);

// скачивание архива с обновлением:
$fp = fopen(__DIR__.'/../data/update.zip', 'w');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://antibot.cloud/static/update/update8.zip');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 600);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_USERAGENT, 'AntiBot');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
curl_setopt($ch, CURLOPT_FTP_SSL, CURLFTPSSL_TRY);
$outch = curl_exec($ch);
curl_close($ch);
fclose($fp);


if ($actual['md5'] == md5_file(__DIR__.'/../data/update.zip')) {
$zip = new ZipArchive;
if ($zip->open(__DIR__.'/../data/update.zip') === TRUE) {
    $zip->extractTo(__DIR__.'/../');
    $zip->close();
$content .= '<div class="alert alert-success" role="alert">
'.abTranslate('The update was successful.').'
</div>';
} else {
$content .= '<div class="alert alert-danger" role="alert">
'.abTranslate('Update failed.').'
</div>';
}

clearstatcache(true); // Clears file status cache
if(function_exists('opcache_reset')) {
opcache_reset();
}

echo '<script>document.location.href="?'.$abw.$abp.'=update2";</script>';
die();
} else {
$content .= '<div class="alert alert-danger" role="alert">
'.abTranslate('Update failed.').' '.abTranslate('The MD5 archive hash does not match the reference.').'
</div>';
}

}

$title = abTranslate('Update');

// не установлен ZIP
if (!class_exists('ZipArchive')) {
$content .= '<div class="alert alert-danger" role="alert">
'.abTranslate('Class ZipArchive not exists. Install ZIP extension for PHP.').'
</div>';
}

$antibotdir = realpath(__DIR__.'/../');

// получение массива актуальных файлов:
function getDirContents($dir, &$results = array()) {
global $antibotdir;
    $files = scandir($dir);
    foreach ($files as $key => $value) {
        $path = $dir . DIRECTORY_SEPARATOR . $value;
        if (!is_dir($path)) {
//            $results[$path] = md5_file($path);
            $filename = explode($antibotdir.'/', $path);
//            echo $filename[1].'<br>';
            $results[$filename[1]] = md5_file($path).'_'.md5($filename[1]);
        } else if ($value != "." && $value != "..") {
            getDirContents($path, $results);
            //$results[$path] = md5_file($path);
        }
    }
    return $results;
}

$local = getDirContents(realpath(__DIR__.'/../')); // локальный массив

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://antibot.cloud/static/update/update8.json');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 600);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_USERAGENT, 'AntiBot');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
curl_setopt($ch, CURLOPT_FTP_SSL, CURLFTPSSL_TRY);
$actual = @json_decode(trim(curl_exec($ch)), true);
curl_close($ch);

if (isset($actual['md5'])) {
unset($actual['md5']);

// Сравнивает array1 с одним или несколькими другими массивами и возвращает значения из array1, которые отсутствуют во всех других массивах.
$differences = array_diff($actual, $local); // Отличающиеся файлы, которые есть в архиве
$content .= '<div class="alert alert-info" role="alert">'.abTranslate('Your software version:').' '.$ab_version.' (<a href="'.abTranslate('https://antibot.cloud/static/update/changelog8.txt').'" target="_blank" rel="noopener">changelog</a>)</div>
<p>'.abTranslate('These files will be replaced or added:').'</p>
<ul>';
$upderror = 0;
$updcount = 0;
foreach ($differences as $k => $v) {
if (file_exists(__DIR__.'/../'.$k) AND is_writable(__DIR__.'/../'.$k)) {
$content .= '<li class="text-success">'.$k.' ('.abTranslate('will be replaced').')</li>';
} elseif (!file_exists(__DIR__.'/../'.$k)) {
$content .= '<li class="text-success">'.$k.' ('.abTranslate('will be added').')</li>';
} else {
$content .= '<li class="text-danger">'.$k.' ('.abTranslate('set write permissions on this file').')</li>';
$upderror = 1;
}
$updcount++;
}
$content .= '</ul>';
if ($upderror == 1) {
$content .= '<div class="alert alert-danger" role="alert">
'.abTranslate('Updating is not possible. Correct the errors indicated above.').'
</div>';
} elseif ($updcount == 0) {
$content .= '<div class="alert alert-success" role="alert">
'.abTranslate('No update required.').'
</div>';
} elseif ($host == 'antibot-cloud') {
$content .= '<div class="alert alert-danger" role="alert">
Тут нельзя обновлять.
</div>';
} else {
$content .= '<p><form class="form-inline" action="?'.$abw.$abp.'=update" method="post">
<input name="upd" type="hidden" value="1">
<input style="cursor:pointer;" class="btn btn-sm btn-success" type="submit" name="update_submit" value="'.abTranslate('Make update').'">
</form></p>';
}

$differences = array_diff($local, $actual); // различия
foreach ($differences as $k => $v) {
if (isset($actual[$k])) {unset($differences[$k]);}
}
$content .= '<p>'.abTranslate('Local files that will not be changed:').'</p>
<ul>';
foreach ($differences as $k => $v) {
$content .= '<li>'.$k.'</li>';
}
$content .= '</ul>';

// обновление шаблона:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://antibot.cloud/static/update/tpl8.json');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 600);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_USERAGENT, 'AntiBot');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
curl_setopt($ch, CURLOPT_FTP_SSL, CURLFTPSSL_TRY);
$actual_tpl = @json_decode(trim(curl_exec($ch)), true);
curl_close($ch);

$local_tpl = md5_file(__DIR__.'/../data/tpl.txt');
if (isset($actual_tpl['md5']) AND $actual_tpl['md5'] != $local_tpl) {
$content .= '<div class="alert alert-danger" role="alert">
'.abTranslate('The tpl.txt template is different from the current one:').' <a href="https://antibot.cloud/static/update/tpl8.txt" rel="noopener" target="_blank">tpl.txt</a>
</div>';
$content .= '<p><form class="form-inline" action="?'.$abw.$abp.'=updatetpl" method="post">
<input name="upd" type="hidden" value="1">
<input style="cursor:pointer;" class="btn btn-sm btn-success" type="submit" name="updatetpl_submit" value="'.abTranslate('Make update').'">
</form></p>';
} else {
$content .= '<div class="alert alert-success" role="alert">
'.abTranslate('The tpl.txt template does not require updating.').'
</div>';
}
} else {
$content .= '<div class="alert alert-danger" role="alert">
'.abTranslate('Error checking for updates.').'
</div>';
}
