<?php
/**
 * RET CMS — ret-setup.php 1.0.1: установка из одного файла на shared hosting (docs/ret-setup-v1.md).
 * Copyright (c) 2026 Dmitrii Zamoshnikov. All rights reserved. См. LICENSE.
 *
 * Владелец кладёт этот файл в web-root домена (FTP) и открывает https://домен/ret-setup.php:
 *   проверка (только чтение) → подтверждение доступа (пустой файл ret-setup-<C> рядом по FTP) →
 *   план → retcms.com: подписанный latest → проверка цепочки → распаковка → раскладка
 *   (приватное — рядом с web-root, публичное — в него, index.php последним) → проверка →
 *   одноразовый билет → Web Installer v2 (/install/), доступ уже принят.
 *
 * Bootstrap только ДОСТАВЛЯЕТ и РАСКЛАДЫВАЕТ подписанный релиз: базу, site/config.php,
 * site/paths.php не пишет (это installer). Раскладка — только на чистое место по закрытому
 * списку; чужое не перезаписывает, не удаляет и не «чинит». Правила раскладки и зоны — из
 * проверенного релиза (public/kernel2/Layout.php, tools/lib/core/RetZone.php), билет — его
 * tools/lib/install/web/WebHandoff.php: своих копий этих правил здесь нет.
 *
 * Доверие: ключи релизов ниже (Ed25519) — те же, что в public/kernel2/Release.php версии
 * (release.php check сверяет); цепочка latest.json → index.json → метаданные версии → SHA-256
 * архива → release.json → файлы. Сам файл не подписан — он якорь (как install.sh): усиленная
 * проверка — SHA-256 файла с https://github.com/retcms/retcms-trust.
 *
 * Без exec/proc_open/shell; PHP 8.1+ (файл разбирается и на 7.4 — чтобы показать причину).
 * Источник релизов — константа BASE_URL; только для CI — переменная окружения СЕРВЕРА
 * RET_SETUP_BASE (https или http://127.0.0.1…); из запроса не меняется ничего.
 *
 * CLI: php ret-setup.php --keys   ключи релизов этого файла и их отпечатки
 *      php ret-setup.php --version
 */

final class RetSetupRefuse extends Exception {}      // жёсткий отказ: показать причину, ничего не делать
final class RetSetupTransport extends Exception {}   // сеть: можно повторить
final class RetSetupVerify extends Exception {}      // подпись/хеш/формат/версия: стоп без fallback
final class RetSetupRestage extends Exception {}     // элемента нет ни в stage, ни на месте

final class RetSetup
{
    const VERSION = '1.0.1';
    /** Версия ядра, под которую собран файл: latest ниже — отказ (откат на старый подписанный latest) */
    const BUILT_FOR = '0.25.1';
    /** Первая версия ядра, которую bootstrap умеет разложить (zone, WebHandoff, cores() по физическим каталогам) */
    const MIN_CORE = '0.25.1';
    const BASE_URL = 'https://retcms.com/releases';
    /** Формат журнала var/setup/state.json */
    const JOURNAL = 1;

    /** key_id => ['public' => base64 Ed25519, 'role' => 'primary'|'backup'] — как RetRelease::KEYS */
    const KEYS = [
        // keys:begin
        'release-primary-2026' => ['public' => '7wTZdxhzNOsfSqz0S56TP3Yv8On5hIMagzKQ6YYV7/0=', 'role' => 'primary'],
        'release-backup-2026' => ['public' => 'ougsjIxkJkNpisnA0hns3ttyFdJVpL4DUex1tKu2biI=', 'role' => 'backup'],
        // keys:end
    ];

    /** cookie сессии bootstrap'а (= WebHandoff::COOKIE): секрет 32 байта hex */
    const COOKIE = 'RETSETUP';
    const GRANT_TTL = 7200;
    const LOCK_STALE = 600;

    /** До распаковки — копия правил имени web-root; после — сверка RetLayout::validName() из релиза */
    const NAME_RE = '/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/';
    const RESERVED = ['site', 'var', 'tools', 'deploy', 'modules', 'schema', 'dist', 'docs', 'dev'];
    /** Родитель web-root с таким именем или такими файлами — общий/публичный (ядро вне web-root не спрятать) */
    const PARENT_NAMES = ['public_html', 'www', 'htdocs', 'httpdocs', 'httpsdocs', 'html', 'web', 'public', 'wwwroot', 'private_html'];
    const PARENT_FILES = ['index.php', 'index.html', 'index.htm', '.htaccess', 'web.config', 'wp-config.php'];
    /** Чистый web-root: эти обычные файлы не трогаются */
    const KEEP_FILES = ['.user.ini', 'php.ini', '.ftpquota', 'error_log'];
    const STUB_NAMES = ['index.html', 'index.htm', 'default.html', 'default.htm'];
    /** Корень установки: этих элементов быть не должно (кроме своего var/setup/) */
    const HOME_TARGETS = ['site', 'var', 'tools', 'deploy', 'schema', 'modules', 'README.md', 'CHANGELOG.md', 'LICENSE', 'ARCHITECTURE.md'];
    /** S1 … S8 */
    const PHASES = ['granted', 'downloaded', 'verified', 'staged', 'private', 'public', 'enabled', 'handed'];
    /** Файлы, которые bootstrap кладёт в deploy/ сверх релиза (подписанные метаданные, как install.sh/adopt) */
    const DEPLOY_EXTRA = ['release-meta.json', 'release-meta.json.sig'];

    const MAX_JSON = 1048576;
    const MAX_ARCHIVE = 67108864;
    const MAX_UNPACKED = 268435456;
    const MAX_ENTRIES = 20000;
    const MAX_SMALL = 65536;

    private $web = '';        // web-root (физически, / как разделитель)
    private $home = '';       // корень установки = родитель web-root
    private $pub = '';        // имя web-root
    private $lang = 'en';
    private $secret = '';
    private $nonce = '';
    private $base = '';
    private $testBase = false;
    private $lockFh = null;
    private $lockDir = null;
    private $flash = [];

    /* =================================================================== вход */

    public static function main(): void
    {
        if (PHP_SAPI === 'cli') { self::cli(); return; }
        $s = new self();
        $s->run();
    }

    private static function cli(): void
    {
        global $argv;
        $a = isset($argv[1]) ? $argv[1] : '';
        if ($a === '--version') { echo 'ret-setup.php ', self::VERSION, ' (RET CMS ', self::BUILT_FOR, "+)\n"; return; }
        if ($a === '--keys') {
            echo "Ключи релизов этого ret-setup.php (Ed25519; отпечаток — SHA-256 открытого ключа):\n";
            foreach (self::KEYS as $id => $k) printf("  %-24s %-8s SHA256:%s\n", $id, $k['role'], hash('sha256', (string)base64_decode($k['public'], true)));
            echo "Сверить: https://github.com/retcms/retcms-trust\n";
            return;
        }
        echo "ret-setup.php — установка RET CMS из одного файла на хостинг: положите файл в web-root домена\n"
           . "и откройте https://домен/ret-setup.php (docs/ret-setup-v1.md).\n"
           . "  php ret-setup.php --keys      ключи релизов и отпечатки\n"
           . "  php ret-setup.php --version\n";
    }

    private function run(): void
    {
        ini_set('display_errors', '0');
        ini_set('zend.exception_ignore_args', '1');
        error_reporting(E_ALL);
        $this->nonce = rtrim(strtr(base64_encode(random_bytes(16)), '+/', '-_'), '=');
        $this->lang = $this->pickLang();
        $this->headers();

        if (version_compare(PHP_VERSION, '8.1.0', '<')) {
            $this->page($this->t('title_refuse'), $this->box('err', $this->t('php_old', ['v' => PHP_VERSION])), 503);
            return;
        }
        $method = strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET'));
        if (!in_array($method, ['GET', 'HEAD', 'POST'], true)) { http_response_code(405); header('Allow: GET, POST'); return; }

        try {
            $this->checkRequest();
            $this->base();
        } catch (RetSetupRefuse $e) {
            $this->page($this->t('title_refuse'), $this->box('err', $e->getMessage()) . '<p>' . $this->t('refuse_hint') . '</p>', 403);
            return;
        }

        $state = $this->readState();
        if ($state === false) { $state = null; $bad = true; } else $bad = false;
        // §10: установка уже есть — инертен
        if (is_file("{$this->home}/site/install.json") || is_file("{$this->home}/site/config.php")) {
            if ($state !== null) $this->finalize();
            $this->inert();
            return;
        }
        if ($state === null && !$bad && is_file("{$this->web}/kernel2/VERSION")) {
            if (is_file("{$this->home}/var/logs/setup.log") || is_dir("{$this->home}/var/setup")) { $this->inert(); return; }
            $this->pageManual();
            return;
        }

        $this->secret = $this->sessionSecret();
        $granted = $this->granted();
        if ($state !== null && ($state['phase'] ?? '') === 'handed') {
            if (!$granted) { $this->finalize(); $this->inert(); return; }
        }

        try {
            if ($method === 'POST') {
                if (!$this->postOk()) {
                    $this->page($this->t('title_rejected'), $this->box('err', $this->t('rejected')) . $this->linkHome(), 403);
                    return;
                }
                $action = (string)($_POST['action'] ?? '');
                if ($action === 'confirm') { $this->doConfirm($state, $bad); return; }
                if (!$granted) { $this->redirect(); return; }
                $this->lock();
                try {
                    $state = $this->readState();
                    if ($state === false) {
                        if ($action === 'cancel') { $this->doCancel(null); return; }
                        throw new RetSetupRefuse($this->t('journal_bad'));
                    }
                    if ($state === null) $state = $this->newState();
                    $this->dispatch($action, $state);
                } finally {
                    $this->unlock();
                }
                return;
            }
            if (!$granted) { $this->pageConfirm($state, $bad); return; }
            if ($bad) { $this->pageJournalBad(); return; }
            if ($state === null) { $state = $this->newState(); $this->saveState($state); }
            $this->pageForState($state);
        } catch (RetSetupRefuse $e) {
            $this->pageError($e->getMessage(), $state ?: null);
        } catch (RetSetupVerify $e) {
            $this->pageError($this->t('verify_stop', ['e' => $e->getMessage()]), $state ?: null);
        } catch (Exception $e) {
            $this->pageError($e->getMessage(), $state ?: null);
        }
    }

    /* =================================================================== §5: проверки запроса */

    private function checkRequest(): void
    {
        $sn = (string)($_SERVER['SCRIPT_NAME'] ?? '');
        $pi = (string)($_SERVER['PATH_INFO'] ?? '');
        if ($sn !== '/ret-setup.php' || $pi !== '') throw new RetSetupRefuse($this->t('req_root'));
        $web = realpath(__DIR__);
        if ($web === false) throw new RetSetupRefuse($this->t('req_root'));
        $this->web = self::slash($web);
        $sf = (string)($_SERVER['SCRIPT_FILENAME'] ?? '');
        $sfd = $sf === '' ? false : realpath(dirname($sf));
        if ($sfd === false || !self::same(self::slash($sfd), $this->web)) throw new RetSetupRefuse($this->t('req_script'));
        $dr = (string)($_SERVER['DOCUMENT_ROOT'] ?? '');
        if ($dr !== '') {
            $drr = realpath($dr);
            if ($drr === false || !self::same(self::slash($drr), $this->web)) throw new RetSetupRefuse($this->t('req_docroot'));
        }
        $this->pub = basename($this->web);
        if (!self::validName($this->pub)) throw new RetSetupRefuse($this->t('req_name'));
        $home = self::slash(dirname($this->web));
        if ($home === $this->web || $home === '' || $home === '/' || preg_match('~^[A-Za-z]:/?$~', $home) || preg_match('~^//[^/]+/[^/]+/?$~', $home)) {
            throw new RetSetupRefuse($this->t('req_diskroot'));
        }
        $this->home = $home;
        if (!self::inOpenBasedir($home)) throw new RetSetupRefuse($this->t('req_basedir'));
        if (in_array(strtolower(basename($home)), self::PARENT_NAMES, true)) throw new RetSetupRefuse($this->t('req_parent_name'));
        foreach (self::PARENT_FILES as $f) {
            if (self::exists("{$home}/{$f}")) throw new RetSetupRefuse($this->t('req_parent_site'));
        }
    }

    private static function validName(string $n): bool
    {
        if (class_exists('RetLayout', false)) return RetLayout::validName($n);
        return preg_match(self::NAME_RE, $n) === 1 && !in_array(strtolower($n), self::RESERVED, true) && strpos($n, '..') === false;
    }

    private static function inOpenBasedir(string $p): bool
    {
        $ob = (string)ini_get('open_basedir');
        if ($ob === '') return true;
        foreach (explode(PATH_SEPARATOR, $ob) as $d) {
            $d = trim($d);
            if ($d === '') continue;
            $r = realpath($d);
            $d = self::slash($r === false ? $d : $r);
            if (self::same($p, $d) || self::under($p, $d)) return true;
        }
        return false;
    }

    private function base(): void
    {
        $env = getenv('RET_SETUP_BASE');
        if (is_string($env) && $env !== '') {
            $env = rtrim($env, '/');
            if (!preg_match('#^https://[A-Za-z0-9.-]+(:\d+)?(/[A-Za-z0-9._~/-]*)?$#', $env) && !preg_match('#^http://(127\.0\.0\.1|localhost)(:\d+)?(/[A-Za-z0-9._~/-]*)?$#', $env)) {
                throw new RetSetupRefuse('RET_SETUP_BASE: https://… или http://127.0.0.1…');
            }
            $this->base = $env;
            $this->testBase = true;
            return;
        }
        $this->base = self::BASE_URL;
    }

    /* =================================================================== сессия и доступ */

    private function sessionSecret(): string
    {
        $c = (string)($_COOKIE[self::COOKIE] ?? '');
        if (preg_match('/^[0-9a-f]{64}$/', $c)) return $c;
        $s = bin2hex(random_bytes(32));
        $this->setCookie($s);
        return $s;
    }

    private function setCookie(string $v, int $expires = 0): void
    {
        if (headers_sent()) return;
        setcookie(self::COOKIE, $v, ['expires' => $expires, 'path' => '/', 'httponly' => true, 'secure' => $this->https(), 'samesite' => 'Strict']);
    }

    /** challenge C (128 бит) — из секрета сессии односторонне: C не секрет, по нему секрет не узнать */
    private function challenge(): string
    {
        return substr(hash('sha256', "ret-setup challenge\n" . $this->secret), 0, 32);
    }

    private function csrf(): string
    {
        return hash_hmac('sha256', 'ret-setup csrf', $this->secret);
    }

    private function postOk(): bool
    {
        if (!hash_equals($this->csrf(), (string)($_POST['csrf'] ?? ''))) return false;
        $host = strtolower((string)($_SERVER['HTTP_HOST'] ?? ''));
        foreach (['HTTP_ORIGIN', 'HTTP_REFERER'] as $h) {
            $v = (string)($_SERVER[$h] ?? '');
            if ($v === '' || $v === 'null') continue;
            $u = parse_url($v);
            if (!is_array($u) || empty($u['host'])) return false;
            return strtolower($u['host']) . (isset($u['port']) ? ':' . $u['port'] : '') === $host;
        }
        return false;
    }

    private function https(): bool
    {
        return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || strtolower((string)($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https';
    }

    private function setupDir(): string { return "{$this->home}/var/setup"; }

    private function granted(): bool
    {
        $g = $this->readJson($this->setupDir() . '/grant.json');
        return is_array($g) && hash_equals((string)($g['secret_sha256'] ?? ''), hash('sha256', $this->secret)) && (int)($g['expires'] ?? 0) > time();
    }

    private function doConfirm($state, bool $bad): void
    {
        $name = 'ret-setup-' . $this->challenge();
        $f = "{$this->web}/{$name}";
        clearstatcache();
        if (!is_file($f) || is_link($f) || filesize($f) !== 0) {
            $this->flash[] = ['warn', $this->t(is_file($f) && !is_link($f) ? 'confirm_not_empty' : 'confirm_missing', ['name' => $name])];
            $this->pageConfirm($state, $bad);
            return;
        }
        // первая запись на диск — только после подтверждения
        $d = $this->setupDir();
        if (!is_dir("{$this->home}/var") && !@mkdir("{$this->home}/var", 0755)) throw new RetSetupRefuse($this->t('mkdir_fail', ['p' => 'var/']));
        $old = umask(0077);
        try {
            if (!is_dir($d) && !@mkdir($d, 0700)) throw new RetSetupRefuse($this->t('mkdir_fail', ['p' => 'var/setup/']));
            if (DIRECTORY_SEPARATOR === '/') @chmod($d, 0700);
            $this->put("{$d}/grant.json", json_encode(['format' => 1, 'secret_sha256' => hash('sha256', $this->secret), 'created' => time(), 'expires' => time() + self::GRANT_TTL]) . "\n", 0600);
        } finally {
            umask($old);
        }
        @unlink($f);
        $this->log('доступ подтверждён (challenge-file)');
        $this->redirect();
    }

    /* =================================================================== журнал */

    /** null — нет; false — не читается или другой формат; иначе массив */
    private function readState()
    {
        $f = $this->setupDir() . '/state.json';
        if (!is_file($f)) return null;
        $j = $this->readJson($f);
        if (!is_array($j) || ($j['format'] ?? 0) !== self::JOURNAL || !in_array($j['phase'] ?? '', self::PHASES, true)) return false;
        if (($j['webroot'] ?? '') !== $this->pub) return false;
        return $j;
    }

    private function newState(): array
    {
        return ['format' => self::JOURNAL, 'setup_version' => self::VERSION, 'webroot' => $this->pub, 'phase' => 'granted',
                'started' => false, 'failed' => null, 'x' => null, 'archive_sha256' => null, 'acks' => [], 'stubs' => [],
                'htaccess' => null, 'backup' => null, 'created' => gmdate('c'), 'updated' => gmdate('c')];
    }

    private function saveState(array $s): void
    {
        $s['updated'] = gmdate('c');
        $this->put($this->setupDir() . '/state.json', json_encode($s, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n", 0600);
    }

    private function phaseNo(array $s): int
    {
        return (int)array_search($s['phase'], self::PHASES, true) + 1;
    }

    private function lock(): void
    {
        $d = $this->setupDir();
        $fh = @fopen("{$d}/lock", 'c');
        if ($fh) {
            $wb = 0;
            if (@flock($fh, LOCK_EX | LOCK_NB, $wb)) { $this->lockFh = $fh; return; }
            if ($wb) { fclose($fh); $this->busy(); }
            fclose($fh);
        }
        // ФС без flock (NFS): каталог-замок, протухание 10 мин
        $ld = "{$d}/lock.d";
        if (is_dir($ld) && time() - (int)@filemtime($ld) > self::LOCK_STALE) @rmdir($ld);
        if (!@mkdir($ld, 0700)) $this->busy();
        $this->lockDir = $ld;
    }

    private function unlock(): void
    {
        if ($this->lockFh) { @flock($this->lockFh, LOCK_UN); fclose($this->lockFh); $this->lockFh = null; }
        if ($this->lockDir) { @rmdir($this->lockDir); $this->lockDir = null; }
    }

    private function busy(): void
    {
        $this->page($this->t('title_busy'), $this->box('warn', $this->t('busy')) . $this->linkHome(), 409);
        exit;
    }

    private function log(string $msg): void
    {
        $d = "{$this->home}/var/logs";
        if (!is_dir($d) && !@mkdir($d, 0755, true)) return;
        $f = "{$d}/setup.log";
        $new = !is_file($f);
        @file_put_contents($f, gmdate('Y-m-d H:i:s') . ' ret-setup ' . self::VERSION . ": {$msg}\n", FILE_APPEND | LOCK_EX);
        if ($new && DIRECTORY_SEPARATOR === '/') @chmod($f, 0600);
    }

    /* =================================================================== действия */

    private function dispatch(string $action, array $s): void
    {
        switch ($action) {
            case 'install':
                if ($s['started']) { $this->pageForState($s); return; }
                $this->doInstall($s);
                return;
            case 'step':     $this->doStep($s); return;
            case 'restart':  $this->doRestart($s); return;
            case 'disable':  $this->doDisable($s); return;
            case 'cancel':   $this->doCancel($s); return;
            case 'handoff':  $this->doHandoff($s); return;
        }
        $this->redirect();
    }

    /** [Установить файлы]: галочки, закрепление плана (заглушки, .htaccess) → S2 */
    private function doInstall(array $s): void
    {
        $pf = $this->preflight();
        foreach ($pf['items'] as $it) if ($it[0] === 'hard') throw new RetSetupRefuse($this->t('preflight_failed'));
        $w = $this->inspectWeb([]);
        $h = $this->inspectHome([], $s);
        if ($w['refuse'] || $h['refuse']) throw new RetSetupRefuse($this->t('not_clean'));
        $acks = (array)($_POST['ack'] ?? []);
        foreach ($pf['items'] as $it) {
            if ($it[0] === 'warn' && empty($acks[$it[1]])) { $this->flash[] = ['warn', $this->t('need_ack')]; $this->pagePlan($s); return; }
        }
        if ($w['stubs'] && empty($acks['stubs'])) { $this->flash[] = ['warn', $this->t('need_ack')]; $this->pagePlan($s); return; }
        if ($w['htaccess'] !== null && empty($acks['htaccess'])) { $this->flash[] = ['warn', $this->t('need_ack')]; $this->pagePlan($s); return; }
        $s['acks'] = array_keys(array_filter($acks));
        $s['stubs'] = [];
        foreach ($w['stubs'] as $n => $x) $s['stubs'][$n] = $x['sha256'];
        $s['htaccess'] = $w['htaccess'] === null ? ['orig_sha256' => null] : ['orig_sha256' => $w['htaccess']['sha256']];
        $s['started'] = true;
        $this->saveState($s);
        $this->log('план принят: заглушки ' . count($s['stubs']) . ', .htaccess хостинга — ' . ($w['htaccess'] ? 'есть' : 'нет'));
        $this->doStep($s);
    }

    /** Одна фаза за запрос */
    private function doStep(array $s): void
    {
        if (!$s['started']) { $this->pagePlan($s); return; }
        if ($s['failed']) { $this->pageFailed($s); return; }
        if (in_array($s['phase'], ['enabled', 'handed'], true)) { $this->pageForState($s); return; }
        $phase = $s['phase'];
        try {
            switch ($phase) {
                case 'granted':    $s = $this->phaseDownload($s); break;
                case 'downloaded': $s = $this->phaseVerify($s); break;
                case 'verified':   $s = $this->phaseStage($s); break;
                case 'staged':     $s = $this->phasePrivate($s); break;
                case 'private':    $s = $this->phasePublic($s); break;
                case 'public':     $s = $this->phaseEnable($s); break;
            }
        } catch (RetSetupTransport $e) {
            $this->log("{$phase}: сеть — " . $e->getMessage());
            $this->pageProgress($s, ['err', $this->t('transport', ['e' => $e->getMessage()])], false);
            return;
        } catch (RetSetupVerify $e) {
            $this->rmTree($this->setupDir() . '/dl');
            $this->rmTree($this->setupDir() . '/stage');
            $s['failed'] = ['phase' => $phase, 'reason' => $e->getMessage(), 'verify' => true];
            $this->saveState($s);
            $this->log("{$phase}: ПРОВЕРКА НЕ ПРОЙДЕНА — " . $e->getMessage());
            $this->pageFailed($s);
            return;
        } catch (RetSetupRestage $e) {
            $this->rmTree($this->setupDir() . '/stage');
            $s['phase'] = 'verified';
            $this->saveState($s);
            $this->log("{$phase}: " . $e->getMessage() . ' — stage пересобирается');
            $this->pageProgress($s, ['warn', $this->t('restage')], true);
            return;
        } catch (RetSetupRefuse $e) {
            $this->log("{$phase}: отказ — " . $e->getMessage());
            $this->pageProgress($s, ['err', $e->getMessage()], false);
            return;
        }
        $this->saveState($s);
        $this->log("фаза {$s['phase']} (S" . $this->phaseNo($s) . ') — готово' . ($s['x'] ? ", RET CMS {$s['x']}" : ''));
        if ($s['phase'] === 'enabled') { $this->pageEnabled($s); return; }
        $this->pageProgress($s, null, true);
    }

    /** Начать заново (после отказа проверки): только пока ничего не разложено */
    private function doRestart(array $s): void
    {
        if (in_array($s['phase'], ['private', 'public', 'enabled', 'handed'], true) && $this->anyPlaced($s)) {
            throw new RetSetupRefuse($this->t('restart_placed'));
        }
        $this->rmTree($this->setupDir() . '/dl');
        $this->rmTree($this->setupDir() . '/stage');
        $s['phase'] = 'granted'; $s['failed'] = null; $s['x'] = null; $s['archive_sha256'] = null; $s['started'] = false;
        $this->saveState($s);
        $this->log('начато заново');
        $this->redirect();
    }

    /* =================================================================== S2–S4: загрузка, проверка, stage */

    private function dl(): string { return $this->setupDir() . '/dl'; }
    private function stageTop(string $x): string { return $this->setupDir() . "/stage/ret-cms-{$x}"; }

    /** S2: latest/index/метаданные (подписи), архив — в dl/ */
    private function phaseDownload(array $s): array
    {
        $dl = $this->dl();
        $this->rmTree($dl);
        if (!@mkdir($dl, 0700, true)) throw new RetSetupRefuse($this->t('mkdir_fail', ['p' => 'var/setup/dl/']));
        foreach (['latest.json', 'latest.json.sig', 'index.json', 'index.json.sig'] as $f) {
            $this->put("{$dl}/{$f}", $this->fetch("{$this->base}/{$f}", self::MAX_JSON), 0600);
        }
        [$x, $entry] = $this->checkIndex($dl, $s['x']);
        foreach (["ret-cms-{$x}.json", "ret-cms-{$x}.json.sig"] as $f) {
            $this->put("{$dl}/{$f}", $this->fetch("{$this->base}/{$x}/{$f}", self::MAX_JSON), 0600);
        }
        $meta = $this->checkMeta($dl, $x, $entry);
        $a = $meta['archives']["ret-cms-{$x}.zip"];
        $part = "{$dl}/ret-cms-{$x}.zip.part";
        $this->fetch("{$this->base}/{$x}/ret-cms-{$x}.zip", (int)$a['bytes'], $part);
        if (filesize($part) !== (int)$a['bytes'] || !hash_equals($a['sha256'], (string)hash_file('sha256', $part))) {
            throw new RetSetupVerify($this->t('v_archive_sum', ['x' => $x]));
        }
        if (!@rename($part, "{$dl}/ret-cms-{$x}.zip")) throw new RetSetupRefuse($this->t('write_fail', ['p' => "dl/ret-cms-{$x}.zip"]));
        $s['phase'] = 'downloaded';
        return $s;
    }

    /** S3: вся цепочка dl/ заново, без сети → закрепить X и сумму архива */
    private function phaseVerify(array $s): array
    {
        $v = $this->verifyDl($s['x']);
        if ($s['x'] !== null && $s['x'] !== $v['x']) throw new RetSetupVerify($this->t('v_pinned', ['x' => $s['x']]));
        $s['x'] = $v['x'];
        $s['archive_sha256'] = $v['meta']['archives']["ret-cms-{$v['x']}.zip"]['sha256'];
        $s['phase'] = 'verified';
        return $s;
    }

    /** S4: распаковка во var/setup/stage/ret-cms-X/ и сверка с release.json */
    private function phaseStage(array $s): array
    {
        $v = $this->verifyDl($s['x']);
        $x = $v['x'];
        $root = $this->setupDir() . '/stage';
        $this->rmTree($root);
        if (!@mkdir($root, 0700, true)) throw new RetSetupRefuse($this->t('mkdir_fail', ['p' => 'var/setup/stage/']));
        $this->unzip("{$this->dl()}/ret-cms-{$x}.zip", $root, "ret-cms-{$x}");
        $this->verifyStage($s, $v['meta']);
        $s['phase'] = 'staged';
        return $s;
    }

    /** latest.json + index.json из $dir → [X, запись индекса] */
    private function checkIndex(string $dir, ?string $pinned): array
    {
        $latest = $this->signedJson("{$dir}/latest.json", 'ret-cms-latest');
        $index = $this->signedJson("{$dir}/index.json", 'ret-cms-index');
        if (($latest['channel'] ?? '') !== 'stable') throw new RetSetupVerify('latest.json: channel ' . ($latest['channel'] ?? '?'));
        $lx = (string)($latest['version'] ?? '');
        if (!preg_match('/^\d+\.\d+\.\d+$/', $lx)) throw new RetSetupVerify("latest.json: версия «{$lx}»");
        $x = $pinned ?? $lx;
        $entry = null;
        foreach ((array)($index['versions'] ?? []) as $e) if (is_array($e) && ($e['version'] ?? '') === $x) $entry = $e;
        if ($entry === null) throw new RetSetupVerify($this->t('v_not_in_index', ['x' => $x]));
        if (!empty($entry['yanked'])) throw new RetSetupVerify($this->t('v_yanked', ['x' => $x, 'r' => (string)($entry['reason'] ?? '')]));
        if (($entry['meta'] ?? '') !== "{$x}/ret-cms-{$x}.json" || !preg_match('/^[0-9a-f]{64}$/', (string)($entry['meta_sha256'] ?? ''))) {
            throw new RetSetupVerify("index.json: {$x} — meta/meta_sha256");
        }
        if ($pinned === null && (($latest['meta'] ?? '') !== $entry['meta'] || ($latest['meta_sha256'] ?? '') !== $entry['meta_sha256'])) {
            throw new RetSetupVerify($this->t('v_latest_index'));
        }
        if (version_compare($x, self::BUILT_FOR, '<')) throw new RetSetupVerify($this->t('v_old', ['x' => $x, 'b' => self::BUILT_FOR]));
        if (version_compare($x, self::MIN_CORE, '<')) throw new RetSetupVerify($this->t('v_old', ['x' => $x, 'b' => self::MIN_CORE]));
        return [$x, $entry];
    }

    /** Метаданные версии из $dir: сумма = индекс, подпись, формат, требования, архив zip */
    private function checkMeta(string $dir, string $x, array $entry): array
    {
        $f = "{$dir}/ret-cms-{$x}.json";
        $raw = (string)@file_get_contents($f);
        if (!hash_equals((string)$entry['meta_sha256'], hash('sha256', $raw))) throw new RetSetupVerify($this->t('v_meta_sum', ['x' => $x]));
        $m = $this->signedJson($f, 'ret-cms-version');
        if (($m['format_version'] ?? 0) !== 1 || ($m['version'] ?? '') !== $x) throw new RetSetupVerify("ret-cms-{$x}.json: версия " . ($m['version'] ?? '?'));
        if (preg_match('/^>=\s*(\d+\.\d+(\.\d+)?)$/', (string)($m['requires']['php'] ?? ''), $r) && version_compare(PHP_VERSION, $r[1], '<')) {
            throw new RetSetupVerify($this->t('v_php', ['x' => $x, 'p' => $r[1], 'v' => PHP_VERSION]));
        }
        $a = $m['archives']["ret-cms-{$x}.zip"] ?? null;
        if (!is_array($a) || !preg_match('/^[0-9a-f]{64}$/', (string)($a['sha256'] ?? '')) || !is_int($a['bytes'] ?? null) || $a['bytes'] <= 0 || $a['bytes'] > self::MAX_ARCHIVE) {
            throw new RetSetupVerify("ret-cms-{$x}.json: нет суммы ret-cms-{$x}.zip");
        }
        if (!preg_match('/^[0-9a-f]{64}$/', (string)($m['release_json']['sha256'] ?? ''))) throw new RetSetupVerify("ret-cms-{$x}.json: release_json.sha256");
        return $m;
    }

    /** Полная офлайн-проверка dl/ → ['x', 'meta', 'entry'] */
    private function verifyDl(?string $pinned): array
    {
        $dl = $this->dl();
        foreach (['latest.json', 'latest.json.sig', 'index.json', 'index.json.sig'] as $f) {
            if (!is_file("{$dl}/{$f}")) throw new RetSetupRestage('dl/: нет ' . $f);
        }
        [$x, $entry] = $this->checkIndex($dl, $pinned);
        $meta = $this->checkMeta($dl, $x, $entry);
        $z = "{$dl}/ret-cms-{$x}.zip";
        $a = $meta['archives']["ret-cms-{$x}.zip"];
        if (!is_file($z) || filesize($z) !== $a['bytes'] || !hash_equals($a['sha256'], (string)hash_file('sha256', $z))) {
            throw new RetSetupVerify($this->t('v_archive_sum', ['x' => $x]));
        }
        return ['x' => $x, 'meta' => $meta, 'entry' => $entry];
    }

    /** JSON + .sig: подпись любым ключом KEYS, формат, продукт */
    private function signedJson(string $f, string $format): array
    {
        $n = basename($f);
        $d = @file_get_contents($f);
        $s = @file_get_contents("{$f}.sig");
        if ($d === false || $s === false) throw new RetSetupVerify("{$n}: нет файла или подписи");
        $j = json_decode($s, true);
        $sig = is_array($j) && is_string($j['sig'] ?? null) ? base64_decode($j['sig'], true) : false;
        if (!is_array($j) || !is_string($j['key_id'] ?? null) || $sig === false || strlen($sig) !== SODIUM_CRYPTO_SIGN_BYTES) throw new RetSetupVerify("{$n}.sig: не подпись");
        $ids = array_keys(self::KEYS);
        if (isset(self::KEYS[$j['key_id']])) $ids = array_merge([$j['key_id']], array_values(array_diff($ids, [$j['key_id']])));
        $okId = null;
        foreach ($ids as $id) {
            $pub = base64_decode(self::KEYS[$id]['public'], true);
            if ($pub !== false && strlen($pub) === SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES && sodium_crypto_sign_verify_detached($sig, $d, $pub)) { $okId = $id; break; }
        }
        if ($okId === null) throw new RetSetupVerify($this->t('v_sig', ['n' => $n]));
        $x = json_decode($d, true);
        if (!is_array($x) || ($x['format'] ?? '') !== $format || ($x['format_version'] ?? 0) !== 1) throw new RetSetupVerify("{$n}: не {$format} v1");
        if (($x['product'] ?? '') !== 'ret-cms') throw new RetSetupVerify("{$n}: продукт " . ($x['product'] ?? '?'));
        $x['_key_id'] = $okId;
        return $x;
    }

    /** Распаковка zip: только под TOP/, без «..», «\», абсолютных путей, ссылок; лимиты */
    private function unzip(string $zip, string $root, string $top): void
    {
        if (!class_exists('ZipArchive')) throw new RetSetupRefuse($this->t('no_ext', ['e' => 'zip']));
        $z = new ZipArchive();
        if ($z->open($zip) !== true) throw new RetSetupVerify('zip: не открыть');
        try {
            $n = $z->numFiles;
            if ($n < 1 || $n > self::MAX_ENTRIES) throw new RetSetupVerify("zip: записей {$n}");
            $total = 0; $seen = [];
            for ($i = 0; $i < $n; $i++) {
                $st = $z->statIndex($i);
                $p = (string)($st['name'] ?? '');
                $dir = substr($p, -1) === '/';
                $q = $dir ? substr($p, 0, -1) : $p;
                if ($q === '' || $q[0] === '/' || strpos($q, '\\') !== false || strpos($q, "\0") !== false || strpos($q, ':') !== false
                    || preg_match('~(^|/)\.\.?(/|$)~', $q) || ($q !== $top && strncmp($q, "{$top}/", strlen($top) + 1) !== 0)) {
                    throw new RetSetupVerify("zip: недопустимый путь {$p}");
                }
                $opsys = 0; $attr = 0;
                if ($z->getExternalAttributesIndex($i, $opsys, $attr) && $opsys === ZipArchive::OPSYS_UNIX) {
                    $type = ($attr >> 16) & 0170000;
                    if ($type === 0120000) throw new RetSetupVerify("zip: ссылка {$p}");
                    if ($type !== 0 && $type !== 0100000 && $type !== 0040000) throw new RetSetupVerify("zip: не файл и не каталог {$p}");
                }
                if (isset($seen[$q])) throw new RetSetupVerify("zip: дважды {$p}");
                $seen[$q] = 1;
                $total += (int)($st['size'] ?? 0);
                if ($total > self::MAX_UNPACKED) throw new RetSetupVerify('zip: слишком большой после распаковки');
                $t = "{$root}/{$q}";
                if ($dir) {
                    if (!is_dir($t) && !@mkdir($t, 0755, true)) throw new RetSetupRefuse($this->t('mkdir_fail', ['p' => 'stage']));
                    continue;
                }
                if (!is_dir(dirname($t)) && !@mkdir(dirname($t), 0755, true)) throw new RetSetupRefuse($this->t('mkdir_fail', ['p' => 'stage']));
                $data = $z->getFromIndex($i);
                if ($data === false || strlen($data) !== (int)$st['size']) throw new RetSetupVerify("zip: не прочитать {$p}");
                if (@file_put_contents($t, $data) !== strlen($data)) throw new RetSetupRefuse($this->t('write_fail', ['p' => 'stage']));
                @chmod($t, substr($q, -3) === '.sh' ? 0755 : 0644);
            }
        } finally {
            $z->close();
        }
        if (!is_dir("{$root}/{$top}")) throw new RetSetupVerify("zip: нет {$top}/");
    }

    /** stage = release.json: сумма release.json = метаданные, состав и суммы файлов */
    private function verifyStage(array $s, array $meta): array
    {
        $x = (string)$s['x'];
        $top = $this->stageTop($x);
        $rel = $this->releaseJson("{$top}/deploy/release.json", $meta, $x);
        $have = [];
        $this->walk($top, '', $have);
        unset($have['deploy/release.json']);
        $want = $rel['files'];
        $miss = array_diff_key($want, $have);
        $extra = array_diff_key($have, $want);
        if ($miss || $extra) throw new RetSetupVerify($this->t('v_stage_set', ['n' => count($miss) + count($extra)]) . ' ' . implode(', ', array_slice(array_keys($miss + $extra), 0, 5)));
        foreach ($want as $p => $f) {
            $file = "{$top}/{$p}";
            if (filesize($file) !== (int)$f['bytes'] || !hash_equals((string)$f['sha256'], (string)hash_file('sha256', $file))) {
                throw new RetSetupVerify($this->t('v_stage_sum', ['p' => $p]));
            }
        }
        if (trim((string)@file_get_contents("{$top}/public/kernel2/VERSION")) !== $x) throw new RetSetupVerify("public/kernel2/VERSION ≠ {$x}");
        return $rel;
    }

    /** release.json: сумма = метаданные, формат, пути */
    private function releaseJson(string $f, array $meta, string $x): array
    {
        $raw = @file_get_contents($f);
        if ($raw === false || !hash_equals((string)$meta['release_json']['sha256'], hash('sha256', $raw))) throw new RetSetupVerify($this->t('v_release_json'));
        $rel = json_decode($raw, true);
        if (!is_array($rel) || ($rel['format'] ?? '') !== 'ret-cms-release' || ($rel['format_version'] ?? 0) !== 1 || ($rel['version'] ?? '') !== $x || !is_array($rel['files'] ?? null)) {
            throw new RetSetupVerify('release.json: не ret-cms-release v1 ' . $x);
        }
        foreach ($rel['files'] as $p => $e) {
            if (!is_string($p) || !preg_match('~^[A-Za-z0-9._/@+-]+$~', $p) || preg_match('~(^|/)\.\.?(/|$)~', $p) || !is_array($e)
                || !preg_match('/^[0-9a-f]{64}$/', (string)($e['sha256'] ?? '')) || !is_int($e['bytes'] ?? null)) {
                throw new RetSetupVerify("release.json: запись {$p}");
            }
        }
        foreach (['public/kernel2/Layout.php', 'public/index.php', 'tools/lib/core/RetZone.php', 'tools/lib/install/web/WebHandoff.php'] as $need) {
            if (!isset($rel['files'][$need])) throw new RetSetupVerify("release.json: нет {$need}");
        }
        return $rel;
    }

    /** Проверенный release.json закреплённой версии (из stage или с места) */
    private function rel(array $s): array
    {
        try {
            $v = $this->verifyDl($s['x']);
        } catch (RetSetupRestage $e) {
            // после S8 dl/ уже удалён: подписанные метаданные лежат в deploy/release-meta.json(.sig)
            $mf = "{$this->home}/deploy/release-meta.json";
            if ($s['x'] === null || !is_file($mf)) throw $e;
            $m = $this->signedJson($mf, 'ret-cms-version');
            if (($m['version'] ?? '') !== $s['x']) throw new RetSetupVerify('deploy/release-meta.json: версия ' . ($m['version'] ?? '?'));
            $v = ['x' => $s['x'], 'meta' => $m];
        }
        $x = $v['x'];
        $cands = [$this->stageTop($x) . '/deploy/release.json', "{$this->home}/deploy/release.json"];
        foreach ($cands as $f) if (is_file($f)) return ['rel' => $this->releaseJson($f, $v['meta'], $x), 'meta' => $v['meta'], 'x' => $x];
        throw new RetSetupRestage('нет release.json');
    }

    /* =================================================================== S5–S7: раскладка */

    /** Элементы верхнего уровня: ['private' => [имя => логический путь], 'public' => [...]] */
    private function items(array $rel): array
    {
        $priv = []; $pub = [];
        foreach (array_keys($rel['files']) as $p) {
            $seg = explode('/', $p);
            if ($seg[0] === 'public') {
                if (count($seg) < 2) continue;
                if ($seg[1] === 'index.php' || $seg[1] === '.htaccess') continue;
                $pub[$seg[1]] = "public/{$seg[1]}";
            } else {
                $priv[$seg[0]] = $seg[0];
            }
        }
        $priv['deploy'] = 'deploy';                  // release.json — в deploy/, даже если других файлов там нет
        ksort($priv, SORT_STRING); ksort($pub, SORT_STRING);
        return ['private' => $priv, 'public' => $pub];
    }

    /** Библиотека релиза (Layout, RetZone, WebHandoff): из stage или с места, сумма = release.json */
    private function lib(array $s, array $rel, string $logical): void
    {
        $f = $this->stageTop((string)$s['x']) . "/{$logical}";
        if (!is_file($f)) $f = $this->phys($logical);
        $e = $rel['files'][$logical];
        if (!is_file($f) || !hash_equals((string)$e['sha256'], (string)hash_file('sha256', $f))) throw new RetSetupVerify($this->t('v_stage_sum', ['p' => $logical]));
        require_once $f;
    }

    private function libs(array $s, array $rel): void
    {
        $this->lib($s, $rel, 'public/kernel2/Layout.php');
        $this->lib($s, $rel, 'tools/lib/core/RetZone.php');
        if (!RetLayout::validName($this->pub)) throw new RetSetupRefuse($this->t('req_name'));
    }

    /** Логический путь → физический: правила релиза (RetLayout::phys), до их загрузки — public/ → web-root */
    private function phys(string $logical): string
    {
        if (class_exists('RetLayout', false)) return self::slash(RetLayout::phys($this->home, $logical, $this->pub));
        if ($logical === 'public') return $this->web;
        if (strncmp($logical, 'public/', 7) === 0) return $this->web . substr($logical, 6);
        return "{$this->home}/{$logical}";
    }

    private function phasePrivate(array $s): array
    {
        $r = $this->rel($s);
        $this->libs($s, $r['rel']);
        $this->cleanOrRefuse($s, $r['rel']);
        foreach ($this->items($r['rel'])['private'] as $logical) $this->place($s, $r['rel'], $logical);
        $s['phase'] = 'private';
        return $s;
    }

    private function phasePublic(array $s): array
    {
        $r = $this->rel($s);
        $this->libs($s, $r['rel']);
        $this->cleanOrRefuse($s, $r['rel']);
        foreach ($this->items($r['rel'])['private'] as $logical) {
            if (!$this->matches($r['rel'], $logical, $this->phys($logical))) throw new RetSetupRefuse($this->t('placed_changed', ['p' => $logical]));
        }
        foreach ($this->items($r['rel'])['public'] as $logical) $this->place($s, $r['rel'], $logical);
        $s['phase'] = 'public';
        return $s;
    }

    /**
     * S7: заглушки → backup; .htaccess (зона); подписанные метаданные; var/releases/X/;
     * полная проверка; index.php последним.
     */
    private function phaseEnable(array $s): array
    {
        $r = $this->rel($s);
        $rel = $r['rel']; $x = $r['x'];
        $this->libs($s, $rel);
        $this->cleanOrRefuse($s, $rel);
        $top = $this->stageTop($x);
        $bk = $this->backupDir($s);
        $s['backup'] = substr($bk, strlen($this->home) + 1);
        $this->saveState($s);

        // заглушки хостинга → backup
        $bj = $this->readJson("{$bk}/backup.json");
        $bj = is_array($bj) ? $bj : ['format' => 1, 'created' => gmdate('c'), 'files' => []];
        foreach ($s['stubs'] as $name => $sha) {
            $src = "{$this->web}/{$name}"; $dst = "{$bk}/{$name}";
            if (is_file($dst) && !is_file($src)) continue;
            if (!is_file($src) || is_link($src) || !hash_equals($sha, (string)hash_file('sha256', $src))) throw new RetSetupRefuse($this->t('stub_changed', ['n' => $name]));
            $bj['files'][$name] = ['bytes' => filesize($src), 'sha256' => $sha, 'mtime' => gmdate('c', (int)filemtime($src))];
            $this->put("{$bk}/backup.json", json_encode($bj, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n", 0600);
            $this->moveFile($src, $dst, $sha);
        }

        // .htaccess: текст хостинга дословно, зона RET CMS в конец (RetZone из релиза)
        $this->htaccess($s, $top, $bk, $bj);

        // подписанные метаданные установленного релиза и архив для отката без сети
        foreach (["ret-cms-{$x}.json" => 'release-meta.json', "ret-cms-{$x}.json.sig" => 'release-meta.json.sig'] as $from => $to) {
            $this->copyOnce("{$this->dl()}/{$from}", "{$this->home}/deploy/{$to}");
        }
        $rd = "{$this->home}/var/releases/{$x}";
        if (!is_dir($rd) && !@mkdir($rd, 0755, true)) throw new RetSetupRefuse($this->t('mkdir_fail', ['p' => "var/releases/{$x}/"]));
        foreach (["ret-cms-{$x}.zip", "ret-cms-{$x}.json", "ret-cms-{$x}.json.sig"] as $f) $this->copyOnce("{$this->dl()}/{$f}", "{$rd}/{$f}");

        // всё, кроме index.php, = release.json — затем включение
        $bad = $this->verifyPlaced($rel, ['public/index.php']);
        if ($bad) throw new RetSetupRefuse($this->t('verify_failed', ['n' => count($bad)]) . ' ' . implode('; ', array_slice($bad, 0, 5)));
        $this->place($s, $rel, 'public/index.php');
        $bad = $this->verifyPlaced($rel, []);
        if ($bad) throw new RetSetupRefuse($this->t('verify_failed', ['n' => count($bad)]) . ' ' . implode('; ', array_slice($bad, 0, 5)));
        $s['phase'] = 'enabled';
        return $s;
    }

    private function backupDir(array $s): string
    {
        $bk = $s['backup'] ? "{$this->home}/{$s['backup']}" : $this->setupDir() . '/backup/' . gmdate('Ymd\THis\Z');
        if (!is_dir($bk) && !@mkdir($bk, 0700, true)) throw new RetSetupRefuse($this->t('mkdir_fail', ['p' => 'var/setup/backup/']));
        return $bk;
    }

    /** .htaccess в web-root: нет — копия зоны из релиза; есть (хостинга) — дословно + зона в конец */
    private function htaccess(array $s, string $top, string $bk, array $bj): void
    {
        $f = "{$this->web}/.htaccess";
        $relFile = "{$top}/public/.htaccess";
        $release = (string)@file_get_contents($relFile);
        $orig = $s['htaccess']['orig_sha256'] ?? null;
        if ($orig !== null) {
            if (!is_file("{$bk}/.htaccess")) {
                if (!is_file($f) || !hash_equals($orig, (string)hash_file('sha256', $f))) throw new RetSetupRefuse($this->t('htaccess_changed'));
                $bj['files']['.htaccess'] = ['bytes' => filesize($f), 'sha256' => $orig, 'mtime' => gmdate('c', (int)filemtime($f)), 'copy' => true];
                $this->put("{$bk}/backup.json", json_encode($bj, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n", 0600);
                $this->put("{$bk}/.htaccess", (string)file_get_contents($f), 0600);
            }
            $base = (string)file_get_contents("{$bk}/.htaccess");
            if (!hash_equals($orig, hash('sha256', $base))) throw new RetSetupRefuse($this->t('htaccess_changed'));
        } else {
            $base = null;
        }
        $d = RetZone::decide($release, $base, null, true);
        if (!in_array($d['action'], ['create', 'same', 'update', 'force-append'], true)) throw new RetSetupRefuse($this->t('htaccess_zone_bad', ['r' => (string)$d['reason']]));
        $want = $d['action'] === 'same' ? (string)$base : (string)$d['data'];
        $cur = is_file($f) ? (string)file_get_contents($f) : null;
        if ($cur === $want) return;
        if ($cur !== null && ($orig === null || !hash_equals($orig, hash('sha256', $cur)))) throw new RetSetupRefuse($this->t('htaccess_changed'));
        if ($cur === null && $orig !== null) throw new RetSetupRefuse($this->t('htaccess_changed'));
        $this->put($f, $want, 0644);
    }

    /** Файл → $dst, существующий $dst не перезаписывается (кроме того же содержимого) */
    private function copyOnce(string $src, string $dst): void
    {
        $data = (string)@file_get_contents($src);
        if (is_file($dst)) {
            if (hash_equals(hash('sha256', $data), (string)hash_file('sha256', $dst))) return;
            throw new RetSetupRefuse($this->t('exists_differs', ['p' => $this->rel2home($dst)]));
        }
        $this->put($dst, $data, 0644);
    }

    /** Перенос файла (заглушки) с проверкой суммы; разные ФС — копия + сверка + удаление */
    private function moveFile(string $src, string $dst, string $sha): void
    {
        if (is_file($dst)) throw new RetSetupRefuse($this->t('exists_differs', ['p' => $this->rel2home($dst)]));
        if (!$this->renameRetry($src, $dst)) {
            $data = (string)@file_get_contents($src);
            $this->put($dst, $data, 0600);
            if (!hash_equals($sha, (string)hash_file('sha256', $dst)) || !@unlink($src)) throw new RetSetupRefuse($this->t('write_fail', ['p' => basename($dst)]));
        }
    }

    /**
     * Один элемент верхнего уровня (§8): только в stage → rename (между ФС — копия во временный
     * сосед, сверка, rename); только на месте и = release.json → сделано; на месте и ≠ → отказ;
     * и там, и там: на месте = release.json (копирование между ФС прервалось после rename) — убрать
     * копию из stage, иначе отказ; нигде → пересобрать stage.
     */
    private function place(array $s, array $rel, string $logical): void
    {
        $src = $this->stageTop((string)$s['x']) . "/{$logical}";
        $dst = $this->phys($logical);
        $tmp = dirname($dst) . '/.' . basename($dst) . '.ret-setup-tmp';
        if (self::exists($tmp)) $this->rmTree($tmp);
        $inStage = self::exists($src);
        $atPlace = self::exists($dst);
        if (!$inStage && !$atPlace) throw new RetSetupRestage("{$logical}: нет ни в stage, ни на месте");
        if ($atPlace) {
            if (!$this->matches($rel, $logical, $dst)) throw new RetSetupRefuse($this->t('exists_differs', ['p' => $this->rel2home($dst)]));
            if ($inStage) $this->rmTree($src);
            return;
        }
        if ($this->renameRetry($src, $dst)) return;
        $this->copyTree($src, $tmp);
        if (!$this->matches($rel, $logical, $tmp)) { $this->rmTree($tmp); throw new RetSetupRefuse($this->t('write_fail', ['p' => $this->rel2home($dst)])); }
        if (self::exists($dst) || !$this->renameRetry($tmp, $dst)) { $this->rmTree($tmp); throw new RetSetupRefuse($this->t('write_fail', ['p' => $this->rel2home($dst)])); }
        $this->rmTree($src);
    }

    /** Элемент (файл или каталог) по $path = release.json для $logical: тот же состав, те же суммы */
    private function matches(array $rel, string $logical, string $path): bool
    {
        if (is_link($path)) return false;
        if (isset($rel['files'][$logical])) {
            if (!is_file($path)) return false;
            $e = $rel['files'][$logical];
            return filesize($path) === (int)$e['bytes'] && hash_equals((string)$e['sha256'], (string)hash_file('sha256', $path));
        }
        if (!is_dir($path)) return false;
        $have = [];
        $this->walk($path, '', $have);
        $want = [];
        foreach ($rel['files'] as $p => $e) if (strncmp($p, "{$logical}/", strlen($logical) + 1) === 0) $want[substr($p, strlen($logical) + 1)] = $e;
        if ($logical === 'deploy') {
            $want['release.json'] = null;
            foreach (self::DEPLOY_EXTRA as $x) if (isset($have[$x])) $want[$x] = null;
        }
        if (array_diff_key($have, $want) || array_diff_key($want, $have)) return false;
        foreach ($want as $p => $e) {
            if ($e === null) continue;
            $f = "{$path}/{$p}";
            if (filesize($f) !== (int)$e['bytes'] || !hash_equals((string)$e['sha256'], (string)hash_file('sha256', $f))) return false;
        }
        return true;
    }

    /** Каждый файл release.json по физическому пути (зоны — по телу) → список расхождений */
    private function verifyPlaced(array $rel, array $skip): array
    {
        $bad = [];
        foreach ($rel['files'] as $p => $e) {
            if (in_array($p, $skip, true)) continue;
            $f = $this->phys($p);
            if (!is_file($f) || is_link($f)) { $bad[] = "нет {$p}"; continue; }
            if (isset($e['zone'])) {
                if (!RetZone::bodyMatches((string)file_get_contents($f), $e['zone'])) $bad[] = "зона {$p}";
                continue;
            }
            if (filesize($f) !== (int)$e['bytes'] || !hash_equals((string)$e['sha256'], (string)hash_file('sha256', $f))) $bad[] = "сумма {$p}";
        }
        return $bad;
    }

    private function anyPlaced(array $s): bool
    {
        foreach (self::HOME_TARGETS as $t) if ($t !== 'var' && self::exists("{$this->home}/{$t}")) return true;
        foreach (['kernel2', 'admin2', 'handlers', 'uploads', 'index.php'] as $t) if (self::exists("{$this->web}/{$t}")) return true;
        return false;
    }

    /** Перед каждой фазой S5–S7: web-root и корень установки чисты, кроме своего (журнал) */
    private function cleanOrRefuse(array $s, array $rel): void
    {
        $it = $this->items($rel);
        $wexp = array_merge(array_keys($it['public']), ['index.php']);
        $w = $this->inspectWeb($wexp, $s);
        $h = $this->inspectHome(array_keys($it['private']), $s);
        $all = array_merge($w['refuse'], $h['refuse']);
        if ($all) throw new RetSetupRefuse($this->t('not_clean') . ' ' . implode(' ', $all));
    }

    /* =================================================================== отключение, отмена, handoff */

    /** «Откатить включение» (отмена S7): index.php → stage, .htaccess — оригинал, заглушки обратно */
    private function doDisable(array $s): void
    {
        if ($s['phase'] !== 'enabled') { $this->redirect(); return; }
        $r = $this->rel($s);
        $this->libs($s, $r['rel']);
        $this->undoEnable($s, $r['rel'], true);
        $s['phase'] = 'public';
        $this->saveState($s);
        $this->log('включение откачено (index.php убран, .htaccess и заглушки восстановлены)');
        $this->flash[] = ['ok', $this->t('disabled')];
        $this->pageProgress($s, null, false);
    }

    private function undoEnable(array $s, array $rel, bool $keep): void
    {
        $idx = "{$this->web}/index.php";
        if (self::exists($idx)) {
            if (!$this->matches($rel, 'public/index.php', $idx)) throw new RetSetupRefuse($this->t('exists_differs', ['p' => $this->rel2home($idx)]));
            $back = $this->stageTop((string)$s['x']) . '/public/index.php';
            if ($keep && is_dir(dirname($back)) && !self::exists($back)) {
                if (!$this->renameRetry($idx, $back)) { $this->copyTree($idx, $back); @unlink($idx); }
            } else {
                @unlink($idx);
            }
        }
        $bk = $s['backup'] ? "{$this->home}/{$s['backup']}" : null;
        $f = "{$this->web}/.htaccess";
        $orig = $s['htaccess']['orig_sha256'] ?? null;
        if ($orig !== null && $bk && is_file("{$bk}/.htaccess")) {
            $this->put($f, (string)file_get_contents("{$bk}/.htaccess"), 0644);
            @unlink("{$bk}/.htaccess");
        } elseif ($orig === null && is_file($f)) {
            $cur = (string)file_get_contents($f);
            $z = RetZone::parse($cur);
            if ($z['state'] === 'one' && trim($z['before'] . $z['after']) === '') @unlink($f);
            else throw new RetSetupRefuse($this->t('htaccess_changed'));
        }
        if ($bk) {
            $bj = $this->readJson("{$bk}/backup.json");
            foreach (array_keys((array)($s['stubs'] ?? [])) as $name) {
                $src = "{$bk}/{$name}"; $dst = "{$this->web}/{$name}";
                if (is_file($src) && !self::exists($dst)) $this->moveFile($src, $dst, (string)hash_file('sha256', $src));
            }
            if (is_array($bj)) {
                $bj['restored'] = gmdate('c');
                $this->put("{$bk}/backup.json", json_encode($bj, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n", 0600);
            }
        }
    }

    /** Отмена (после подтверждения): в обратном порядке, удаляется только то, что = release.json X */
    private function doCancel($s): void
    {
        $left = [];
        if (is_array($s) && $s['x'] !== null) {
            try {
                $r = $this->rel($s);
                $rel = $r['rel'];
                $this->libs($s, $rel);
                if (in_array($s['phase'], ['enabled', 'handed', 'public'], true)) $this->undoEnable($s, $rel, false);
                $it = $this->items($rel);
                foreach (array_merge(array_values($it['public']), array_reverse(array_values($it['private']))) as $logical) {
                    $p = $this->phys($logical);
                    if (!self::exists($p)) continue;
                    if ($this->matches($rel, $logical, $p)) $this->rmTree($p);
                    else $left[] = $this->rel2home($p);
                }
                $rd = "{$this->home}/var/releases/{$r['x']}";
                if (is_dir($rd)) {
                    $ok = true;
                    foreach (array_diff(scandir($rd) ?: [], ['.', '..']) as $f) {
                        if (!is_file("{$this->dl()}/{$f}") || !hash_equals((string)hash_file('sha256', "{$this->dl()}/{$f}"), (string)hash_file('sha256', "{$rd}/{$f}"))) $ok = false;
                    }
                    if ($ok) { $this->rmTree($rd); @rmdir("{$this->home}/var/releases"); } else $left[] = "var/releases/{$r['x']}/";
                }
            } catch (RetSetupRestage $e) {
                // нечего сверять — ничего не разложено
            } catch (RetSetupVerify $e) {
                $left[] = $this->t('cancel_unverified');
            }
        }
        $d = $this->setupDir();
        foreach (['dl', 'stage'] as $x) $this->rmTree("{$d}/{$x}");
        foreach (['state.json', 'grant.json', 'lock'] as $x) @unlink("{$d}/{$x}");
        $this->unlock();
        @rmdir("{$d}/lock.d");
        if (is_dir("{$d}/backup")) {
            foreach (array_diff(scandir("{$d}/backup") ?: [], ['.', '..']) as $b) {
                $rest = array_diff(scandir("{$d}/backup/{$b}") ?: [], ['.', '..', 'backup.json']);
                if (!$rest) $this->rmTree("{$d}/backup/{$b}"); else $left[] = "var/setup/backup/{$b}/";
            }
            @rmdir("{$d}/backup");
        }
        @rmdir($d);
        foreach (glob("{$this->web}/ret-setup-*") ?: [] as $c) if (is_file($c) && !is_link($c) && filesize($c) === 0) @unlink($c);
        $this->log('отменено' . ($left ? ': оставлено — ' . implode(', ', $left) : ''));
        $this->setCookie('', 1);
        $body = $this->box($left ? 'warn' : 'ok', $this->t($left ? 'cancelled_left' : 'cancelled'));
        if ($left) $body .= '<ul>' . implode('', array_map(fn($x) => '<li><code>' . $this->h($x) . '</code></li>', $left)) . '</ul>';
        $this->page($this->t('title_cancelled'), $body . '<p>' . $this->t('cancelled_next') . '</p>' . $this->linkHome());
    }

    /** S8: билет кодом WebHandoff установки → auto-submit форма на /install/; очистка; самоудаление */
    private function doHandoff(array $s): void
    {
        if (!in_array($s['phase'], ['enabled', 'handed'], true)) { $this->redirect(); return; }
        $r = $this->rel($s);
        $rel = $r['rel'];
        $this->libs($s, $rel);
        $bad = $this->verifyPlaced($rel, []);
        if ($bad) throw new RetSetupRefuse($this->t('verify_failed', ['n' => count($bad)]) . ' ' . implode('; ', array_slice($bad, 0, 5)));
        $this->lib($s, $rel, 'tools/lib/install/web/WebHandoff.php');
        try {
            $ticket = WebHandoff::issue($this->home, $this->pub, $this->secret);
        } catch (RuntimeException $e) {
            throw new RetSetupRefuse($e->getMessage());
        }
        $s['phase'] = 'handed';
        $this->saveState($s);
        $this->log("передача в web installer: билет выдан (RET CMS {$r['x']})");
        $d = $this->setupDir();
        $this->rmTree("{$d}/stage");
        $this->rmTree("{$d}/dl");
        foreach (glob("{$this->web}/ret-setup-*") ?: [] as $c) if (is_file($c) && !is_link($c) && filesize($c) === 0 && preg_match('/^ret-setup-[0-9a-f]{32}$/', basename($c))) @unlink($c);
        $this->unlock();
        if (@unlink(__FILE__)) {
            $this->finalize();
            $this->log('ret-setup.php удалён');
        } else {
            $this->log('ret-setup.php удалить не удалось — он инертен; удалите его вручную');
        }
        $body = '<p>' . $this->t('handoff_go') . '</p>'
              . '<form id="ho" method="post" action="/install/"><input type="hidden" name="action" value="handoff">'
              . '<input type="hidden" name="ticket" value="' . $this->h($ticket) . '">'
              . '<button type="submit">' . $this->t('btn_installer') . '</button></form>'
              . '<script nonce="' . $this->nonce . '">document.getElementById("ho").submit();</script>';
        $this->page($this->t('title_handoff'), $body);
    }

    /** После S8: журнал, grant, замок — удалить; var/setup — если пуст (backup остаётся) */
    private function finalize(): void
    {
        $d = $this->setupDir();
        foreach (['dl', 'stage'] as $x) $this->rmTree("{$d}/{$x}");
        foreach (['state.json', 'grant.json', 'lock'] as $x) @unlink("{$d}/{$x}");
        @rmdir("{$d}/lock.d");
        @rmdir($d);
    }

    /** Инертен: 404 без подробностей; попытка удалить себя */
    private function inert(): void
    {
        @unlink(__FILE__);
        while (ob_get_level() > 0) ob_end_clean();
        http_response_code(404);
        header('Content-Type: text/plain; charset=utf-8');
        echo "Not Found\n";
    }

    /* =================================================================== §6: preflight */

    /** → ['items' => [[hard|warn|info, ключ, текст]], 'release' => ['x', 'released', 'bytes', 'key']|null] */
    private function preflight(): array
    {
        $it = [];
        if (version_compare(PHP_VERSION, '8.1.0', '<')) $it[] = ['hard', 'php', $this->t('php_old', ['v' => PHP_VERSION])];
        $miss = [];
        foreach (['sodium', 'zip', 'json', 'hash', 'mbstring', 'mysqli'] as $e) if (!extension_loaded($e)) $miss[] = $e;
        if ($miss) $it[] = ['hard', 'ext', $this->t('no_ext', ['e' => implode(', ', $miss)])];
        if (!function_exists('curl_init') && !(ini_get('allow_url_fopen') && extension_loaded('openssl'))) $it[] = ['hard', 'http', $this->t('no_http')];
        foreach ([[$this->home, 'home'], [$this->web, 'web']] as [$dir, $k]) {
            $p = $this->probe($dir);
            if ($p !== null) $it[] = ['hard', "write_{$k}", $this->t('probe_fail', ['p' => $this->shown($dir), 'e' => $p])];
            if (DIRECTORY_SEPARATOR === '/' && (@fileperms($dir) & 0002)) $it[] = ['hard', "ww_{$k}", $this->t('world_writable', ['p' => $this->shown($dir)])];
        }
        // предупреждения (галочка)
        if (function_exists('posix_geteuid') && DIRECTORY_SEPARATOR === '/') {
            $me = posix_geteuid(); $own = @fileowner(__FILE__);
            if ($own !== false && $own !== $me) $it[] = ['warn', 'owner', $this->t('w_owner')];
        }
        $sd = @stat($this->setupDir()); $wd = @stat($this->web);
        if ($sd && $wd && $sd['dev'] !== $wd['dev']) $it[] = ['warn', 'dev', $this->t('w_dev')];
        if (!$this->https() && !$this->localHost()) $it[] = ['warn', 'https', $this->t('w_https')];
        foreach ($this->siblings() as $sib) $it[] = ['warn', 'sib', $this->t('w_sibling', ['n' => $sib])];
        // инфо
        $met = (int)ini_get('max_execution_time');
        if ($met > 0 && $met < 30) $it[] = ['info', 'met', $this->t('i_met', ['n' => $met])];
        $ml = self::bytes((string)ini_get('memory_limit'));
        if ($ml > 0 && $ml < 64 * 1048576) $it[] = ['info', 'mem', $this->t('i_mem', ['n' => (string)ini_get('memory_limit')])];

        // сеть и latest (подписи) — без записи: во временный каталог var/setup/probe
        $release = null;
        if (!array_filter($it, fn($x) => $x[0] === 'hard')) {
            $tmp = $this->setupDir() . '/probe';
            $this->rmTree($tmp);
            @mkdir($tmp, 0700, true);
            try {
                foreach (['latest.json', 'latest.json.sig', 'index.json', 'index.json.sig'] as $f) $this->put("{$tmp}/{$f}", $this->fetch("{$this->base}/{$f}", self::MAX_JSON), 0600);
                [$x, $entry] = $this->checkIndex($tmp, null);
                foreach (["ret-cms-{$x}.json", "ret-cms-{$x}.json.sig"] as $f) $this->put("{$tmp}/{$f}", $this->fetch("{$this->base}/{$x}/{$f}", self::MAX_JSON), 0600);
                $m = $this->checkMeta($tmp, $x, $entry);
                $bytes = (int)$m['archives']["ret-cms-{$x}.zip"]['bytes'];
                $release = ['x' => $x, 'released' => (string)($m['released'] ?? ''), 'bytes' => $bytes, 'key' => $m['_key_id'],
                            'fp' => 'SHA256:' . hash('sha256', (string)base64_decode(self::KEYS[$m['_key_id']]['public'], true)), 'security' => !empty($m['security'])];
                $free = @disk_free_space($this->home);
                if (is_float($free) && $free < 4 * $bytes) $it[] = ['info', 'disk', $this->t('i_disk', ['n' => (string)round($free / 1048576)])];
            } catch (RetSetupTransport $e) {
                $it[] = ['hard', 'net', $this->t('transport', ['e' => $e->getMessage()])];
            } catch (RetSetupVerify $e) {
                $it[] = ['hard', 'verify', $this->t('verify_stop', ['e' => $e->getMessage()])];
            } finally {
                $this->rmTree($tmp);
            }
        }
        return ['items' => $it, 'release' => $release];
    }

    /** Реальная проба записи: каталог → файл → rename → удаление; null — прошла, иначе ошибка */
    private function probe(string $dir): ?string
    {
        $n = "{$dir}/.ret-setup-probe-" . bin2hex(random_bytes(4));
        if (!@mkdir($n, 0700)) return 'mkdir';
        $ok = @file_put_contents("{$n}/a", 'x') === 1 && @rename("{$n}/a", "{$n}/b") && @unlink("{$n}/b");
        @unlink("{$n}/a"); @unlink("{$n}/b");
        $rm = @rmdir($n);
        if (!$ok) return 'file/rename';
        return $rm ? null : 'rmdir';
    }

    private function localHost(): bool
    {
        $h = strtolower((string)preg_replace('/:\d+$/', '', (string)($_SERVER['HTTP_HOST'] ?? '')));
        return $h === 'localhost' || $h === '127.0.0.1' || $h === '[::1]' || substr($h, -5) === '.test' || substr($h, -10) === '.localhost';
    }

    /** Соседние каталоги-сайты в корне установки (предупреждение) */
    private function siblings(): array
    {
        $out = [];
        foreach (@scandir($this->home) ?: [] as $e) {
            if ($e === '.' || $e === '..' || self::same($e, $this->pub)) continue;
            $p = "{$this->home}/{$e}";
            if (is_link($p) || !is_dir($p) || in_array($e, self::HOME_TARGETS, true)) continue;
            foreach (['index.php', 'index.html', 'index.htm'] as $f) if (is_file("{$p}/{$f}")) { $out[] = $e; break; }
        }
        return $out;
    }

    private static function bytes(string $v): int
    {
        $v = trim($v);
        if ($v === '' || $v === '-1') return -1;
        $n = (int)$v; $u = strtolower(substr($v, -1));
        return $u === 'g' ? $n << 30 : ($u === 'm' ? $n << 20 : ($u === 'k' ? $n << 10 : $n));
    }

    /* =================================================================== §7: чистый web-root и корень установки */

    /**
     * Web-root по закрытому списку (lstat: симлинк не разыменовывается).
     * $ours — элементы, которые уже мог положить этот bootstrap (журнал): их решает place().
     * → ['entries' => [[имя, решение, примечание]], 'refuse' => [текст], 'stubs' => [имя => [...]],
     *    'htaccess' => null|['sha256', 'bytes', 'text', 'zone'], 'files' => N, 'dirs' => M]
     */
    private function inspectWeb(array $ours, array $s = []): array
    {
        $r = ['entries' => [], 'refuse' => [], 'stubs' => [], 'htaccess' => null, 'files' => 0, 'dirs' => 0];
        $list = @scandir($this->web);
        if ($list === false) { $r['refuse'][] = $this->t('scandir_fail'); return $r; }
        $self = basename(__FILE__);
        $stubCand = [];
        $planned = array_keys((array)($s['stubs'] ?? []));
        foreach ($list as $e) {
            if ($e === '.' || $e === '..') continue;
            $p = "{$this->web}/{$e}";
            $link = is_link($p);
            $isDir = !$link && is_dir($p);
            $isFile = !$link && is_file($p);
            if ($e !== $self && strncmp($e, 'ret-setup-', 10) !== 0) { if ($isDir) $r['dirs']++; else $r['files']++; }
            if ($link) { $r['entries'][] = [$e, 'refuse', $this->t('e_link')]; $r['refuse'][] = $this->t('r_item', ['n' => $e, 'w' => $this->t('e_link')]); continue; }
            if (self::nameIn($e, [$self]) && $isFile) { $r['entries'][] = [$e, 'keep', $this->t('e_self')]; continue; }
            if (strncmp($e, 'ret-setup-', 10) === 0) {
                if ($isFile && preg_match('/^ret-setup-[0-9a-f]{32}$/', $e) && filesize($p) === 0) { $r['entries'][] = [$e, 'keep', $this->t('e_challenge')]; continue; }
                $r['entries'][] = [$e, 'refuse', $this->t('e_bad_setup')]; $r['refuse'][] = $this->t('r_item', ['n' => $e, 'w' => $this->t('e_bad_setup')]); continue;
            }
            if (self::nameIn($e, ['.well-known']) && $isDir) { $r['entries'][] = [$e, 'keep', $this->t('e_wellknown')]; continue; }
            if (self::nameIn($e, ['cgi-bin']) && $isDir && count(array_diff(@scandir($p) ?: ['x'], ['.', '..'])) === 0) { $r['entries'][] = [$e, 'keep', $this->t('e_cgibin')]; continue; }
            if (self::nameIn($e, self::KEEP_FILES) && $isFile) { $r['entries'][] = [$e, 'keep', $this->t('e_hosting')]; continue; }
            if (self::nameIn($e, $ours)) { $r['entries'][] = [$e, 'ours', $this->t('e_ours')]; continue; }
            if (self::nameIn($e, ['.htaccess']) && $isFile) {
                $why = $this->htaccessProblem($p, $info);
                if ($why === null) { $r['htaccess'] = $info; $r['entries'][] = [$e, 'ht', $this->t($info['zone'] ? 'e_htaccess_zone' : 'e_htaccess')]; continue; }
                $r['entries'][] = [$e, 'refuse', $why]; $r['refuse'][] = $this->t('r_item', ['n' => $e, 'w' => $why]); continue;
            }
            if (self::nameIn($e, self::STUB_NAMES) && $isFile) { $stubCand[] = $e; continue; }
            if (self::isPhp($e)) { $r['entries'][] = [$e, 'refuse', $this->t('e_php')]; $r['refuse'][] = $this->t('r_item', ['n' => $e, 'w' => $this->t('e_php')]); continue; }
            $w = $this->t($isDir ? 'e_dir' : 'e_unknown');
            if (in_array($e, ['kernel2', 'admin2', 'handlers', 'uploads', 'index.php'], true)) $w = $this->t('e_retcms');
            $r['entries'][] = [$e, 'refuse', $w];
            $r['refuse'][] = $this->t('r_item', ['n' => $e, 'w' => $w]);
        }
        // заглушки хостинга: не больше двух, каждая проходит все условия
        if (count($stubCand) > 2) {
            foreach ($stubCand as $e) { $r['entries'][] = [$e, 'refuse', $this->t('e_stub_many')]; $r['refuse'][] = $this->t('r_item', ['n' => $e, 'w' => $this->t('e_stub_many')]); }
        } else {
            foreach ($stubCand as $e) {
                $why = $this->stubProblem("{$this->web}/{$e}");
                if ($why === null) {
                    $r['stubs'][$e] = ['sha256' => (string)hash_file('sha256', "{$this->web}/{$e}"), 'bytes' => filesize("{$this->web}/{$e}")];
                    if (!empty($s['started']) && !in_array($e, $planned, true)) { $r['entries'][] = [$e, 'refuse', $this->t('e_stub_new')]; $r['refuse'][] = $this->t('r_item', ['n' => $e, 'w' => $this->t('e_stub_new')]); continue; }
                    $r['entries'][] = [$e, 'stub', $this->t('e_stub')];
                } else {
                    $r['entries'][] = [$e, 'refuse', $why]; $r['refuse'][] = $this->t('r_item', ['n' => $e, 'w' => $why]);
                }
            }
        }
        return $r;
    }

    /** Имя из списка: точно; Windows — без регистра (§7) */
    private static function nameIn(string $n, array $list): bool
    {
        if (DIRECTORY_SEPARATOR !== '\\') return in_array($n, $list, true);
        foreach ($list as $x) if (strcasecmp($n, $x) === 0) return true;
        return false;
    }

    private static function isPhp(string $n): bool
    {
        return preg_match('/\.(php\d?|phtml|phar|pht|phps|inc)$/i', $n) === 1;
    }

    /** .htaccess хостинга: null — можно сохранить и дописать зону; иначе причина отказа */
    private function htaccessProblem(string $f, &$info): ?string
    {
        $info = null;
        $size = filesize($f);
        if ($size === false || $size > self::MAX_SMALL) return $this->t('h_big');
        $t = (string)@file_get_contents($f);
        if (strpos($t, "\0") !== false) return $this->t('h_binary');
        $lines = preg_split('/\r?\n/', $t);
        $outside = []; $in = false; $ours = 0; $oursEnd = 0;
        foreach ($lines as $l) {
            $x = trim($l);
            if (preg_match('/^#[ \t]*BEGIN[ \t]+RET[ \t]+CMS$/', $x)) { $ours++; $in = true; continue; }
            if (preg_match('/^#[ \t]*END[ \t]+RET[ \t]+CMS$/', $x)) { $oursEnd++; $in = false; continue; }
            if (!$in) $outside[] = $x;
        }
        if ($ours !== $oursEnd || $ours > 1) return $this->t('h_zone_broken');
        foreach ($outside as $x) {
            if (preg_match('/^#\s*(BEGIN|END)\s+(\S.*)$/i', $x, $m)) return $this->t('h_foreign', ['m' => $x]);
            if (preg_match('/^RewriteRule\s.*\bindex\.php\b/i', $x)) return $this->t('h_frontctl');
        }
        $info = ['sha256' => hash('sha256', $t), 'bytes' => strlen($t), 'text' => $t, 'zone' => $ours === 1];
        return null;
    }

    /** Заглушка хостинга (§7): null — можно перенести в backup; иначе причина */
    private function stubProblem(string $f): ?string
    {
        $size = filesize($f);
        if ($size === false || $size > self::MAX_SMALL) return $this->t('s_big');
        $t = (string)@file_get_contents($f);
        if (strpos($t, "\0") !== false) return $this->t('s_binary');
        $x = ltrim(preg_replace('/^\xEF\xBB\xBF/', '', $t));
        if ($x === '' || $x[0] !== '<') return $this->t('s_not_html');
        if (stripos($t, '<form') !== false || strpos($t, '<?') !== false) return $this->t('s_form');
        preg_match_all('/\b(?:src|href)\s*=\s*(?:"([^"]*)"|\'([^\']*)\'|([^\s>]+))/i', $t, $m1, PREG_SET_ORDER);
        preg_match_all('/url\(\s*(?:"([^"]*)"|\'([^\']*)\'|([^)\s]*))\s*\)/i', $t, $m2, PREG_SET_ORDER);
        foreach (array_merge($m1, $m2) as $m) {
            $u = trim(($m[1] ?? '') . ($m[2] ?? '') . ($m[3] ?? ''));
            if (!preg_match('~^(https?://|//|#|data:|mailto:|tel:)~i', $u)) return $this->t('s_local', ['u' => mb_substr($u, 0, 60)]);
        }
        return null;
    }

    /**
     * Корень установки: цели HOME_TARGETS не существуют (кроме своего var/ и элементов журнала $ours),
     * второго ядра нет; симлинк на web-root (DirectAdmin private_html) — алиас.
     */
    private function inspectHome(array $ours, array $s): array
    {
        $r = ['refuse' => [], 'entries' => []];
        foreach (self::HOME_TARGETS as $t) {
            $p = "{$this->home}/{$t}";
            if (!self::exists($p)) continue;
            if ($t === 'var' && !is_link($p) && is_dir($p) && $this->varIsOurs($p, $s)) { $r['entries'][] = [$t, 'ours']; continue; }
            if (in_array($t, $ours, true) && !is_link($p)) { $r['entries'][] = [$t, 'ours']; continue; }
            $r['entries'][] = [$t, 'refuse'];
            $r['refuse'][] = $this->t('r_home', ['n' => $t]);
        }
        foreach (@scandir($this->home) ?: [] as $e) {
            if ($e === '.' || $e === '..' || self::same($e, $this->pub)) continue;
            $p = "{$this->home}/{$e}";
            if (!is_file("{$p}/kernel2/VERSION")) continue;
            if (is_link($p)) {
                $rp = realpath($p);
                if ($rp !== false && self::same(self::slash($rp), $this->web)) continue;
            }
            $r['refuse'][] = $this->t('r_core', ['n' => $e]);
        }
        return $r;
    }

    /** var/ — только своё: setup/, logs/setup.log, releases/X (закреплённая версия) */
    private function varIsOurs(string $p, array $s): bool
    {
        foreach (array_diff(@scandir($p) ?: ['?'], ['.', '..']) as $e) {
            if ($e === 'setup' && is_dir("{$p}/setup") && !is_link("{$p}/setup")) continue;
            if ($e === 'logs' && is_dir("{$p}/logs") && !array_diff(@scandir("{$p}/logs") ?: ['?'], ['.', '..', 'setup.log'])) continue;
            if ($e === 'releases' && !empty($s['x']) && !array_diff(@scandir("{$p}/releases") ?: ['?'], ['.', '..', (string)$s['x']])) continue;
            return false;
        }
        return true;
    }

    /* =================================================================== HTTP */

    /** GET без редиректов, только https (CI — http://127.0.0.1), лимит байтов; $to — в файл */
    private function fetch(string $url, int $max, ?string $to = null): string
    {
        $buf = ''; $n = 0; $over = false;
        $fh = null;
        if ($to !== null) { $fh = @fopen($to, 'wb'); if (!$fh) throw new RetSetupRefuse($this->t('write_fail', ['p' => basename($to)])); }
        try {
            if (function_exists('curl_init')) {
                $ch = curl_init($url);
                $proto = $this->testBase && strncmp($url, 'http://', 7) === 0 ? CURLPROTO_HTTP : CURLPROTO_HTTPS;
                curl_setopt_array($ch, [
                    CURLOPT_FOLLOWLOCATION => false, CURLOPT_PROTOCOLS => $proto, CURLOPT_REDIR_PROTOCOLS => $proto,
                    CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_CONNECTTIMEOUT => 20, CURLOPT_TIMEOUT => 300,
                    CURLOPT_USERAGENT => 'ret-setup/' . self::VERSION, CURLOPT_HTTPHEADER => ['Accept: */*'], CURLOPT_ENCODING => '',
                    CURLOPT_WRITEFUNCTION => function ($ch, $d) use (&$buf, &$n, &$over, $max, $fh) {
                        $n += strlen($d);
                        if ($n > $max) { $over = true; return 0; }
                        if ($fh) fwrite($fh, $d); else $buf .= $d;
                        return strlen($d);
                    },
                ]);
                $ok = curl_exec($ch);
                $code = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
                $err = curl_errno($ch); $msg = curl_error($ch);
                curl_close($ch);
                if ($over) throw new RetSetupVerify($this->t('v_size', ['u' => basename($url)]));
                if ($ok === false) {
                    if (in_array($err, [35, 51, 53, 54, 58, 59, 60, 64, 66, 77, 80, 82, 83], true)) throw new RetSetupTransport($this->t('tls', ['e' => $msg]));
                    throw new RetSetupTransport(basename($url) . ": {$msg}");
                }
                if ($code !== 200) throw new RetSetupTransport(basename($url) . ": HTTP {$code}");
            } else {
                $ctx = stream_context_create([
                    'http' => ['follow_location' => 0, 'max_redirects' => 0, 'timeout' => 60, 'ignore_errors' => true, 'user_agent' => 'ret-setup/' . self::VERSION],
                    'ssl' => ['verify_peer' => true, 'verify_peer_name' => true, 'allow_self_signed' => false],
                ]);
                if (!$this->testBase && strncmp($url, 'https://', 8) !== 0) throw new RetSetupTransport('только https');
                $in = @fopen($url, 'rb', false, $ctx);
                if (!$in) { $e = error_get_last(); throw new RetSetupTransport(basename($url) . ': ' . (string)($e['message'] ?? 'нет соединения')); }
                $code = 0;
                foreach ((array)($http_response_header ?? []) as $l) if (preg_match('#^HTTP/\S+\s+(\d{3})#', $l, $m)) $code = (int)$m[1];
                if ($code !== 200) { fclose($in); throw new RetSetupTransport(basename($url) . ": HTTP {$code}"); }
                while (!feof($in)) {
                    $d = fread($in, 65536);
                    if ($d === false) break;
                    $n += strlen($d);
                    if ($n > $max) { fclose($in); throw new RetSetupVerify($this->t('v_size', ['u' => basename($url)])); }
                    if ($fh) fwrite($fh, $d); else $buf .= $d;
                }
                fclose($in);
            }
        } finally {
            if ($fh) fclose($fh);
        }
        return $buf;
    }

    /* =================================================================== ФС */

    private static function slash(string $p): string
    {
        $p = str_replace('\\', '/', $p);
        return strlen($p) > 1 ? rtrim($p, '/') : $p;
    }

    private static function same(string $a, string $b): bool
    {
        $a = self::slash($a); $b = self::slash($b);
        return DIRECTORY_SEPARATOR === '\\' ? strcasecmp($a, $b) === 0 : $a === $b;
    }

    private static function under(string $p, string $dir): bool
    {
        $p = self::slash($p) . '/'; $dir = self::slash($dir) . '/';
        return DIRECTORY_SEPARATOR === '\\' ? strncasecmp($p, $dir, strlen($dir)) === 0 : strncmp($p, $dir, strlen($dir)) === 0;
    }

    private static function exists(string $p): bool
    {
        return file_exists($p) || is_link($p);
    }

    private function readJson(string $f)
    {
        if (!is_file($f)) return null;
        $j = json_decode((string)@file_get_contents($f), true);
        return is_array($j) ? $j : null;
    }

    /** Атомарная запись: временный файл рядом → rename */
    private function put(string $f, string $data, int $mode): void
    {
        $tmp = dirname($f) . '/.' . basename($f) . '.' . bin2hex(random_bytes(4)) . '.tmp';
        if (@file_put_contents($tmp, $data) !== strlen($data)) { @unlink($tmp); throw new RetSetupRefuse($this->t('write_fail', ['p' => $this->rel2home($f)])); }
        @chmod($tmp, $mode);
        if (!$this->renameRetry($tmp, $f, true)) { @unlink($tmp); throw new RetSetupRefuse($this->t('write_fail', ['p' => $this->rel2home($f)])); }
    }

    /** rename; Windows — до 3 повторов (антивирус). $replace — цель-файл может существовать (только put) */
    private function renameRetry(string $a, string $b, bool $replace = false): bool
    {
        if (!$replace && self::exists($b)) return false;
        for ($i = 0; $i < (DIRECTORY_SEPARATOR === '\\' ? 4 : 1); $i++) {
            if (@rename($a, $b)) return true;
            if (!self::exists($a)) return false;
            usleep(200000);
        }
        return false;
    }

    /** Рекурсивный список файлов: [относительный путь => 1]; ссылки — как файлы (сверка их отвергнет) */
    private function walk(string $dir, string $pre, array &$out): void
    {
        foreach (@scandir($dir) ?: [] as $e) {
            if ($e === '.' || $e === '..') continue;
            $p = "{$dir}/{$e}";
            if (!is_link($p) && is_dir($p)) $this->walk($p, "{$pre}{$e}/", $out);
            else $out["{$pre}{$e}"] = 1;
        }
    }

    private function copyTree(string $a, string $b): void
    {
        if (!is_link($a) && is_dir($a)) {
            if (!@mkdir($b, 0755, true) && !is_dir($b)) throw new RetSetupRefuse($this->t('mkdir_fail', ['p' => $this->rel2home($b)]));
            foreach (@scandir($a) ?: [] as $e) if ($e !== '.' && $e !== '..') $this->copyTree("{$a}/{$e}", "{$b}/{$e}");
            return;
        }
        if (!@copy($a, $b)) throw new RetSetupRefuse($this->t('write_fail', ['p' => $this->rel2home($b)]));
        @chmod($b, substr($a, -3) === '.sh' ? 0755 : 0644);
    }

    private function rmTree(string $p): void
    {
        if (is_link($p) || is_file($p)) { @unlink($p); return; }
        if (!is_dir($p)) return;
        foreach (@scandir($p) ?: [] as $e) if ($e !== '.' && $e !== '..') $this->rmTree("{$p}/{$e}");
        @rmdir($p);
    }

    /** Путь для показа (после подтверждения): относительно корня установки */
    private function rel2home(string $p): string
    {
        $p = self::slash($p);
        return self::under($p, $this->home) ? substr($p, strlen($this->home) + 1) : basename($p);
    }

    private function shown(string $dir): string
    {
        return self::same($dir, $this->web) ? "{$this->pub}/" : $this->t('home_dir');
    }

    /* =================================================================== страницы */

    private function pageForState(array $s): void
    {
        if ($s['failed']) { $this->pageFailed($s); return; }
        if (!$s['started']) { $this->pagePlan($s); return; }
        if ($s['phase'] === 'enabled') { $this->pageEnabled($s); return; }
        if ($s['phase'] === 'handed') { $this->pageHanded($s); return; }
        $this->pageProgress($s, null, false);
    }

    /** S0: подтверждение доступа (до него — без путей и имён) */
    private function pageConfirm($state, bool $bad): void
    {
        $name = 'ret-setup-' . $this->challenge();
        $w = $this->inspectWeb([]);
        $body = '<p>' . $this->t('s0_intro') . '</p>';
        if ($state !== null || $bad) $body .= $this->box('warn', $this->t('s0_journal'));
        $body .= '<ol><li>' . $this->t('s0_step1') . '<div class="name"><code>' . $this->h($name) . '</code></div></li>'
               . '<li>' . $this->t('s0_step2') . '</li></ol>'
               . $this->form('confirm', $this->t('btn_confirm'));
        $facts = [$this->t('s0_counts', ['f' => $w['files'], 'd' => $w['dirs']])];
        $facts[] = $this->t(@is_writable($this->home) ? 's0_home_w' : 's0_home_nw');
        if ($w['refuse']) $facts[] = $this->t('s0_not_clean');
        $body .= '<h3>' . $this->t('s0_facts') . '</h3><ul>' . implode('', array_map(fn($x) => "<li>{$x}</li>", $facts)) . '</ul>'
               . '<p class="small">' . $this->t('s0_why') . '</p>';
        $this->page($this->t('title_confirm'), $body);
    }

    /** S1: preflight, состав web-root и корня установки, релиз, план, галочки */
    private function pagePlan(array $s): void
    {
        $pf = $this->preflight();
        $w = $this->inspectWeb([]);
        $hm = $this->inspectHome([], $s);
        $hard = array_filter($pf['items'], fn($x) => $x[0] === 'hard');
        $blocked = $hard || $w['refuse'] || $hm['refuse'];
        $b = '';
        if ($this->testBase) $b .= $this->box('warn', $this->t('test_base', ['u' => $this->base]));
        $b .= '<h3>' . $this->t('p_env') . '</h3>';
        if (!$pf['items']) $b .= '<p class="ok">✓ ' . $this->t('p_env_ok') . '</p>';
        else $b .= '<ul class="checks">' . implode('', array_map(fn($x) => '<li class="' . $x[0] . '">' . ['hard' => '✗', 'warn' => '⚠', 'info' => 'ℹ'][$x[0]] . ' ' . $x[2] . '</li>', $pf['items'])) . '</ul>';

        $b .= '<h3>' . $this->t('p_web', ['n' => $this->h($this->pub)]) . '</h3><table>';
        foreach ($w['entries'] as [$n, $dec, $note]) {
            $b .= '<tr class="' . $dec . '"><td><code>' . $this->h($n) . '</code></td><td>' . $this->h($note) . '</td></tr>';
        }
        if (!$w['entries']) $b .= '<tr><td colspan="2">' . $this->t('p_web_empty') . '</td></tr>';
        $b .= '</table>';
        if ($hm['refuse']) $b .= '<h3>' . $this->t('p_home') . '</h3><ul class="checks">' . implode('', array_map(fn($x) => '<li class="hard">✗ ' . $x . '</li>', $hm['refuse'])) . '</ul>';

        if ($pf['release']) {
            $rl = $pf['release'];
            $b .= '<h3>' . $this->t('p_release') . '</h3><p>' . $this->t('p_release_line', ['x' => $rl['x'], 'd' => $this->h($rl['released']), 'k' => $this->h($rl['key']), 'f' => $this->h($rl['fp']), 'kb' => (string)round($rl['bytes'] / 1024)]) . '</p>';
        }
        if ($blocked) {
            $b .= $this->box('err', $this->t('p_blocked'));
            $b .= '<p>' . $this->form('cancel', $this->t('btn_cancel'), [], 'secondary') . '</p>';
            $this->page($this->t('title_plan'), $b);
            return;
        }
        $b .= '<h3>' . $this->t('p_plan') . '</h3><ul>'
            . '<li>' . $this->t('p_plan_private', ['h' => $this->t('home_dir')]) . ' <code>tools/ deploy/ schema/ site/ README.md CHANGELOG.md LICENSE ARCHITECTURE.md</code></li>'
            . '<li>' . $this->t('p_plan_public', ['n' => $this->h($this->pub)]) . ' <code>kernel2/ admin2/ handlers/ uploads/</code>, ' . $this->t('p_plan_index') . '</li>'
            . '<li>' . $this->t('p_plan_untouched') . '</li></ul>';
        $acks = '';
        foreach ($pf['items'] as $x) if ($x[0] === 'warn') $acks .= $this->check($x[1], $x[2]);
        if ($w['stubs']) $acks .= $this->check('stubs', $this->t('ack_stubs', ['n' => implode(', ', array_map([$this, 'h'], array_keys($w['stubs'])))]));
        if ($w['htaccess'] !== null) {
            $b .= '<h4>' . $this->t('p_htaccess') . '</h4><pre>' . $this->h($w['htaccess']['text']) . '</pre>';
            $acks .= $this->check('htaccess', $this->t($w['htaccess']['zone'] ? 'ack_htaccess_zone' : 'ack_htaccess'));
        }
        $b .= $this->form('install', $this->t('btn_install'), [], 'primary', $acks);
        $b .= '<p>' . $this->form('cancel', $this->t('btn_cancel'), [], 'secondary') . '</p>';
        $this->page($this->t('title_plan'), $b);
    }

    private function pageProgress(array $s, ?array $msg, bool $auto): void
    {
        $no = $this->phaseNo($s);
        $b = $this->steps($no);
        if ($msg) $b .= $this->box($msg[0], $this->h($msg[1]));
        if ($s['phase'] === 'public' && $auto) $b .= '<p>' . $this->t('enabling_next') . '</p>';
        $b .= $this->form('step', $this->t($msg && $msg[0] === 'err' ? 'btn_retry' : 'btn_continue'), [], 'primary', '', $auto ? 'next' : '');
        if ($auto) $b .= '<script nonce="' . $this->nonce . '">document.getElementById("next").submit();</script>';
        $b .= '<p>' . $this->form('cancel', $this->t('btn_cancel'), [], 'secondary') . '</p>';
        $this->page($this->t('title_progress', ['x' => $s['x'] ?? '']), $b);
    }

    private function pageFailed(array $s): void
    {
        $f = $s['failed'];
        $b = $this->steps($this->phaseNo($s));
        $b .= $this->box('err', $this->t('verify_stop', ['e' => $this->h((string)$f['reason'])]));
        $b .= '<p>' . $this->t('failed_hint') . '</p>';
        $b .= '<p>' . $this->form('restart', $this->t('btn_restart'), [], 'primary') . ' ' . $this->form('cancel', $this->t('btn_cancel'), [], 'secondary') . '</p>';
        $this->page($this->t('title_failed'), $b, 200);
    }

    private function pageError(string $msg, ?array $s): void
    {
        $b = $this->box('err', $this->h($msg)) . '<p>' . $this->form('step', $this->t('btn_retry'), [], 'primary') . '</p>';
        if ($s) $b .= '<p>' . $this->form('cancel', $this->t('btn_cancel'), [], 'secondary') . '</p>';
        $this->page($this->t('title_refuse'), $b, 409);
    }

    /** После S7: проверка браузером (предупреждение), передача, «откатить включение» */
    private function pageEnabled(array $s): void
    {
        $b = $this->steps(7, true);
        $b .= $this->box('ok', $this->t('enabled', ['x' => $s['x']]));
        $b .= '<div id="bc" class="box info">' . $this->t('bc_wait') . '</div>';
        $b .= '<div id="bcfail" class="box warn" hidden>' . $this->t('bc_fail') . '<p>' . $this->form('disable', $this->t('btn_disable'), [], 'secondary') . '</p></div>';
        $b .= $this->form('handoff', $this->t('btn_installer'), [], 'primary');
        $b .= '<p>' . $this->form('cancel', $this->t('btn_cancel'), [], 'secondary') . '</p>';
        $ok = json_encode($this->t('bc_ok')); $bad = json_encode($this->t('bc_bad'));
        $b .= '<script nonce="' . $this->nonce . '">(function(){var e=document.getElementById("bc"),f=document.getElementById("bcfail");'
            . 'fetch("/",{redirect:"manual",cache:"no-store",credentials:"same-origin"}).then(function(r){'
            . 'if(r.type==="opaqueredirect"||(r.status>=300&&r.status<400)){e.className="box ok";e.textContent=' . $ok . ';}'
            . 'else{e.className="box warn";e.textContent=' . $bad . '.replace("{s}",r.status);f.hidden=false;}'
            . '}).catch(function(){e.className="box warn";e.textContent=' . $bad . '.replace("{s}","?");f.hidden=false;});})();</script>';
        $this->page($this->t('title_enabled'), $b);
    }

    /** S8, ret-setup.php удалить не удалось: новый билет, пока жив доступ */
    private function pageHanded(array $s): void
    {
        $b = $this->box('ok', $this->t('handed'));
        $b .= $this->form('handoff', $this->t('btn_installer'), [], 'primary');
        $b .= '<p class="small">' . $this->t('handed_delete') . '</p>';
        $this->page($this->t('title_enabled'), $b);
    }

    private function pageJournalBad(): void
    {
        $b = $this->box('err', $this->t('journal_bad')) . '<p>' . $this->form('cancel', $this->t('btn_cancel'), [], 'secondary') . '</p>';
        $this->page($this->t('title_refuse'), $b);
    }

    /** RET CMS разложена вручную, не установлена — ничего не пишем, ссылка на installer */
    private function pageManual(): void
    {
        $this->page($this->t('title_manual'), $this->box('info', $this->t('manual')) . '<p><a class="btn primary" href="/install/">' . $this->t('btn_installer') . '</a></p>');
    }

    private function steps(int $cur, bool $doneAll = false): string
    {
        $names = ['s_access', 's_download', 's_verify', 's_stage', 's_private', 's_public', 's_enable'];
        $o = '<ol class="steps">';
        foreach ($names as $i => $k) {
            $n = $i + 1;
            $c = ($doneAll || $n <= $cur) ? 'done' : ($n === $cur + 1 ? 'now' : '');
            $o .= '<li class="' . $c . '">' . ($c === 'done' ? '✓ ' : '') . $this->t($k) . '</li>';
        }
        return $o . '</ol>';
    }

    private function form(string $action, string $label, array $extra = [], string $cls = 'primary', string $inner = '', string $id = ''): string
    {
        $o = '<form method="post" action="/ret-setup.php?lang=' . $this->lang . '"' . ($id !== '' ? ' id="' . $id . '"' : '') . ' class="inline">'
           . '<input type="hidden" name="csrf" value="' . $this->csrf() . '"><input type="hidden" name="action" value="' . $action . '">';
        foreach ($extra as $k => $v) $o .= '<input type="hidden" name="' . $this->h($k) . '" value="' . $this->h($v) . '">';
        return $o . $inner . '<button type="submit" class="btn ' . $cls . '">' . $label . '</button></form>';
    }

    private function check(string $key, string $label): string
    {
        return '<label class="ack"><input type="checkbox" name="ack[' . $this->h($key) . ']" value="1"> ' . $label . '</label>';
    }

    private function box(string $cls, string $html): string
    {
        return '<div class="box ' . $cls . '">' . $html . '</div>';
    }

    private function linkHome(): string
    {
        return '<p><a href="/ret-setup.php?lang=' . $this->lang . '">' . $this->t('btn_back') . '</a></p>';
    }

    private function redirect(): void
    {
        http_response_code(303);
        header('Location: /ret-setup.php?lang=' . $this->lang);
    }

    private function headers(): void
    {
        header('Cache-Control: no-store');
        header('Pragma: no-cache');
        header('X-Robots-Tag: noindex, nofollow');
        header('Referrer-Policy: same-origin');
        header('X-Content-Type-Options: nosniff');
        header('X-Frame-Options: DENY');
        header("Content-Security-Policy: default-src 'none'; style-src 'nonce-{$this->nonce}'; script-src 'nonce-{$this->nonce}'; connect-src 'self'; "
             . "img-src data:; form-action 'self'; base-uri 'none'; frame-ancestors 'none'");
    }

    private function page(string $title, string $body, int $code = 200): void
    {
        if (!headers_sent()) {
            http_response_code($code);
            header('Content-Type: text/html; charset=utf-8');
        }
        $fl = '';
        foreach ($this->flash as [$c, $m]) $fl .= $this->box($c, $m);
        $other = $this->lang === 'ru' ? 'en' : 'ru';
        echo '<!DOCTYPE html><html lang="' . $this->lang . '"><head><meta charset="utf-8"><meta name="robots" content="noindex, nofollow">'
           . '<meta name="viewport" content="width=device-width, initial-scale=1"><title>' . $this->h($title) . ' — RET CMS setup</title>'
           . '<style nonce="' . $this->nonce . '">' . self::CSS . '</style></head><body><main>'
           . '<header><b>RET CMS</b> setup ' . self::VERSION . '<a class="lang" href="/ret-setup.php?lang=' . $other . '">' . strtoupper($other) . '</a></header>'
           . '<h1>' . $this->h($title) . '</h1>' . $fl . $body . '</main></body></html>';
    }

    private function h($s): string
    {
        return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }

    const CSS = 'body{font:15px/1.5 -apple-system,"Segoe UI",Roboto,Arial,sans-serif;color:#222;background:#f4f5f7;margin:0}'
        . 'main{max-width:820px;margin:24px auto;background:#fff;padding:24px 32px;border-radius:8px;box-shadow:0 1px 3px rgba(0,0,0,.08)}'
        . 'header{color:#666;font-size:13px;display:flex;gap:6px}header .lang{margin-left:auto}h1{font-size:22px;margin:8px 0 16px}h3{margin:22px 0 8px;font-size:16px}'
        . 'code,pre{background:#f1f2f4;border-radius:4px;padding:1px 5px;font:13px/1.4 Consolas,monospace}pre{padding:10px;overflow:auto;max-height:260px;white-space:pre-wrap}'
        . '.name code{display:inline-block;font-size:16px;padding:6px 10px;margin:6px 0;user-select:all}'
        . '.box{border-radius:6px;padding:10px 14px;margin:12px 0}.box.ok{background:#e8f6ec}.box.warn{background:#fff6e0}.box.err{background:#fde8e8}.box.info{background:#eaf1fb}'
        . '.btn{font:inherit;border:0;border-radius:6px;padding:8px 16px;cursor:pointer;text-decoration:none;display:inline-block}.btn.primary{background:#2457d6;color:#fff}'
        . '.btn.secondary{background:#e9ebef;color:#333}form.inline{display:inline}.ack{display:block;margin:6px 0}'
        . 'table{border-collapse:collapse;width:100%}td{border-bottom:1px solid #eee;padding:4px 6px;vertical-align:top}tr.refuse td{color:#b00020}tr.stub td,tr.ht td{color:#8a5a00}'
        . 'ul.checks{list-style:none;padding:0}.checks .hard{color:#b00020}.checks .warn{color:#8a5a00}.checks .info{color:#555}.small{color:#666;font-size:13px}'
        . 'ol.steps{display:flex;flex-wrap:wrap;gap:6px;list-style:none;padding:0}ol.steps li{background:#eef0f3;border-radius:12px;padding:2px 10px;font-size:13px}'
        . 'ol.steps li.done{background:#d9f0df}ol.steps li.now{background:#dbe6fb}';

    /* =================================================================== строки (en, ru) */

    private function pickLang(): string
    {
        $l = (string)($_GET['lang'] ?? $_POST['lang'] ?? '');
        if ($l === 'en' || $l === 'ru') return $l;
        return preg_match('/^\s*ru\b/i', (string)($_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '')) ? 'ru' : 'en';
    }

    private function t(string $k, array $v = []): string
    {
        $s = self::L[$k][$this->lang === 'ru' ? 1 : 0] ?? $k;
        foreach ($v as $a => $b) $s = str_replace('{' . $a . '}', (string)$b, $s);
        return $s;
    }

    const L = [
        'title_refuse' => ['Cannot continue', 'Продолжить нельзя'],
        'title_rejected' => ['Request rejected', 'Запрос отклонён'],
        'title_busy' => ['Busy', 'Занято'],
        'title_confirm' => ['Install RET CMS — confirm access', 'Установка RET CMS — подтверждение доступа'],
        'title_plan' => ['Install RET CMS — check and plan', 'Установка RET CMS — проверка и план'],
        'title_progress' => ['Installing RET CMS {x} files', 'Раскладка файлов RET CMS {x}'],
        'title_failed' => ['Release check failed', 'Проверка релиза не пройдена'],
        'title_enabled' => ['RET CMS files are in place', 'Файлы RET CMS на месте'],
        'title_handoff' => ['Opening the installer…', 'Открываем установку…'],
        'title_cancelled' => ['Cancelled', 'Отменено'],
        'title_manual' => ['RET CMS is already here', 'RET CMS уже здесь'],
        'php_old' => ['RET CMS needs PHP 8.1 or newer, this site runs PHP {v}. Choose a newer PHP version in the hosting panel and open this page again.',
                      'RET CMS нужен PHP 8.1 или новее, а на сайте PHP {v}. Выберите новую версию PHP в панели хостинга и откройте страницу снова.'],
        'refuse_hint' => ['Nothing has been written to disk.', 'На диск ничего не записано.'],
        'req_root' => ['Put ret-setup.php into the root folder of the site (the web root) and open https://your-domain/ret-setup.php.',
                       'Положите ret-setup.php в корневую папку сайта (web-root) и откройте https://ваш-домен/ret-setup.php.'],
        'req_script' => ['The web server runs this file from a different folder than where it lies — this hosting configuration is not supported.',
                         'Веб-сервер выполняет файл не из той папки, где он лежит, — такая конфигурация хостинга не поддерживается.'],
        'req_docroot' => ['The file is not in the document root of the domain. Put it into the root folder of the site.',
                          'Файл лежит не в document root домена. Положите его в корневую папку сайта.'],
        'req_name' => ['The name of the site root folder is not supported (Latin letters, digits, . _ -; not site, var, tools…).',
                       'Имя корневой папки сайта не поддерживается (латиница, цифры, . _ -; не site, var, tools…).'],
        'req_diskroot' => ['The folder above the web root is the root of the disk — RET CMS keeps its private part there. Use a hosting account where the web root has its own parent folder.',
                           'Папка над web-root — корень диска, а там RET CMS держит приватную часть. Нужен хостинг, где у web-root своя родительская папка.'],
        'req_basedir' => ['PHP (open_basedir) has no access to the folder above the web root — RET CMS keeps config, data and tools there.',
                          'PHP (open_basedir) не видит папку над web-root — RET CMS держит там конфиг, данные и инструменты.'],
        'req_parent_name' => ['The folder above the web root is itself a public site folder. This domain is probably an addon domain inside another site — RET CMS needs a domain whose folder is not inside a public folder (planned for a later version).',
                              'Папка над web-root сама — публичная папка сайта. Похоже, домен — дополнительный внутри другого сайта; RET CMS нужен домен, чья папка не внутри публичной (будет в следующих версиях).'],
        'req_parent_site' => ['The folder above the web root contains site files (index.php, .htaccess…) — it is public or shared with another site. Private files of RET CMS cannot be hidden there.',
                              'В папке над web-root есть файлы сайта (index.php, .htaccess…) — она публичная или общая с другим сайтом. Спрятать там приватную часть RET CMS нельзя.'],
        'rejected' => ['The form is outdated or came from another site. Open the page again.', 'Форма устарела или пришла с чужого сайта. Откройте страницу заново.'],
        'busy' => ['Another step is running right now. Wait a few seconds and open the page again.', 'Сейчас выполняется другой шаг. Подождите несколько секунд и откройте страницу снова.'],
        'btn_back' => ['Back', 'Назад'],
        'btn_confirm' => ['Check', 'Проверить'],
        'btn_install' => ['Install files', 'Установить файлы'],
        'btn_continue' => ['Continue', 'Продолжить'],
        'btn_retry' => ['Try again', 'Повторить'],
        'btn_restart' => ['Start over', 'Начать заново'],
        'btn_cancel' => ['Cancel and remove', 'Отменить и убрать'],
        'btn_installer' => ['Open the installer', 'Открыть установку'],
        'btn_disable' => ['Roll back enabling', 'Откатить включение'],
        's0_intro' => ['This page installs RET CMS into this domain. First prove that you control the files of the site — nothing is written to disk before that.',
                       'Эта страница установит RET CMS на домен. Сначала подтвердите, что у вас есть доступ к файлам сайта, — до этого на диск ничего не пишется.'],
        's0_step1' => ['Create an <b>empty</b> file with exactly this name in the same folder as ret-setup.php (FTP or the file manager of the hosting):',
                       'Создайте <b>пустой</b> файл ровно с таким именем в той же папке, где лежит ret-setup.php (FTP или файловый менеджер хостинга):'],
        's0_step2' => ['Press «Check». The file will be removed automatically.', 'Нажмите «Проверить». Файл удалится сам.'],
        's0_facts' => ['What is here now', 'Что здесь сейчас'],
        's0_counts' => ['web root: {f} files and {d} folders besides ret-setup.php', 'web-root: файлов — {f}, папок — {d} (кроме ret-setup.php)'],
        's0_home_w' => ['the folder above the web root is writable', 'папка над web-root доступна на запись'],
        's0_home_nw' => ['the folder above the web root is not writable by PHP — installation will not be possible', 'папка над web-root недоступна PHP на запись — установить не получится'],
        's0_not_clean' => ['the web root is not empty — details after confirmation', 'web-root не пустой — подробности после подтверждения'],
        's0_journal' => ['An unfinished installation was found. Confirm access to continue it or to cancel it.', 'Найдена незавершённая установка. Подтвердите доступ, чтобы продолжить или отменить её.'],
        's0_why' => ['The file name is tied to this browser. Anyone else opening this page sees another name and cannot continue without access to your files.',
                     'Имя файла привязано к этому браузеру: кто-то другой увидит другое имя и без доступа к вашим файлам дальше не пройдёт.'],
        'confirm_missing' => ['The file {name} was not found next to ret-setup.php. Check the name and the folder.', 'Файл {name} рядом с ret-setup.php не найден. Проверьте имя и папку.'],
        'confirm_not_empty' => ['The file {name} is not empty — create an empty one.', 'Файл {name} не пустой — нужен пустой.'],
        'mkdir_fail' => ['Cannot create {p} above the web root. Give PHP write access to that folder.', 'Не создать {p} над web-root. Дайте PHP право записи в эту папку.'],
        'write_fail' => ['Cannot write {p}.', 'Не записать {p}.'],
        'journal_bad' => ['The journal of an earlier installation (var/setup/state.json) is from another version of ret-setup.php or is damaged. It can only be cancelled.',
                          'Журнал прежней установки (var/setup/state.json) — от другой версии ret-setup.php или повреждён. Его можно только отменить.'],
        'p_env' => ['Environment', 'Окружение'],
        'p_env_ok' => ['PHP, extensions, writing above and inside the web root, connection to retcms.com — everything is fine.', 'PHP, расширения, запись над web-root и в него, связь с retcms.com — всё в порядке.'],
        'p_web' => ['Web root {n}/', 'Web-root {n}/'],
        'p_web_empty' => ['empty', 'пусто'],
        'p_home' => ['Folder above the web root', 'Папка над web-root'],
        'p_release' => ['Release', 'Релиз'],
        'p_release_line' => ['RET CMS <b>{x}</b> ({d}), {kb} KB; signature verified: key {k} ({f}).', 'RET CMS <b>{x}</b> ({d}), {kb} КБ; подпись верна: ключ {k} ({f}).'],
        'p_blocked' => ['Installation is not possible until the problems above are fixed. Fix them and open the page again.', 'Установка невозможна, пока не устранены проблемы выше. Исправьте их и откройте страницу снова.'],
        'p_plan' => ['Plan', 'План'],
        'p_plan_private' => ['private part — next to the web root, in {h}:', 'приватная часть — рядом с web-root, в {h}:'],
        'p_plan_public' => ['public part — into {n}/:', 'публичная часть — в {n}/:'],
        'p_plan_index' => ['<code>index.php</code> last', '<code>index.php</code> — последним'],
        'p_plan_untouched' => ['the database, site/config.php and site/paths.php are written by the installer at the next step; nothing else is overwritten or removed',
                               'базу, site/config.php и site/paths.php запишет installer на следующем шаге; чужое не перезаписывается и не удаляется'],
        'p_htaccess' => ['.htaccess of the hosting', '.htaccess хостинга'],
        'ack_stubs' => ['Move the hosting placeholder page ({n}) to var/setup/backup/ (it can be restored).', 'Перенести страницу-заглушку хостинга ({n}) в var/setup/backup/ (её можно вернуть).'],
        'ack_htaccess' => ['Keep this .htaccess as it is and append the RET CMS block at the end (the original is saved to var/setup/backup/).',
                           'Сохранить этот .htaccess как есть и дописать в конец блок RET CMS (оригинал — в var/setup/backup/).'],
        'ack_htaccess_zone' => ['Keep this .htaccess; the RET CMS block in it will be replaced by the block of the release.', 'Сохранить этот .htaccess; блок RET CMS в нём заменится блоком релиза.'],
        'need_ack' => ['Tick the boxes to confirm the warnings.', 'Отметьте галочками, что предупреждения прочитаны.'],
        'test_base' => ['Test mode: releases from {u} (RET_SETUP_BASE).', 'Тестовый режим: релизы с {u} (RET_SETUP_BASE).'],
        'home_dir' => ['the folder above the web root', 'папке над web-root'],
        'no_ext' => ['PHP extensions missing: {e}. Enable them in the hosting panel (PHP settings).', 'Нет расширений PHP: {e}. Включите их в панели хостинга (настройки PHP).'],
        'no_http' => ['PHP cannot make HTTPS requests (no curl, and allow_url_fopen/openssl are off).', 'PHP не может делать HTTPS-запросы (нет curl, выключены allow_url_fopen/openssl).'],
        'probe_fail' => ['PHP cannot write to {p} ({e}).', 'PHP не может писать в {p} ({e}).'],
        'world_writable' => ['{p} is writable by everyone (permissions …7) — on shared hosting other accounts could change files. Set 755.',
                             '{p} доступна на запись всем (права …7) — на общем хостинге чужие аккаунты могли бы менять файлы. Поставьте 755.'],
        'w_owner' => ['PHP creates files as a different user than the owner of ret-setup.php — you may not be able to edit or delete them by FTP.',
                      'PHP создаёт файлы от другого пользователя, чем владелец ret-setup.php, — по FTP их может не получиться менять или удалить.'],
        'w_dev' => ['The web root and the folder above it are on different file systems — files will be copied instead of moved (slower, still safe).',
                    'Web-root и папка над ним на разных файловых системах — файлы будут копироваться, а не переноситься (дольше, но безопасно).'],
        'w_https' => ['The page is opened without HTTPS. The installer will require HTTPS on a public domain — enable an SSL certificate in the hosting panel.',
                      'Страница открыта без HTTPS. На публичном домене installer потребует HTTPS — включите SSL-сертификат в панели хостинга.'],
        'w_sibling' => ['Next to the web root there is another site folder ({n}) — make sure the folder above the web root belongs to this domain only.',
                        'Рядом с web-root есть папка другого сайта ({n}) — убедитесь, что папка над web-root принадлежит только этому домену.'],
        'i_met' => ['max_execution_time is {n} s — long steps may be cut off; they can be continued.', 'max_execution_time — {n} с: долгие шаги могут прерваться; их можно продолжить.'],
        'i_mem' => ['memory_limit is {n}.', 'memory_limit — {n}.'],
        'i_disk' => ['Free disk space: about {n} MB.', 'Свободно на диске: около {n} МБ.'],
        'transport' => ['Network: {e}. Try again later.', 'Сеть: {e}. Повторите позже.'],
        'tls' => ['secure connection to retcms.com failed ({e}). PHP needs a CA certificate bundle (curl.cainfo / openssl.cafile in php.ini).',
                  'не удалось защищённое соединение с retcms.com ({e}). PHP нужен набор корневых сертификатов (curl.cainfo / openssl.cafile в php.ini).'],
        'verify_stop' => ['The release did not pass verification: {e}. Installation is stopped — no other source and no «continue anyway».',
                          'Релиз не прошёл проверку: {e}. Установка остановлена — без другого источника и без «продолжить всё равно».'],
        'failed_hint' => ['Downloaded files were removed. You can start over (the same strict check) or cancel.', 'Скачанное удалено. Можно начать заново (та же строгая проверка) или отменить.'],
        'v_sig' => ['{n}: the signature does not match any release key of this ret-setup.php', '{n}: подпись не проходит ни одним ключом релизов этого ret-setup.php'],
        'v_not_in_index' => ['version {x} is not in index.json', 'версии {x} нет в index.json'],
        'v_yanked' => ['version {x} is withdrawn: {r}', 'версия {x} отозвана: {r}'],
        'v_latest_index' => ['latest.json and index.json disagree', 'latest.json и index.json не согласованы'],
        'v_old' => ['the release {x} is older than this ret-setup.php needs ({b}) — download a fresh ret-setup.php from retcms.com',
                    'релиз {x} старше, чем нужно этому ret-setup.php ({b}), — скачайте свежий ret-setup.php с retcms.com'],
        'v_meta_sum' => ['metadata of {x}: SHA-256 differs from index.json', 'метаданные {x}: SHA-256 не совпадает с index.json'],
        'v_php' => ['RET CMS {x} needs PHP {p}+, this site runs {v}', 'RET CMS {x} нужен PHP {p}+, а здесь {v}'],
        'v_archive_sum' => ['archive ret-cms-{x}.zip: SHA-256 or size differs from the signed metadata', 'архив ret-cms-{x}.zip: SHA-256 или размер не совпадают с подписанными метаданными'],
        'v_size' => ['{u} is larger than expected', '{u} больше ожидаемого'],
        'v_pinned' => ['the installation was started with RET CMS {x}', 'установка начата с RET CMS {x}'],
        'v_release_json' => ['deploy/release.json differs from the signed metadata', 'deploy/release.json не совпадает с подписанными метаданными'],
        'v_stage_set' => ['unpacked archive differs from release.json ({n} files):', 'распакованный архив не совпадает с release.json (файлов: {n}):'],
        'v_stage_sum' => ['file {p} differs from release.json', 'файл {p} не совпадает с release.json'],
        'restage' => ['Part of the unpacked release is missing — it is unpacked again from the verified archive.', 'Части распакованного релиза нет — она распаковывается заново из проверенного архива.'],
        'restart_placed' => ['Files are already in place — cancel first (it removes only RET CMS files), then start again.', 'Файлы уже разложены — сначала отмените (уберёт только файлы RET CMS), потом начните заново.'],
        'preflight_failed' => ['The environment check is not passed — open the page again to see why.', 'Проверка окружения не пройдена — откройте страницу снова, чтобы увидеть причину.'],
        'not_clean' => ['The web root or the folder above it contains something that is not expected:', 'В web-root или в папке над ним есть то, чего там быть не должно:'],
        'placed_changed' => ['{p} has changed after it was placed.', '{p} изменился после раскладки.'],
        'stub_changed' => ['The placeholder page {n} has changed since the plan — open the page again.', 'Страница-заглушка {n} изменилась после плана — откройте страницу заново.'],
        'htaccess_changed' => ['.htaccess has changed since the plan — open the page again.', '.htaccess изменился после плана — откройте страницу заново.'],
        'htaccess_zone_bad' => ['.htaccess: {r}', '.htaccess: {r}'],
        'exists_differs' => ['{p} already exists and is not the file of this release — it is not overwritten.', '{p} уже есть и это не файл этого релиза — не перезаписывается.'],
        'verify_failed' => ['Placed files differ from the release ({n}):', 'Разложенные файлы не совпадают с релизом ({n}):'],
        'enabling_next' => ['Next: enabling — the placeholder page is moved to backup, .htaccess gets the RET CMS block, index.php is placed last.',
                            'Дальше — включение: заглушка в backup, в .htaccess — блок RET CMS, index.php — последним.'],
        'enabled' => ['RET CMS {x} files are in place and match the signed release.', 'Файлы RET CMS {x} на месте и совпадают с подписанным релизом.'],
        'bc_wait' => ['Checking how the server answers the home page…', 'Проверяем, как сервер отвечает на главную…'],
        'bc_ok' => ['The server answers correctly: the home page leads to the installer.', 'Сервер отвечает правильно: главная ведёт на установку.'],
        'bc_bad' => ['The home page answers with status {s} instead of a redirect to /install/. The server may not accept .htaccess (e.g. «Options» is forbidden) — see the error log of the hosting.',
                     'Главная отвечает кодом {s} вместо перехода на /install/. Возможно, сервер не принимает .htaccess (например, запрещён «Options») — смотрите журнал ошибок хостинга.'],
        'bc_fail' => ['You can roll back enabling (index.php is removed, .htaccess and the placeholder are restored), fix the server and enable again, or continue anyway.',
                      'Можно откатить включение (index.php убирается, .htaccess и заглушка возвращаются), поправить сервер и включить снова — или продолжить как есть.'],
        'disabled' => ['Enabling is rolled back: index.php removed, .htaccess and the placeholder restored. «Continue» enables again.',
                       'Включение откачено: index.php убран, .htaccess и заглушка восстановлены. «Продолжить» включит снова.'],
        'handoff_go' => ['Access is passed to the RET CMS installer — it opens now.', 'Доступ передаётся установщику RET CMS — он сейчас откроется.'],
        'handed' => ['Files are in place and the installer was opened. If it asked for a code, open it again from here.', 'Файлы на месте, установка открывалась. Если она попросила код — откройте её отсюда снова.'],
        'handed_delete' => ['ret-setup.php could not delete itself — delete it by FTP after the installation.', 'ret-setup.php не смог удалить себя — удалите его по FTP после установки.'],
        'cancelled' => ['Cancelled: the files of RET CMS and the setup journal are removed, .htaccess and the placeholder are restored.',
                        'Отменено: файлы RET CMS и журнал установки убраны, .htaccess и заглушка восстановлены.'],
        'cancelled_left' => ['Cancelled, but some items were left because they differ from the release (they are not removed):', 'Отменено, но часть оставлена — она отличается от релиза (такое не удаляется):'],
        'cancelled_next' => ['Delete ret-setup.php by FTP, or open it again to start over.', 'Удалите ret-setup.php по FTP или откройте его снова, чтобы начать заново.'],
        'cancel_unverified' => ['the downloaded release could not be verified — placed files were not removed', 'скачанный релиз не проверить — разложенное не удалялось'],
        'manual' => ['The files of RET CMS are already in this web root. Nothing is written here — open the installer.', 'Файлы RET CMS уже в этом web-root. Здесь ничего не пишется — откройте установку.'],
        's_access' => ['access', 'доступ'], 's_download' => ['download', 'загрузка'], 's_verify' => ['check', 'проверка'], 's_stage' => ['unpack', 'распаковка'],
        's_private' => ['private part', 'приватная часть'], 's_public' => ['public part', 'публичная часть'], 's_enable' => ['enable', 'включение'],
        'scandir_fail' => ['the web root cannot be listed', 'web-root не прочитать'],
        'r_item' => ['{n} — {w}.', '{n} — {w}.'],
        'r_home' => ['{n} already exists above the web root — config and data are never overwritten or reused; move it away by hand.',
                     '{n} уже есть над web-root — конфиг и данные не перезаписываются и не переиспользуются; перенесите вручную.'],
        'r_core' => ['{n}/ next to the web root contains another RET CMS core — remove or move it.', '{n}/ рядом с web-root содержит другое ядро RET CMS — уберите или перенесите его.'],
        'e_link' => ['symbolic link — not allowed', 'символическая ссылка — нельзя'],
        'e_self' => ['this file', 'этот файл'],
        'e_challenge' => ['confirmation file', 'файл подтверждения'],
        'e_bad_setup' => ['unknown ret-setup file (not empty or wrong name)', 'непонятный файл ret-setup (не пустой или неверное имя)'],
        'e_wellknown' => ['kept (certificates)', 'остаётся (сертификаты)'],
        'e_cgibin' => ['empty, kept', 'пустой, остаётся'],
        'e_hosting' => ['hosting file, kept', 'файл хостинга, остаётся'],
        'e_ours' => ['placed by this setup', 'разложено этой установкой'],
        'e_htaccess' => ['kept; the RET CMS block is appended', 'остаётся; дописывается блок RET CMS'],
        'e_htaccess_zone' => ['kept; the RET CMS block is replaced', 'остаётся; блок RET CMS заменяется'],
        'e_php' => ['PHP file — another application; RET CMS is installed only into an empty web root', 'PHP-файл — другое приложение; RET CMS ставится только в пустой web-root'],
        'e_dir' => ['folder — not allowed in a clean web root', 'папка — в чистом web-root нельзя'],
        'e_unknown' => ['unknown file — not allowed in a clean web root', 'неизвестный файл — в чистом web-root нельзя'],
        'e_retcms' => ['file of RET CMS from another attempt — remove it or use the installer', 'файл RET CMS от другой попытки — уберите его или используйте установку'],
        'e_stub' => ['hosting placeholder — moved to backup', 'заглушка хостинга — переносится в backup'],
        'e_stub_many' => ['more than two placeholder pages', 'страниц-заглушек больше двух'],
        'e_stub_new' => ['appeared after the plan', 'появился после плана'],
        'h_big' => ['.htaccess larger than 64 KB', '.htaccess больше 64 КБ'],
        'h_binary' => ['.htaccess is not text', '.htaccess — не текст'],
        'h_zone_broken' => ['RET CMS markers in .htaccess are damaged', 'маркеры RET CMS в .htaccess повреждены'],
        'h_foreign' => ['.htaccess has a block of another product ({m})', 'в .htaccess блок другого продукта ({m})'],
        'h_frontctl' => ['.htaccess sends requests to another index.php (RewriteRule)', '.htaccess направляет запросы на чужой index.php (RewriteRule)'],
        's_big' => ['larger than 64 KB — not a placeholder', 'больше 64 КБ — не заглушка'],
        's_binary' => ['not text', 'не текст'],
        's_not_html' => ['does not look like an HTML placeholder', 'не похоже на HTML-заглушку'],
        's_form' => ['has a form or PHP — not a placeholder', 'есть форма или PHP — не заглушка'],
        's_local' => ['refers to local files ({u}) — not a placeholder', 'ссылается на локальные файлы ({u}) — не заглушка'],
    ];
}

RetSetup::main();
