<?php
/**
 * Elite-Board 5 — распаковщик дистрибутива (шаг 0).
 * Один файл: стили и графика встроены. Требуется PHP 7.2+ и расширение zip.
 */

session_start();
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store');

const ARCHIVE_PATTERN = '/^eliteboard_.*\.zip$/i';

$texts = [
    'ru' => [
        'wizard' => 'Мастер установки', 'badge' => 'Шаг 0 из 7',
        'title' => 'Распаковка', 'lang' => 'Язык мастера установки:',
        'intro' => 'Выберите архив с дистрибутивом Elite-Board 5. Файлы будут распакованы в текущую папку, после чего откроется мастер установки.',
        'steps' => ['Лицензия', 'Права', 'Окружение', 'База данных', 'Сайт', 'Установка', 'Готово'],
        'empty' => 'Архивы не найдены. Загрузите файл eliteboard_*.zip в папку со скриптом и обновите страницу.',
        'note' => 'Существующие файлы с теми же именами будут перезаписаны. После успешной распаковки архив удаляется.',
        'refresh' => 'Обновить список', 'unpack' => 'Распаковать →', 'busy' => 'Распаковка…',
        'e_zip' => 'На сервере не установлено расширение PHP zip.',
        'e_write' => 'Нет прав на запись в папку со скриптом.',
        'e_token' => 'Сессия устарела. Обновите страницу и повторите.',
        'e_file' => 'Архив не найден.',
        'e_open' => 'Не удалось открыть архив. Возможно, он повреждён или загружен не полностью.',
        'e_unsafe' => 'Архив содержит недопустимые пути. Распаковка отменена.',
        'e_extract' => 'Ошибка при распаковке. Проверьте права доступа и свободное место на диске.',
        'e_install' => 'Архив распакован, но папка install не найдена.',
    ],
    'en' => [
        'wizard' => 'Installation wizard', 'badge' => 'Step 0 of 7',
        'title' => 'Unpacking', 'lang' => 'Wizard language:',
        'intro' => 'Choose the Elite-Board 5 distribution archive. Its files will be extracted into the current folder, then the installation wizard will open.',
        'steps' => ['License', 'Permissions', 'Environment', 'Database', 'Website', 'Install', 'Done'],
        'empty' => 'No archives found. Upload an eliteboard_*.zip file next to this script and refresh the page.',
        'note' => 'Existing files with the same names will be overwritten. The archive is deleted after successful extraction.',
        'refresh' => 'Refresh list', 'unpack' => 'Unpack →', 'busy' => 'Unpacking…',
        'e_zip' => 'The PHP zip extension is not installed on this server.',
        'e_write' => 'The script folder is not writable.',
        'e_token' => 'Your session has expired. Reload the page and try again.',
        'e_file' => 'Archive not found.',
        'e_open' => 'Cannot open the archive. It may be damaged or incompletely uploaded.',
        'e_unsafe' => 'The archive contains unsafe paths. Extraction cancelled.',
        'e_extract' => 'Extraction failed. Check permissions and free disk space.',
        'e_install' => 'The archive was extracted, but the install folder is missing.',
    ],
];

$lang = $_GET['lang'] ?? 'ru';
if (!is_string($lang) || !isset($texts[$lang])) {
    $lang = 'ru';
}
$t = $texts[$lang];

function e($value)
{
    return htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

/** Список архивов дистрибутива рядом со скриптом. */
function findArchives($dir)
{
    $list = [];
    foreach (scandir($dir) ?: [] as $name) {
        if (preg_match(ARCHIVE_PATTERN, $name) && is_file($dir . '/' . $name)) {
            $list[] = $name;
        }
    }
    natsort($list);
    return array_reverse(array_values($list)); // новые версии сверху
}

/** Возвращает null при успехе или ключ сообщения об ошибке. */
function unpackArchive($file, $dir)
{
    $zip = new ZipArchive();
    if ($zip->open($file) !== true) {
        return 'e_open';
    }
    // Защита от выхода за пределы папки (Zip Slip)
    for ($i = 0; $i < $zip->numFiles; $i++) {
        $name = $zip->getNameIndex($i);
        if ($name === false || preg_match('~^[/\\\\]|^[a-z]:|(^|[/\\\\])\.\.([/\\\\]|$)~i', $name)) {
            $zip->close();
            return 'e_unsafe';
        }
    }
    $ok = $zip->extractTo($dir);
    $zip->close();
    return $ok ? null : 'e_extract';
}

if (empty($_SESSION['unzip_token'])) {
    $_SESSION['unzip_token'] = bin2hex(random_bytes(16));
}

$error = null;
if (!class_exists('ZipArchive')) {
    $error = 'e_zip';
} elseif (!is_writable(__DIR__)) {
    $error = 'e_write';
}
$blocked = $error !== null;
$archives = findArchives(__DIR__);

if (!$blocked && ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
    $token = $_POST['token'] ?? '';
    $file = $_POST['file'] ?? '';

    if (!is_string($token) || !hash_equals($_SESSION['unzip_token'], $token)) {
        $error = 'e_token';
    } elseif (!is_string($file) || !in_array($file, $archives, true)) {
        $error = 'e_file';
    } else {
        @set_time_limit(0);
        $path = __DIR__ . '/' . $file;
        $error = unpackArchive($path, __DIR__);
        if ($error === null) {
            if (is_dir(__DIR__ . '/install')) {
                @unlink($path);
                header('Location: install/');
                exit;
            }
            $error = 'e_install';
        }
    }
}

$logoSvg = <<<'SVG'
<svg xmlns="http://www.w3.org/2000/svg" viewBox="137 137 1656 1656">
<defs>
<clipPath id="ball"><circle cx="965" cy="965" r="828"/></clipPath>
<linearGradient id="gDark" x1="0.35" y1="0" x2="0.6" y2="1"><stop offset="0" stop-color="#087038"/><stop offset="1" stop-color="#05403a"/></linearGradient>
<linearGradient id="gMid" x1="0.15" y1="0.15" x2="0.75" y2="0.95"><stop offset="0" stop-color="#55b020"/><stop offset="0.45" stop-color="#2ea830"/><stop offset="0.8" stop-color="#05955a"/><stop offset="1" stop-color="#05904f"/></linearGradient>
<radialGradient id="gLight" cx="0.45" cy="0.3" r="0.75"><stop offset="0" stop-color="#b8ee6c"/><stop offset="0.35" stop-color="#96e000"/><stop offset="0.75" stop-color="#8ae000"/><stop offset="1" stop-color="#55c800"/></radialGradient>
<linearGradient id="gLobe" x1="0" y1="0.3" x2="1" y2="0.6"><stop offset="0" stop-color="#38c746"/><stop offset="0.4" stop-color="#7ddc00"/><stop offset="0.75" stop-color="#6adf2a"/><stop offset="1" stop-color="#5de05a"/></linearGradient>
<filter id="shadow" x="-20%" y="-20%" width="140%" height="140%"><feGaussianBlur stdDeviation="22"/></filter>
</defs>
<g clip-path="url(#ball)">
<rect x="100" y="100" width="1740" height="1740" fill="url(#gDark)"/>
<path filter="url(#shadow)" opacity="0.55" fill="#022d1c" d="M137,990 C200,1280 420,1413 620,1413 C900,1413 1100,1230 1300,1180 C1550,1120 1680,1180 1730,1315 L1900,1315 L1900,0 L0,0 L0,990 Z"/>
<path fill="url(#gMid)" d="M137,960 C200,1250 420,1383 620,1383 C900,1383 1100,1200 1300,1150 C1550,1090 1680,1150 1730,1285 L1900,1285 L1900,0 L0,0 L0,960 Z"/>
<path filter="url(#shadow)" opacity="0.5" fill="#2f6e0a" d="M600,195 C480,270 431,400 431,515 C431,650 520,810 590,900 C680,990 800,1005 880,1005 C1050,1005 1180,920 1230,865 C1300,810 1370,760 1430,750 C1650,720 1780,910 1790,1065 L1790,0 L600,0 Z"/>
<path fill="url(#gLight)" d="M620,215 C500,290 451,400 451,515 C451,650 540,800 610,880 C700,960 800,975 880,975 C1050,975 1180,890 1230,835 C1300,780 1370,730 1430,720 C1650,690 1780,880 1790,1035 L1800,0 L620,0 Z"/>
<path filter="url(#shadow)" opacity="0.35" fill="#3a8a10" d="M1230,203 C1050,170 923,290 923,440 C923,640 1080,770 1250,770 C1330,770 1400,755 1430,740 Z"/>
<path fill="url(#gLobe)" d="M1230,183 C1050,150 903,280 903,440 C903,640 1080,750 1250,750 C1330,750 1400,735 1430,720 C1650,690 1780,880 1790,1035 L1800,965 C1800,600 1550,320 1230,183 Z"/>
</g>
</svg>
SVG;
$logo = 'data:image/svg+xml;base64,' . base64_encode($logoSvg);
?>
<!DOCTYPE html>
<html lang="<?= e($lang) ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title>Elite-Board 5 — <?= e($t['wizard']) ?></title>
<link rel="icon" href="<?= $logo ?>">
<style>
:root{--bg:#07100b;--card:#0e1c15;--inset:#09150f;--line:#27372e;--text:#f2f7f3;--muted:#a9bbb0;--accent:#92e000}
*{box-sizing:border-box;margin:0;padding:0}
body{min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px 16px;background:var(--bg);color:var(--text);font:15px/1.5 "Segoe UI",system-ui,-apple-system,Roboto,Arial,sans-serif;overflow-x:hidden}
body::before{content:"";position:fixed;right:-140px;bottom:-320px;width:800px;height:800px;background:url("<?= $logo ?>") center/contain no-repeat;opacity:.12;pointer-events:none}
.card{position:relative;width:100%;max-width:980px;background:var(--card);border:1px solid var(--line);border-radius:20px;box-shadow:0 24px 70px rgba(0,0,0,.45)}
header,main,footer{padding:24px 36px}
header{display:flex;align-items:center;gap:18px;border-bottom:1px solid var(--line)}
header img{width:44px;height:44px}
.brand{font-size:22px;font-weight:800;line-height:1.2}
.brand b{color:var(--accent)}
.sub{font-size:13px;color:var(--muted)}
.badge{margin-left:auto;padding:5px 15px;border:1px solid var(--line);border-radius:99px;font-size:13px;font-weight:600;color:var(--muted);white-space:nowrap}
.steps{display:grid;grid-template-columns:repeat(7,1fr);gap:10px;list-style:none;margin-bottom:30px}
.steps li{border-top:4px solid var(--line);border-radius:2px;padding-top:9px;font-size:12px;font-weight:600;color:var(--muted)}
.top{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px;margin-bottom:16px}
h1{font-size:28px;font-weight:900}
.top label{font-size:13px}
select{margin-left:6px;padding:11px 12px;background:var(--card);color:var(--text);border:1px solid var(--line);border-radius:9px;font:inherit;font-size:13px}
.intro{max-width:780px;color:var(--muted);margin-bottom:22px}
.panel{max-height:240px;overflow:auto;padding:12px;background:var(--inset);border:1px solid var(--line);border-radius:12px}
.file{display:flex;align-items:center;gap:14px;padding:13px 16px;border:1px solid transparent;border-radius:10px;cursor:pointer}
.file+.file{margin-top:6px}
.file:hover{background:var(--card)}
.file:focus-within{border-color:var(--line)}
input[type=radio]{width:18px;height:18px;accent-color:var(--accent);flex:none}
.name{font-weight:600;overflow-wrap:anywhere}
.meta{margin-left:auto;font-size:13px;color:var(--muted);white-space:nowrap}
.empty{padding:24px;text-align:center;color:var(--muted)}
.note{margin-top:16px;font-size:13px;color:var(--muted)}
.error{margin-bottom:18px;padding:13px 18px;border:1px solid #8c3b3b;border-radius:10px;background:#2a1414;color:#ffc9c9}
footer{display:flex;justify-content:space-between;gap:12px;border-top:1px solid var(--line)}
.btn{display:inline-block;padding:10px 22px;border:1px solid var(--line);border-radius:10px;background:transparent;color:var(--muted);font:inherit;font-weight:700;text-decoration:none;cursor:pointer}
.btn:hover{border-color:var(--muted);color:var(--text)}
.primary{background:var(--accent);border-color:var(--accent);color:#0a1a05}
.primary:hover{filter:brightness(1.1);border-color:var(--accent);color:#0a1a05}
.primary:disabled{opacity:.45;cursor:not-allowed;filter:none}
:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
@media(max-width:700px){header,main,footer{padding:18px}header{gap:10px}.brand{font-size:18px;white-space:nowrap}.badge{padding:4px 9px;font-size:12px}.btn{padding:10px 14px;white-space:nowrap;font-size:14px}.steps{gap:5px}.steps li{font-size:0}.file{flex-wrap:wrap}.meta{margin-left:32px}}
</style>
</head>
<body>
<div class="card">
    <header>
        <img src="<?= $logo ?>" alt="">
        <div>
            <div class="brand">Elite-Board <b>5</b></div>
            <div class="sub"><?= e($t['wizard']) ?></div>
        </div>
        <span class="badge"><?= e($t['badge']) ?></span>
    </header>

    <main>
        <ol class="steps">
            <?php foreach ($t['steps'] as $step): ?><li><?= e($step) ?></li><?php endforeach; ?>
        </ol>

        <div class="top">
            <h1><?= e($t['title']) ?></h1>
            <form method="get">
                <label><?= e($t['lang']) ?>
                    <select name="lang" onchange="this.form.submit()">
                        <option value="ru"<?= $lang === 'ru' ? ' selected' : '' ?>>Русский</option>
                        <option value="en"<?= $lang === 'en' ? ' selected' : '' ?>>English</option>
                    </select>
                </label>
                <noscript><button class="btn">OK</button></noscript>
            </form>
        </div>
        <p class="intro"><?= e($t['intro']) ?></p>

        <?php if ($error !== null): ?>
            <div class="error" role="alert"><?= e($t[$error]) ?></div>
        <?php endif; ?>

        <form id="unpack" method="post" action="?lang=<?= e($lang) ?>">
            <input type="hidden" name="token" value="<?= e($_SESSION['unzip_token']) ?>">
            <div class="panel">
                <?php if (!$archives): ?>
                    <div class="empty"><?= e($t['empty']) ?></div>
                <?php endif; ?>
                <?php foreach ($archives as $i => $name): ?>
                    <label class="file">
                        <input type="radio" name="file" value="<?= e($name) ?>" required<?= $i === 0 ? ' checked' : '' ?>>
                        <span class="name"><?= e($name) ?></span>
                        <span class="meta"><?= number_format(filesize(__DIR__ . '/' . $name) / 1048576, 2, '.', ' ') ?> MB · <?= date('d.m.Y H:i', filemtime(__DIR__ . '/' . $name)) ?></span>
                    </label>
                <?php endforeach; ?>
            </div>
        </form>
        <p class="note"><?= e($t['note']) ?></p>
    </main>

    <footer>
        <a class="btn" href="?lang=<?= e($lang) ?>"><?= e($t['refresh']) ?></a>
        <button class="btn primary" id="go" type="submit" form="unpack"<?= ($blocked || !$archives) ? ' disabled' : '' ?>><?= e($t['unpack']) ?></button>
    </footer>
</div>
<script>
document.getElementById('unpack').addEventListener('submit', function () {
    var b = document.getElementById('go');
    b.disabled = true;
    b.textContent = <?= json_encode($t['busy'], JSON_UNESCAPED_UNICODE) ?>;
});
</script>
</body>
</html>