#!/usr/bin/env php
<?php
/**
 * zenith-shell — the only door Zenith's SSH key opens.
 *
 * Installed as the forced command of that key in ~/.ssh/authorized_keys,
 * it replaces whatever Zenith asks by one of a handful of verbs: describe
 * the machine, read the site's inventory, diagnose a site that no longer
 * answers, read its error log, and — only when this file's configuration
 * allows it — carry out a few remediation actions or an update.
 *
 * Zenith always sends one argument: a base64 JSON request. Everything in it
 * is checked here; nothing in it is ever handed to a shell.
 *
 * Verbs: describe, inventory, diagnostic, log, audit, integrity, weblogs,
 * put, control, update. The first seven only read; the last three need the
 * configuration below to say yes.
 *
 * Configuration, first file found (or the file named by ZENITH_SHELL_CONF):
 *   ~/.config/zenith/shell.conf
 *   /etc/zenith/shell.conf
 * with lines such as:
 *   control=yes      allow cache flush, plugin on/off, cron, maintenance
 *   update=yes       allow updates through wp-cli
 *   self_update=yes  allow install_shell alone: Zenith may replace this script
 *                    (and nothing else) where control stays closed
 *   wp=/usr/local/bin/wp
 *   php=/usr/bin/php8.2
 *   shell=/usr/local/bin/zenith-shell   where install_shell writes the new copy
 *   weblogs=system   also read /var/log/apache2, /var/log/nginx, /var/log/httpd
 *   log=file         write the request log to ~/.zenith/shell.log even when syslog works
 *
 * Every request leaves one line in syslog (facility auth, ident zenith-shell)
 * or, where syslog is not available, in ~/.zenith/shell.log.
 *
 * Runs on PHP 7.4 and later. Answers in JSON on stdout, exit 0; on refusal
 * or failure, JSON with ok:false and a non-zero exit. Every list is capped,
 * every child process is bounded by the deadline the request carries, and
 * nothing from the request is ever interpreted by a shell.
 */

define('ZENITH_SHELL_VERSION', '1.13.0');

// The wp-cli release install_wpcli fetches, and the SHA-512 its authors
// published for it: both move together, at each new release of wp-cli.
define('ZENITH_WPCLI_VERSION', '2.12.0');
define('ZENITH_WPCLI_SHA512', 'be928f6b8ca1e8dfb9d2f4b75a13aa4aee0896f8a9a0a1c45cd5d2c98605e6172e6d014dda2e27f88c98befc16c040cbb2bd1bfa121510ea5cdf5f6a30fe8832');

// File transfer (verb put): what one transfer may weigh in all, per piece,
// and how long an unfinished one is kept before being swept.
define('ZENITH_PUT_MAX_BYTES', 32 * 1024 * 1024);
define('ZENITH_PUT_CHUNK_MAX_BYTES', 256 * 1024);
define('ZENITH_PUT_MAX_CHUNKS', 1024);
define('ZENITH_PUT_STALE_SECONDS', 3600);

// The audit and the integrity walk have a budget, told by Zenith in the
// request, with a default and a ceiling of their own.
define('ZENITH_DEADLINE_DEFAULT', 480);
define('ZENITH_DEADLINE_MAX', 900);

// Lists never grow past this: find is cut by head, and the answer says so.
define('ZENITH_FIND_MAX_LINES', 2000);

// The integrity report names at most this many files, all sections taken
// together: the answer must still fit in one SSH exchange.
define('ZENITH_INTEGRITY_MAX_FILES', 30000);

// The maintenance page is never left up by accident: WordPress drops it
// ten minutes after the stamp, and the stamp is set two hours ahead at most.
define('ZENITH_MAINTENANCE_MAX_SECONDS', 7200);
define('ZENITH_MAINTENANCE_GRACE_SECONDS', 600);

// Cron: one hook may not hold the run longer than this, and the whole run
// stops handing out hooks past the budget.
define('ZENITH_CRON_HOOK_SECONDS', 30);
define('ZENITH_CRON_BUDGET_SECONDS', 150);

// The request log written next to the snapshots, rotated once, at 1 MB.
define('ZENITH_LOG_MAX_BYTES', 1024 * 1024);

// Snapshots kept per plugin: enough to go back, not enough to fill a disk.
define('ZENITH_SNAPSHOTS_KEPT', 3);

main(isset($argv) ? $argv : []);

/**
 * @param string[] $argv
 */
function main(array $argv)
{
    $GLOBALS['zenith_started'] = microtime(true);
    $GLOBALS['zenith_log'] = ['verb' => '-', 'action' => '-', 'actor' => '-', 'path' => '-'];
    $GLOBALS['zenith_config'] = null;
    $original = getenv('SSH_ORIGINAL_COMMAND');
    $restricted = false;

    if (count($argv) < 2 && is_string($original) && '' !== trim($original)) {
        // Forced command: what Zenith typed is in the environment, and the
        // key can do nothing but reach this line.
        $restricted = true;
        $parts = preg_split('/\s+/', trim($original)) ?: [];

        if (isset($parts[0]) && 'zenith-shell' === basename($parts[0])) {
            array_shift($parts);
        }

        $token = isset($parts[0]) ? $parts[0] : '';
    } else {
        $token = isset($argv[1]) ? $argv[1] : '';
    }

    if ('--version' === $token) {
        echo ZENITH_SHELL_VERSION, "\n";
        exit(0);
    }

    $request = decode_request($token);

    if (null === $request) {
        refuse('requête illisible : un seul argument attendu, JSON en base64', 2);
    }

    $config = load_config();
    $GLOBALS['zenith_config'] = $config;
    $verb = isset($request['verb']) && is_string($request['verb']) ? $request['verb'] : '';
    $GLOBALS['zenith_log'] = [
        'verb' => '' === $verb ? '-' : $verb,
        'action' => isset($request['action']) && is_string($request['action']) && '' !== $request['action'] ? $request['action'] : '-',
        'actor' => null !== actor($request) ? actor($request) : '-',
        'path' => isset($request['path']) && is_string($request['path']) && '' !== $request['path'] ? $request['path'] : '-',
    ];
    set_deadline($request);
    // The path of the site's public address: a multisite by path answers
    // for another blog on every other path (see wp_bootstrap).
    $GLOBALS['zenith_site_uri'] = site_uri($request);

    try {
        switch ($verb) {
            case 'describe':
                $data = verb_describe($request, $config, $restricted);
                break;
            case 'inventory':
                $data = verb_inventory($request, $config);
                break;
            case 'diagnostic':
                $data = verb_diagnostic($request, $config);
                break;
            case 'log':
                $data = verb_log($request);
                break;
            case 'audit':
                $data = verb_audit($request, $config);
                break;
            case 'integrity':
                $data = verb_integrity($request, $config);
                break;
            case 'weblogs':
                $data = verb_weblogs($request, $config);
                break;
            case 'put':
                $data = verb_put($request, $config);
                break;
            case 'control':
                $data = verb_control($request, $config);
                break;
            case 'update':
                $data = verb_update($request, $config);
                break;
            case 'updates':
                $data = verb_updates($request, $config);
                break;
            case 'git':
                $data = verb_git($request, $config);

                // Composer's tree follows the lock Git just moved (1.11.0).
                if (is_drupal_request($request) && isset($request['action'], $data['status']) && in_array($request['action'], ['checkout', 'pull', 'reset', 'discard'], true) && 'ok' === $data['status']) {
                    $data['vendor'] = drupal_sync_vendor($request, $config);
                } elseif (is_symfony_request($request) && isset($request['action'], $data['status']) && in_array($request['action'], ['checkout', 'pull', 'reset', 'discard'], true) && 'ok' === $data['status']) {
                    $data['vendor'] = symfony_sync_vendor($request, $config);
                }

                break;
            case 'db':
                $data = verb_db($request, $config);
                break;
            case 'verify':
                $data = verb_verify($request, $config);
                break;
            default:
                refuse(sprintf('verbe inconnu : %s', $verb), 2);
                return;
        }
    } catch (RuntimeException $e) {
        refuse($e->getMessage(), 1);
        return;
    }

    request_log(0);
    echo json_encode(['ok' => true, 'verb' => $verb, 'shell' => ZENITH_SHELL_VERSION, 'data' => $data], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PARTIAL_OUTPUT_ON_ERROR), "\n";
    exit(0);
}

function refuse($message, $code)
{
    request_log($code, $message);
    echo json_encode(['ok' => false, 'shell' => ZENITH_SHELL_VERSION, 'error' => $message], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), "\n";
    exit($code);
}

// ------------------------------------------------------------ request log

/**
 * One line per request, whatever its outcome: the verb and action, who
 * asked, on which path, the exit code and how long it took. Written to
 * syslog under the auth facility, where a host's login trail already is;
 * where syslog cannot be reached, or when the configuration says so, to
 * ~/.zenith/shell.log, rotated once at ZENITH_LOG_MAX_BYTES so a busy
 * fleet never fills a home directory with its own audit trail.
 */
function request_log($code, $error = null)
{
    $context = isset($GLOBALS['zenith_log']) && is_array($GLOBALS['zenith_log']) ? $GLOBALS['zenith_log'] : [];
    $started = isset($GLOBALS['zenith_started']) ? (float) $GLOBALS['zenith_started'] : microtime(true);
    $config = isset($GLOBALS['zenith_config']) && is_array($GLOBALS['zenith_config']) ? $GLOBALS['zenith_config'] : null;
    $field = function ($key) use ($context) {
        $value = isset($context[$key]) && is_string($context[$key]) ? $context[$key] : '-';

        return str_cut((string) preg_replace('/[\s"]+/', '_', $value), 0, 200);
    };
    $line = sprintf(
        'verb=%s action=%s actor=%s path=%s code=%d duration=%.2f%s',
        $field('verb'),
        $field('action'),
        $field('actor'),
        $field('path'),
        (int) $code,
        microtime(true) - $started,
        null === $error ? '' : ' error="' . str_cut((string) preg_replace('/[\s"]+/', ' ', (string) $error), 0, 200) . '"'
    );

    $toFile = null !== $config && isset($config['log']) && 'file' === $config['log'];

    if (!$toFile && function_exists('openlog') && function_exists('syslog') && @openlog('zenith-shell', LOG_PID, LOG_AUTH)) {
        $sent = @syslog(LOG_INFO, $line);
        closelog();

        if ($sent) {
            return;
        }
    }

    $file = zenith_home() . '/.zenith/shell.log';
    $dir = dirname($file);

    if (!is_dir($dir) && !@mkdir($dir, 0700, true)) {
        return;
    }

    if (is_file($file) && filesize($file) > ZENITH_LOG_MAX_BYTES) {
        @rename($file, $file . '.1');
    }

    @file_put_contents($file, gmdate('Y-m-d\TH:i:s\Z') . ' ' . $line . "\n", FILE_APPEND | LOCK_EX);
}

/**
 * Where the shell keeps its own files: the home of the account, or the
 * temporary directory when the environment names none.
 */
function zenith_home()
{
    $home = getenv('HOME');

    return is_string($home) && '' !== $home ? rtrim($home, '/') : sys_get_temp_dir();
}

// ---------------------------------------------------------------- deadline

/**
 * The whole request has one budget, told by Zenith so that both sides
 * agree on when to give up: past it, every child process is cut short
 * rather than left running after the connection is gone.
 */
function set_deadline(array $request)
{
    $seconds = isset($request['deadline']) && is_int($request['deadline']) && $request['deadline'] > 0 ? min(ZENITH_DEADLINE_MAX, $request['deadline']) : ZENITH_DEADLINE_DEFAULT;
    $GLOBALS['zenith_deadline'] = (isset($GLOBALS['zenith_started']) ? (float) $GLOBALS['zenith_started'] : microtime(true)) + $seconds;
}

/**
 * How many seconds a step may take: what it asks for, or what is left of
 * the request's budget, whichever is smaller — never less than one, so a
 * step past the deadline still gets to fail cleanly.
 */
function budget($seconds)
{
    if (!isset($GLOBALS['zenith_deadline'])) {
        return (int) $seconds;
    }

    return max(1, min((int) $seconds, (int) floor((float) $GLOBALS['zenith_deadline'] - microtime(true))));
}

function out_of_time()
{
    return isset($GLOBALS['zenith_deadline']) && microtime(true) >= (float) $GLOBALS['zenith_deadline'];
}

/**
 * @return array<string, mixed>|null
 */
function decode_request($token)
{
    if (!is_string($token)) {
        return null;
    }

    // Under a forced command the line arrives as typed, quotes included:
    // the argument Zenith wraps in single quotes must be unwrapped here.
    $token = trim($token, " \t'\"");

    if ('' === $token || !preg_match('/^[A-Za-z0-9+\/=_-]+$/', $token)) {
        return null;
    }

    $json = base64_decode(strtr($token, '-_', '+/'), true);

    if (false === $json) {
        return null;
    }

    $request = json_decode($json, true);

    return is_array($request) ? $request : null;
}

/**
 * @return array{file: ?string, control: bool, update: bool, wp: ?string, php: string, shell: ?string, weblogs_system: bool, log: string}
 */
function load_config()
{
    $home = getenv('HOME');
    $candidates = [];
    $named = getenv('ZENITH_SHELL_CONF');

    // A file named by the environment comes first: how a test, or a host
    // with an unusual layout, points the shell at its configuration.
    if (is_string($named) && '' !== $named) {
        $candidates[] = $named;
    }

    if (is_string($home) && '' !== $home) {
        $candidates[] = $home . '/.config/zenith/shell.conf';
    }

    $candidates[] = '/etc/zenith/shell.conf';
    $config = ['file' => null, 'control' => false, 'update' => false, 'self_update' => false, 'wp' => null, 'php' => PHP_BINARY ?: 'php', 'shell' => null, 'weblogs_system' => false, 'log' => 'auto'];

    foreach ($candidates as $file) {
        if (!is_readable($file)) {
            continue;
        }

        $config['file'] = $file;

        foreach (file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $line) {
            $line = trim($line);

            if ('' === $line || '#' === $line[0] || false === strpos($line, '=')) {
                continue;
            }

            list($key, $value) = array_map('trim', explode('=', $line, 2));

            switch (strtolower($key)) {
                case 'control':
                    $config['control'] = is_yes($value);
                    break;
                case 'update':
                    $config['update'] = is_yes($value);
                    break;
                case 'self_update':
                    $config['self_update'] = is_yes($value);
                    break;
                case 'wp':
                    $config['wp'] = '' === $value ? null : $value;
                    break;
                case 'php':
                    $config['php'] = '' === $value ? $config['php'] : $value;
                    break;
                case 'shell':
                    $config['shell'] = '' === $value ? null : $value;
                    break;
                case 'weblogs':
                    $config['weblogs_system'] = 'system' === strtolower($value);
                    break;
                case 'log':
                    $config['log'] = 'file' === strtolower($value) ? 'file' : 'auto';
                    break;
            }
        }

        break;
    }

    return $config;
}

function is_yes($value)
{
    return in_array(strtolower((string) $value), ['1', 'yes', 'on', 'true', 'oui'], true);
}

// ---------------------------------------------------------------- helpers

/**
 * Runs a program with arguments, never through a shell, and waits for it
 * up to the given number of seconds — or up to the request's deadline,
 * whichever comes first.
 *
 * The command is handed to proc_open as an array: each element reaches
 * the program as one argument, whatever it holds, so nothing here needs
 * quoting and nothing can be misread as an option separator by a shell.
 *
 * @param string[] $command
 * @return array{exit: int, stdout: string, stderr: string, seconds: float, timeout: bool}
 */
function run(array $command, $timeout = 60, $cwd = null, $stdin = null, array $env = null)
{
    $timeout = budget($timeout);
    $spec = [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
    // A secret handed to a child goes through its environment, which only
    // the same user and root can read, never through the command line,
    // which every process on the machine can list.
    $environment = null === $env ? null : array_merge(environment(), $env);
    $process = proc_open(array_values(array_map('strval', $command)), $spec, $pipes, $cwd, $environment);

    if (!is_resource($process)) {
        return ['exit' => 255, 'stdout' => '', 'stderr' => 'proc_open indisponible', 'seconds' => 0.0, 'timeout' => false];
    }

    if (null !== $stdin) {
        fwrite($pipes[0], $stdin);
    }

    fclose($pipes[0]);
    stream_set_blocking($pipes[1], false);
    stream_set_blocking($pipes[2], false);

    $started = microtime(true);
    $stdout = '';
    $stderr = '';
    $timedOut = false;

    while (true) {
        $stdout .= (string) stream_get_contents($pipes[1]);
        $stderr .= (string) stream_get_contents($pipes[2]);
        $status = proc_get_status($process);

        if (!$status['running']) {
            break;
        }

        if (microtime(true) - $started > $timeout) {
            proc_terminate($process, 9);
            $timedOut = true;
            break;
        }

        usleep(50000);
    }

    $stdout .= (string) stream_get_contents($pipes[1]);
    $stderr .= (string) stream_get_contents($pipes[2]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    $exit = proc_close($process);

    if (isset($status) && !$status['running'] && isset($status['exitcode']) && -1 !== $status['exitcode']) {
        $exit = $status['exitcode'];
    }

    return ['exit' => $timedOut ? 124 : (int) $exit, 'stdout' => $stdout, 'stderr' => $stderr, 'seconds' => round(microtime(true) - $started, 2), 'timeout' => $timedOut];
}

/**
 * The site directory, checked before anything runs from it: it must exist
 * and hold the framework it claims to.
 */
/**
 * The environment as the shell got it, for a child that needs one more
 * variable: proc_open replaces the whole environment when given one.
 *
 * @return array<string, string>
 */
function environment()
{
    $env = [];

    foreach ($_SERVER as $key => $value) {
        if (is_string($key) && is_string($value) && false !== getenv($key)) {
            $env[$key] = $value;
        }
    }

    return $env;
}

function site_path(array $request, $required = true)
{
    $path = isset($request['path']) && is_string($request['path']) ? $request['path'] : '';

    if ('' === $path) {
        if ($required) {
            throw new RuntimeException('chemin du site manquant dans la requête');
        }

        return null;
    }

    $real = realpath($path);

    if (false === $real || !is_dir($real)) {
        throw new RuntimeException(sprintf('chemin introuvable : %s', $path));
    }

    return rtrim($real, '/');
}

function framework(array $request)
{
    $framework = isset($request['framework']) && is_string($request['framework']) ? strtolower($request['framework']) : 'wordpress';

    if (!in_array($framework, ['wordpress', 'drupal'], true)) {
        throw new RuntimeException(sprintf('framework non pris en charge par ce shell : %s', $framework));
    }

    return $framework;
}

function is_wordpress($path)
{
    return null !== $path && (is_file($path . '/wp-load.php') || is_file($path . '/wp-config.php'));
}

function site_host(array $request)
{
    $host = isset($request['host']) && is_string($request['host']) ? $request['host'] : 'localhost';

    return preg_match('/^[A-Za-z0-9.\-:]+$/', $host) ? $host : 'localhost';
}

/**
 * The path under which the site answers, always with a trailing slash:
 * "/" for a site at the root of its host, "/blog/" for a sub-directory
 * site of a multisite by path. Anything that is not a plain path is read
 * as the root rather than handed to WordPress.
 */
function site_uri(array $request)
{
    $uri = isset($request['url_path']) && is_string($request['url_path']) ? $request['url_path'] : '/';

    if (!preg_match('#^/[A-Za-z0-9._~/-]*$#', $uri) || false !== strpos($uri, '..')) {
        return '/';
    }

    $trimmed = trim($uri, '/');

    return '' === $trimmed ? '/' : '/' . $trimmed . '/';
}

/**
 * A short list of clean strings taken from the request: plugin slugs or
 * plugin files. A leading dash is refused because the items end on a
 * wp-cli command line, where it would read as an option; a ".." is
 * refused because they also name directories under wp-content/plugins.
 *
 * @return string[]
 */
function items(array $request, $key = 'items')
{
    $items = isset($request[$key]) && is_array($request[$key]) ? $request[$key] : [];
    $clean = [];

    foreach ($items as $item) {
        if (is_string($item) && is_clean_slug($item, 120)) {
            $clean[] = $item;
        }
    }

    return array_values(array_unique($clean));
}

/**
 * Whether a string can safely name a plugin, a file under it, or a
 * snapshot: letters, digits, dots, underscores, dashes and slashes, not
 * starting with a dash, with no ".." anywhere.
 */
function is_clean_slug($value, $maxLength = 120)
{
    return is_string($value)
        && strlen($value) <= $maxLength
        && 1 === preg_match('/^[A-Za-z0-9._][A-Za-z0-9._\/-]*$/', $value)
        && false === strpos($value, '..');
}

/**
 * mb_substr where the mbstring extension is loaded, substr where it is
 * not: a host without mbstring must still get its answers, cut a little
 * roughly in the middle of a multibyte character at worst.
 */
function str_cut($text, $start, $length)
{
    return function_exists('mb_substr') ? mb_substr((string) $text, $start, $length) : substr((string) $text, $start, $length);
}

function actor(array $request)
{
    $actor = isset($request['actor']) && is_string($request['actor']) ? trim($request['actor']) : '';

    return '' === $actor ? null : str_cut($actor, 0, 60);
}

function tool_version(array $command, $pattern)
{
    $result = run($command, 15);

    // A PHP built with --enable-sigchild (OVH's /usr/local/phpX.Y/bin/php)
    // gives no exit code: run() answers -1 though the tool has spoken. Its
    // word is then taken only where the pattern recognises a version, never
    // as a first line read on trust (1.12.3). Until then install_shell
    // discarded every shell it received on such a machine, « annonce rien ».
    $silent = -1 === $result['exit'] && empty($result['timeout']);

    if ((0 !== $result['exit'] && !$silent) || '' === trim($result['stdout'])) {
        return null;
    }

    if (preg_match($pattern, $result['stdout'], $m)) {
        return $m[1];
    }

    return $silent ? null : trim(strtok($result['stdout'], "\n"));
}

function which($binary)
{
    $result = run(['sh', '-c', 'command -v ' . escapeshellarg($binary)], 5);

    return 0 === $result['exit'] ? trim($result['stdout']) : null;
}

/**
 * The wp-cli this machine has, as the start of a command line, or null:
 * the configured path first, then the PATH and the usual places, then a
 * wp-cli.phar left at the site, at its docroot or in the home — the way
 * a shared host without a global binary carries it.
 *
 * @return string[]|null
 */
function wp_binary(array $config, $path = null)
{
    $candidates = [];

    if (null !== $config['wp']) {
        $candidates[] = $config['wp'];
    }

    $found = which('wp');

    if (null !== $found) {
        $candidates[] = $found;
    }

    $home = getenv('HOME');

    if (is_string($home) && '' !== $home) {
        $candidates[] = $home . '/bin/wp';
        $candidates[] = $home . '/.local/bin/wp';
    }

    $candidates[] = '/usr/local/bin/wp';

    if (null !== $path) {
        $dir = $path;

        for ($i = 0; $i < 4; ++$i) {
            $candidates[] = $dir . '/wp-cli.phar';
            $parent = dirname($dir);

            if ($parent === $dir) {
                break;
            }

            $dir = $parent;
        }
    }

    if (is_string($home) && '' !== $home) {
        $candidates[] = $home . '/wp-cli.phar';
        $candidates[] = $home . '/bin/wp-cli.phar';
    }

    foreach ($candidates as $candidate) {
        if (!is_file($candidate)) {
            continue;
        }

        // A phar, or anything not executable by itself, runs through PHP.
        if ('phar' === strtolower((string) pathinfo($candidate, PATHINFO_EXTENSION)) || !is_executable($candidate)) {
            return [$config['php'], $candidate];
        }

        return [$candidate];
    }

    return null;
}

/**
 * Composer as a global binary, or as a composer.phar left at the site, at
 * its docroot or in the home, run through PHP.
 */
function composer_version(array $config, $path)
{
    $version = tool_version(['composer', '--version', '--no-ansi'], '/Composer(?: version)?\s+([0-9][0-9a-z.\-]*)/i');

    if (null !== $version) {
        return $version;
    }

    $candidates = [];
    $dir = $path;

    for ($i = 0; null !== $dir && $i < 4; ++$i) {
        $candidates[] = $dir . '/composer.phar';
        $parent = dirname($dir);

        if ($parent === $dir) {
            break;
        }

        $dir = $parent;
    }

    $home = getenv('HOME');

    if (is_string($home) && '' !== $home) {
        $candidates[] = $home . '/composer.phar';
        $candidates[] = $home . '/bin/composer.phar';
        $candidates[] = $home . '/bin/composer';
    }

    foreach ($candidates as $candidate) {
        if (is_file($candidate)) {
            return tool_version([$config['php'], $candidate, '--version', '--no-ansi'], '/Composer(?: version)?\s+([0-9][0-9a-z.\-]*)/i');
        }
    }

    return null;
}

function tail_lines($file, $lines = 40, $maxBytes = 262144)
{
    if (!is_file($file) || !is_readable($file)) {
        return null;
    }

    $size = filesize($file);
    $handle = fopen($file, 'r');

    if (false === $handle) {
        return null;
    }

    fseek($handle, max(0, $size - $maxBytes));
    $chunk = (string) stream_get_contents($handle);
    fclose($handle);

    $all = preg_split('/\R/', rtrim($chunk)) ?: [];

    return array_values(array_slice($all, -$lines));
}

/**
 * Bootstraps WordPress in a child process and runs a snippet in it, so a
 * site that dies on load kills the child and not this shell — and says why.
 *
 * @return array{ok: bool, output: string, error: ?string, seconds: float, json: mixed}
 */
function wp_bootstrap($path, $host, $code, array $config, $timeout = 90)
{
    // A multisite by path picks the blog from the request path: the site
    // is asked for under its own address, not under the root of its host.
    $uri = isset($GLOBALS['zenith_site_uri']) && is_string($GLOBALS['zenith_site_uri']) ? $GLOBALS['zenith_site_uri'] : '/';

    // Page caches (WP Rocket, W3TC, Super Cache) hook in through WP_CACHE
    // and advanced-cache.php, and would answer with the cached home page
    // and exit before the snippet runs: the cache is switched off for this
    // process, and the request made one no cache would serve anyway.
    $script = '<?php'
        . ' error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED); ini_set("display_errors", "stderr");'
        . ' define("WP_USE_THEMES", false); define("ZENITH_SSH", true); define("WP_CACHE", false); define("DONOTCACHEPAGE", true); define("DONOTCACHEOBJECT", false);'
        . ' $_SERVER["HTTP_HOST"] = ' . var_export($host, true) . ';'
        . ' $_SERVER["SERVER_NAME"] = ' . var_export($host, true) . ';'
        . ' $_SERVER["REQUEST_URI"] = ' . var_export($uri . '?zenith-shell=1&nowprocket=1', true) . '; $_SERVER["QUERY_STRING"] = "zenith-shell=1&nowprocket=1"; $_GET = ["zenith-shell" => "1", "nowprocket" => "1"];'
        . ' $_SERVER["REQUEST_METHOD"] = "GET"; $_SERVER["SERVER_PORT"] = 443; $_SERVER["HTTPS"] = "on"; $_SERVER["HTTP_USER_AGENT"] = "zenith-shell";'
        . ' chdir(' . var_export($path, true) . ');'
        . ' require ' . var_export($path . '/wp-load.php', true) . ';'
        . ' ' . $code;

    $result = run([$config['php'], '-d', 'memory_limit=512M', '-d', 'max_execution_time=0'], $timeout, $path, $script);
    $output = trim($result['stdout']);
    $error = trim($result['stderr']);

    // The snippet prints one JSON document last; whatever the site echoed
    // before it (a notice, a plugin's stray output) is skipped.
    $json = null;
    $start = strrpos($output, "\n{");
    $candidate = false === $start ? $output : substr($output, $start + 1);

    if ('' !== $candidate && '{' === $candidate[0]) {
        $json = json_decode($candidate, true);
    }

    $failure = null;

    if ($result['timeout']) {
        $failure = sprintf('WordPress ne s\'est pas chargé en %d s', $timeout);
    } elseif (0 !== $result['exit'] || null === $json) {
        if ('' !== $error) {
            $failure = last_error_line($error);
        } elseif (preg_match('/^\s*<(!doctype|html)/i', $output)) {
            $failure = 'WordPress a rendu une page au lieu de répondre : un cache de page ou une redirection a pris la main avant la sonde';
        } elseif ('' !== $output) {
            $failure = str_cut(strip_tags($output), 0, 300);
        } else {
            $failure = sprintf('sortie %d sans réponse', $result['exit']);
        }
    }

    return ['ok' => null === $failure, 'output' => $output, 'error' => $failure, 'seconds' => $result['seconds'], 'json' => $json];
}

function last_error_line($stderr)
{
    $lines = array_values(array_filter(preg_split('/\R/', trim($stderr)) ?: [], 'strlen'));

    foreach (array_reverse($lines) as $line) {
        if (false !== stripos($line, 'fatal') || false !== stripos($line, 'error')) {
            return str_cut(trim($line), 0, 300);
        }
    }

    return str_cut((string) end($lines), 0, 300);
}

/**
 * Database settings read off wp-config.php without loading it, for the
 * case where loading it is exactly what fails.
 *
 * @return array<string, string>
 */
function wp_config_constants($path)
{
    $file = is_file($path . '/wp-config.php') ? $path . '/wp-config.php' : dirname($path) . '/wp-config.php';
    $constants = [];

    if (!is_readable($file)) {
        return $constants;
    }

    $source = (string) file_get_contents($file);

    if (preg_match_all('/define\s*\(\s*[\'"](DB_NAME|DB_USER|DB_PASSWORD|DB_HOST|WP_DEBUG_LOG|WP_DEBUG|WP_DEBUG_DISPLAY|DISABLE_WP_CRON|DISALLOW_FILE_MODS|DISALLOW_FILE_EDIT|WP_CACHE|WPLANG|FS_METHOD)[\'"]\s*,\s*(.+?)\s*\)\s*;/s', $source, $matches, PREG_SET_ORDER)) {
        foreach ($matches as $m) {
            $value = trim($m[2]);

            if (preg_match('/^[\'"](.*)[\'"]$/s', $value, $q)) {
                $value = stripslashes($q[1]);
            }

            $constants[$m[1]] = $value;
        }
    }

    return $constants;
}

function json_from_request($request, $key)
{
    return isset($request[$key]) ? $request[$key] : null;
}

// ------------------------------------------------------------------ verbs

/**
 * @return array<string, mixed>
 */
function verb_describe(array $request, array $config, $restricted)
{
    $path = site_path($request, false);
    $osRelease = is_readable('/etc/os-release') ? parse_ini_string((string) file_get_contents('/etc/os-release'), false, INI_SCANNER_RAW) : [];
    $load = is_readable('/proc/loadavg') ? array_map('floatval', array_slice(explode(' ', trim((string) file_get_contents('/proc/loadavg'))), 0, 3)) : null;
    $uptime = is_readable('/proc/uptime') ? (int) floatval(strtok((string) file_get_contents('/proc/uptime'), ' ')) : null;
    $memory = meminfo();
    $diskPath = null !== $path ? $path : (getenv('HOME') ?: '/');
    $free = @disk_free_space($diskPath);
    $total = @disk_total_space($diskPath);
    $drupal = is_drupal_request($request);
    // A Symfony, Sulu or Laravel application: no WordPress to look for, and
    // the paths it is made of are its own (1.8.8).
    $app = is_composer_app_request($request);
    $wp = $drupal || $app ? null : wp_binary($config, $path);

    return [
        'shell' => [
            'version' => ZENITH_SHELL_VERSION,
            'restricted' => $restricted,
            'config_file' => $config['file'],
            'control' => $config['control'],
            'update' => $config['update'],
            'self_update' => $config['self_update'],
        ],
        'authorized' => authorized_keys_options($request),
        'tools' => [
            'php' => PHP_VERSION,
            'php_binary' => $config['php'],
            'site_php' => site_php_version($config),
            'wp' => null === $wp ? null : tool_version(array_merge($wp, ['--version', '--skip-plugins', '--skip-themes']), '/WP-CLI\s+([0-9][0-9a-z.\-]*)/i'),
            'wp_binary' => null === $wp ? null : implode(' ', $wp),
            'git' => tool_version(['git', '--version'], '/git version\s+([0-9][0-9a-z.\-]*)/i'),
            'mysqldump' => which('mysqldump') ?: which('mariadb-dump'),
            'mysql' => which('mysql') ?: which('mariadb'),
            'composer' => composer_version($config, $path),
            'drush' => $drupal && null !== $path ? drush_version($config, $path) : null,
        ],
        'host' => [
            'hostname' => php_uname('n'),
            'os' => isset($osRelease['PRETTY_NAME']) ? $osRelease['PRETTY_NAME'] : php_uname('s'),
            'os_id' => isset($osRelease['ID']) ? $osRelease['ID'] : null,
            'os_version' => isset($osRelease['VERSION_ID']) ? $osRelease['VERSION_ID'] : null,
            'kernel' => php_uname('r'),
            'arch' => php_uname('m'),
            'uptime_seconds' => $uptime,
            'load' => $load,
            'cpus' => cpu_count(),
            'memory' => $memory,
            'disk' => array_merge([
                'path' => $diskPath,
                'free_bytes' => false === $free ? null : (int) $free,
                'total_bytes' => false === $total ? null : (int) $total,
            ], inodes($diskPath)),
            'time_utc' => gmdate('Y-m-d H:i:s'),
            'user' => get_current_user(),
        ],
        'sshd' => sshd_settings(),
        'site' => [
            'path' => $path,
            'framework' => isset($request['framework']) ? $request['framework'] : null,
            'found' => $app ? null !== composer_app_root($path) : ($drupal ? null !== drupal_root($path) : is_wordpress($path)),
            'root' => $app ? composer_app_root($path) : ($drupal ? drupal_root($path) : null),
        ],
        'updates' => system_updates(),
        'crontab' => crontab_status(),
        'git' => git_status($path),
        'wp_config' => null !== $path && !$drupal && !$app ? wp_config_status($path) : null,
        'drupal' => $drupal && null !== $path ? drupal_settings_status($path) : null,
        'ownership' => null !== $path ? ($app ? composer_app_ownership_status($path, $request) : ($drupal ? drupal_ownership_status($path) : ownership_status($path))) : null,
        'clock' => clock_status(),
        'mysql' => null !== $path && !$app ? mysql_status($drupal ? drupal_database_constants($path, $config) : wp_config_constants($path)) : null,
        'logs' => null !== $path ? logs_status($path) : null,
        'snapshots' => snapshots_list(),
        'maintenance' => null !== $path && !$drupal && !$app ? maintenance_status($path) : null,
    ];
}

/**
 * The version of the PHP the site is run with from here — the binary the
 * configuration names, or the one running this script. Zenith holds it
 * against the version the web server reports: a shell that bootstraps
 * WordPress with another PHP than the site's reads another site.
 */
function site_php_version(array $config)
{
    if (PHP_BINARY === $config['php']) {
        return PHP_VERSION;
    }

    $result = run([$config['php'], '-n', '-r', 'echo PHP_VERSION;'], 10);

    return 0 === $result['exit'] && preg_match('/^\d+\.\d+\.\d+/', trim($result['stdout']), $m) ? $m[0] : null;
}

/**
 * Whether WordPress is showing its maintenance page, and since when: the
 * .maintenance file at the root, and the stamp it carries.
 *
 * @return array{active: bool, since: ?string, until: ?string, file: string}
 */
function maintenance_status($path)
{
    $file = $path . '/.maintenance';

    if (!is_file($file)) {
        return ['active' => false, 'since' => null, 'until' => null, 'file' => $file];
    }

    $stamp = preg_match('/\$upgrading\s*=\s*(\d+)/', (string) file_get_contents($file, false, null, 0, 4096), $m) ? (int) $m[1] : null;
    $modified = (int) filemtime($file);

    // WordPress keeps the page up for ten minutes past the stamp: a file
    // whose stamp is older than that is a leftover, not a maintenance.
    return [
        'active' => null === $stamp || $stamp + ZENITH_MAINTENANCE_GRACE_SECONDS > time(),
        'since' => gmdate('Y-m-d H:i:s', $modified),
        'until' => null === $stamp ? null : gmdate('Y-m-d H:i:s', $stamp + ZENITH_MAINTENANCE_GRACE_SECONDS),
        'file' => $file,
    ];
}

/**
 * The lines of ~/.ssh/authorized_keys that concern Zenith, and what each
 * allows. A line is Zenith's when it carries the public key the request
 * names — the one certain sign — or, failing that, the word "zenith" in
 * its comment or its forced command. Every such line is reported: a key
 * installed twice, once restricted and once bare, is a door left open
 * next to the guarded one, and the summary flags must say so.
 *
 * @return array<string, mixed>
 */
function authorized_keys_options(array $request = [])
{
    $home = getenv('HOME');
    $file = is_string($home) ? $home . '/.ssh/authorized_keys' : null;
    $result = ['file' => $file, 'found' => false, 'restrict' => null, 'from' => null, 'command' => null, 'command_path' => null, 'lines' => 0, 'entries' => []];
    $blob = isset($request['public_key']) && is_string($request['public_key']) && preg_match('/(?:^|\s)(ssh-[a-z0-9-]+|ecdsa-[a-z0-9-]+)\s+([A-Za-z0-9+\/=]+)/', $request['public_key'], $m) ? $m[2] : null;

    if (null === $file || !is_readable($file)) {
        $result['readable'] = false;

        return $result;
    }

    $result['readable'] = true;

    foreach (file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $number => $line) {
        $line = trim($line);

        if ('' === $line || '#' === $line[0]) {
            continue;
        }

        $byKey = null !== $blob && false !== strpos($line, $blob);
        $byName = false !== stripos($line, 'zenith');

        if (!$byKey && !$byName) {
            continue;
        }

        $entry = [
            'line' => $number + 1,
            'key_match' => $byKey,
            'restrict' => (bool) preg_match('/(^|,)restrict(,|\s)/', $line),
            'from' => (bool) preg_match('/(^|,)from="[^"]+"/', $line),
            'command' => (bool) preg_match('/(^|,)command="[^"]*zenith-shell[^"]*"/', $line),
            'command_path' => preg_match('/(^|,)command="([^"]+)"/', $line, $c) ? $c[2] : null,
            'comment' => preg_match('/\s(ssh-[a-z0-9-]+|ecdsa-[a-z0-9-]+)\s+[A-Za-z0-9+\/=]+\s+(.+)$/', $line, $k) ? str_cut(trim($k[2]), 0, 60) : null,
        ];
        $result['entries'][] = $entry;
        ++$result['lines'];

        // The summary is the weakest line: one bare line among restricted
        // ones is the one an attacker would use.
        $result['found'] = true;
        $result['restrict'] = null === $result['restrict'] ? $entry['restrict'] : ($result['restrict'] && $entry['restrict']);
        $result['from'] = null === $result['from'] ? $entry['from'] : ($result['from'] && $entry['from']);
        $result['command'] = null === $result['command'] ? $entry['command'] : ($result['command'] && $entry['command']);

        if (null === $result['command_path'] && $entry['command'] && null !== $entry['command_path']) {
            $result['command_path'] = $entry['command_path'];
        }
    }

    return $result;
}

/**
 * What sshd is told about passwords and root, read the way sshd reads it:
 * the first value met wins, Include lines are followed where they stand, and
 * what sits under a Match block is conditional, so the reading stops there.
 *
 * A directive that an unreadable included file could have set first is not
 * guessed: it comes back null, with the files that could not be read. The
 * OpenSSH default is only given when everything before the end was read.
 *
 * @return array<string, mixed>
 */
function sshd_settings()
{
    $named = getenv('ZENITH_SHELL_SSHD_CONFIG');
    $file = is_string($named) && '' !== $named ? $named : '/etc/ssh/sshd_config';

    if (!is_readable($file)) {
        return ['readable' => false, 'password_authentication' => null, 'permit_root_login' => null, 'unreadable_includes' => []];
    }

    $state = ['password' => null, 'root' => null, 'password_open' => true, 'root_open' => true, 'unread' => [], 'match' => false];
    sshd_read($file, dirname($file), $state, 0);

    $defaults = ['password' => 'yes', 'root' => 'prohibit-password'];
    $values = [];

    foreach ($defaults as $key => $default) {
        if (null !== $state[$key]) {
            $values[$key] = $state[$key];
        } else {
            // Never set where it could be read: the default, unless a file
            // that could not be read had the first word.
            $values[$key] = $state[$key . '_open'] ? $default : null;
        }
    }

    return [
        'readable' => true,
        'password_authentication' => $values['password'],
        'permit_root_login' => $values['root'],
        'unreadable_includes' => array_slice(array_values(array_unique($state['unread'])), 0, 20),
    ];
}

/**
 * @param array<string, mixed> $state
 */
function sshd_read($file, $base, array &$state, $depth)
{
    foreach (file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $line) {
        $line = trim($line);

        if ('' === $line || '#' === $line[0]) {
            continue;
        }

        if ($state['match']) {
            return;
        }

        if (!preg_match('/^(\S+?)(?:\s*=\s*|\s+)(.+)$/', $line, $m)) {
            continue;
        }

        $keyword = strtolower($m[1]);
        $value = trim(preg_replace('/\s+#.*$/', '', $m[2]));

        if ('match' === $keyword) {
            $state['match'] = true;

            return;
        }

        if ('include' === $keyword) {
            if ($depth >= 4) {
                continue;
            }

            foreach (preg_split('/\s+/', $value) ?: [] as $pattern) {
                $pattern = trim($pattern, '"');

                if ('' === $pattern) {
                    continue;
                }

                if ('/' !== $pattern[0]) {
                    $pattern = $base . '/' . $pattern;
                }

                $folder = dirname($pattern);

                // A folder that cannot be listed hides its files: the same
                // doubt as a file that cannot be read.
                if (is_dir($folder) && !is_readable($folder)) {
                    sshd_unread($pattern, $state);

                    continue;
                }

                $found = glob($pattern) ?: [];
                sort($found);

                foreach ($found as $included) {
                    if (!is_file($included)) {
                        continue;
                    }

                    if (!is_readable($included)) {
                        sshd_unread($included, $state);

                        continue;
                    }

                    sshd_read($included, $base, $state, $depth + 1);

                    if ($state['match']) {
                        // A Match opened in an included file ends with it.
                        $state['match'] = false;
                    }
                }
            }

            continue;
        }

        $value = strtolower(trim($value, '"'));

        if ('passwordauthentication' === $keyword && null === $state['password'] && $state['password_open']) {
            $state['password'] = $value;
        } elseif ('permitrootlogin' === $keyword && null === $state['root'] && $state['root_open']) {
            $state['root'] = 'without-password' === $value ? 'prohibit-password' : $value;
        }
    }
}

/**
 * A file sshd reads and this account cannot: whatever was not settled before
 * it stays unknown from here on.
 *
 * @param array<string, mixed> $state
 */
function sshd_unread($file, array &$state)
{
    $state['unread'][] = $file;

    if (null === $state['password']) {
        $state['password_open'] = false;
    }

    if (null === $state['root']) {
        $state['root_open'] = false;
    }
}

function meminfo()
{
    if (!is_readable('/proc/meminfo')) {
        return null;
    }

    $values = [];

    foreach (file('/proc/meminfo', FILE_IGNORE_NEW_LINES) ?: [] as $line) {
        if (preg_match('/^(MemTotal|MemAvailable|SwapTotal|SwapFree):\s+(\d+)/', $line, $m)) {
            $values[$m[1]] = (int) $m[2] * 1024;
        }
    }

    return [
        'total_bytes' => isset($values['MemTotal']) ? $values['MemTotal'] : null,
        'available_bytes' => isset($values['MemAvailable']) ? $values['MemAvailable'] : null,
        'swap_total_bytes' => isset($values['SwapTotal']) ? $values['SwapTotal'] : null,
        'swap_free_bytes' => isset($values['SwapFree']) ? $values['SwapFree'] : null,
    ];
}

function cpu_count()
{
    if (!is_readable('/proc/cpuinfo')) {
        return null;
    }

    return max(1, preg_match_all('/^processor\s*:/m', (string) file_get_contents('/proc/cpuinfo')));
}

/**
 * The site's inventory, exactly as the Zenith plugin serves it over HTTP:
 * the REST route is called from inside the site, with the site's own read
 * key, so what comes back is the same document the scan reads.
 *
 * @return array<string, mixed>
 */
function verb_inventory(array $request, array $config)
{
    if ('drupal' === framework($request)) {
        return drupal_inventory($request, $config);
    }

    $path = site_path($request);

    if (!is_wordpress($path)) {
        throw new RuntimeException(sprintf('aucun WordPress dans %s', $path));
    }

    $checks = isset($request['checks']) && is_string($request['checks']) && preg_match('/^[a-z,]+$/', $request['checks']) ? $request['checks'] : 'all';

    $code = 'if (!function_exists("zenith_api_callback")) { fwrite(STDERR, "plugin Zenith absent\n"); exit(3); }'
        . ' $server = rest_get_server();'
        . ' $req = new WP_REST_Request("GET", "/zenith/v1/data");'
        . ' $req->set_header("X-Zenith-Token", function_exists("zenith_setting") ? (string) zenith_setting("api_key", "") : (string) get_option("zenith_api_key"));'
        . ' $req->set_param("checks", ' . var_export($checks, true) . ');'
        . ' $resp = rest_do_request($req);'
        . ' if ($resp->is_error()) { fwrite(STDERR, "erreur REST: " . $resp->as_error()->get_error_message() . "\n"); exit(4); }'
        . ' echo "\n", wp_json_encode($server->response_to_data($resp, false)), "\n";';

    $result = wp_bootstrap($path, site_host($request), $code, $config, 180);

    if (!$result['ok']) {
        throw new RuntimeException(sprintf('inventaire impossible : %s', $result['error']));
    }

    return is_array($result['json']) ? $result['json'] : [];
}

/**
 * What the site looks like from inside the machine when nothing answers
 * from outside: whether WordPress still loads, whether its database still
 * answers, what its logs say last, and what the machine itself is at.
 *
 * @return array<string, mixed>
 */
function verb_diagnostic(array $request, array $config)
{
    if ('drupal' === framework($request)) {
        return drupal_diagnostic($request, $config);
    }

    $path = site_path($request);
    $host = site_host($request);
    $constants = wp_config_constants($path);

    $diagnostic = [
        'at' => gmdate('Y-m-d H:i:s'),
        'path' => $path,
        'php' => ['version' => PHP_VERSION, 'binary' => $config['php']],
        'site_found' => is_wordpress($path),
        'bootstrap' => null,
        'database' => null,
        'wordpress' => null,
        'maintenance' => is_file($path . '/.maintenance'),
        'disk' => null,
        'load' => null,
        'memory' => meminfo(),
        'logs' => [],
        'http_local' => null,
    ];

    $free = @disk_free_space($path);
    $total = @disk_total_space($path);
    $diagnostic['disk'] = ['free_bytes' => false === $free ? null : (int) $free, 'total_bytes' => false === $total ? null : (int) $total];
    $diagnostic['load'] = is_readable('/proc/loadavg') ? array_map('floatval', array_slice(explode(' ', trim((string) file_get_contents('/proc/loadavg'))), 0, 3)) : null;

    // The database first and on its own: a site that dies on load usually
    // dies there, and the answer has to come whatever WordPress does next.
    if (isset($constants['DB_HOST'], $constants['DB_USER'], $constants['DB_NAME']) && function_exists('mysqli_init')) {
        $hostParts = explode(':', $constants['DB_HOST'], 2);
        $socket = null;
        $port = 3306;

        if (isset($hostParts[1])) {
            if (is_numeric($hostParts[1])) {
                $port = (int) $hostParts[1];
            } else {
                $socket = $hostParts[1];
            }
        }

        mysqli_report(MYSQLI_REPORT_OFF);
        $mysqli = mysqli_init();
        $mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
        $connected = @$mysqli->real_connect($hostParts[0], $constants['DB_USER'], isset($constants['DB_PASSWORD']) ? $constants['DB_PASSWORD'] : '', $constants['DB_NAME'], $port, $socket);
        $diagnostic['database'] = ['ok' => (bool) $connected, 'host' => $constants['DB_HOST'], 'error' => $connected ? null : str_cut((string) $mysqli->connect_error, 0, 200)];

        if ($connected) {
            $mysqli->close();
        }
    } elseif (!isset($constants['DB_HOST'])) {
        $diagnostic['database'] = ['ok' => null, 'host' => null, 'error' => 'wp-config.php illisible ou sans réglages de base'];
    }

    if (is_wordpress($path)) {
        $code = 'global $wp_version, $wpdb;'
            . ' $active = (array) get_option("active_plugins", []);'
            . ' $theme = wp_get_theme();'
            . ' echo "\n", json_encode(['
            . '   "version" => $wp_version,'
            . '   "db_ok" => (bool) $wpdb->check_connection(false),'
            . '   "active_plugins" => array_values($active),'
            . '   "theme" => ["name" => $theme->get("Name"), "version" => $theme->get("Version")],'
            . '   "paused" => function_exists("wp_paused_plugins") ? array_keys((array) wp_paused_plugins()->get_all()) : [],'
            . '   "home" => home_url(),'
            . '   "zenith_plugin" => defined("ZENITH_VERSION") ? ZENITH_VERSION : null,'
            . ' ]), "\n";';

        $result = wp_bootstrap($path, $host, $code, $config, 60);
        $diagnostic['bootstrap'] = ['ok' => $result['ok'], 'seconds' => $result['seconds'], 'error' => $result['error']];
        $diagnostic['wordpress'] = $result['ok'] ? $result['json'] : null;
    }

    // Logs: the debug log where WordPress writes it, the PHP log next to
    // the site if there is one, and the last fatal error either has seen.
    $logs = [];

    foreach (log_candidates($path, $constants) as $file) {
        $tail = tail_lines($file, 30);

        if (null === $tail) {
            continue;
        }

        $logs[] = ['path' => $file, 'size_bytes' => (int) filesize($file), 'modified_at' => gmdate('Y-m-d H:i:s', (int) filemtime($file)), 'tail' => $tail, 'last_fatal' => last_fatal($tail)];
    }

    $diagnostic['logs'] = $logs;

    // The web server as seen from the machine itself: a 200 here with
    // nothing from outside points at the network; an error here points at
    // the site.
    $diagnostic['http_local'] = local_http($host, site_uri($request));

    return $diagnostic;
}

function last_fatal(array $lines)
{
    foreach (array_reverse($lines) as $line) {
        if (preg_match('/PHP (Fatal error|Parse error)[^:]*:\s*(.+)$/', $line, $m)) {
            return str_cut(trim($m[2]), 0, 300);
        }
    }

    return null;
}

function local_http($host, $uri = '/')
{
    if (!function_exists('curl_init')) {
        return null;
    }

    $status = null;
    $seconds = null;
    $error = null;

    // The name is resolved to the machine itself rather than sent as a bare
    // Host header: with TLS, the name must also be in the handshake (SNI),
    // or Apache answers 421 to a request it deems misdirected.
    foreach (['https://' . $host . $uri, 'http://' . $host . $uri] as $url) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_NOBODY => true,
            CURLOPT_RESOLVE => [$host . ':443:127.0.0.1', $host . ':80:127.0.0.1'],
            CURLOPT_HTTPHEADER => ['Cache-Control: no-cache'],
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT => 20,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_USERAGENT => 'zenith-shell/' . ZENITH_SHELL_VERSION,
        ]);
        curl_exec($ch);
        $code = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        $error = curl_error($ch) ?: null;
        $seconds = round((float) curl_getinfo($ch, CURLINFO_TOTAL_TIME), 2);
        curl_close($ch);

        if ($code > 0) {
            $status = $code;
            $error = null;
            break;
        }
    }

    return ['status' => $status, 'seconds' => $seconds, 'error' => $error];
}

/**
 * @return array<string, mixed>
 */
function verb_log(array $request)
{
    $path = site_path($request);
    $lines = isset($request['lines']) && is_int($request['lines']) ? max(10, min(400, $request['lines'])) : 80;
    $constants = wp_config_constants($path);
    $files = [];

    foreach (log_candidates($path, $constants) as $file) {
        $tail = tail_lines($file, $lines, 1048576);

        if (null !== $tail) {
            $files[] = ['path' => $file, 'size_bytes' => (int) filesize($file), 'modified_at' => gmdate('Y-m-d H:i:s', (int) filemtime($file)), 'lines' => $tail];
        }
    }

    return ['files' => $files];
}

/**
 * The remediation actions, each one carried out inside WordPress and
 * written to the plugin's journal when the plugin is there. The shapes
 * match what the plugin's own control endpoint answers, so the dashboard
 * reads both the same way.
 *
 * @return array<string, mixed>
 */
function verb_control(array $request, array $config)
{
    $action = isset($request['action']) && is_string($request['action']) ? $request['action'] : '';

    // Replacing this very script is the one write self_update=yes opens on
    // its own: a door kept read-only can still receive its next version.
    if (!$config['control'] && !('install_shell' === $action && $config['self_update'])) {
        throw new RuntimeException('pilotage refusé : control=no dans la configuration de zenith-shell' . ('install_shell' === $action ? ' (self_update=yes ouvrirait cette seule action)' : ''));
    }

    // A Symfony application (1.12.0): its caches, and this script itself.
    if (is_symfony_request($request)) {
        if ('install_shell' === $action) {
            return control_install_shell($request, $config);
        }

        if ('cache_flush' === $action) {
            return symfony_cache_flush($request, $config);
        }

        throw new RuntimeException(sprintf('action « %s » non prise en charge pour une application Symfony par ce shell', $action));
    }

    $framework = framework($request);
    $path = site_path($request);
    $actor = actor($request);

    if ('drupal' === $framework && 'install_shell' !== $action) {
        return drupal_control($action, $path, $request, $actor, $config);
    }

    if ('maintenance_set' === $action) {
        return control_maintenance($path, isset($request['enabled']) && true === $request['enabled'], $actor, site_host($request), $config);
    }

    if ('install_wpcli' === $action) {
        return control_install_wpcli($config);
    }

    if ('install_shell' === $action) {
        return control_install_shell($request, $config);
    }

    if ('install_agent' === $action) {
        return control_install_agent($path, $request, $actor, site_host($request), $config);
    }

    if ('snapshot_restore' === $action) {
        return control_snapshot_restore($path, isset($request['snapshot']) && is_string($request['snapshot']) ? $request['snapshot'] : '', $actor, site_host($request), $config);
    }

    if (!is_wordpress($path)) {
        throw new RuntimeException(sprintf('aucun WordPress dans %s', $path));
    }

    if ('config_set' === $action) {
        return control_config_set($path, $request, $actor, site_host($request), $config);
    }

    if ('plugin_install' === $action) {
        return control_plugin_install($path, $request, $actor, site_host($request), $config);
    }

    if ('htaccess_allow_ip' === $action) {
        return control_htaccess_allow_ip($path, $request, $actor, site_host($request), $config);
    }

    if ('htaccess_read' === $action) {
        return control_htaccess_read($path);
    }

    switch ($action) {
        case 'cache_flush':
            $code = '$flushed = ["object_cache" => function_exists("wp_cache_flush") ? (bool) wp_cache_flush() : null, "opcache" => function_exists("opcache_reset") ? @opcache_reset() : null, "transients" => null, "page_cache" => []];'
                . ' if (function_exists("delete_expired_transients")) { delete_expired_transients(true); $flushed["transients"] = true; }'
                . ' foreach (["wp_cache_clear_cache", "w3tc_flush_all", "rocket_clean_domain", "sg_cachepress_purge_cache", "wpfc_clear_all_cache", "LiteSpeed_Cache_API::purge_all"] as $fn) { if (is_callable($fn)) { try { call_user_func($fn); $flushed["page_cache"][$fn] = true; } catch (\Throwable $e) { $flushed["page_cache"][$fn] = false; } } }'
                . ' $result = ["status" => "ok", "flushed" => $flushed];';
            break;
        case 'cron_run':
            $hook = isset($request['hook']) && is_string($request['hook']) && preg_match('/^[A-Za-z0-9_][A-Za-z0-9_\-]{0,119}$/', $request['hook']) ? $request['hook'] : null;
            $force = isset($request['force']) && true === $request['force'];
            $params = ['hook' => $hook, 'force' => $force];
            // Only what WP-Cron itself would run: a hook absent from the
            // cron table is refused, as the plugin answers 404, rather than
            // run without its arguments. The lock is the one wp-cron.php
            // takes, so a run in progress is not doubled; force treats a
            // recent lock as the leftover of a broken loopback, which is
            // the one case it exists for.
            // Each hook gets ZENITH_CRON_HOOK_SECONDS: an alarm where pcntl
            // is there, the CPU clock of set_time_limit otherwise. The run
            // as a whole stops handing out hooks past its budget, and says
            // which ones it did not reach rather than pretending it did.
            $code = '$ran = []; $errors = []; $skipped = []; $result = null; $only = ' . var_export($hook, true) . '; $force = ' . var_export($force, true) . '; $crons = (array) _get_cron_array(); $now = time(); $runStarted = microtime(true);'
                . ' if (null !== $only) { $known = false; foreach ($crons as $hooks) { if (is_array($hooks) && isset($hooks[$only])) { $known = true; break; } } if (!$known) { $result = ["status" => "failed", "refused" => true, "message" => "hook \'" . $only . "\' non planifié dans WP-Cron"]; } }'
                . ' $lockTimeout = defined("WP_CRON_LOCK_TIMEOUT") ? (int) WP_CRON_LOCK_TIMEOUT : 60; $held = get_transient("doing_cron");'
                . ' if (null === $result && !$force && $held && (float) $held + $lockTimeout > microtime(true)) { $result = ["status" => "failed", "refused" => true, "lock_age_seconds" => round(microtime(true) - (float) $held, 1), "message" => "WP-Cron semble en cours d\'exécution (verrou doing_cron) : relancer en forçant si le loopback du site est cassé"]; }'
                . ' if (null === $result) { $lock = sprintf("%.22F", microtime(true)); set_transient("doing_cron", $lock);'
                . ' $hookLimit = ' . ZENITH_CRON_HOOK_SECONDS . '; $runBudget = ' . ZENITH_CRON_BUDGET_SECONDS . '; $alarm = function_exists("pcntl_alarm") && function_exists("pcntl_signal") && function_exists("pcntl_async_signals");'
                . ' if ($alarm) { pcntl_async_signals(true); pcntl_signal(SIGALRM, function () use ($hookLimit) { throw new \RuntimeException("délai de " . $hookLimit . " s dépassé"); }); }'
                . ' try { foreach ($crons as $timestamp => $hooks) { if (!is_array($hooks)) { continue; } if ($timestamp > $now && null === $only) { continue; } foreach ($hooks as $hookName => $events) { if (null !== $only && $hookName !== $only) { continue; } foreach ((array) $events as $sig => $event) { $args = isset($event["args"]) ? (array) $event["args"] : [];'
                . '   if (microtime(true) - $runStarted > $runBudget) { $skipped[] = ["hook" => $hookName, "reason" => "budget de " . $runBudget . " s épuisé"]; continue; }'
                . '   $started = microtime(true); if ($alarm) { pcntl_alarm($hookLimit); } else { set_time_limit($hookLimit); }'
                . '   try { do_action_ref_array($hookName, $args); $ran[] = ["hook" => $hookName, "seconds" => round(microtime(true) - $started, 2), "forced" => $timestamp > $now]; } catch (\Throwable $e) { $errors[] = ["hook" => $hookName, "message" => $e->getMessage(), "seconds" => round(microtime(true) - $started, 2)]; }'
                . '   if ($alarm) { pcntl_alarm(0); } else { set_time_limit(0); }'
                . '   if (isset($event["schedule"]) && $event["schedule"] && isset($event["interval"])) { wp_reschedule_event($timestamp, $event["schedule"], $hookName, $args); } wp_unschedule_event($timestamp, $hookName, $args); } } } }'
                . ' finally { if (get_transient("doing_cron") === $lock) { delete_transient("doing_cron"); } }'
                . ' $result = ["status" => [] === $errors && [] === $skipped ? "ok" : "partial", "ran" => $ran, "errors" => $errors, "skipped" => $skipped, "message" => [] === $skipped ? null : count($skipped) . " tâche(s) non exécutée(s), budget épuisé"]; }';
            break;
        case 'plugin_deactivate':
        case 'plugin_activate':
            $items = items($request);

            if ([] === $items) {
                throw new RuntimeException('aucune extension indiquée');
            }

            $activate = 'plugin_activate' === $action;
            $code = 'require_once ABSPATH . "wp-admin/includes/plugin.php"; $results = []; $items = ' . var_export($items, true) . ';'
                . ' foreach ($items as $item) { $file = false === strpos($item, "/") && !preg_match("/\.php$/", $item) ? null : $item;'
                . '   if (null === $file) { foreach (array_keys(get_plugins()) as $candidate) { if (dirname($candidate) === $item || $candidate === $item . ".php") { $file = $candidate; break; } } }'
                . '   if (null === $file) { $results[] = ["item" => $item, "status" => "failed", "message" => "extension inconnue"]; continue; }'
                . ($activate
                    ? '   if (is_plugin_active($file)) { $results[] = ["item" => $file, "status" => "skipped", "message" => "déjà active"]; continue; } $r = activate_plugin($file); $results[] = is_wp_error($r) ? ["item" => $file, "status" => "failed", "message" => $r->get_error_message()] : ["item" => $file, "status" => "activated", "message" => null];'
                    : '   if (!is_plugin_active($file)) { $results[] = ["item" => $file, "status" => "skipped", "message" => "déjà inactive"]; continue; } deactivate_plugins($file); $results[] = ["item" => $file, "status" => is_plugin_active($file) ? "failed" : "deactivated", "message" => null];')
                . ' }'
                . ' $failed = count(array_filter($results, function ($r) { return "failed" === $r["status"]; }));'
                . ' $result = ["status" => 0 === $failed ? "ok" : ($failed === count($results) ? "failed" : "partial"), "results" => $results];';
            break;
        case 'user_display_name':
            // Since 1.10.3: the name a site shows for an account, when it is
            // the login itself (an author line that spells the credential).
            $who = isset($request['user']) && is_string($request['user']) && preg_match('/^[A-Za-z0-9 _.@+\-]{1,60}$/', $request['user']) ? $request['user'] : null;
            $name = isset($request['display_name']) && is_string($request['display_name']) ? trim(preg_replace('/\s+/', ' ', $request['display_name'])) : '';

            if (null === $who || '' === $name || strlen($name) > 120) {
                throw new RuntimeException('indiquer le compte (login ou id) et le nom à afficher (120 caractères au plus)');
            }

            $params = ['user' => $who, 'display_name' => $name];
            $code = '$who = ' . var_export($who, true) . '; $name = ' . var_export($name, true) . ';'
                . ' $account = ctype_digit($who) ? get_user_by("id", (int) $who) : (get_user_by("login", $who) ?: get_user_by("email", $who));'
                . ' if (!$account) { $result = ["status" => "failed", "refused" => true, "message" => "compte inconnu : " . $who]; }'
                . ' elseif ($account->display_name === $name) { $result = ["status" => "ok", "user" => $account->user_login, "display_name" => $name, "message" => "le compte portait déjà ce nom"]; }'
                . ' else { $r = wp_update_user(["ID" => $account->ID, "display_name" => $name]); $result = is_wp_error($r) ? ["status" => "failed", "message" => $r->get_error_message()] : ["status" => "ok", "user" => $account->user_login, "display_name" => $name, "still_login" => 0 === strcasecmp($name, $account->user_login), "message" => null]; }';
            break;
        default:
            throw new RuntimeException(sprintf('action inconnue de zenith-shell : %s', $action));
    }

    $code .= journal_snippet($action, $actor, isset($params) ? $params : (isset($items) ? ['items' => $items] : []));
    $code .= ' echo "\n", json_encode($result), "\n";';

    $result = wp_bootstrap($path, site_host($request), $code, $config, 'cron_run' === $action ? ZENITH_CRON_BUDGET_SECONDS + ZENITH_CRON_HOOK_SECONDS + 30 : 180);

    if (!$result['ok']) {
        throw new RuntimeException(sprintf('%s : %s', $action, $result['error']));
    }

    $answer = is_array($result['json']) ? $result['json'] : ['status' => 'failed', 'message' => 'réponse illisible'];

    // Refused before anything ran — a hook WP-Cron does not know, a lock
    // still held: the answer is a refusal, as the plugin's 404 and 409
    // are, not a run that happened to do nothing.
    if (isset($answer['refused']) && true === $answer['refused']) {
        throw new RuntimeException(isset($answer['message']) && is_string($answer['message']) ? $answer['message'] : sprintf('%s refusé', $action));
    }

    return $answer;
}

/**
 * A line in the plugin's journal, when the plugin is there to keep one: a
 * zenith.control event, the type the plugin writes for its own /control
 * and the one /actions reads, with the action, its parameters, its
 * outcome, and who asked for it over SSH.
 *
 * The plugin only knows how to name an actor for a REST request: the
 * entry is patched right after it is written, under the plugin's own
 * lock, to say the action came from the command line (actor.type cli),
 * over SSH (actor.via), and from whom (actor.login). The immediate push
 * of that entry is switched off first: it would carry the copy the
 * plugin made before the patch, and the next heartbeat carries the
 * stored one.
 *
 * One action leaves no line when it went well: cron_run. Zenith runs the
 * queue every time a heartbeat is late, and those entries were most of a
 * journal that keeps five hundred; the plugin (1.21) and the module (0.4.2)
 * stopped writing them for their own /control, and the shell follows. A
 * run that failed, even in part, is journaled.
 *
 * @param array<string, mixed> $params
 */
function journal_snippet($action, $actor, array $params)
{
    $actorValue = var_export(['type' => 'cli', 'id' => null, 'login' => $actor, 'via' => 'ssh'], true);
    $routine = 'cron_run' === $action ? ' && !(isset($result["status"]) && "ok" === $result["status"])' : '';

    return ' if (function_exists("zenith_event_record")' . $routine . ') { try {'
        . ' if (function_exists("remove_all_actions")) { remove_all_actions("zenith_event_recorded"); }'
        . ' $zenithId = (int) zenith_event_record("zenith.control", ["action" => ' . var_export($action, true) . ', "params" => ' . var_export($params, true) . ', "status" => isset($result["status"]) ? $result["status"] : null, "message" => isset($result["message"]) ? $result["message"] : null], "warning");'
        . ' $zenithLock = function_exists("zenith_lock_acquire") ? zenith_lock_acquire("events", 5, 2000) : null;'
        . ' $zenithStore = get_option("zenith_events", null);'
        . ' if (is_array($zenithStore) && isset($zenithStore["items"]) && is_array($zenithStore["items"])) { foreach ($zenithStore["items"] as $zenithKey => $zenithEvent) { if (is_array($zenithEvent) && isset($zenithEvent["id"]) && (int) $zenithEvent["id"] === $zenithId) { $zenithStore["items"][$zenithKey]["actor"] = ' . $actorValue . '; update_option("zenith_events", $zenithStore, "no"); break; } } }'
        . ' if (function_exists("zenith_lock_release")) { zenith_lock_release($zenithLock); }'
        . ' } catch (\Throwable $e) {} }';
}

/**
 * The maintenance page WordPress shows while a file named .maintenance
 * sits at its root: the way to take a broken site off the air, or to put
 * a fixed one back, without loading anything.
 *
 * @return array<string, mixed>
 */
function control_maintenance($path, $enabled, $actor, $host, array $config)
{
    $file = $path . '/.maintenance';
    $was = is_file($file);

    $until = time() + ZENITH_MAINTENANCE_MAX_SECONDS - ZENITH_MAINTENANCE_GRACE_SECONDS;

    if ($enabled) {
        // WordPress drops the page by itself ten minutes after this stamp:
        // set two hours ahead at most, so a site put on hold and forgotten
        // comes back on its own. Asking again pushes the stamp forward.
        if (false === file_put_contents($file, "<?php \$upgrading = " . $until . ";\n")) {
            throw new RuntimeException(sprintf('impossible d\'écrire %s', $file));
        }
    } elseif ($was && !@unlink($file)) {
        throw new RuntimeException(sprintf('impossible de supprimer %s', $file));
    }

    if (is_wordpress($path)) {
        wp_bootstrap($path, $host, '$result = ["status" => "ok"];' . journal_snippet('maintenance_set', $actor, ['enabled' => $enabled]) . ' echo "\n{}\n";', $config, 30);
    }

    return [
        'status' => 'ok',
        'maintenance' => $enabled,
        'changed' => $was !== $enabled,
        'until' => $enabled ? gmdate('Y-m-d H:i:s', $until + ZENITH_MAINTENANCE_GRACE_SECONDS) : null,
        'message' => $enabled ? sprintf('Page de maintenance en place jusqu\'à %s UTC au plus tard.', gmdate('H:i', $until + ZENITH_MAINTENANCE_GRACE_SECONDS)) : 'Page de maintenance retirée.',
    ];
}

/**
 * A constant of wp-config.php set or withdrawn (1.10.4): the file no other
 * channel writes — the plugin leaves it alone by design, and a deployment
 * only carries wp-config-dist.php — and the one place where WordPress's
 * own automatic updates are switched off for good. The constants are a
 * closed list, the value a boolean, a short word or nothing (withdrawn).
 *
 * wp-cli does the edit when it is there (`wp config set --type=constant`,
 * which knows the file's anchors); the shell otherwise rewrites the file
 * itself, guarded: a copy under ~/.zenith/restore first, the define
 * replaced in place or inserted before « That's all, stop editing! » /
 * the require of wp-settings.php, `php -l` on the candidate before the
 * file is touched and on the file after, the copy put back if that last
 * check fails. The plugin's journal gets a zenith.control line when the
 * site still loads.
 *
 * @return array<string, mixed>
 */
function control_config_set($path, array $request, $actor, $host, array $config)
{
    $allowed = ['WP_AUTO_UPDATE_CORE', 'AUTOMATIC_UPDATER_DISABLED', 'DISALLOW_FILE_MODS', 'DISALLOW_FILE_EDIT', 'WP_DEBUG', 'WP_DEBUG_DISPLAY', 'WP_DEBUG_LOG', 'DISABLE_WP_CRON', 'FS_METHOD'];
    $constant = isset($request['constant']) && is_string($request['constant']) ? strtoupper(trim($request['constant'])) : '';

    if (!in_array($constant, $allowed, true)) {
        throw new RuntimeException(sprintf('constante refusée : %s (connues : %s)', '' === $constant ? '(vide)' : $constant, implode(', ', $allowed)));
    }

    $value = array_key_exists('value', $request) ? $request['value'] : null;

    if (is_string($value)) {
        $value = trim($value);
    }

    if (null !== $value && !is_bool($value) && !(is_string($value) && preg_match('#^[A-Za-z0-9_./-]{1,120}$#', $value))) {
        throw new RuntimeException('valeur refusée : true, false, un mot court (lettres, chiffres, _ . / -) ou null pour retirer la constante');
    }

    $file = is_file($path . '/wp-config.php') ? $path . '/wp-config.php' : dirname($path) . '/wp-config.php';

    if (!is_file($file)) {
        throw new RuntimeException(sprintf('wp-config.php introuvable dans %s ni au-dessus', $path));
    }

    if (!is_readable($file) || !is_writable($file)) {
        throw new RuntimeException(sprintf('%s n\'est pas accessible en écriture pour %s', $file, function_exists('posix_geteuid') && function_exists('posix_getpwuid') ? (string) (posix_getpwuid(posix_geteuid())['name'] ?? posix_geteuid()) : 'cet utilisateur'));
    }

    $literal = null === $value ? null : (is_bool($value) ? ($value ? 'true' : 'false') : "'" . $value . "'");
    $before = config_constant_literal((string) file_get_contents($file), $constant);
    $method = null;
    $attempts = [];

    if ($before === $literal) {
        $outcome = ['status' => 'ok', 'constant' => $constant, 'before' => $before, 'after' => $before, 'changed' => false, 'method' => null, 'file' => $file, 'backup' => null, 'message' => null === $literal ? sprintf('%s n\'était pas définie dans wp-config.php.', $constant) : sprintf('%s valait déjà %s.', $constant, $literal)];
    } else {
        $wp = wp_binary($config, $path);

        if (null !== $wp) {
            $base = array_merge($wp, ['--path=' . $path, '--no-color', '--skip-plugins', '--skip-themes']);
            $command = null === $literal
                ? array_merge($base, ['config', 'delete', $constant, '--type=constant'])
                : array_merge($base, ['config', 'set', $constant, is_bool($value) ? $literal : $value, '--type=constant'], is_bool($value) ? ['--raw'] : []);
            $result = run($command, 60, $path);
            $after = config_constant_literal((string) file_get_contents($file), $constant);

            if (0 === $result['exit'] && $after === $literal) {
                $method = 'wp-cli';
            } else {
                $attempts[] = 'wp-cli : ' . str_cut(trim('' !== $result['stderr'] ? $result['stderr'] : $result['stdout']), 0, 200);
            }
        }

        $backup = null;

        if (null === $method) {
            $rewrite = config_rewrite($file, $constant, $literal, $config);
            $method = 'rewrite';
            $backup = $rewrite['backup'];
        }

        $after = config_constant_literal((string) file_get_contents($file), $constant);

        if ($after !== $literal) {
            throw new RuntimeException(sprintf('%s vaut %s après l\'écriture au lieu de %s', $constant, null === $after ? 'rien' : $after, null === $literal ? 'rien' : $literal));
        }

        $outcome = [
            'status' => 'ok',
            'constant' => $constant,
            'before' => $before,
            'after' => $after,
            'changed' => true,
            'method' => $method,
            'file' => $file,
            'backup' => $backup,
            'attempts' => $attempts,
            'message' => null === $literal
                ? sprintf('%s retirée de wp-config.php (valait %s).', $constant, $before)
                : sprintf('%s %s %s dans wp-config.php (%s).', $constant, null === $before ? 'posée à' : 'passée de ' . $before . ' à', $literal, $method),
        ];
    }

    // The plugin's journal, when WordPress still loads with the file as it
    // now stands: best effort, the edit itself is already made and checked.
    $journal = wp_bootstrap($path, $host, '$result = ' . var_export(['status' => 'ok', 'message' => $outcome['message']], true) . ';' . journal_snippet('config_set', $actor, ['constant' => $constant, 'value' => null === $literal ? '-' : $literal]) . ' echo "\n{}\n";', $config, 30);
    $outcome['journaled'] = $journal['ok'];

    return $outcome;
}

/**
 * The literal a constant is defined with in a wp-config.php source, as
 * written (`false`, `'minor'`), or null when it is not defined there.
 */
function config_constant_literal($source, $constant)
{
    if (!preg_match('/define\s*\(\s*[\'"]' . preg_quote($constant, '/') . '[\'"]\s*,\s*(.+?)\s*\)\s*;/s', $source, $m)) {
        return null;
    }

    return preg_replace('/^"(.*)"$/s', "'$1'", trim($m[1]));
}

/**
 * An extension installed from wordpress.org by wp-cli (1.10.5): the slug
 * as the directory names it, a version if one is wanted, activated only
 * when asked. Code arriving on the site is an update-class write: it needs
 * update=yes like the update verb, on top of control=yes. An extension
 * already there is left as it is unless a version is named (then wp-cli
 * replaces it, --force). Written in the plugin's journal like every action.
 *
 * @return array<string, mixed>
 */
function control_plugin_install($path, array $request, $actor, $host, array $config)
{
    if (!$config['update']) {
        throw new RuntimeException('installation refusée : update=no dans la configuration de zenith-shell (installer du code est une mise à jour)');
    }

    $slug = isset($request['slug']) && is_string($request['slug']) ? trim($request['slug']) : '';

    if (!is_clean_slug($slug, 120)) {
        throw new RuntimeException('slug d\'extension refusé : lettres, chiffres, tirets et points attendus');
    }

    $version = isset($request['version']) && is_string($request['version']) && preg_match('/^[0-9][0-9A-Za-z.\-]{0,30}$/', $request['version']) ? $request['version'] : null;
    $activate = isset($request['activate']) && true === $request['activate'];
    $wp = wp_binary($config, $path);

    if (null === $wp) {
        throw new RuntimeException('wp-cli introuvable sur cette machine : l\'installation d\'une extension passe par lui');
    }

    $base = array_merge($wp, ['--path=' . $path, '--no-color', '--skip-themes']);
    $listed = function () use ($base, $path, $slug) {
        $list = run(array_merge($base, ['plugin', 'list', '--format=json', '--fields=name,status,version']), 60, $path);

        foreach ((array) json_decode(trim($list['stdout']), true) as $row) {
            if (is_array($row) && isset($row['name']) && $row['name'] === $slug) {
                return ['version' => isset($row['version']) ? (string) $row['version'] : null, 'active' => isset($row['status']) && 'active' === $row['status']];
            }
        }

        return null;
    };
    $before = $listed();
    $installed = false;

    if (null === $before || null !== $version) {
        // A folder left behind without its main file — a checkout that took
        // the tracked files away — reads as « already installed » to wp-cli,
        // which then installs nothing: forced over it, like a named version.
        $leftover = null === $before && is_dir($path . '/wp-content/plugins/' . $slug);
        $command = array_merge($base, ['plugin', 'install', $slug], null !== $version ? ['--version=' . $version] : [], $activate ? ['--activate'] : [], null !== $before || $leftover ? ['--force'] : []);
        $result = run($command, 300, $path);

        if (0 !== $result['exit']) {
            throw new RuntimeException(sprintf('installation de %s refusée par wp-cli : %s', $slug, last_error_line('' !== $result['stderr'] ? $result['stderr'] : $result['stdout'])));
        }

        $installed = true;
    } elseif ($activate && !$before['active']) {
        $result = run(array_merge($base, ['plugin', 'activate', $slug]), 120, $path);

        if (0 !== $result['exit']) {
            throw new RuntimeException(sprintf('activation de %s refusée par wp-cli : %s', $slug, last_error_line('' !== $result['stderr'] ? $result['stderr'] : $result['stdout'])));
        }
    }

    $after = $listed();

    if (null === $after) {
        throw new RuntimeException(sprintf('%s absente de la liste des extensions après l\'installation', $slug));
    }

    $message = $installed
        ? sprintf('%s installée en %s%s.', $slug, (string) $after['version'], $after['active'] ? ' et activée' : ' (inactive)')
        : sprintf('%s déjà installée en %s%s.', $slug, (string) $after['version'], $activate && !$before['active'] ? ', activée' : ($after['active'] ? ', active' : ', inactive'));
    $outcome = [
        'status' => 'ok',
        'slug' => $slug,
        'installed' => $installed,
        'before' => $before,
        'version' => $after['version'],
        'active' => $after['active'],
        'message' => $message,
    ];
    $journal = wp_bootstrap($path, $host, '$result = ' . var_export(['status' => 'ok', 'message' => $message], true) . ';' . journal_snippet('plugin_install', $actor, ['slug' => $slug, 'version' => (string) $after['version']]) . ' echo "\n{}\n";', $config, 30);
    $outcome['journaled'] = $journal['ok'];

    return $outcome;
}

/**
 * An address let through the Basic Auth that keeps a preproduction private
 * (1.10.8): the site's .htaccess, or a parent's up to three levels, that
 * holds « AuthType Basic » gets a « Require ip » beside its « Require
 * valid-user », the two under a <RequireAny>. For the tool's acceptance
 * run, which then reads the site without credentials — credentials it
 * would otherwise have to hand to every request of its browser, third
 * parties included. A copy of the file is kept under restore/; the site is
 * asked again from here afterwards and must still answer, or the copy is
 * put back. An authentication kept in the vhost is out of reach and said
 * as such.
 *
 * @return array<string, mixed>
 */
function control_htaccess_allow_ip($path, array $request, $actor, $host, array $config)
{
    $ip = isset($request['ip']) && is_string($request['ip']) ? trim($request['ip']) : '';

    if (false === filter_var($ip, FILTER_VALIDATE_IP)) {
        throw new RuntimeException('adresse IP refusée : une IPv4 ou IPv6 est attendue');
    }

    $label = isset($request['label']) && is_string($request['label']) && preg_match('/^[\w .:-]{1,80}$/u', $request['label']) ? $request['label'] : 'Zenith';
    // How the address is let through. « any », the default: <RequireAny>
    // around Require ip and Require valid-user (mod_authz_core), which
    // leaves every other Require of the tree in force — the « Require all
    // denied » the locks put on readme.html, .git or debug.log included.
    // « satisfy » : Allow from + Satisfy any beside Require valid-user
    // (mod_access_compat), the older recipe, kept for a server whose
    // authorization refuses the first; it grants the address before any
    // Require is read, so those files open to it — and to the scan.
    $mode = isset($request['mode']) && 'satisfy' === $request['mode'] ? 'satisfy' : 'any';

    // The probe alone, nothing written: what the site answers from here to
    // a plain request and to one shaped like WordPress's own loopback.
    if (isset($request['probe_only']) && true === $request['probe_only']) {
        return ['status' => 'ok', 'message' => null, 'changed' => false, 'probe' => htaccess_probe($host)];
    }

    $file = null;
    $dir = rtrim($path, '/');

    for ($level = 0; $level <= 3 && '' !== $dir && '/' !== $dir; ++$level) {
        $candidate = $dir . '/.htaccess';

        if (is_file($candidate) && is_readable($candidate) && preg_match('/^\s*AuthType\s+Basic/mi', (string) file_get_contents($candidate))) {
            $file = $candidate;
            break;
        }

        $dir = dirname($dir);
    }

    if (null === $file) {
        return ['status' => 'failed', 'message' => sprintf('aucun .htaccess avec « AuthType Basic » dans %s ni ses trois parents : l\'authentification est tenue par le vhost Apache, hors de portée du shell', $path), 'file' => null, 'changed' => false];
    }

    if (!is_writable($file)) {
        throw new RuntimeException(sprintf('%s n\'est pas accessible en écriture pour cet utilisateur', $file));
    }

    $source = (string) file_get_contents($file);

    if ('any' === $mode && preg_match('/^\s*Require\s+ip\s+' . preg_quote($ip, '/') . '\s*$/mi', $source)) {
        return ['status' => 'ok', 'message' => sprintf('%s déjà admise dans %s.', $ip, $file), 'file' => $file, 'changed' => false, 'backup' => null];
    }

    if ('satisfy' === $mode && preg_match('/^\s*Allow\s+from\s+' . preg_quote($ip, '/') . '\s*$/mi', $source) && preg_match('/^\s*Satisfy\s+any\s*$/mi', $source)) {
        return ['status' => 'ok', 'message' => sprintf('%s déjà admise (Satisfy any) dans %s.', $ip, $file), 'file' => $file, 'changed' => false, 'backup' => null];
    }

    $line = '    Require ip ' . $ip . "\n";
    $candidate = null;

    // The « satisfy » block an earlier pass wrote, taken away before the
    // RequireAny is built: left there, Satisfy any would keep bypassing the
    // other Require directives for the address.
    if ('any' === $mode && preg_match('/^# [\w .:-]{1,80} : recette depuis l\'outil, sans identifiants, admise par adresse\n(?:(?:Order deny,allow|Deny from all|Allow from \S+|Satisfy any)\n)+/m', $source, $m, PREG_OFFSET_CAPTURE)) {
        $source = substr($source, 0, $m[0][1]) . substr($source, $m[0][1] + strlen($m[0][0]));
    }

    if ('satisfy' === $mode) {
        $comment = '# ' . $label . ' : recette depuis l\'outil, sans identifiants, admise par adresse';
        $satisfy = "Require valid-user\n" . $comment . "\nOrder deny,allow\nDeny from all\nAllow from " . $ip . "\nSatisfy any";

        if (preg_match('/^(\s*)Satisfy\s+any\s*$/mi', $source, $m, PREG_OFFSET_CAPTURE)) {
            // A Satisfy any already there: the address joins its Allow lines.
            $candidate = substr($source, 0, $m[0][1]) . $m[1][0] . 'Allow from ' . $ip . "\n" . substr($source, $m[0][1]);
        } elseif (preg_match('/^[ \t]*<RequireAny>.*?Require\s+valid-user.*?<\/RequireAny>[ \t]*/mis', $source, $m, PREG_OFFSET_CAPTURE)) {
            // The block « any » wrote: replaced whole.
            $candidate = substr($source, 0, $m[0][1]) . $satisfy . substr($source, $m[0][1] + strlen($m[0][0]));
        } elseif (preg_match('/^(\s*)Require\s+valid-user\s*$/mi', $source, $m, PREG_OFFSET_CAPTURE)) {
            $candidate = substr($source, 0, $m[0][1]) . $m[1][0] . str_replace("\n", "\n" . $m[1][0], $satisfy) . substr($source, $m[0][1] + strlen($m[0][0]));
        }
    } elseif (preg_match('/^(\s*)<RequireAny>\s*$/mi', $source, $m, PREG_OFFSET_CAPTURE)) {
        // A RequireAny already there: the address joins it.
        $at = $m[0][1] + strlen($m[0][0]);
        $candidate = substr($source, 0, $at) . "\n" . $m[1][0] . '    # ' . $label . ' : recette depuis l\'outil, sans identifiants' . "\n" . $m[1][0] . $line . substr($source, $at + 1);
    } elseif (preg_match('/^(\s*)(Require\s+(?:valid-user|user\s+\S.*|group\s+\S.*))\s*$/mi', $source, $m, PREG_OFFSET_CAPTURE)) {
        $indent = $m[1][0];
        $block = $indent . "<RequireAny>\n" . $indent . '    # ' . $label . ' : recette depuis l\'outil, sans identifiants' . "\n" . $indent . $line . $indent . '    ' . trim($m[2][0]) . "\n" . $indent . '</RequireAny>';
        $candidate = substr($source, 0, $m[0][1]) . $block . substr($source, $m[0][1] + strlen($m[0][0]));
    }

    if (null === $candidate) {
        return ['status' => 'failed', 'message' => sprintf('%s porte AuthType Basic mais ni « Require valid-user » ni <RequireAny> : à compléter à la main', $file), 'file' => $file, 'changed' => false];
    }

    $folder = restore_folder($config);

    if (!is_dir($folder) && !@mkdir($folder, 0700, true)) {
        throw new RuntimeException(sprintf('impossible de créer %s pour la copie de secours', $folder));
    }

    $backup = $folder . '/htaccess-' . gmdate('Ymd-His') . '.bak';

    if (false === file_put_contents($backup, $source) || !chmod($backup, 0600)) {
        throw new RuntimeException(sprintf('impossible d\'écrire la copie de secours %s', $backup));
    }

    if (false === file_put_contents($file, $candidate)) {
        throw new RuntimeException(sprintf('impossible d\'écrire %s (copie de secours : %s)', $file, $backup));
    }

    // The site asked again from here, the home page and a rewritten
    // address alike: Apache must still read the file. A 500 means a
    // directive it refuses — the copy goes back at once.
    $probe = htaccess_probe($host);
    $worst = max(array_filter($probe, 'is_int') ?: [0]);

    if ($worst >= 500) {
        file_put_contents($file, $source);

        throw new RuntimeException(sprintf('Apache répond %d avec le .htaccess réécrit : copie remise en place (%s)', $worst, $backup));
    }

    $outcome = [
        'status' => 'ok',
        'file' => $file,
        'changed' => true,
        'mode' => $mode,
        'backup' => $backup,
        'probe' => $probe,
        'message' => sprintf('%s admise sans identifiants dans %s, mode %s (depuis le serveur : accueil %s, adresse réécrite %s).', $ip, $file, $mode, null === $probe['home'] ? '?' : (string) $probe['home'], null === $probe['rewritten'] ? '?' : (string) $probe['rewritten']),
    ];
    $journal = wp_bootstrap($path, $host, '$result = ' . var_export(['status' => 'ok', 'message' => $outcome['message']], true) . ';' . journal_snippet('htaccess_allow_ip', $actor, ['ip' => $ip, 'file' => $file]) . ' echo "\n{}\n";', $config, 30);
    $outcome['journaled'] = $journal['ok'];

    return $outcome;
}

/**
 * The .htaccess files from the site's folder up to three parents, as they
 * are (1.10.9): what a person reads to understand a 401, a 403 or a
 * rewrite, without a terminal on the machine. Read only, each file cut at
 * 32 KB.
 *
 * @return array<string, mixed>
 */
function control_htaccess_read($path)
{
    $files = [];
    $dir = rtrim($path, '/');

    for ($level = 0; $level <= 3 && '' !== $dir && '/' !== $dir; ++$level) {
        $candidate = $dir . '/.htaccess';

        if (is_file($candidate)) {
            $content = is_readable($candidate) ? (string) file_get_contents($candidate, false, null, 0, 32768) : null;
            $files[] = ['file' => $candidate, 'readable' => null !== $content, 'bytes' => @filesize($candidate) ?: 0, 'auth' => null !== $content && 1 === preg_match('/^\s*AuthType\s+Basic/mi', $content), 'content' => $content];
        }

        $dir = dirname($dir);
    }

    return ['status' => 'ok', 'message' => null, 'files' => $files];
}

/**
 * The HTTP statuses the site answers from its own machine — the home
 * page, and an address mod_rewrite sends to index.php, which Apache's
 * authorization may treat differently — or null when nothing here can ask.
 *
 * @return array{home: int|null, rewritten: int|null}
 */
function htaccess_probe($host)
{
    $curl = which('curl');
    $out = ['home' => null, 'rewritten' => null];

    if (null === $curl || !is_string($host) || '' === $host) {
        return $out;
    }

    foreach (['home' => '/', 'rewritten' => '/wp-json/zenith/v1/ping'] as $key => $uri) {
        $run = run([$curl, '-s', '-o', '/dev/null', '-w', '%{http_code}', '--max-time', '20', 'https://' . $host . $uri], 30);
        $code = (int) trim($run['stdout']);
        $out[$key] = 0 === $run['exit'] && $code > 0 ? $code : null;
    }

    // The same address asked the way WordPress asks it of itself: its
    // user agent, no cache, certificate unchecked. A server rule keyed on
    // that user agent shows here and nowhere else.
    $run = run([$curl, '-s', '-k', '-A', 'WordPress/7.1; https://' . $host, '-H', 'Cache-Control: no-cache', '-w', '\n%{http_code}', '--max-time', '20', 'https://' . $host . '/wp-json/zenith/v1/ping'], 30);
    $lines = explode("\n", rtrim($run['stdout']));
    $code = (int) array_pop($lines);
    $out['wordpress'] = 0 === $run['exit'] && $code > 0 ? $code : null;
    $out['wordpress_body'] = str_cut(trim(strip_tags(implode("\n", $lines))), 0, 200);

    return $out;
}

/**
 * The guarded rewrite behind control_config_set, for a machine without
 * wp-cli: the define replaced where it stands, inserted before the anchor
 * WordPress's own file carries, or dropped with its line. Nothing reaches
 * the file before `php -l` accepted the candidate.
 *
 * @return array{backup: string}
 */
function config_rewrite($file, $constant, $literal, array $config)
{
    $source = (string) file_get_contents($file);
    $pattern = '/define\s*\(\s*([\'"])' . preg_quote($constant, '/') . '\1\s*,\s*(.+?)\s*\)\s*;/s';
    $line = '/^[ \t]*define\s*\(\s*([\'"])' . preg_quote($constant, '/') . '\1\s*,\s*(.+?)\s*\)\s*;[ \t]*(?:(?:\/\/|#)[^\n]*)?\r?\n?/m';

    if (null === $literal) {
        $candidate = preg_replace($line, '', $source, 1, $dropped);

        if (0 === $dropped) {
            throw new RuntimeException(sprintf('%s n\'est pas définie sur une ligne à elle dans %s : à retirer à la main', $constant, $file));
        }
    } elseif (preg_match($pattern, $source)) {
        $candidate = preg_replace_callback($pattern, function ($m) use ($constant, $literal) {
            return 'define(' . $m[1] . $constant . $m[1] . ', ' . $literal . ');';
        }, $source, 1);
    } else {
        $define = sprintf("define('%s', %s);\n", $constant, $literal);
        $anchors = [
            '/^[ \t]*\/\*\*?\s*That\'s all, stop editing/mi',
            '/^[ \t]*\/\*\*?\s*C\'est tout/mi',
            '/^[ \t]*(?:require|include)(?:_once)?\s*\(?\s*ABSPATH\s*\.\s*[\'"]wp-settings\.php[\'"]/m',
        ];
        $candidate = null;

        foreach ($anchors as $anchor) {
            if (preg_match($anchor, $source, $m, PREG_OFFSET_CAPTURE)) {
                $candidate = substr($source, 0, $m[0][1]) . $define . substr($source, $m[0][1]);
                break;
            }
        }

        if (null === $candidate) {
            // No anchor: at the end, inside the PHP block when one is closed.
            $candidate = preg_match('/\?>\s*$/', $source, $m, PREG_OFFSET_CAPTURE)
                ? rtrim(substr($source, 0, $m[0][1])) . "\n" . $define . substr($source, $m[0][1])
                : rtrim($source) . "\n" . $define;
        }
    }

    $folder = restore_folder($config);

    if (!is_dir($folder) && !@mkdir($folder, 0700, true)) {
        throw new RuntimeException(sprintf('impossible de créer %s pour la copie de secours', $folder));
    }

    $stamp = gmdate('Ymd-His');
    $backup = $folder . '/wp-config-' . $stamp . '.php';
    $trial = $folder . '/wp-config-' . $stamp . '.candidate';

    if (false === file_put_contents($backup, $source) || !chmod($backup, 0600)) {
        throw new RuntimeException(sprintf('impossible d\'écrire la copie de secours %s', $backup));
    }

    file_put_contents($trial, $candidate);
    chmod($trial, 0600);
    $lint = run([$config['php'], '-n', '-l', $trial], 30);
    @unlink($trial);

    if (0 !== $lint['exit']) {
        throw new RuntimeException(sprintf('le wp-config.php réécrit ne passe pas php -l, rien n\'a été écrit : %s', last_error_line('' !== $lint['stderr'] ? $lint['stderr'] : $lint['stdout'])));
    }

    if (false === file_put_contents($file, $candidate)) {
        throw new RuntimeException(sprintf('impossible d\'écrire %s (copie de secours : %s)', $file, $backup));
    }

    $check = run([$config['php'], '-n', '-l', $file], 30);

    if (0 !== $check['exit']) {
        file_put_contents($file, $source);

        throw new RuntimeException(sprintf('%s réécrit ne passe pas php -l, copie de secours remise en place : %s', $file, last_error_line('' !== $check['stderr'] ? $check['stderr'] : $check['stdout'])));
    }

    return ['backup' => $backup];
}

/**
 * Updates through wp-cli, the one tool that knows how to swap WordPress's
 * files safely from the command line: the core, the plugins named, and
 * the themes WordPress reports behind when asked. A major release of the
 * core is only crossed when the request says so.
 *
 * @return array<string, mixed>
 */
function verb_update(array $request, array $config)
{
    if (!$config['update']) {
        throw new RuntimeException('mise à jour refusée : update=no dans la configuration de zenith-shell');
    }

    if (is_symfony_request($request)) {
        return symfony_update($request, $config);
    }

    if ('drupal' === framework($request)) {
        return drupal_update($request, $config);
    }

    $path = site_path($request);
    $wp = wp_binary($config, $path);

    if (null === $wp) {
        throw new RuntimeException('wp-cli introuvable sur cette machine : les mises à jour par SSH passent par lui');
    }

    $core = isset($request['core']) && true === $request['core'];
    $themes = isset($request['themes']) && true === $request['themes'];
    $themeItems = items($request, 'theme_items');
    $translations = isset($request['translations']) && true === $request['translations'];
    $allowMajor = isset($request['allow_major']) && true === $request['allow_major'];
    $items = items($request);
    $dryRun = isset($request['dry_run']) && true === $request['dry_run'];
    $results = [];
    $base = array_merge($wp, ['--path=' . $path, '--skip-themes', '--no-color', '--format=json']);

    if ($core) {
        // What WordPress offers, minor and major told apart: a major
        // release is named but not crossed unless allowed.
        $check = run(array_merge($base, ['core', 'check-update']), 60, $path);
        $updates = json_decode(trim($check['stdout']), true);
        $minor = null;
        $major = null;

        foreach (is_array($updates) ? $updates : [] as $update) {
            if (!is_array($update) || !isset($update['version'])) {
                continue;
            }

            if (isset($update['update_type']) && 'major' === $update['update_type']) {
                $major = null === $major ? (string) $update['version'] : $major;
            } else {
                $minor = null === $minor ? (string) $update['version'] : $minor;
            }
        }

        $target = $allowMajor ? (null !== $major ? $major : $minor) : $minor;

        if ($dryRun) {
            $message = null !== $target ? sprintf('vers %s', $target) : (null !== $major ? sprintf('montée majeure %s disponible, non autorisée', $major) : 'déjà à jour');
            $results[] = ['item' => 'core', 'status' => null !== $target ? 'planned' : 'skipped', 'message' => $message];
        } elseif (null === $target) {
            $results[] = ['item' => 'core', 'status' => 'skipped', 'message' => null !== $major ? sprintf('montée majeure %s disponible, non autorisée', $major) : 'déjà à jour'];
        } else {
            $args = array_merge($wp, ['--path=' . $path, '--skip-themes', '--no-color', 'core', 'update']);

            if (!$allowMajor) {
                $args[] = '--minor';
            }

            $run = run($args, 300, $path);
            $results[] = ['item' => 'core', 'status' => 0 === $run['exit'] ? 'updated' : 'failed', 'message' => str_cut(trim(0 === $run['exit'] ? $run['stdout'] : ($run['stderr'] ?: $run['stdout'])), 0, 200)];
        }
    }

    foreach ($items as $item) {
        $slug = false === strpos($item, '/') ? preg_replace('/\.php$/', '', $item) : dirname($item);

        if (!is_clean_slug($slug, 120) || false !== strpos($slug, '/')) {
            $results[] = ['item' => $item, 'status' => 'failed', 'message' => 'nom d\'extension invalide'];
            continue;
        }

        if ($dryRun) {
            // wp-cli's own rehearsal, in the very conditions of the real run
            // (--skip-themes): what it would update, read from the transient
            // as this process sees it (1.10.16).
            $preview = run(array_merge($wp, ['--path=' . $path, '--skip-themes', '--no-color', 'plugin', 'update', $slug, '--dry-run']), 120, $path);
            $text = trim($preview['stdout'] . "\n" . $preview['stderr']);
            $results[] = [
                'item' => $slug,
                'status' => 'planned',
                'message' => str_cut($text, 0, 300),
                'would_update' => 0 === $preview['exit'] && false !== stripos($preview['stdout'], $slug) && false === stripos($preview['stdout'], 'already updated'),
            ];
            continue;
        }

        // The directory as it is, kept aside before wp-cli replaces it: the
        // way back when the new version breaks the site, premium plugins
        // included, which wordpress.org cannot reinstall. No "--" before
        // the slug: wp-cli 2.12 reads it as a plugin name and fails the
        // whole command; is_clean_slug() already refuses a leading dash.
        $snapshot = snapshot_plugin($path, $slug);
        $pluginDir = $path . '/wp-content/plugins/' . $slug;
        $before = is_dir($pluginDir) ? plugin_version($pluginDir) : null;
        $run = run(array_merge($wp, ['--path=' . $path, '--skip-themes', '--no-color', 'plugin', 'update', $slug]), 300, $path);
        $after = is_dir($pluginDir) ? plugin_version($pluginDir) : null;
        $said = str_cut(trim(0 === $run['exit'] ? $run['stdout'] : ($run['stderr'] ?: $run['stdout'])), 0, 200);

        // wp-cli exits 0 for an update it had nothing to do about (the
        // transient it read holds no update for the plugin: « already
        // updated »): the version on disk, read before and after, says
        // whether anything happened (1.10.14, WP Rocket on OWLIA: 59
        // hourly campaigns that « updated » it without a file changed).
        if (0 === $run['exit'] && null !== $before && 'unknown' !== $before && $before === $after) {
            $results[] = [
                'item' => $slug,
                'status' => 'unchanged',
                'message' => sprintf('version %s avant et après : wp-cli n\'a rien installé (« %s »)', $before, $said),
                'snapshot' => $snapshot,
                'version_before' => $before,
                'version_after' => $after,
            ];
            continue;
        }

        $results[] = [
            'item' => $slug,
            'status' => 0 === $run['exit'] ? 'updated' : 'failed',
            'message' => $said,
            'snapshot' => $snapshot,
            'version_before' => $before,
            'version_after' => $after,
        ];
    }

    if ($themes || [] !== $themeItems) {
        foreach (update_themes($wp, $path, $dryRun, $themeItems) as $row) {
            $results[] = $row;
        }
    }

    if ($translations) {
        foreach (update_translations($wp, $path, $dryRun) as $row) {
            $results[] = $row;
        }
    }

    $failed = count(array_filter($results, function ($r) { return 'failed' === $r['status']; }));

    return ['status' => $dryRun ? 'planned' : (0 === $failed ? 'ok' : ($failed === count($results) ? 'failed' : 'partial')), 'dry_run' => $dryRun, 'results' => $results];
}

/**
 * The translations WordPress reports behind — the core's, the plugins'
 * and the themes' — updated as one lot: WordPress treats them so, and a
 * translation never breaks a site (1.9.0).
 *
 * @param string[] $wp
 *
 * @return list<array<string, mixed>>
 */
function update_translations(array $wp, $path, $dryRun)
{
    $results = [];

    // The packs the site's languages lack — an extension just installed on
    // an en_US site has no French pack yet, and wp-cli calls nothing
    // « behind » (1.10.7): installed here, so that a production in that
    // language receives them from the repository.
    foreach (['plugin' => [], 'theme' => []] as $kind => $unused) {
        $missing = array_values(array_filter(missing_language_packs($wp, $path), function ($row) use ($kind) { return $row['kind'] === $kind; }));

        if ([] === $missing) {
            continue;
        }

        $what = sprintf('%d pack(s) de langue manquant(s) : %s', count($missing), str_cut(implode(', ', array_map(function ($row) { return $row['slug'] . ' ' . $row['language']; }, array_slice($missing, 0, 50))), 0, 160));

        if ($dryRun) {
            $results[] = ['item' => 'traductions ' . $kind . ' (manquantes)', 'status' => 'planned', 'message' => $what];
            continue;
        }

        $failed = [];

        foreach (array_slice($missing, 0, 50) as $row) {
            $run = run(array_merge($wp, ['--path=' . $path, '--no-color', 'language', $kind, 'install', $row['slug'], $row['language']]), 120, $path);

            if (0 !== $run['exit']) {
                $failed[] = $row['slug'] . ' ' . $row['language'] . ' : ' . last_error_line($run['stderr'] ?: $run['stdout']);
            }
        }

        $results[] = [
            'item' => 'traductions ' . $kind . ' (manquantes)',
            'status' => [] === $failed ? 'updated' : (count($failed) === count($missing) ? 'failed' : 'updated'),
            'message' => [] === $failed ? $what : $what . ' — en échec : ' . str_cut(implode(' ; ', $failed), 0, 200),
        ];
    }

    foreach (['core' => ['core'], 'plugin' => ['plugin', '--all'], 'theme' => ['theme', '--all']] as $kind => $target) {
        $list = run(array_merge($wp, ['--path=' . $path, '--no-color', 'language'], $target, ['list', '--update=available', '--format=json']), 120, $path);
        $rows = json_decode(trim($list['stdout']), true);

        if (0 !== $list['exit'] || !is_array($rows)) {
            $results[] = ['item' => 'traductions ' . $kind, 'status' => 'failed', 'message' => sprintf('liste des traductions illisible : %s', last_error_line($list['stderr'] ?: ($list['stdout'] ?: 'wp language list a échoué')))];
            continue;
        }

        if ([] === $rows) {
            $results[] = ['item' => 'traductions ' . $kind, 'status' => 'skipped', 'message' => 'aucune traduction en retard'];
            continue;
        }

        $names = [];

        foreach (array_slice($rows, 0, 50) as $row) {
            if (!is_array($row)) {
                continue;
            }

            $names[] = trim((isset($row['plugin']) ? $row['plugin'] . ' ' : (isset($row['theme']) ? $row['theme'] . ' ' : '')) . (isset($row['language']) ? $row['language'] : ''));
        }

        $what = sprintf('%d traduction(s) : %s', count($rows), str_cut(implode(', ', array_filter($names)), 0, 160));

        if ($dryRun) {
            $results[] = ['item' => 'traductions ' . $kind, 'status' => 'planned', 'message' => $what];
            continue;
        }

        $run = run(array_merge($wp, ['--path=' . $path, '--no-color', 'language'], $target, ['update']), 300, $path);
        $results[] = [
            'item' => 'traductions ' . $kind,
            'status' => 0 === $run['exit'] ? 'updated' : 'failed',
            'message' => 0 === $run['exit'] ? $what : str_cut(trim($run['stderr'] ?: $run['stdout']), 0, 200),
        ];
    }

    return $results;
}

/**
 * The language packs wordpress.org offers for the site's languages that
 * the site does not hold: for every installed locale but en_US, every
 * plugin and theme whose pack is « uninstalled » (1.10.7). Empty when the
 * locales cannot be read — a translation never blocks anything.
 *
 * @param string[] $wp
 *
 * @return list<array{kind: string, slug: string, language: string}>
 */
function missing_language_packs(array $wp, $path)
{
    static $cache = [];

    if (isset($cache[$path])) {
        return $cache[$path];
    }

    $missing = [];
    $list = run(array_merge($wp, ['--path=' . $path, '--no-color', 'language', 'core', 'list', '--format=json', '--fields=language,status']), 120, $path);
    $rows = json_decode(trim($list['stdout']), true);
    $locales = [];

    foreach (0 === $list['exit'] && is_array($rows) ? $rows : [] as $row) {
        if (is_array($row) && isset($row['language'], $row['status']) && in_array($row['status'], ['installed', 'active'], true) && 'en_US' !== $row['language'] && preg_match('/^[a-z]{2,3}(_[A-Za-z]{2,}){0,2}$/', (string) $row['language'])) {
            $locales[] = (string) $row['language'];
        }
    }

    foreach ($locales as $locale) {
        foreach (['plugin' => 'plugin', 'theme' => 'theme'] as $kind => $field) {
            $list = run(array_merge($wp, ['--path=' . $path, '--no-color', 'language', $kind, 'list', '--all', '--status=uninstalled', '--language=' . $locale, '--format=json', '--fields=' . $field . ',language']), 120, $path);
            $rows = json_decode(trim($list['stdout']), true);

            foreach (0 === $list['exit'] && is_array($rows) ? $rows : [] as $row) {
                if (is_array($row) && isset($row[$field]) && is_clean_slug((string) $row[$field])) {
                    $missing[] = ['kind' => $kind, 'slug' => (string) $row[$field], 'language' => $locale];
                }
            }
        }
    }

    return $cache[$path] = $missing;
}

/**
 * The themes WordPress reports behind, one by one: named in a rehearsal,
 * updated otherwise. Plugins are left loaded here, since a premium theme
 * gets its updates through one of them. Never more than fifty: a site
 * with more themes than that has another problem.
 *
 * @param string[] $wp
 *
 * @return list<array<string, mixed>>
 */
function update_themes(array $wp, $path, $dryRun, array $only = [])
{
    $list = run(array_merge($wp, ['--path=' . $path, '--no-color', 'theme', 'list', '--update=available', '--fields=name,version,update_version', '--format=json']), 120, $path);
    $rows = json_decode(trim($list['stdout']), true);

    if (0 !== $list['exit'] || !is_array($rows)) {
        return [['item' => 'thèmes', 'status' => 'failed', 'message' => sprintf('liste des thèmes illisible : %s', last_error_line($list['stderr'] ?: ($list['stdout'] ?: 'wp theme list a échoué')))]];
    }

    if ([] === $rows) {
        return [['item' => 'thèmes', 'status' => 'skipped', 'message' => 'aucun thème en retard selon WordPress']];
    }

    $results = [];

    foreach (array_slice($rows, 0, 50) as $row) {
        $name = is_array($row) && isset($row['name']) ? (string) $row['name'] : '';

        if (!is_clean_slug($name, 120) || false !== strpos($name, '/')) {
            continue;
        }

        // A campaign names the themes it updates, one at a time; the
        // dashboard's button takes them all.
        if ([] !== $only && !in_array($name, $only, true)) {
            continue;
        }

        $transition = isset($row['version'], $row['update_version']) ? sprintf('%s → %s', $row['version'], $row['update_version']) : null;

        if ($dryRun) {
            $results[] = ['item' => 'thème ' . $name, 'status' => 'planned', 'message' => $transition];
            continue;
        }

        $run = run(array_merge($wp, ['--path=' . $path, '--no-color', 'theme', 'update', $name]), 300, $path);
        $results[] = [
            'item' => 'thème ' . $name,
            'status' => 0 === $run['exit'] ? 'updated' : 'failed',
            'message' => 0 === $run['exit'] && null !== $transition ? $transition : str_cut(trim($run['stderr'] ?: $run['stdout']), 0, 200),
        ];
    }

    return $results;
}

// ------------------------------------------- updates, git, db (1.9.0)

/**
 * What WordPress reports behind, read for a campaign to plan from: the
 * core with its minor and major candidates, every plugin and theme with
 * an update, the translations, the state of the Git worktree and the room
 * on disk. A reading: it needs no update=yes, but it does ask wordpress.org
 * through wp-cli.
 *
 * @return array<string, mixed>
 */
function verb_updates(array $request, array $config)
{
    if (is_symfony_request($request)) {
        return symfony_updates($request, $config);
    }

    if ('drupal' === framework($request)) {
        return drupal_updates($request, $config);
    }

    $path = site_path($request);
    $wp = wp_binary($config, $path);

    if (null === $wp) {
        throw new RuntimeException('wp-cli introuvable sur cette machine : l\'inventaire des mises à jour passe par lui');
    }

    $base = array_merge($wp, ['--path=' . $path, '--no-color', '--format=json']);
    $out = ['core' => null, 'plugins' => [], 'themes' => [], 'translations' => [], 'errors' => []];

    $version = run(array_merge($wp, ['--path=' . $path, '--no-color', '--skip-plugins', '--skip-themes', 'core', 'version']), 60, $path);
    $check = run(array_merge($base, ['core', 'check-update']), 90, $path);
    $updates = json_decode(trim($check['stdout']), true);
    $minor = null;
    $major = null;

    foreach (is_array($updates) ? $updates : [] as $update) {
        if (!is_array($update) || !isset($update['version'])) {
            continue;
        }

        if (isset($update['update_type']) && 'major' === $update['update_type']) {
            $major = null === $major ? (string) $update['version'] : $major;
        } else {
            $minor = null === $minor ? (string) $update['version'] : $minor;
        }
    }

    $out['core'] = ['current' => 0 === $version['exit'] ? trim($version['stdout']) : null, 'minor' => $minor, 'major' => $major];

    if (0 !== $check['exit'] && 0 !== strpos(trim($check['stdout']), '[')) {
        $out['errors'][] = 'cœur : ' . last_error_line($check['stderr'] ?: $check['stdout']);
    }

    // The requirements of the new version travel with it when wp-cli
    // knows them (2.5+): what explains an update it calls unavailable.
    $plugins = run(array_merge($base, ['plugin', 'list', '--fields=name,title,status,version,update,update_version,auto_update,requires,requires_php,update_package']), 120, $path);
    $rows = json_decode(trim($plugins['stdout']), true);

    if (0 !== $plugins['exit'] || !is_array($rows)) {
        $plugins = run(array_merge($base, ['plugin', 'list', '--fields=name,title,status,version,update,update_version,auto_update']), 120, $path);
        $rows = json_decode(trim($plugins['stdout']), true);
    }

    if (0 !== $plugins['exit'] || !is_array($rows)) {
        $out['errors'][] = 'extensions : ' . last_error_line($plugins['stderr'] ?: ($plugins['stdout'] ?: 'wp plugin list a échoué'));
    } else {
        foreach ($rows as $row) {
            if (!is_array($row) || !isset($row['name']) || !is_clean_slug((string) $row['name'], 120)) {
                continue;
            }

            $out['plugins'][] = [
                'name' => (string) $row['name'],
                'title' => isset($row['title']) ? str_cut((string) $row['title'], 0, 80) : (string) $row['name'],
                'status' => isset($row['status']) ? (string) $row['status'] : null,
                'version' => isset($row['version']) ? (string) $row['version'] : null,
                'update' => isset($row['update']) ? (string) $row['update'] : 'none',
                'update_version' => isset($row['update_version']) && '' !== (string) $row['update_version'] ? (string) $row['update_version'] : null,
                'auto_update' => isset($row['auto_update']) ? (string) $row['auto_update'] : null,
                'requires' => isset($row['requires']) && '' !== (string) $row['requires'] ? (string) $row['requires'] : null,
                'requires_php' => isset($row['requires_php']) && '' !== (string) $row['requires_php'] ? (string) $row['requires_php'] : null,
                'update_package' => isset($row['update_package']) ? ('' !== (string) $row['update_package']) : null,
            ];
        }
    }

    $themes = run(array_merge($base, ['theme', 'list', '--fields=name,title,status,version,update,update_version']), 120, $path);
    $rows = json_decode(trim($themes['stdout']), true);

    if (0 !== $themes['exit'] || !is_array($rows)) {
        $out['errors'][] = 'thèmes : ' . last_error_line($themes['stderr'] ?: ($themes['stdout'] ?: 'wp theme list a échoué'));
    } else {
        foreach ($rows as $row) {
            if (!is_array($row) || !isset($row['name']) || !is_clean_slug((string) $row['name'], 120)) {
                continue;
            }

            $out['themes'][] = [
                'name' => (string) $row['name'],
                'title' => isset($row['title']) ? str_cut((string) $row['title'], 0, 80) : (string) $row['name'],
                'status' => isset($row['status']) ? (string) $row['status'] : null,
                'version' => isset($row['version']) ? (string) $row['version'] : null,
                'update' => isset($row['update']) ? (string) $row['update'] : 'none',
                'update_version' => isset($row['update_version']) && '' !== (string) $row['update_version'] ? (string) $row['update_version'] : null,
            ];
        }
    }

    foreach (['core' => ['core'], 'plugin' => ['plugin', '--all'], 'theme' => ['theme', '--all']] as $kind => $target) {
        $list = run(array_merge($wp, ['--path=' . $path, '--no-color', 'language'], $target, ['list', '--update=available', '--format=json']), 120, $path);
        $rows = json_decode(trim($list['stdout']), true);

        if (0 !== $list['exit'] || !is_array($rows)) {
            $out['errors'][] = 'traductions ' . $kind . ' : ' . last_error_line($list['stderr'] ?: ($list['stdout'] ?: 'wp language list a échoué'));
            continue;
        }

        foreach (array_slice($rows, 0, 100) as $row) {
            if (!is_array($row)) {
                continue;
            }

            $out['translations'][] = [
                'kind' => $kind,
                'slug' => isset($row['plugin']) ? (string) $row['plugin'] : (isset($row['theme']) ? (string) $row['theme'] : 'core'),
                'language' => isset($row['language']) ? (string) $row['language'] : null,
                'version' => isset($row['version']) ? (string) $row['version'] : null,
            ];
        }
    }

    // The packs the site's languages lack, which an update would never
    // bring (1.10.7): listed with the translations behind, installed with
    // them.
    foreach (array_slice(missing_language_packs($wp, $path), 0, 100) as $row) {
        $out['translations'][] = ['kind' => $row['kind'], 'slug' => $row['slug'], 'language' => $row['language'], 'version' => null, 'missing' => true];
    }

    $out['git'] = git_status($path);
    $out['disk'] = ['free_bytes' => @disk_free_space($path) ?: null, 'total_bytes' => @disk_total_space($path) ?: null];
    $out['tools'] = ['wp' => implode(' ', $wp), 'git' => which('git'), 'mysqldump' => which('mysqldump') ?: which('mariadb-dump'), 'gzip' => which('gzip')];

    return $out;
}

/**
 * The Git repository above the site, driven for a campaign: read, a
 * branch opened, the changes committed, the branch pushed, the worktree
 * put back. Every write needs update=yes; a push carries its token in the
 * environment of the child process and nowhere else; a hard reset is only
 * accepted on a branch the campaign opened (zenith/…).
 *
 * @return array<string, mixed>
 */
function verb_git(array $request, array $config)
{
    $action = isset($request['action']) && is_string($request['action']) ? $request['action'] : 'status';
    $path = site_path($request);
    $status = git_status($path);

    if (!is_array($status) || true !== $status['available']) {
        throw new RuntimeException('dépôt Git indisponible : ' . (is_array($status) && isset($status['reason']) ? $status['reason'] : 'aucun dépôt'));
    }

    $root = $status['repo_root'];
    $git = function (array $args, $timeout = 60, array $env = null) use ($root) {
        return run(array_merge(['git', '-C', $root], $args), $timeout, $root, null, $env);
    };

    if ('status' === $action) {
        // A private repository answers ls-remote only with credentials:
        // the token, when Zenith hands one, travels as for the push.
        $token = isset($request['token']) && is_string($request['token']) ? $request['token'] : '';

        return git_status_detail($status, $git, $token);
    }

    if ('show' === $action) {
        // What one commit touched, file by file: a campaign reads the
        // commit of an update to see whether it stayed in its own folder.
        $ref = isset($request['ref']) && is_string($request['ref']) && preg_match('/^[0-9a-f]{7,40}$/i', $request['ref']) ? $request['ref'] : '';

        if ('' === $ref) {
            throw new RuntimeException('référence invalide : un SHA est attendu');
        }

        $run = $git(['show', '--numstat', '--format=%H%x1f%s', $ref], 60);

        if (0 !== $run['exit']) {
            return ['status' => 'failed', 'message' => last_error_line($run['stderr'] ?: $run['stdout'])];
        }

        $lines = preg_split('/\R/', trim($run['stdout'])) ?: [];
        $head = explode("\x1f", (string) array_shift($lines));
        $files = [];
        $added = 0;
        $deleted = 0;
        $total = 0;

        foreach ($lines as $line) {
            $parts = preg_split('/\t/', $line);

            if (!is_array($parts) || 3 !== count($parts)) {
                continue;
            }

            ++$total;

            $file = $parts[2];

            if (false !== strpos($file, ' => ')) {
                $file = preg_replace('/\{[^}]* => ([^}]*)\}/', '$1', $file);
                $file = preg_replace('/^.* => /', '', (string) $file);
            }

            $plus = is_numeric($parts[0]) ? (int) $parts[0] : 0;
            $minus = is_numeric($parts[1]) ? (int) $parts[1] : 0;
            $added += $plus;
            $deleted += $minus;

            if (count($files) < 400) {
                $files[] = ['path' => (string) $file, 'added' => $plus, 'deleted' => $minus, 'binary' => '-' === $parts[0]];
            }
        }

        return ['status' => 'ok', 'sha' => isset($head[0]) ? $head[0] : $ref, 'subject' => isset($head[1]) ? str_cut($head[1], 0, 160) : '', 'files' => $files, 'total' => $total, 'added' => $added, 'deleted' => $deleted];
    }

    if (!$config['update']) {
        throw new RuntimeException('écriture Git refusée : update=no dans la configuration de zenith-shell');
    }

    $branch = isset($request['branch']) && is_string($request['branch']) ? $request['branch'] : '';
    $isCampaignBranch = function ($name) {
        return 1 === preg_match('#^zenith/[A-Za-z0-9._-]{1,80}$#', $name);
    };

    switch ($action) {
        case 'branch':
            if (!$isCampaignBranch($branch)) {
                throw new RuntimeException('nom de branche refusé : attendu zenith/<nom>');
            }

            $run = $git(['checkout', '-B', $branch]);

            if (0 !== $run['exit']) {
                return ['status' => 'failed', 'message' => last_error_line($run['stderr'] ?: $run['stdout'])];
            }

            return ['status' => 'ok', 'branch' => $branch, 'from' => $status['branch'], 'base' => $status['head']];

        case 'commit':
            if (!$isCampaignBranch($status['branch'])) {
                throw new RuntimeException('commit refusé hors d\'une branche zenith/… (branche courante : ' . $status['branch'] . ')');
            }

            $message = isset($request['message']) && is_string($request['message']) ? trim($request['message']) : '';

            if ('' === $message) {
                throw new RuntimeException('message de commit manquant');
            }

            $paths = items($request, 'paths');
            $add = $git(array_merge(['add', '-A', '--'], [] === $paths ? ['.'] : $paths), 120);

            if (0 !== $add['exit']) {
                return ['status' => 'failed', 'message' => 'git add : ' . last_error_line($add['stderr'] ?: $add['stdout'])];
            }

            $staged = $git(['diff', '--cached', '--shortstat']);

            if ('' === trim($staged['stdout'])) {
                return ['status' => 'skipped', 'message' => 'rien à committer', 'sha' => null, 'summary' => null];
            }

            $name = isset($request['author_name']) && is_string($request['author_name']) && '' !== $request['author_name'] ? $request['author_name'] : 'Zenith';
            $email = isset($request['author_email']) && is_string($request['author_email']) && '' !== $request['author_email'] ? $request['author_email'] : 'zenith@feelandclic.com';
            $commit = $git(['-c', 'user.name=' . $name, '-c', 'user.email=' . $email, 'commit', '-q', '-m', $message], 120);

            if (0 !== $commit['exit']) {
                return ['status' => 'failed', 'message' => 'git commit : ' . last_error_line($commit['stderr'] ?: $commit['stdout'])];
            }

            $sha = $git(['rev-parse', 'HEAD']);

            return ['status' => 'ok', 'sha' => trim($sha['stdout']), 'summary' => trim($staged['stdout']), 'branch' => $status['branch']];

        case 'push':
            if (!$isCampaignBranch($status['branch'])) {
                throw new RuntimeException('push refusé hors d\'une branche zenith/… (branche courante : ' . $status['branch'] . ')');
            }

            $token = isset($request['token']) && is_string($request['token']) ? $request['token'] : '';
            $remote = isset($status['remote']) ? (string) $status['remote'] : '';

            if ('' === $token) {
                throw new RuntimeException('jeton GitHub manquant pour le push');
            }

            if (!preg_match('#^https://github\.com/#i', $remote)) {
                throw new RuntimeException('le dépôt distant n\'est pas un dépôt GitHub en HTTPS : ' . $remote);
            }

            // The token travels in the child's environment and is read by
            // the credential helper; it never appears in a command line.
            $helper = '!f() { echo "username=x-access-token"; echo "password=$ZENITH_GIT_TOKEN"; }; f';
            $push = $git(['-c', 'credential.helper=', '-c', 'credential.helper=' . $helper, 'push', '-u', 'origin', $status['branch']], 180, ['ZENITH_GIT_TOKEN' => $token, 'GIT_TERMINAL_PROMPT' => '0']);

            if (0 !== $push['exit']) {
                return ['status' => 'failed', 'message' => 'git push : ' . last_error_line(str_replace($token, '***', $push['stderr'] ?: $push['stdout']))];
            }

            return ['status' => 'ok', 'branch' => $status['branch'], 'remote' => $remote, 'head' => $status['head']];

        case 'checkout':
            if ('' === $branch || !preg_match('#^[A-Za-z0-9._/-]{1,120}$#', $branch) || false !== strpos($branch, '..')) {
                throw new RuntimeException('nom de branche invalide');
            }

            $run = $git(['checkout', '-q', $branch]);

            return 0 === $run['exit'] ? ['status' => 'ok', 'branch' => $branch] : ['status' => 'failed', 'message' => last_error_line($run['stderr'] ?: $run['stdout'])];

        case 'pull':
            // The branch the site serves, brought even with origin once the
            // pull request is merged: fast-forward only, token in the
            // environment as for the push.
            if ('' === $branch || !preg_match('#^[A-Za-z0-9._/-]{1,120}$#', $branch) || false !== strpos($branch, '..') || $branch !== $status['branch']) {
                throw new RuntimeException('pull refusé : la branche demandée doit être la branche courante');
            }

            $token = isset($request['token']) && is_string($request['token']) ? $request['token'] : '';
            $helper = '!f() { echo "username=x-access-token"; echo "password=$ZENITH_GIT_TOKEN"; }; f';
            $args = '' === $token ? ['pull', '--ff-only', '-q', 'origin', $branch] : ['-c', 'credential.helper=', '-c', 'credential.helper=' . $helper, 'pull', '--ff-only', '-q', 'origin', $branch];
            $pull = $git($args, 180, '' === $token ? null : ['ZENITH_GIT_TOKEN' => $token, 'GIT_TERMINAL_PROMPT' => '0']);

            if (0 !== $pull['exit']) {
                return ['status' => 'failed', 'message' => 'git pull : ' . last_error_line('' === $token ? ($pull['stderr'] ?: $pull['stdout']) : str_replace($token, '***', $pull['stderr'] ?: $pull['stdout']))];
            }

            $head = $git(['rev-parse', 'HEAD']);

            return ['status' => 'ok', 'branch' => $branch, 'head' => trim($head['stdout'])];

        case 'delete_branch':
            if (!$isCampaignBranch($branch) || $branch === $status['branch']) {
                throw new RuntimeException('seule une branche zenith/… autre que la branche courante peut être supprimée');
            }

            $run = $git(['branch', '-D', $branch]);

            return 0 === $run['exit'] ? ['status' => 'ok', 'branch' => $branch] : ['status' => 'failed', 'message' => last_error_line($run['stderr'] ?: $run['stdout'])];

        case 'reset':
            if (!$isCampaignBranch($status['branch'])) {
                throw new RuntimeException('reset refusé hors d\'une branche zenith/… (branche courante : ' . $status['branch'] . ')');
            }

            $ref = isset($request['ref']) && is_string($request['ref']) && preg_match('/^[0-9a-f]{7,40}$/i', $request['ref']) ? $request['ref'] : '';

            if ('' === $ref) {
                throw new RuntimeException('référence de reset invalide : un SHA est attendu');
            }

            $run = $git(['reset', '-q', '--hard', $ref], 120);

            return 0 === $run['exit'] ? ['status' => 'ok', 'head' => $ref] : ['status' => 'failed', 'message' => last_error_line($run['stderr'] ?: $run['stdout'])];

        case 'discard':
            // What an update left in the worktree when its acceptance run
            // failed: tracked files put back, new files removed. Only on
            // a campaign branch, which started from a clean tree.
            if (!$isCampaignBranch($status['branch'])) {
                throw new RuntimeException('discard refusé hors d\'une branche zenith/… (branche courante : ' . $status['branch'] . ')');
            }

            $checkout = $git(['checkout', '-q', '--', '.'], 120);
            $clean = $git(['clean', '-qfd'], 120);

            if (0 !== $checkout['exit'] || 0 !== $clean['exit']) {
                return ['status' => 'failed', 'message' => last_error_line(($checkout['stderr'] ?: '') . ($clean['stderr'] ?: ''))];
            }

            return ['status' => 'ok', 'branch' => $status['branch']];

        case 'log':
            $limit = isset($request['limit']) && is_int($request['limit']) ? max(1, min(50, $request['limit'])) : 10;
            $run = $git(['log', '-n', (string) $limit, '--format=%H%x1f%cI%x1f%an%x1f%s']);
            $entries = [];

            foreach (preg_split('/\R/', trim($run['stdout'])) ?: [] as $line) {
                $parts = explode("\x1f", $line);

                if (4 === count($parts)) {
                    $entries[] = ['sha' => $parts[0], 'at' => $parts[1], 'author' => $parts[2], 'subject' => str_cut($parts[3], 0, 160)];
                }
            }

            return ['status' => 'ok', 'commits' => $entries];

        default:
            throw new RuntimeException(sprintf('action git inconnue : %s', $action));
    }
}

/**
 * The worktree, by where its changes are: a count per top directory, the
 * ignored paths left out. What a pre-flight shows when it refuses to start
 * on a dirty tree.
 *
 * @param array<string, mixed> $status
 *
 * @return array<string, mixed>
 */
function git_status_detail(array $status, $git, $token = '')
{
    $porcelain = $git(['status', '--porcelain=v1', '--untracked-files=all'], 60);
    $byDir = [];
    $byKind = ['modified' => 0, 'added' => 0, 'deleted' => 0, 'untracked' => 0, 'other' => 0];
    $samples = [];

    // No trim on the whole output: the first line may open with a space,
    // which is its status column.
    foreach (preg_split('/\R/', rtrim($porcelain['stdout'])) ?: [] as $line) {
        if (strlen($line) < 4) {
            continue;
        }

        $code = substr($line, 0, 2);
        $file = trim(substr($line, 3));

        if (false !== ($arrow = strpos($file, ' -> '))) {
            $file = substr($file, $arrow + 4);
        }

        $kind = '??' === $code ? 'untracked' : (false !== strpos($code, 'D') ? 'deleted' : (false !== strpos($code, 'A') ? 'added' : (false !== strpos($code, 'M') ? 'modified' : 'other')));
        ++$byKind[$kind];
        $segments = explode('/', trim($file, '/'));
        $dir = implode('/', array_slice($segments, 0, min(5, max(1, count($segments) - 1))));
        $byDir[$dir] = (isset($byDir[$dir]) ? $byDir[$dir] : 0) + 1;

        if (count($samples) < 20) {
            $samples[] = $file;
        }
    }

    arsort($byDir);
    $dirs = [];

    foreach (array_slice($byDir, 0, 25, true) as $dir => $count) {
        $dirs[] = ['dir' => $dir, 'count' => $count];
    }

    $helper = '!f() { echo "username=x-access-token"; echo "password=$ZENITH_GIT_TOKEN"; }; f';
    $remote = '' === $token
        ? $git(['ls-remote', '--heads', 'origin', (string) $status['branch']], 30, ['GIT_TERMINAL_PROMPT' => '0'])
        : $git(['-c', 'credential.helper=', '-c', 'credential.helper=' . $helper, 'ls-remote', '--heads', 'origin', (string) $status['branch']], 30, ['ZENITH_GIT_TOKEN' => $token, 'GIT_TERMINAL_PROMPT' => '0']);
    $remoteHead = null;

    if (0 === $remote['exit'] && preg_match('/^([0-9a-f]{40})\s/', trim($remote['stdout']), $m)) {
        $remoteHead = $m[1];
    }

    return $status + [
        'changes' => ['by_kind' => $byKind, 'by_dir' => $dirs, 'total' => array_sum($byKind), 'samples' => $samples],
        'remote_reachable' => 0 === $remote['exit'],
        'remote_head' => $remoteHead,
        'remote_error' => 0 === $remote['exit'] ? null : last_error_line('' === $token ? ($remote['stderr'] ?: $remote['stdout']) : str_replace($token, '***', $remote['stderr'] ?: $remote['stdout'])),
    ];
}

/**
 * The restore point of a campaign: the database dumped before anything
 * is updated, kept outside the web root next to the shell's configuration,
 * put back if the campaign is rolled back, dropped when it is over. Every
 * action needs update=yes; a file is only ever named inside that folder.
 *
 * @return array<string, mixed>
 */
function verb_db(array $request, array $config)
{
    if (is_symfony_request($request)) {
        return symfony_db($request, $config);
    }

    if ('drupal' === framework($request)) {
        return drupal_db($request, $config);
    }

    if (!$config['update']) {
        throw new RuntimeException('point de reprise refusé : update=no dans la configuration de zenith-shell');
    }

    $action = isset($request['action']) && is_string($request['action']) ? $request['action'] : 'list';
    $path = site_path($request);
    $wp = wp_binary($config, $path);
    $folder = restore_folder($config);

    if ('list' === $action) {
        return ['status' => 'ok', 'folder' => $folder, 'files' => restore_files($folder)];
    }

    if (null === $wp) {
        throw new RuntimeException('wp-cli introuvable : le point de reprise passe par lui');
    }

    switch ($action) {
        case 'dump':
            if (!is_dir($folder) && !@mkdir($folder, 0700, true)) {
                throw new RuntimeException('dossier de reprise non créé : ' . $folder);
            }

            @chmod($folder, 0700);
            $file = $folder . '/' . gmdate('Ymd-His') . '.sql';
            $dump = run(array_merge($wp, ['--path=' . $path, '--skip-plugins', '--skip-themes', '--no-color', 'db', 'export', $file, '--add-drop-table', '--single-transaction', '--quick']), 600, $path);

            if (0 !== $dump['exit'] || !is_file($file)) {
                @unlink($file);

                return ['status' => 'failed', 'message' => 'wp db export : ' . last_error_line($dump['stderr'] ?: $dump['stdout'])];
            }

            $size = (int) filesize($file);

            if (null !== which('gzip')) {
                $zip = run(['gzip', '-f', $file], 300);

                if (0 === $zip['exit'] && is_file($file . '.gz')) {
                    $file .= '.gz';
                }
            }

            @chmod($file, 0600);

            return ['status' => 'ok', 'file' => basename($file), 'folder' => $folder, 'bytes' => (int) filesize($file), 'sql_bytes' => $size, 'seconds' => $dump['seconds']];

        case 'restore':
            $file = restore_file($folder, $request);
            $import = '.gz' === substr($file, -3)
                ? run(['sh', '-c', 'gunzip -c "$0" | ' . implode(' ', array_map('escapeshellarg', array_merge($wp, ['--path=' . $path, '--skip-plugins', '--skip-themes', '--no-color', 'db', 'import', '-']))), $file], 900, $path)
                : run(array_merge($wp, ['--path=' . $path, '--skip-plugins', '--skip-themes', '--no-color', 'db', 'import', $file]), 900, $path);

            if (0 !== $import['exit']) {
                return ['status' => 'failed', 'message' => 'wp db import : ' . last_error_line($import['stderr'] ?: $import['stdout'])];
            }

            return ['status' => 'ok', 'file' => basename($file), 'seconds' => $import['seconds']];

        case 'delete':
            $file = restore_file($folder, $request);
            @unlink($file);

            return ['status' => is_file($file) ? 'failed' : 'ok', 'file' => basename($file)];

        case 'verify':
            // Is the restore point one a rollback could rely on? The
            // archive readable end to end, the dump closed by mysqldump's
            // own last line, as many tables in it as in the live base.
            // Cheaper than a restore into a scratch base, which a shared
            // host rarely allows, and enough to catch a dump cut short.
            $file = restore_file($folder, $request);
            $gz = '.gz' === substr($file, -3);
            $gzipOk = true;

            if ($gz) {
                $test = run(['gzip', '-t', $file], 300);
                $gzipOk = 0 === $test['exit'];
            }

            $count = $gz
                ? run(['sh', '-c', 'gunzip -c "$0" | grep -c "^CREATE TABLE"', $file], 300)
                : run(['grep', '-c', '^CREATE TABLE', $file], 300);
            $inDump = is_numeric(trim($count['stdout'])) ? (int) trim($count['stdout']) : 0;
            $tail = $gz
                ? run(['sh', '-c', 'gunzip -c "$0" | tail -c 400', $file], 300)
                : run(['tail', '-c', '400', $file], 60);
            $complete = false !== strpos($tail['stdout'], 'Dump completed');
            $tables = run(array_merge($wp, ['--path=' . $path, '--skip-plugins', '--skip-themes', '--no-color', 'db', 'tables', '--all-tables', '--format=csv']), 120, $path);
            $live = 0 === $tables['exit'] ? table_count($tables['stdout']) : null;
            $ok = $gzipOk && $complete && $inDump > 0 && (null === $live || $inDump >= $live);
            $why = [];

            if (!$gzipOk) {
                $why[] = 'archive gzip illisible';
            }

            if (!$complete) {
                $why[] = 'dump sans ligne de fin (tronqué ?)';
            }

            if (null !== $live && $inDump < $live) {
                $why[] = sprintf('%d table(s) dans le dump, %d dans la base', $inDump, $live);
            }

            return ['status' => $ok ? 'ok' : 'failed', 'file' => basename($file), 'bytes' => (int) filesize($file), 'gzip_ok' => $gzipOk, 'complete' => $complete, 'tables_in_dump' => $inDump, 'tables_live' => $live, 'message' => [] === $why ? null : implode(' ; ', $why)];

        default:
            throw new RuntimeException(sprintf('action db inconnue : %s', $action));
    }
}

/**
 * What a campaign checks around an update, beyond the pages: the state of
 * WordPress itself (which plugins are active, which theme, the options a
 * broken update silently changes), the files of the core and of a plugin
 * against the checksums wordpress.org publishes, and the database schema
 * brought up to the core just installed. Reads need nothing; update_db
 * writes, and needs update=yes.
 *
 * @return array<string, mixed>
 */
function verb_verify(array $request, array $config)
{
    if (is_symfony_request($request)) {
        return symfony_verify($request, $config);
    }

    if ('drupal' === framework($request)) {
        return drupal_verify($request, $config);
    }

    $action = isset($request['action']) && is_string($request['action']) ? $request['action'] : 'state';
    $path = site_path($request);
    $wp = wp_binary($config, $path);

    if (null === $wp) {
        throw new RuntimeException('wp-cli introuvable : la vérification passe par lui');
    }

    // The plugins' own code left out: a plugin that fatals at load would
    // otherwise take the reading down with it, which is the very thing
    // the reading is meant to show.
    $quiet = array_merge($wp, ['--path=' . $path, '--skip-plugins', '--skip-themes', '--no-color']);

    switch ($action) {
        case 'state':
            $code = 'echo json_encode(['
                . '"active_plugins" => array_values(array_map("strval", (array) get_option("active_plugins", []))),'
                . '"network_plugins" => is_multisite() ? array_keys((array) get_site_option("active_sitewide_plugins", [])) : [],'
                . '"template" => (string) get_option("template"),'
                . '"stylesheet" => (string) get_option("stylesheet"),'
                . '"siteurl" => (string) get_option("siteurl"),'
                . '"home" => (string) get_option("home"),'
                . '"permalink_structure" => (string) get_option("permalink_structure"),'
                . '"blog_public" => (string) get_option("blog_public"),'
                . '"users_can_register" => (string) get_option("users_can_register"),'
                . '"default_role" => (string) get_option("default_role"),'
                . '"WPLANG" => (string) get_option("WPLANG"),'
                . '"db_version" => (string) get_option("db_version"),'
                . '"wp_db_version" => (string) $GLOBALS["wp_db_version"],'
                . '"initial_db_version" => (string) get_option("initial_db_version"),'
                . ']);';
            $eval = run(array_merge($quiet, ['eval', $code]), 60, $path);
            $options = json_decode(trim($eval['stdout']), true);

            if (0 !== $eval['exit'] || !is_array($options)) {
                return ['status' => 'failed', 'message' => 'wp eval : ' . last_error_line($eval['stderr'] ?: ($eval['stdout'] ?: 'sans réponse'))];
            }

            // --skip-update-check: run with every plugin skipped, `plugin list`
            // would otherwise drop and rebuild the update_plugins transient
            // without the updates the plugins add for themselves (WP Rocket,
            // the agent…), and the update that follows would read « already
            // updated » (OWLIA, 59 campaigns, 29/10-02/11). Same for themes.
            $list = run(array_merge($quiet, ['plugin', 'list', '--skip-update-check', '--fields=name,status,version', '--format=json']), 120, $path);
            $rows = json_decode(trim($list['stdout']), true);
            $plugins = [];

            foreach (is_array($rows) ? $rows : [] as $row) {
                if (is_array($row) && isset($row['name']) && is_clean_slug((string) $row['name'], 120)) {
                    $plugins[(string) $row['name']] = ['status' => isset($row['status']) ? (string) $row['status'] : null, 'version' => isset($row['version']) ? (string) $row['version'] : null];
                }
            }

            $themes = run(array_merge($quiet, ['theme', 'list', '--skip-update-check', '--fields=name,status,version', '--format=json']), 120, $path);
            $rows = json_decode(trim($themes['stdout']), true);
            $themeRows = [];

            foreach (is_array($rows) ? $rows : [] as $row) {
                if (is_array($row) && isset($row['name']) && is_clean_slug((string) $row['name'], 120)) {
                    $themeRows[(string) $row['name']] = ['status' => isset($row['status']) ? (string) $row['status'] : null, 'version' => isset($row['version']) ? (string) $row['version'] : null];
                }
            }

            $tables = run(array_merge($quiet, ['db', 'tables', '--all-tables', '--format=csv']), 120, $path);
            $active = $options['active_plugins'];
            $network = $options['network_plugins'];
            unset($options['active_plugins'], $options['network_plugins']);

            return [
                'status' => 'ok',
                'active_plugins' => $active,
                'network_plugins' => $network,
                'plugins' => $plugins,
                'themes' => $themeRows,
                'options' => $options,
                'tables' => 0 === $tables['exit'] ? table_count($tables['stdout']) : null,
                'db_upgrade_needed' => isset($options['db_version'], $options['wp_db_version']) && '' !== $options['db_version'] && $options['db_version'] !== $options['wp_db_version'],
                'plugin_list_ok' => 0 === $list['exit'] && is_array(json_decode(trim($list['stdout']), true)),
            ];

        case 'checksums':
            $out = ['status' => 'ok', 'core' => null, 'plugins' => []];

            if (isset($request['core']) && true === $request['core']) {
                $core = run(array_merge($quiet, ['core', 'verify-checksums']), 300, $path);
                $out['core'] = checksum_reading($core, null);
            }

            foreach (items($request, 'plugins') as $slug) {
                $plugin = run(array_merge($quiet, ['plugin', 'verify-checksums', $slug, '--format=json']), 300, $path);
                $out['plugins'][$slug] = checksum_reading($plugin, $slug);
            }

            foreach (array_merge([$out['core']], array_values($out['plugins'])) as $reading) {
                if (is_array($reading) && 'failed' === $reading['status']) {
                    $out['status'] = 'failed';
                }
            }

            return $out;

        case 'update_db':
            if (!$config['update']) {
                throw new RuntimeException('update-db refusé : update=no dans la configuration de zenith-shell');
            }

            // Plugins loaded this time: the upgrade routine fires hooks
            // the plugins listen to.
            $run = run(array_merge($wp, ['--path=' . $path, '--skip-themes', '--no-color', 'core', 'update-db']), 300, $path);
            $message = trim($run['stdout'] ?: $run['stderr']);

            return ['status' => 0 === $run['exit'] ? 'ok' : 'failed', 'message' => str_cut(last_error_line($message) ?: $message, 0, 200), 'already' => false !== stripos($message, 'already')];

        default:
            throw new RuntimeException(sprintf('action verify inconnue : %s', $action));
    }
}

/**
 * One verify-checksums run, read: ok when every file verifies, failed
 * with the files that do not, unknown when wordpress.org publishes no
 * checksums for this version (a premium plugin, a plugin not on the
 * directory), which is not a finding.
 *
 * @param array{exit: int, stdout: string, stderr: string} $run
 *
 * @return array{status: string, files: list<string>, message: ?string}
 */
function checksum_reading(array $run, $slug)
{
    $text = $run['stderr'] . "\n" . $run['stdout'];

    if (0 === $run['exit'] && false === stripos($text, 'Warning:') && false === stripos($text, 'Error:')) {
        return ['status' => 'ok', 'files' => [], 'message' => null];
    }

    if (preg_match('/could not retrieve|no checksums|not available|unable to retrieve|does not exist/i', $text)) {
        return ['status' => 'unknown', 'files' => [], 'message' => str_cut(last_error_line($text), 0, 160)];
    }

    $files = [];
    $rows = json_decode(trim($run['stdout']), true);

    if (is_array($rows)) {
        foreach ($rows as $row) {
            if (is_array($row) && isset($row['file']) && count($files) < 50) {
                $files[] = (string) $row['file'] . (isset($row['message']) ? ' (' . str_cut((string) $row['message'], 0, 60) . ')' : '');
            }
        }
    }

    if ([] === $files) {
        foreach (preg_split('/\R/', $text) ?: [] as $line) {
            if (preg_match('/^Warning:\s+(.*)$/', trim($line), $m) && count($files) < 50) {
                $files[] = str_cut($m[1], 0, 160);
            }
        }
    }

    return ['status' => 'failed', 'files' => $files, 'message' => [] === $files ? str_cut(last_error_line($text), 0, 160) : sprintf('%d fichier(s) ne correspondent pas', count($files))];
}

/**
 * How many tables `wp db tables --format=csv` names: one line, comma
 * separated (not one per line, which 1.10.0 first assumed).
 */
function table_count($stdout)
{
    return count(array_filter(preg_split('/[\s,]+/', trim((string) $stdout)) ?: [], 'strlen'));
}

function restore_folder(array $config)
{
    $base = is_string($config['file']) && '' !== $config['file'] ? dirname($config['file']) : sys_get_temp_dir();

    return rtrim($base, '/') . '/restore';
}

/**
 * @return list<array<string, mixed>>
 */
function restore_files($folder)
{
    $files = [];

    foreach (glob($folder . '/*.sql*') ?: [] as $file) {
        $files[] = ['file' => basename($file), 'bytes' => (int) filesize($file), 'modified_at' => gmdate('Y-m-d H:i:s', (int) filemtime($file))];
    }

    return $files;
}

/**
 * A file named by the request, confined to the restore folder.
 */
function restore_file($folder, array $request)
{
    $name = isset($request['file']) && is_string($request['file']) ? basename($request['file']) : '';

    if ('' === $name || !preg_match('/^[0-9]{8}-[0-9]{6}\.sql(\.gz)?$/', $name) || !is_file($folder . '/' . $name)) {
        throw new RuntimeException('point de reprise introuvable : ' . $name);
    }

    return $folder . '/' . $name;
}

// --------------------------------------------------- describe, the sections

/**
 * @return array<string, mixed>
 */
function inodes($path)
{
    $result = run(['df', '-Pi', $path], 10);

    if (0 !== $result['exit']) {
        return ['inodes_total' => null, 'inodes_free' => null];
    }

    $lines = preg_split('/\R/', trim($result['stdout'])) ?: [];
    $last = preg_split('/\s+/', trim((string) end($lines))) ?: [];

    // Filesystem Inodes IUsed IFree IUse% Mounted
    if (count($last) < 5 || !is_numeric($last[1]) || !is_numeric($last[3])) {
        return ['inodes_total' => null, 'inodes_free' => null];
    }

    return ['inodes_total' => (int) $last[1], 'inodes_free' => (int) $last[3]];
}

/**
 * Packages waiting for an upgrade, as apt simulates it; readable without
 * root on Debian and Ubuntu, meaningless on a shared host.
 *
 * @return array<string, mixed>|null
 */
function system_updates()
{
    if (!is_executable('/usr/bin/apt-get') || !is_readable('/var/lib/apt/lists')) {
        return ['available' => false, 'pending' => null, 'security' => null, 'reboot_required' => is_file('/var/run/reboot-required'), 'lists_updated_at' => null];
    }

    $result = run(['/usr/bin/apt-get', '-s', '-o', 'Debug::NoLocking=true', 'upgrade'], 30);

    if (0 !== $result['exit']) {
        return ['available' => false, 'pending' => null, 'security' => null, 'reboot_required' => is_file('/var/run/reboot-required'), 'lists_updated_at' => null, 'error' => last_error_line($result['stderr'] ?: $result['stdout'])];
    }

    $pending = 0;
    $security = 0;
    $samples = [];

    foreach (preg_split('/\R/', $result['stdout']) ?: [] as $line) {
        if (!preg_match('/^Inst\s+(\S+)\s+\[([^\]]*)\]\s+\(([^\s]+)\s+([^)]*)\)/', $line, $m)) {
            continue;
        }

        ++$pending;

        if (false !== stripos($m[4], 'security')) {
            ++$security;

            if (count($samples) < 10) {
                $samples[] = $m[1] . ' ' . $m[2] . ' → ' . $m[3];
            }
        }
    }

    $stamp = is_file('/var/lib/apt/periodic/update-success-stamp') ? filemtime('/var/lib/apt/periodic/update-success-stamp') : (is_dir('/var/lib/apt/lists') ? filemtime('/var/lib/apt/lists') : false);

    return [
        'available' => true,
        'pending' => $pending,
        'security' => $security,
        'security_samples' => $samples,
        'reboot_required' => is_file('/var/run/reboot-required'),
        'lists_updated_at' => false === $stamp ? null : gmdate('Y-m-d H:i:s', (int) $stamp),
    ];
}

/**
 * @return array<string, mixed>
 */
function crontab_status()
{
    $result = run(['crontab', '-l'], 10);

    if (0 !== $result['exit']) {
        $reason = trim($result['stderr'] ?: $result['stdout']);

        return ['available' => false, 'lines' => [], 'wp_cron' => false, 'zenith_heartbeat' => false, 'reason' => '' === $reason ? 'crontab indisponible' : str_cut($reason, 0, 120)];
    }

    $lines = [];
    $wpCron = false;
    $heartbeat = false;
    $console = 0;
    $scheduler = false;
    $appHeartbeat = false;

    foreach (preg_split('/\R/', $result['stdout']) ?: [] as $line) {
        $line = trim($line);

        if ('' === $line || '#' === $line[0]) {
            continue;
        }

        $lines[] = str_cut($line, 0, 200);

        // The site's scheduled work relayed by the system: wp-cron.php or
        // wp-cli for WordPress, drush cron or Drupal's cron URL (cron.php on
        // Drupal 7, /cron/<key> since) for Drupal. One flag, kept under its
        // first name, whichever framework the line drives.
        if (preg_match('#wp-cron\.php|wp\s+cron\s+event\s+run|cron\s+event\s+run|drush(?:\.phar)?\b[^|;&]*\s(?:core[:-])?cron\b|/cron/[A-Za-z0-9_\-]{10,}|/cron\.php#i', $line)) {
            $wpCron = true;
        }

        // The heartbeat scheduled by hand (plugin 1.12, DISABLE_WP_CRON):
        // the site's push is alive even though WP-Cron itself is not run.
        if (preg_match('/wp\s+zenith\s+heartbeat|drush(?:\.phar)?\b[^|;&]*\szenith[:-]heartbeat/i', $line)) {
            $heartbeat = true;
        }

        // A Symfony, Sulu or Laravel application has no cron of its own:
        // the crontab runs its console. Kept under their own keys (1.8.8),
        // so an account shared with a WordPress does not light `wp_cron`.
        if (preg_match('#\bbin/(?:admin|website)?console\b|\bartisan\b#', $line)) {
            ++$console;
            // What drives every other scheduled task of the application.
            $scheduler = $scheduler || 1 === preg_match('/\bschedule:(?:run|work)\b|\bmessenger:consume\b[^|;&]*\bscheduler_|\btask:run\b/', $line);
            $appHeartbeat = $appHeartbeat || false !== strpos($line, 'zenith:heartbeat');
        }
    }

    // `wp_cron` kept as it was read by Zenith 1.x (cron or heartbeat: the
    // site's push is alive); `site_cron` says whether the site's own cron
    // is driven — a heartbeat line alone runs no cron.
    return ['available' => true, 'lines' => array_slice($lines, 0, 30), 'count' => count($lines), 'wp_cron' => $wpCron || $heartbeat, 'site_cron' => $wpCron, 'zenith_heartbeat' => $heartbeat, 'console' => $console, 'scheduler' => $scheduler, 'app_heartbeat' => $appHeartbeat, 'reason' => null];
}

/**
 * The repository the site is deployed from, looked for at the site's root
 * and up to four levels above it.
 *
 * @return array<string, mixed>|null
 */
function git_status($path)
{
    if (null === $path) {
        return null;
    }

    $root = null;
    $dir = $path;

    for ($i = 0; $i < 5; ++$i) {
        if (is_dir($dir . '/.git') || is_file($dir . '/.git')) {
            $root = $dir;
            break;
        }

        $parent = dirname($dir);

        if ($parent === $dir) {
            break;
        }

        $dir = $parent;
    }

    if (null === $root) {
        return ['available' => false, 'reason' => 'aucun dépôt Git au-dessus de la racine du site', 'repo_root' => null];
    }

    if (null === which('git')) {
        return ['available' => false, 'reason' => 'binaire git absent', 'repo_root' => $root, 'in_docroot' => $root === $path];
    }

    $git = function (array $args) use ($root) {
        $r = run(array_merge(['git', '-C', $root], $args), 20);

        return 0 === $r['exit'] ? trim($r['stdout']) : null;
    };

    $status = $git(['status', '--porcelain=v1', '--branch', '--untracked-files=normal']);
    $lines = null === $status ? [] : (preg_split('/\R/', $status) ?: []);
    $header = [] === $lines ? '' : array_shift($lines);
    $ahead = null;
    $behind = null;
    $upstream = null;

    if (preg_match('/^## (\S+?)(?:\.\.\.(\S+))?(?: \[(.*)\])?$/', $header, $m)) {
        $upstream = isset($m[2]) && '' !== $m[2] ? $m[2] : null;
        $ahead = isset($m[3]) && preg_match('/ahead (\d+)/', $m[3], $a) ? (int) $a[1] : 0;
        $behind = isset($m[3]) && preg_match('/behind (\d+)/', $m[3], $b) ? (int) $b[1] : 0;
    }

    $changed = count(array_filter($lines, 'strlen'));
    $untrackedLines = array_values(array_filter($lines, function ($l) { return 0 === strpos($l, '??'); }));
    $untracked = count($untrackedLines);
    $untrackedSamples = array_map(function ($l) { return trim(substr($l, 3)); }, array_slice($untrackedLines, 0, 20));
    $head = $git(['rev-parse', 'HEAD']);
    $branch = $git(['rev-parse', '--abbrev-ref', 'HEAD']);
    $lastCommit = $git(['log', '-1', '--format=%cI']);

    return [
        'available' => true,
        'reason' => null,
        'repo_root' => $root,
        'in_docroot' => $root === $path,
        'branch' => 'HEAD' === $branch ? null : $branch,
        'detached' => 'HEAD' === $branch,
        'head' => $head,
        'remote' => $git(['remote', 'get-url', 'origin']),
        'upstream' => $upstream,
        'ahead' => $ahead,
        'behind' => $behind,
        'last_commit_at' => $lastCommit,
        'worktree' => ['available' => null !== $status, 'dirty' => $changed > 0, 'changed_files' => $changed, 'untracked' => $untracked, 'untracked_samples' => $untrackedSamples, 'reason' => null === $status ? 'git status a échoué' : null],
    ];
}

/**
 * @return array<string, mixed>
 */
function wp_config_status($path)
{
    $file = is_file($path . '/wp-config.php') ? $path . '/wp-config.php' : dirname($path) . '/wp-config.php';
    $constants = wp_config_constants($path);
    $flag = function ($name) use ($constants) {
        if (!isset($constants[$name])) {
            return null;
        }

        return in_array(strtolower($constants[$name]), ['true', '1'], true) ? true : (in_array(strtolower($constants[$name]), ['false', '0', ''], true) ? false : $constants[$name]);
    };
    $perms = is_file($file) ? fileperms($file) : false;
    $owner = is_file($file) ? fileowner($file) : false;
    $me = function_exists('posix_geteuid') ? posix_geteuid() : null;

    return [
        'file' => is_file($file) ? $file : null,
        'outside_docroot' => is_file($file) && dirname($file) !== $path,
        'mode' => false === $perms ? null : substr(sprintf('%o', $perms), -4),
        'world_readable' => false === $perms ? null : (bool) ($perms & 0004),
        'group_readable' => false === $perms ? null : (bool) ($perms & 0040),
        'owned_by_me' => false === $owner || null === $me ? null : $owner === $me,
        'disable_wp_cron' => $flag('DISABLE_WP_CRON'),
        'wp_debug' => $flag('WP_DEBUG'),
        'wp_debug_log' => $flag('WP_DEBUG_LOG'),
        'wp_debug_display' => $flag('WP_DEBUG_DISPLAY'),
        'disallow_file_mods' => $flag('DISALLOW_FILE_MODS'),
        'disallow_file_edit' => $flag('DISALLOW_FILE_EDIT'),
        'wp_cache' => $flag('WP_CACHE'),
        'fs_method' => isset($constants['FS_METHOD']) ? $constants['FS_METHOD'] : null,
    ];
}

/**
 * The database server behind the site, as the site's own account sees it:
 * what it was given, how it is used, and how much of the site it can hold
 * in memory.
 *
 * @param array<string, string> $constants
 *
 * @return array<string, mixed>
 */
function mysql_status(array $constants)
{
    if (!isset($constants['DB_HOST'], $constants['DB_USER'], $constants['DB_NAME']) || !function_exists('mysqli_init')) {
        return ['available' => false, 'reason' => isset($constants['DB_HOST']) ? 'extension mysqli absente' : 'réglages de base illisibles dans wp-config.php'];
    }

    $hostParts = explode(':', $constants['DB_HOST'], 2);
    $socket = null;
    $port = 3306;

    if (isset($hostParts[1])) {
        if (is_numeric($hostParts[1])) {
            $port = (int) $hostParts[1];
        } else {
            $socket = $hostParts[1];
        }
    }

    mysqli_report(MYSQLI_REPORT_OFF);
    $mysqli = mysqli_init();
    $mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 4);

    if (!@$mysqli->real_connect($hostParts[0], $constants['DB_USER'], isset($constants['DB_PASSWORD']) ? $constants['DB_PASSWORD'] : '', $constants['DB_NAME'], $port, $socket)) {
        return ['available' => false, 'reason' => str_cut((string) $mysqli->connect_error, 0, 200)];
    }

    $status = [];
    $variables = [];
    $wanted = ['Uptime', 'Questions', 'Slow_queries', 'Created_tmp_disk_tables', 'Created_tmp_tables', 'Threads_connected', 'Max_used_connections', 'Aborted_connects', 'Aborted_clients', 'Innodb_buffer_pool_read_requests', 'Innodb_buffer_pool_reads', 'Innodb_buffer_pool_wait_free', 'Select_full_join', 'Sort_merge_passes', 'Table_locks_waited', 'Opened_tables', 'Open_tables', 'Connections'];
    $result = @$mysqli->query("SHOW GLOBAL STATUS WHERE Variable_name IN ('" . implode("','", $wanted) . "')");

    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $status[$row['Variable_name']] = is_numeric($row['Value']) ? (float) $row['Value'] : $row['Value'];
        }

        $result->free();
    }

    $wantedVars = ['version', 'version_comment', 'innodb_buffer_pool_size', 'max_connections', 'slow_query_log', 'long_query_time', 'query_cache_size', 'table_open_cache', 'tmp_table_size', 'max_heap_table_size', 'innodb_log_file_size', 'character_set_server', 'sql_mode', 'wait_timeout', 'max_allowed_packet'];
    $result = @$mysqli->query("SHOW GLOBAL VARIABLES WHERE Variable_name IN ('" . implode("','", $wantedVars) . "')");

    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $variables[$row['Variable_name']] = is_numeric($row['Value']) ? (float) $row['Value'] : $row['Value'];
        }

        $result->free();
    }

    $size = null;
    $tables = null;
    $engines = [];
    $result = @$mysqli->query('SELECT ENGINE, COUNT(*) AS n, COALESCE(SUM(DATA_LENGTH + INDEX_LENGTH), 0) AS bytes FROM information_schema.TABLES WHERE TABLE_SCHEMA = ' . "'" . $mysqli->real_escape_string($constants['DB_NAME']) . "'" . ' GROUP BY ENGINE');

    if ($result) {
        $size = 0;
        $tables = 0;

        while ($row = $result->fetch_assoc()) {
            $size += (int) $row['bytes'];
            $tables += (int) $row['n'];
            $engines[(string) $row['ENGINE']] = (int) $row['n'];
        }

        $result->free();
    }

    $mysqli->close();

    $reads = isset($status['Innodb_buffer_pool_reads'], $status['Innodb_buffer_pool_read_requests']) && $status['Innodb_buffer_pool_read_requests'] > 0
        ? round(100 * (1 - $status['Innodb_buffer_pool_reads'] / $status['Innodb_buffer_pool_read_requests']), 2)
        : null;

    return [
        'available' => true,
        'reason' => null,
        'host' => $constants['DB_HOST'],
        'version' => isset($variables['version']) ? (string) $variables['version'] : null,
        'flavour' => isset($variables['version_comment']) ? (string) $variables['version_comment'] : null,
        'uptime_seconds' => isset($status['Uptime']) ? (int) $status['Uptime'] : null,
        'questions' => isset($status['Questions']) ? (int) $status['Questions'] : null,
        'slow_queries' => isset($status['Slow_queries']) ? (int) $status['Slow_queries'] : null,
        'slow_query_log' => isset($variables['slow_query_log']) ? 'ON' === strtoupper((string) $variables['slow_query_log']) : null,
        'long_query_time' => isset($variables['long_query_time']) ? (float) $variables['long_query_time'] : null,
        'tmp_disk_tables' => isset($status['Created_tmp_disk_tables']) ? (int) $status['Created_tmp_disk_tables'] : null,
        'tmp_tables' => isset($status['Created_tmp_tables']) ? (int) $status['Created_tmp_tables'] : null,
        'threads_connected' => isset($status['Threads_connected']) ? (int) $status['Threads_connected'] : null,
        'max_used_connections' => isset($status['Max_used_connections']) ? (int) $status['Max_used_connections'] : null,
        'max_connections' => isset($variables['max_connections']) ? (int) $variables['max_connections'] : null,
        'aborted_connects' => isset($status['Aborted_connects']) ? (int) $status['Aborted_connects'] : null,
        'connections' => isset($status['Connections']) ? (int) $status['Connections'] : null,
        'buffer_pool_bytes' => isset($variables['innodb_buffer_pool_size']) ? (int) $variables['innodb_buffer_pool_size'] : null,
        'buffer_pool_hit_ratio' => $reads,
        'buffer_pool_wait_free' => isset($status['Innodb_buffer_pool_wait_free']) ? (int) $status['Innodb_buffer_pool_wait_free'] : null,
        'select_full_join' => isset($status['Select_full_join']) ? (int) $status['Select_full_join'] : null,
        'sort_merge_passes' => isset($status['Sort_merge_passes']) ? (int) $status['Sort_merge_passes'] : null,
        'table_locks_waited' => isset($status['Table_locks_waited']) ? (int) $status['Table_locks_waited'] : null,
        'tmp_table_size' => isset($variables['tmp_table_size']) ? (int) $variables['tmp_table_size'] : null,
        'max_allowed_packet' => isset($variables['max_allowed_packet']) ? (int) $variables['max_allowed_packet'] : null,
        'character_set_server' => isset($variables['character_set_server']) ? (string) $variables['character_set_server'] : null,
        'sql_mode' => isset($variables['sql_mode']) ? (string) $variables['sql_mode'] : null,
        'database_bytes' => $size,
        'tables' => $tables,
        'engines' => $engines,
    ];
}

/**
 * The site's own logs and what they carried lately: a fatal error a day
 * is a site that breaks for someone every day.
 *
 * @return array<string, mixed>
 */
function logs_status($path)
{
    $constants = wp_config_constants($path);
    $files = [];

    foreach (log_candidates($path, $constants) as $file) {
        if (!is_file($file) || !is_readable($file)) {
            continue;
        }

        $tail = tail_lines($file, 4000, 2 * 1024 * 1024) ?: [];
        $now = time();
        $day = 0;
        $week = 0;
        $notices = 0;
        $lastFatal = null;
        $lastFatalAt = null;
        $timeouts = [];

        foreach ($tail as $line) {
            // PHP writes the zone it was given: « UTC », but also a named one
            // (« Europe/Paris ») or an offset (« +02:00 »).
            $stamp = preg_match('/^\[(\d{2}-[A-Za-z]{3}-\d{4} \d{2}:\d{2}:\d{2}(?: [A-Za-z0-9_\/+:\-]+)?)\]/', $line, $m) ? strtotime($m[1]) : false;
            $fatal = (bool) preg_match('/PHP (Fatal error|Parse error)|Uncaught (Error|Exception|TypeError)/', $line);

            if (!$fatal) {
                if (preg_match('/PHP (Warning|Notice|Deprecated)/', $line)) {
                    ++$notices;
                }

                continue;
            }

            // A request killed at PHP's time limit, and when: one that comes
            // back at a steady pace is a scheduled task that never finishes.
            if (false !== $stamp && $stamp > $now - 86400 && false !== stripos($line, 'Maximum execution time')) {
                $timeouts[] = gmdate('Y-m-d H:i:s', $stamp);
            }

            if (false !== $stamp) {
                if ($stamp > $now - 86400) {
                    ++$day;
                }

                if ($stamp > $now - 7 * 86400) {
                    ++$week;
                }
            }

            $lastFatal = str_cut(preg_replace('/^\[[^\]]+\]\s*/', '', $line), 0, 300);
            $lastFatalAt = false !== $stamp ? gmdate('Y-m-d H:i:s', $stamp) : null;
        }

        $files[] = [
            'path' => $file,
            'size_bytes' => (int) filesize($file),
            'modified_at' => gmdate('Y-m-d H:i:s', (int) filemtime($file)),
            'fatals_24h' => $day,
            'fatals_7d' => $week,
            'notices_in_tail' => $notices,
            'lines_read' => count($tail),
            'last_fatal' => $lastFatal,
            'last_fatal_at' => $lastFatalAt,
            'timeouts_24h' => count($timeouts),
            'timeout_times' => array_slice($timeouts, -48),
        ];
    }

    return ['files' => $files, 'debug_log_enabled' => isset($constants['WP_DEBUG_LOG']) && !in_array(strtolower($constants['WP_DEBUG_LOG']), ['false', '0', ''], true)];
}

/**
 * Where an account's logs live. Hosts name the directory « logs » or
 * « log », and put it in the home of the account, next to the site or one
 * level above: every reading of a log looks in all of them, so that a
 * host's habit never reads as « no log ».
 *
 * @return string[]
 */
function log_directories($path)
{
    $home = getenv('HOME');
    $candidates = [];

    foreach (['logs', 'log'] as $name) {
        if (is_string($home) && '' !== $home) {
            $candidates[] = rtrim($home, '/') . '/' . $name;
        }

        if (null !== $path) {
            $candidates[] = rtrim(dirname($path), '/') . '/' . $name;
            $candidates[] = rtrim(dirname(dirname($path)), '/') . '/' . $name;
        }
    }

    // One directory, one entry. An account jailed by its host sees the same
    // directory under two names — ~/log and /log — which no path comparison
    // can tell are one: the device and inode can, bind mounts included.
    $dirs = [];
    $seen = [];

    foreach (array_unique($candidates) as $dir) {
        $stat = is_dir($dir) ? @stat($dir) : false;

        if (false === $stat) {
            $dirs[] = $dir;

            continue;
        }

        $id = $stat['dev'] . ':' . $stat['ino'];

        if (!isset($seen[$id])) {
            $seen[$id] = true;
            $dirs[] = $dir;
        }
    }

    return $dirs;
}

/**
 * The error logs a host keeps in those directories: the vhost's own, and
 * the names PHP-FPM pools are usually given.
 *
 * @return string[]
 */
function hosted_error_logs($path)
{
    $files = [];

    foreach (log_directories($path) as $dir) {
        foreach (['error.log', 'php_error.log', 'php-error.log', 'php_errors.log', 'php-errors.log', 'php.log'] as $name) {
            $files[] = $dir . '/' . $name;
        }
    }

    return $files;
}

/**
 * @param array<string, string> $constants
 *
 * @return string[]
 */
function log_candidates($path, array $constants)
{
    $debugLog = isset($constants['WP_DEBUG_LOG']) && '' !== $constants['WP_DEBUG_LOG'] && !in_array(strtolower($constants['WP_DEBUG_LOG']), ['true', 'false', '1', '0'], true) ? $constants['WP_DEBUG_LOG'] : $path . '/wp-content/debug.log';

    // A Drupal named by its Composer project keeps its web root one level
    // down: PHP drops its error_log next to the script that failed, there.
    $root = drupal_root($path);
    $drupal = null !== $root && $root !== $path ? [$root . '/error_log', $root . '/php_errorlog', $root . '/core/error_log'] : (null !== $root ? [$root . '/core/error_log'] : []);

    return array_values(array_unique(array_merge([$debugLog, $path . '/error_log', $path . '/wp-admin/error_log', $path . '/wp-content/error_log', $path . '/php_errorlog', dirname($path) . '/error_log'], $drupal, hosted_error_logs($path))));
}

// ----------------------------------------------------------- snapshots

function snapshots_dir()
{
    return zenith_home() . '/.zenith/snapshots';
}

/**
 * The parts of a snapshot file name — slug, version, moment — or null
 * when the name is not one this shell wrote: only the base name counts,
 * and every part is held to the characters snapshot_plugin() uses.
 *
 * @return array{file: string, slug: string, version: string, stamp: string}|null
 */
function snapshot_parts($name)
{
    if (!is_string($name) || '' === $name || false !== strpos($name, '..') || basename($name) !== $name) {
        return null;
    }

    if (!preg_match('/^([A-Za-z0-9._-]+)__([A-Za-z0-9._-]+)__(\d{8}-\d{6})\.tar\.gz$/', $name, $m) || '.' === $m[1][0]) {
        return null;
    }

    return ['file' => $name, 'slug' => $m[1], 'version' => $m[2], 'stamp' => $m[3]];
}

/**
 * @return list<array<string, mixed>>
 */
function snapshots_list()
{
    $dir = snapshots_dir();

    if (!is_dir($dir)) {
        return [];
    }

    $list = [];

    foreach (glob($dir . '/*.tar.gz') ?: [] as $file) {
        $parts = snapshot_parts(basename($file));

        if (null === $parts) {
            continue;
        }

        $list[] = ['file' => $parts['file'], 'slug' => $parts['slug'], 'version' => $parts['version'], 'taken_at' => preg_replace('/^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})$/', '$1-$2-$3 $4:$5:$6', $parts['stamp']), 'size_bytes' => (int) filesize($file)];
    }

    usort($list, function ($a, $b) { return strcmp($b['taken_at'], $a['taken_at']); });

    return array_slice($list, 0, 30);
}

/**
 * The version a plugin declares in its header, read off its files.
 */
function plugin_version($dir)
{
    foreach (glob($dir . '/*.php') ?: [] as $file) {
        $head = (string) file_get_contents($file, false, null, 0, 8192);

        if (false !== stripos($head, 'Plugin Name:') && preg_match('/^[ \t\/*#@]*Version:\s*(.+?)\s*$/mi', $head, $m)) {
            return trim($m[1]);
        }
    }

    return 'unknown';
}

/**
 * Archives one plugin directory, keeps the last three of each, and says
 * where the archive is — or why there is none.
 *
 * @return array<string, mixed>
 */
function snapshot_plugin($path, $slug)
{
    // The slug is checked before it is joined to any path: a slug is a
    // single directory name, never a dot directory, never a route.
    if (!is_string($slug) || !preg_match('/^[A-Za-z0-9_][A-Za-z0-9._-]{0,119}$/', $slug) || false !== strpos($slug, '..')) {
        return ['taken' => false, 'reason' => 'nom d\'extension invalide', 'file' => null];
    }

    $pluginDir = $path . '/wp-content/plugins/' . $slug;

    if (!is_dir($pluginDir)) {
        return ['taken' => false, 'reason' => 'répertoire introuvable', 'file' => null];
    }

    $dir = snapshots_dir();

    if (!is_dir($dir) && !@mkdir($dir, 0700, true)) {
        return ['taken' => false, 'reason' => sprintf('impossible de créer %s', $dir), 'file' => null];
    }

    $version = preg_replace('/[^A-Za-z0-9._-]/', '_', plugin_version($pluginDir));
    $file = sprintf('%s/%s__%s__%s.tar.gz', $dir, $slug, '' === $version ? 'unknown' : $version, gmdate('Ymd-His'));
    $result = run(['tar', '-czf', $file, '-C', $path . '/wp-content/plugins', '--', $slug], 300);

    if (0 !== $result['exit']) {
        @unlink($file);

        return ['taken' => false, 'reason' => last_error_line($result['stderr'] ?: 'tar a échoué'), 'file' => null];
    }

    // Three per plugin is enough to go back; more is a disk that fills.
    // Sorted on the moment in the name rather than on the whole name, so a
    // version that sorts oddly ("10.0" before "9.0") never keeps an old
    // archive alive at the expense of a newer one.
    $own = [];

    foreach (glob(sprintf('%s/%s__*.tar.gz', $dir, $slug)) ?: [] as $candidate) {
        $parts = snapshot_parts(basename($candidate));

        if (null !== $parts && $parts['slug'] === $slug) {
            $own[$parts['stamp'] . '|' . basename($candidate)] = $candidate;
        }
    }

    ksort($own);

    while (count($own) > ZENITH_SNAPSHOTS_KEPT) {
        @unlink(array_shift($own));
    }

    return ['taken' => true, 'reason' => null, 'file' => basename($file), 'size_bytes' => (int) filesize($file)];
}

/**
 * Puts a plugin back as one of its archives holds it. The current
 * directory is set aside first and only dropped once the archive is out.
 *
 * @return array<string, mixed>
 */
function control_snapshot_restore($path, $snapshot, $actor, $host, array $config)
{
    $parts = snapshot_parts($snapshot);

    if (null === $parts) {
        throw new RuntimeException('nom de snapshot invalide');
    }

    if (!is_wordpress($path)) {
        throw new RuntimeException(sprintf('aucun WordPress dans %s', $path));
    }

    $file = snapshots_dir() . '/' . $parts['file'];

    if (!is_file($file)) {
        throw new RuntimeException(sprintf('snapshot introuvable : %s', $parts['file']));
    }

    $slug = $parts['slug'];
    $pluginsDir = $path . '/wp-content/plugins';
    $current = $pluginsDir . '/' . $slug;
    $aside = $pluginsDir . '/.' . $slug . '.zenith-aside';

    // The archive is read before anything moves: every entry must sit
    // under the plugin's own directory. An archive that reaches anywhere
    // else — a sibling plugin, wp-config.php through "..", an absolute
    // path — is not a snapshot this shell wrote, and is refused whole.
    assert_archive_confined($file, $slug);

    if (is_dir($aside)) {
        run(['rm', '-rf', '--', $aside], 60);
    }

    $had = is_dir($current);

    if ($had && !@rename($current, $aside)) {
        throw new RuntimeException(sprintf('impossible de mettre de côté %s', $current));
    }

    $result = run(['tar', '-xzf', $file, '-C', $pluginsDir, '--no-same-owner', '--', $slug], 300);

    if (0 !== $result['exit'] || !is_dir($current)) {
        if ($had) {
            run(['rm', '-rf', '--', $current], 60);
            @rename($aside, $current);
        }

        throw new RuntimeException(sprintf('extraction en échec : %s', last_error_line($result['stderr'] ?: 'tar a échoué')));
    }

    if ($had) {
        run(['rm', '-rf', '--', $aside], 60);
    }

    wp_bootstrap($path, $host, '$result = ["status" => "ok"];' . journal_snippet('snapshot_restore', $actor, ['snapshot' => $parts['file'], 'items' => [$slug]]) . ' echo "\n{}\n";', $config, 30);

    return ['status' => 'ok', 'results' => [['item' => $slug, 'status' => 'updated', 'message' => sprintf('version %s remise en place depuis %s', $parts['version'], $parts['file'])]], 'restored' => $slug, 'version' => $parts['version']];
}

/**
 * Lists a tar.gz and refuses it unless every entry is the plugin's own
 * directory or something under it, with no ".." and no absolute path.
 */
function assert_archive_confined($file, $slug)
{
    $listing = run(['tar', '-tzf', $file], 120);

    if (0 !== $listing['exit']) {
        throw new RuntimeException(sprintf('archive illisible : %s', last_error_line($listing['stderr'] ?: 'tar a échoué')));
    }

    $entries = array_values(array_filter(preg_split('/\R/', $listing['stdout']) ?: [], 'strlen'));

    if ([] === $entries) {
        throw new RuntimeException('archive vide');
    }

    foreach ($entries as $entry) {
        $clean = preg_replace('#^\./#', '', $entry);

        if ($clean !== $slug && $clean !== $slug . '/' && 0 !== strpos($clean, $slug . '/')) {
            throw new RuntimeException(sprintf('archive refusée : entrée hors de %s/ (%s)', $slug, str_cut($entry, 0, 120)));
        }

        if ('/' === $entry[0] || false !== strpos($entry, '..') || false !== strpos($entry, "\\")) {
            throw new RuntimeException(sprintf('archive refusée : chemin suspect (%s)', str_cut($entry, 0, 120)));
        }
    }
}

/**
 * Fetches wp-cli into ~/bin, checked against the hash its authors publish:
 * what opens updates through the shell on a machine that had none.
 *
 * @return array<string, mixed>
 */
function control_install_wpcli(array $config)
{
    $home = getenv('HOME');

    if (!is_string($home) || '' === $home) {
        throw new RuntimeException('HOME inconnu : nulle part où installer wp-cli');
    }

    if (!function_exists('curl_init')) {
        throw new RuntimeException('extension curl absente : impossible de télécharger wp-cli');
    }

    $dir = $home . '/bin';

    if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
        throw new RuntimeException(sprintf('impossible de créer %s', $dir));
    }

    // One release, one digest, both written into this script: what comes
    // down the wire is held against a value that did not come down the
    // wire with it. A new wp-cli means a new ZENITH_WPCLI_VERSION and a
    // new ZENITH_WPCLI_SHA512, shipped together with the shell.
    $url = sprintf('https://github.com/wp-cli/wp-cli/releases/download/v%s/wp-cli-%s.phar', ZENITH_WPCLI_VERSION, ZENITH_WPCLI_VERSION);
    $phar = fetch_url($url, 120);

    if (null === $phar) {
        throw new RuntimeException(sprintf('téléchargement de wp-cli %s impossible depuis github.com', ZENITH_WPCLI_VERSION));
    }

    if (!hash_equals(ZENITH_WPCLI_SHA512, hash('sha512', $phar))) {
        throw new RuntimeException(sprintf('empreinte SHA-512 de wp-cli %s incorrecte : archive rejetée', ZENITH_WPCLI_VERSION));
    }

    $target = $dir . '/wp';

    if (false === file_put_contents($target, $phar)) {
        throw new RuntimeException(sprintf('impossible d\'écrire %s', $target));
    }

    chmod($target, 0755);
    $version = tool_version([$config['php'], $target, '--version', '--skip-plugins', '--skip-themes'], '/WP-CLI\s+([0-9][0-9a-z.\-]*)/i');

    if (null === $version) {
        @unlink($target);

        throw new RuntimeException('wp-cli téléchargé mais ne s\'exécute pas avec ' . $config['php']);
    }

    return ['status' => 'ok', 'installed' => $target, 'version' => $version, 'message' => sprintf('wp-cli %s installé dans %s. Renseigner wp=%s dans shell.conf si ~/bin n\'est pas dans le PATH.', $version, $target, $target)];
}

function fetch_url($url, $timeout)
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 3, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => budget($timeout), CURLOPT_USERAGENT => 'zenith-shell/' . ZENITH_SHELL_VERSION, CURLOPT_SSL_VERIFYPEER => true]);
    $body = curl_exec($ch);
    $code = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);

    return is_string($body) && 200 === $code && '' !== $body ? $body : null;
}

/**
 * Replaces this script with the copy Zenith brought over by verb_put, at
 * the path the key's forced command names — the one place where a new
 * version takes effect at the next connection. Nothing is written until
 * the copy proves to be a zenith-shell that runs and states its version.
 *
 * @return array<string, mixed>
 */
function control_install_shell(array $request, array $config)
{
    $file = incoming_file($request, 'file');
    $target = shell_install_path($config);
    $source = (string) file_get_contents($file);

    if (!preg_match('/^#!.*\n<\?php\n/', $source) || !preg_match('/define\(\'ZENITH_SHELL_VERSION\', \'([0-9][0-9A-Za-z.\-]*)\'\)/', $source, $m)) {
        @unlink($file);

        throw new RuntimeException('le fichier reçu n\'est pas un zenith-shell');
    }

    $new = $m[1];
    $lint = run([$config['php'], '-n', '-l', $file], 30);

    // A PHP built with --enable-sigchild (OVH's /usr/local/phpX.Y/bin/php)
    // gives proc_close() and proc_get_status() no exit code: run() answers
    // -1 while php -l has written its verdict. The verdict is then read
    // where it stands, in the output (1.8.10).
    $verdict = $lint['stdout'] . $lint['stderr'];
    $passed = 0 === $lint['exit']
        || (-1 === $lint['exit'] && false !== strpos($verdict, 'No syntax errors detected') && false === strpos($verdict, 'Parse error') && false === strpos($verdict, 'Errors parsing'));

    if (!$passed) {
        @unlink($file);

        throw new RuntimeException(sprintf('le shell reçu ne passe pas php -l avec %s : %s', $config['php'], last_error_line($lint['stderr'] ?: $lint['stdout'])));
    }

    $dir = dirname($target);

    if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
        throw new RuntimeException(sprintf('impossible de créer %s', $dir));
    }

    if (!is_writable($dir) && !(is_file($target) && is_writable($target))) {
        @unlink($file);

        throw new RuntimeException(sprintf('%s n\'est pas modifiable par %s : réinstaller le shell avec app:ssh:enroll', $target, get_current_user()));
    }

    $old = is_file($target) ? tool_version([$config['php'], $target, '--version'], '/^([0-9][0-9A-Za-z.\-]*)/') : null;

    // Written next to the target and swapped in by rename: the running
    // copy — this very process — is never half a file.
    $staged = $target . '.zenith-new';

    if (false === file_put_contents($staged, $source) || !chmod($staged, 0755)) {
        @unlink($staged);

        throw new RuntimeException(sprintf('impossible d\'écrire %s', $staged));
    }

    $check = tool_version([$config['php'], $staged, '--version'], '/^([0-9][0-9A-Za-z.\-]*)/');

    if ($check !== $new) {
        @unlink($staged);

        throw new RuntimeException(sprintf('le shell reçu annonce %s au lieu de %s', null === $check ? 'rien' : $check, $new));
    }

    if (!@rename($staged, $target)) {
        @unlink($staged);

        throw new RuntimeException(sprintf('impossible de remplacer %s', $target));
    }

    @unlink($file);

    return [
        'status' => 'ok',
        'path' => $target,
        'previous' => $old,
        'version' => $new,
        'message' => sprintf('zenith-shell %s installé dans %s%s.', $new, $target, null === $old ? '' : sprintf(' (remplace %s)', $old)),
    ];
}

/**
 * Where the shell lives on this machine: the path the configuration
 * names, else the forced command of Zenith's key in authorized_keys,
 * else this very file when it runs from a fixed place.
 */
function shell_install_path(array $config)
{
    if (null !== $config['shell'] && '' !== $config['shell']) {
        return $config['shell'];
    }

    $authorized = authorized_keys_options();

    if (is_string($authorized['command_path']) && '' !== $authorized['command_path']) {
        return $authorized['command_path'];
    }

    $self = realpath(__FILE__);

    if (is_string($self) && 'zenith-shell' === basename($self)) {
        return $self;
    }

    throw new RuntimeException('emplacement du shell inconnu : renseigner shell= dans shell.conf, ou command= dans authorized_keys');
}

// ---------------------------------------------------------------- audit

/**
 * The heavy reading: the whole tree, walked with find and grep, for what
 * the web process cannot see in the time it is given. Every list is capped
 * and says so.
 *
 * @return array<string, mixed>
 */
function verb_audit(array $request, array $config)
{
    if (is_composer_app_request($request)) {
        return composer_app_audit($request, $config);
    }

    if ('drupal' === framework($request)) {
        return drupal_audit($request, $config);
    }

    $path = site_path($request);

    // The audit walks a whole tree and reads the directories above it: it
    // is only ever pointed at a site, never at an arbitrary path.
    if (!is_wordpress($path)) {
        throw new RuntimeException(sprintf('aucun WordPress dans %s', $path));
    }

    $started = microtime(true);
    $me = function_exists('posix_geteuid') && function_exists('posix_getpwuid') ? (posix_getpwuid(posix_geteuid())['name'] ?? get_current_user()) : get_current_user();
    $uploads = $path . '/wp-content/uploads';

    $worldWritable = find_list([$path, '-xdev', '(', '-type', 'f', '-o', '-type', 'd', ')', '-perm', '-o+w', '-not', '-path', '*/node_modules/*', '-not', '-path', '*/cache/*'], 180);
    $otherOwner = find_list([$path, '-xdev', '-not', '-user', $me, '-not', '-path', '*/node_modules/*'], 180);
    // The empty index.php plugins drop in every uploads folder to keep
    // listings closed is not code: only files with something in them count.
    $phpInUploads = is_dir($uploads) ? find_list([$uploads, '-type', 'f', '(', '-iname', '*.php', '-o', '-iname', '*.phtml', '-o', '-iname', '*.php5', '-o', '-iname', '*.php7', '-o', '-iname', '*.phar', '-o', '-iname', '*.phps', ')', '-not', '(', '-name', 'index.php', '-size', '-2k', ')'], 120) : ['count' => 0, 'samples' => [], 'truncated' => false, 'error' => null];
    $recentPhp = recent_outside_git(find_list([$path, '-xdev', '-type', 'f', '-name', '*.php', '-mtime', '-2', '-not', '-path', '*/cache/*', '-not', '-path', '*/node_modules/*', '-not', '-path', '*/.zenith-aside/*'], 180, '%TY-%Tm-%Td %TH:%TM %p\n', true), $path);
    $signatures = signature_scan($path . '/wp-content', 240);
    $htaccessInUploads = is_file($uploads . '/.htaccess');
    $wpConfig = wp_config_status($path);

    // Above and beside the site: what a deploy or a hurried backup leaves
    // where no PHP process is meant to look, and where nothing serves it —
    // unless the parent is itself served.
    $exposure = [];
    $seen = [];

    foreach (array_unique([dirname($path), dirname(dirname($path)), (string) getenv('HOME'), $path]) as $dir) {
        if ('' === $dir || !is_dir($dir) || isset($seen[$dir])) {
            continue;
        }

        $seen[$dir] = true;
        $found = find_list([$dir, '-maxdepth', 2, '-type', 'f', '(', '-iname', '*.sql', '-o', '-iname', '*.sql.gz', '-o', '-iname', '*.sql.zip', '-o', '-iname', '*.zip', '-o', '-iname', '*.tar', '-o', '-iname', '*.tar.gz', '-o', '-iname', '*.tgz', '-o', '-name', '.env', '-o', '-name', '.env.*', '-o', '-iname', '*.bak', '-o', '-iname', '*.old', '-o', '-iname', '*.orig', '-o', '-iname', 'wp-config.php.*', ')', '-size', '+0', '-not', '-path', '*/node_modules/*', '-not', '-path', '*/.zenith/*', '-not', '-path', '*/.ssh/*', '-not', '-path', '*/vendor/*'], 60, '%s %p\n');

        foreach ($found['samples'] as $line) {
            list($size, $file) = array_pad(explode(' ', $line, 2), 2, '');
            // The same file is met from the site and from its parent: once.
            $exposure[$file] = ['file' => $file, 'size_bytes' => (int) $size, 'in_docroot' => 0 === strpos($file, $path . '/')];
        }
    }

    $exposure = array_values($exposure);

    // What weighs: the heaviest directories of the site, the files large
    // enough to be an archive or a dump wherever they sit, and the cache.
    $bigFiles = [];

    foreach (array_unique([$path, dirname($path), dirname(dirname($path)), (string) getenv('HOME')]) as $dir) {
        if ('' === $dir || !is_dir($dir)) {
            continue;
        }

        $args = $dir === $path
            ? [$dir, '-xdev', '-type', 'f', '-size', '+50M', '-not', '-path', $uploads . '/*']
            : [$dir, '-maxdepth', 2, '-xdev', '-type', 'f', '-size', '+50M', '-not', '-path', $path . '/*'];
        $found = find_list($args, 60, '%s %p\n');

        foreach ($found['samples'] as $line) {
            list($size, $file) = array_pad(explode(' ', $line, 2), 2, '');
            $bigFiles[$file] = ['file' => $file, 'size_bytes' => (int) $size, 'in_docroot' => 0 === strpos($file, $path . '/')];
        }
    }

    usort($bigFiles, function ($a, $b) { return $b['size_bytes'] - $a['size_bytes']; });

    return [
        'at' => gmdate('Y-m-d H:i:s'),
        'path' => $path,
        'user' => $me,
        'disk_usage' => disk_usage($path),
        'stale' => stale_directories($path),
        'big_files' => array_slice(array_values($bigFiles), 0, 20),
        'cache_bytes' => is_dir($path . '/wp-content/cache') ? dir_bytes($path . '/wp-content/cache') : null,
        'deadline_reached' => out_of_time(),
        'filesystem' => [
            'world_writable' => $worldWritable,
            'other_owner' => $otherOwner,
            'php_in_uploads' => $phpInUploads,
            'recent_php' => $recentPhp,
            'signatures' => $signatures,
            'uploads_htaccess' => $htaccessInUploads,
            'wp_config' => $wpConfig,
        ],
        'exposure' => array_slice($exposure, 0, 40),
        'uploads' => uploads_stats($uploads, $path),
        'duration_seconds' => round(microtime(true) - $started, 2),
    ];
}

/**
 * Total size of one directory in bytes, as du counts it.
 */
function dir_bytes($dir)
{
    $result = run(['du', '-sxk', $dir], 120);

    if (0 !== $result['exit']) {
        return null;
    }

    return (int) strtok(trim($result['stdout']), "\t ") * 1024;
}

/**
 * The heaviest directories of the site, three levels deep: where the
 * gigabytes are, whichever plugin or cache put them there.
 *
 * @return array<string, mixed>
 */
function disk_usage($path)
{
    $result = run(['du', '-xk', '--max-depth=3', $path], 240);

    if ($result['timeout'] || '' === trim($result['stdout'])) {
        return ['available' => false, 'total_bytes' => null, 'top' => [], 'reason' => $result['timeout'] ? 'du interrompu' : last_error_line($result['stderr'] ?: 'du a échoué')];
    }

    $rows = [];
    $total = null;

    foreach (preg_split('/\R/', trim($result['stdout'])) ?: [] as $line) {
        if (!preg_match('/^(\d+)\s+(.+)$/', $line, $m)) {
            continue;
        }

        $bytes = (int) $m[1] * 1024;
        $dir = $m[2];

        if ($dir === $path) {
            $total = $bytes;
            continue;
        }

        $rows[] = ['dir' => substr($dir, strlen($path) + 1), 'bytes' => $bytes];
    }

    usort($rows, function ($a, $b) { return $b['bytes'] - $a['bytes']; });

    return ['available' => true, 'total_bytes' => $total, 'top' => array_slice($rows, 0, 12), 'reason' => null];
}

/**
 * Runs find with the given arguments and returns a count and a capped
 * sample, whatever the size of the answer.
 *
 * The output is cut by head at ZENITH_FIND_MAX_LINES: a tree with a
 * million matches would otherwise be read whole into this process. The
 * pipe is the only reason a shell appears here, and find's arguments
 * reach it as positional parameters — never as part of the command
 * string, so nothing in a path is ever parsed.
 *
 * @param array<int, string|int> $args
 *
 * @return array{count: int, samples: list<string>, truncated: bool, error: ?string}
 */
function find_list(array $args, $timeout, $printf = null, $keep = false)
{
    $limit = ZENITH_FIND_MAX_LINES + 1;
    $command = array_merge(
        ['sh', '-c', 'find "$@" | head -n ' . $limit, 'find'],
        array_map('strval', $args),
        null === $printf ? ['-print'] : ['-printf', $printf]
    );
    $result = run($command, $timeout);
    $lines = array_values(array_filter(preg_split('/\R/', $result['stdout']) ?: [], 'strlen'));
    $capped = count($lines) >= $limit;
    $lines = array_slice($lines, 0, ZENITH_FIND_MAX_LINES);
    $count = count($lines);

    $out = [
        'count' => $count,
        'samples' => array_slice($lines, 0, 40),
        'truncated' => $count > 40 || $capped || $result['timeout'],
        'error' => $result['timeout'] ? sprintf('parcours interrompu après %d s', budget($timeout)) : ($capped ? sprintf('liste coupée à %d entrées', ZENITH_FIND_MAX_LINES) : (0 !== $result['exit'] && '' !== trim($result['stderr']) ? last_error_line($result['stderr']) : null)),
    ];

    // The whole list, for a caller that reads it before answering (never
    // sent as is): recent_outside_git() strips it again.
    if ($keep) {
        $out['lines'] = $lines;
    }

    return $out;
}

/**
 * Since 1.10.2: which of the recently written files the repository
 * explains. A file Git tracks and reports unchanged holds exactly what the
 * last commit says — it came with a deployment, not from a hand on the
 * server. Everything else — untracked, ignored, changed since the commit —
 * is what a reader has to look at. Null under `git` where there is no
 * repository above the site, or where git cannot be run.
 *
 * @param array<string, mixed> $recent a find_list() taken with $keep
 * @param string $path the site, the repository is looked for above it
 *
 * @return array<string, mixed>
 */
function recent_outside_git(array $recent, $path)
{
    $lines = isset($recent['lines']) && is_array($recent['lines']) ? $recent['lines'] : [];
    unset($recent['lines']);
    $recent['git'] = null;

    if ([] === $lines) {
        return $recent;
    }

    $status = git_status($path);

    if (true !== ($status['available'] ?? false) || !is_string($status['repo_root'] ?? null) || true !== ($status['worktree']['available'] ?? false)) {
        return $recent;
    }

    $root = rtrim($status['repo_root'], '/');
    $tracked = run(['git', '-C', $root, 'ls-files', '-z'], 60);

    if (0 !== $tracked['exit']) {
        return $recent;
    }

    $trackedSet = array_fill_keys(array_filter(explode("\0", $tracked['stdout']), 'strlen'), true);
    $changed = run(['git', '-C', $root, 'status', '--porcelain=v1', '-z', '--untracked-files=all'], 60);
    $changedSet = [];

    if (0 === $changed['exit']) {
        foreach (array_filter(explode("\0", $changed['stdout']), 'strlen') as $entry) {
            // « XY path » ; the second field of a rename is the old path, bare.
            $changedSet[strlen($entry) > 3 && ' ' === $entry[2] ? substr($entry, 3) : $entry] = true;
        }
    }

    $outside = [];
    $explained = 0;
    $generated = 0;

    foreach ($lines as $line) {
        // « %TY-%Tm-%Td %TH:%TM %p » : the path follows the second space.
        $parts = explode(' ', $line, 3);
        $file = isset($parts[2]) ? $parts[2] : $line;
        $rel = 0 === strpos($file, $root . '/') ? substr($file, strlen($root) + 1) : null;

        if (null !== $rel && isset($trackedSet[$rel]) && !isset($changedSet[$rel])) {
            ++$explained;

            continue;
        }

        // What the site writes for itself, outside Git by construction: the
        // configuration a cache extension regenerates, Zenith's own guard,
        // and the agent Zenith delivers (update-agent, install_agent).
        // Counted, never listed.
        if (preg_match('#/wp-content/(wp-rocket-config|w3tc-config|et-cache|litespeed|cache)/|/wp-content/mu-plugins/zenith-guard\.php$|/wp-content/plugins/zenith-wordpress/#', $file)) {
            ++$generated;

            continue;
        }

        $outside[] = $line;
    }

    $recent['git'] = [
        'root' => $root,
        'head' => isset($status['head']) ? $status['head'] : null,
        'last_commit_at' => isset($status['last_commit_at']) ? $status['last_commit_at'] : null,
        'explained' => $explained,
        'generated' => $generated,
        'outside' => ['count' => count($outside), 'samples' => array_slice($outside, 0, 40)],
    ];

    return $recent;
}

/**
 * The constructs malware is made of, by name, as extended regular
 * expressions that PCRE reads the same way (no back-reference: the
 * alternatives are joined into one grep).
 *
 * Since 1.8.4 the /e modifier of preg_replace is read at the delimiter that
 * closes the pattern, and with modifier letters only: before, any word with
 * an « e » after a slash matched, such as the XML Encryption namespace
 * (…/04/xmlenc) every SAML library carries.
 *
 * @return array<string, string>
 */
function signature_patterns()
{
    return [
        'eval de code encodé' => 'eval\s*\(\s*(base64_decode|gzinflate|gzuncompress|str_rot13|strrev|gzdecode)\s*\(',
        // A whole string that spells eval (or @eval, or eval( ) in hex or
        // octal escapes. Before 1.8.5 the four hex escapes matched anywhere,
        // so inside any encoded word that holds « eval »: RetrievalMethod,
        // in the obfuscated xmlseclibs of miniOrange SAML Premium.
        'eval écrit en hexadécimal' => '[\'"](\\\\x40|\\\\100|@)?(\\\\x65|\\\\145)(\\\\x76|\\\\166)(\\\\x61|\\\\141)(\\\\x6[cC]|\\\\154)([\'"(]|\\\\x28|\\\\50)',
        'preg_replace /e' => 'preg_replace\s*\(\s*[\'"](/[^,]*[^\\\\,]/|#[^,]*[^\\\\,]#|~[^,]*[^\\\\,]~)[imsxuADSUXJn]*e[imsxuADSUXJn]*[\'"]\s*,',
        '$GLOBALS imbriqués' => '\$GLOBALS\s*\[\s*\$GLOBALS',
        'assert de code' => 'assert\s*\(\s*(base64_decode|\$_(POST|GET|REQUEST|COOKIE))',
        'exécution d\'un paramètre HTTP' => '(system|passthru|shell_exec|exec)\s*\(\s*\$_(POST|GET|REQUEST|COOKIE)',
        'webshell connu' => 'FilesMan|c99shell|r57shell|WSO\s*2\.|b374k',
    ];
}

/**
 * PHP files carrying the constructs malware is made of, in wp-content
 * only: the core is covered by its checksums.
 *
 * `details` (1.8.4) says, for the first files, which construct matched, on
 * which line, and the matched text (120 characters at most, never the whole
 * line: obfuscated code is often one line of megabytes). It is what lets a
 * person tell a library from a backdoor without opening the file.
 *
 * @return array<string, mixed>
 */
function signature_scan($dir, $timeout, array $moreIncludes = [])
{
    if (!is_dir($dir)) {
        return ['count' => 0, 'samples' => [], 'details' => [], 'truncated' => false, 'error' => 'wp-content introuvable'];
    }

    $patterns = signature_patterns();
    $pattern = implode('|', $patterns);
    $includes = ['--include=*.php', '--include=*.phtml', '--include=*.inc'];

    foreach ($moreIncludes as $glob) {
        $includes[] = '--include=' . $glob;
    }

    $result = run(array_merge(['grep', '-rlIE'], $includes, ['--exclude-dir=cache', '--exclude-dir=node_modules', '-e', $pattern, $dir]), $timeout);
    $lines = array_values(array_filter(preg_split('/\R/', $result['stdout']) ?: [], 'strlen'));

    // grep answers 1 when nothing matched, which is the good news.
    return [
        'count' => count($lines),
        'samples' => array_slice($lines, 0, 40),
        'details' => signature_details(array_slice($lines, 0, 20), $pattern, $patterns),
        'truncated' => count($lines) > 40 || $result['timeout'],
        'error' => $result['timeout'] ? sprintf('analyse interrompue après %d s', $timeout) : ($result['exit'] > 1 && '' !== trim($result['stderr']) ? last_error_line($result['stderr']) : null),
    ];
}

/**
 * For each file, the first matches of the signatures: line, name of the
 * construct, matched text.
 *
 * @param list<string>          $files
 * @param array<string, string> $patterns
 *
 * @return list<array<string, mixed>>
 */
function signature_details(array $files, $pattern, array $patterns)
{
    $details = [];

    foreach ($files as $file) {
        if (out_of_time()) {
            break;
        }

        $result = run(['grep', '-nIoE', '-m', '3', '-e', $pattern, $file], 10);
        $matches = [];

        foreach (array_slice(array_values(array_filter(preg_split('/\R/', $result['stdout']) ?: [], 'strlen')), 0, 3) as $line) {
            $colon = strpos($line, ':');

            if (false === $colon) {
                continue;
            }

            $text = substr($line, $colon + 1);
            $name = null;

            foreach ($patterns as $label => $regex) {
                if (1 === preg_match('%' . $regex . '%', $text)) {
                    $name = $label;
                    break;
                }
            }

            $matches[] = [
                'line' => (int) substr($line, 0, $colon),
                'signature' => $name,
                // Printable ASCII only: the JSON answer must stay valid
                // whatever bytes the file holds.
                'excerpt' => preg_replace('/[^\x20-\x7E]/', '?', substr($text, 0, 120)),
            ];
        }

        $details[] = ['file' => $file, 'matches' => $matches];
    }

    return $details;
}

/**
 * What the media library weighs, file by file: totals by format, and the
 * images heavy enough to cost a page on their own.
 *
 * @return array<string, mixed>
 */
function uploads_stats($uploads, $site = null)
{
    if (!is_dir($uploads)) {
        return ['available' => false, 'reason' => 'wp-content/uploads introuvable'];
    }

    $result = run(['find', $uploads, '-type', 'f', '-printf', '%s %p\n'], 240);
    $total = 0;
    $files = 0;
    $byExtension = [];
    $big = [];
    $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'svg', 'bmp', 'tiff', 'heic'];
    $images = 0;
    $imageBytes = 0;
    $modern = 0;
    $derived = 0;
    $derivedBytes = 0;
    $years = [];

    foreach (preg_split('/\R/', $result['stdout']) ?: [] as $line) {
        if ('' === $line || false === ($space = strpos($line, ' '))) {
            continue;
        }

        $size = (int) substr($line, 0, $space);
        $file = substr($line, $space + 1);
        $ext = strtolower((string) pathinfo($file, PATHINFO_EXTENSION));
        ++$files;
        $total += $size;
        $byExtension[$ext] = isset($byExtension[$ext]) ? $byExtension[$ext] + 1 : 1;

        $rel = substr($file, strlen($uploads) + 1);

        if (preg_match('#^(\d{4})/#', $rel, $y)) {
            $years[$y[1]] = isset($years[$y[1]]) ? $years[$y[1]] + $size : $size;
        }

        if (in_array($ext, $imageExtensions, true)) {
            ++$images;
            $imageBytes += $size;

            // The sizes WordPress derives from each original: "-300x200",
            // "-scaled". Often more than half the library, and regenerable.
            if (preg_match('/-(\d+x\d+|scaled)(\.[a-z0-9]+)?\.[a-z0-9]+$/i', $rel)) {
                ++$derived;
                $derivedBytes += $size;
            }

            if (in_array($ext, ['webp', 'avif'], true)) {
                ++$modern;
            }

            if ($size > 2 * 1024 * 1024) {
                $big[] = ['file' => substr($file, strlen($uploads) + 1), 'size_bytes' => $size];
            }
        }
    }

    usort($big, function ($a, $b) { return $b['size_bytes'] - $a['size_bytes']; });
    arsort($byExtension);
    krsort($years);

    return [
        'available' => true,
        'reason' => null,
        'path' => $uploads,
        'relative_path' => null !== $site && 0 === strpos($uploads, $site . '/') ? substr($uploads, strlen($site) + 1) : basename($uploads),
        'truncated' => $result['timeout'],
        'files' => $files,
        'total_bytes' => $total,
        'derived_images' => $derived,
        'derived_bytes' => $derivedBytes,
        'by_year' => array_slice($years, 0, 6, true),
        'images' => $images,
        'image_bytes' => $imageBytes,
        'modern_images' => $modern,
        'big_images' => count($big),
        'big_images_bytes' => array_sum(array_map(function ($b) { return $b['size_bytes']; }, $big)),
        'big_samples' => array_slice($big, 0, 20),
        'by_extension' => array_slice($byExtension, 0, 12, true),
    ];
}

// ------------------------------------------------------------ integrity

/**
 * MD5 of every file of the core and of every plugin, for Zenith to hold
 * against the checksums wordpress.org publishes. Nothing is judged here:
 * the machine has no reason to reach wordpress.org, and no time limit
 * from the web server to worry about.
 *
 * @return array<string, mixed>
 */
function verb_integrity(array $request, array $config)
{
    if ('drupal' === framework($request)) {
        throw new RuntimeException('intégrité par empreintes sans objet pour Drupal : drupal.org ne publie pas les empreintes de ses fichiers');
    }

    $path = site_path($request);

    if (!is_wordpress($path)) {
        throw new RuntimeException(sprintf('aucun WordPress dans %s', $path));
    }

    $started = microtime(true);
    $version = null;

    if (is_readable($path . '/wp-includes/version.php') && preg_match('/\$wp_version\s*=\s*[\'"]([^\'"]+)[\'"]/', (string) file_get_contents($path . '/wp-includes/version.php'), $m)) {
        $version = $m[1];
    }

    $core = [];
    $coreCount = 0;
    $budgetFiles = ZENITH_INTEGRITY_MAX_FILES;
    $truncated = false;

    foreach (['wp-admin', 'wp-includes'] as $dir) {
        $coreCount += hash_tree($path . '/' . $dir, $path, $core, max(1, min(12000, $budgetFiles - count($core))));
    }

    foreach (glob($path . '/*.php') ?: [] as $file) {
        if ('wp-config.php' !== basename($file) && count($core) < $budgetFiles) {
            $core[basename($file)] = md5_file($file);
            ++$coreCount;
        }
    }

    $budgetFiles -= count($core);
    $plugins = [];
    $pluginsDir = $path . '/wp-content/plugins';

    foreach (scandir($pluginsDir) ?: [] as $entry) {
        if ('.' === $entry || '..' === $entry || 'index.php' === $entry) {
            continue;
        }

        // Past the budget, or the deadline, the remaining plugins are
        // named without their files: Zenith sees they exist and that the
        // report stopped short, rather than a report that never arrives.
        if ($budgetFiles <= 0 || out_of_time()) {
            $truncated = true;
            $full = $pluginsDir . '/' . $entry;

            if (is_dir($full)) {
                $plugins[] = ['slug' => $entry, 'version' => plugin_version($full), 'single_file' => false, 'files' => [], 'files_count' => 0, 'truncated' => true];
            }

            continue;
        }

        $full = $pluginsDir . '/' . $entry;

        if (is_file($full) && 'php' === pathinfo($full, PATHINFO_EXTENSION)) {
            $head = (string) file_get_contents($full, false, null, 0, 8192);

            if (false === stripos($head, 'Plugin Name:')) {
                continue;
            }

            $plugins[] = ['slug' => preg_replace('/\.php$/', '', $entry), 'version' => preg_match('/^[ \t\/*#@]*Version:\s*(.+?)\s*$/mi', $head, $m) ? trim($m[1]) : null, 'single_file' => true, 'files' => [$entry => md5_file($full)], 'files_count' => 1, 'truncated' => false];
            continue;
        }

        if (!is_dir($full)) {
            continue;
        }

        $files = [];
        $cap = max(1, min(4000, $budgetFiles));
        $count = hash_tree($full, $full, $files, $cap);
        $budgetFiles -= $count;
        $truncated = $truncated || $count >= $cap;
        $plugins[] = ['slug' => $entry, 'version' => plugin_version($full), 'single_file' => false, 'files' => $files, 'files_count' => $count, 'truncated' => $count >= $cap];
    }

    return [
        'at' => gmdate('Y-m-d H:i:s'),
        'core' => ['version' => $version, 'files' => $core, 'files_count' => $coreCount],
        'plugins' => $plugins,
        'truncated' => $truncated,
        'max_files' => ZENITH_INTEGRITY_MAX_FILES,
        'duration_seconds' => round(microtime(true) - $started, 2),
    ];
}

/**
 * Fills $out with relative path => md5 for every regular file under $dir,
 * up to $cap files. Returns how many were hashed.
 *
 * @param array<string, string> $out
 */
function hash_tree($dir, $base, array &$out, $cap)
{
    if (!is_dir($dir)) {
        return 0;
    }

    $count = 0;
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS | FilesystemIterator::CURRENT_AS_PATHNAME), RecursiveIteratorIterator::LEAVES_ONLY);

    foreach ($iterator as $file) {
        if (!is_file($file) || is_link($file)) {
            continue;
        }

        $out[substr($file, strlen($base) + 1)] = (string) md5_file($file);

        if (++$count >= $cap) {
            break;
        }
    }

    return $count;
}

// ------------------------------------------------- ownership and clock

/**
 * Who owns what, directory by directory: the code, the media, the
 * configuration. A site whose media belongs to the web server and whose
 * code belongs to the deploy account cannot update itself from the admin,
 * and a code tree the web server can write is a code tree a PHP flaw can
 * rewrite.
 *
 * @return array<string, mixed>
 */
function ownership_status($path)
{
    $me = function_exists('posix_geteuid') ? posix_geteuid() : null;
    $entries = [];

    foreach (['root' => $path, 'wp-config' => is_file($path . '/wp-config.php') ? $path . '/wp-config.php' : dirname($path) . '/wp-config.php', 'wp-content' => $path . '/wp-content', 'plugins' => $path . '/wp-content/plugins', 'themes' => $path . '/wp-content/themes', 'uploads' => $path . '/wp-content/uploads', 'wp-includes' => $path . '/wp-includes'] as $key => $file) {
        if (!file_exists($file)) {
            $entries[$key] = null;
            continue;
        }

        $uid = fileowner($file);
        $gid = filegroup($file);
        $perms = fileperms($file);
        $owner = false !== $uid && function_exists('posix_getpwuid') ? (posix_getpwuid($uid)['name'] ?? (string) $uid) : (string) $uid;
        $group = false !== $gid && function_exists('posix_getgrgid') ? (posix_getgrgid($gid)['name'] ?? (string) $gid) : (string) $gid;

        $entries[$key] = [
            'path' => $file,
            'owner' => $owner,
            'group' => $group,
            'mode' => false === $perms ? null : substr(sprintf('%o', $perms), -4),
            'mine' => null !== $me && false !== $uid ? $uid === $me : null,
            'writable_by_me' => is_writable($file),
            'group_writable' => false === $perms ? null : (bool) ($perms & 0020),
        ];
    }

    return ['user' => null !== $me && function_exists('posix_getpwuid') ? (posix_getpwuid($me)['name'] ?? (string) $me) : get_current_user(), 'entries' => $entries];
}

/**
 * The machine's clock: whether it is kept in sync, and the moment it
 * reads, for Zenith to hold against its own.
 *
 * @return array<string, mixed>
 */
function clock_status()
{
    $ntp = null;
    $source = null;

    if (null !== which('timedatectl')) {
        $result = run(['timedatectl', 'show', '-p', 'NTPSynchronized', '-p', 'NTP'], 10);

        if (0 === $result['exit']) {
            $ntp = false !== stripos($result['stdout'], 'NTPSynchronized=yes');
            $source = 'timedatectl';
        }
    }

    if (null === $ntp) {
        foreach (['/run/chrony', '/run/systemd/timesync', '/var/run/ntpd.pid', '/run/ntpd.pid'] as $marker) {
            if (file_exists($marker)) {
                $ntp = true;
                $source = $marker;
                break;
            }
        }
    }

    return ['time_utc' => gmdate('Y-m-d H:i:s'), 'timestamp' => time(), 'ntp_synchronized' => $ntp, 'source' => $source, 'timezone' => date_default_timezone_get()];
}

// ------------------------------------------------------ stale directories

/**
 * What a hurried fix leaves in wp-content: a plugin copied aside before an
 * update, an unpacked archive, a theme renamed "-old". Still on disk, still
 * served, never updated.
 *
 * @return array<string, mixed>
 */
function stale_directories($path)
{
    $stale = [];
    $pattern = '/(^|[-_. ])(old|bak|backup|orig|copy|copie|save|sauvegarde|tmp|temp|test|v\d+|\(\d+\))$/i';

    foreach (['plugins', 'themes', 'mu-plugins'] as $kind) {
        $dir = $path . '/wp-content/' . $kind;

        if (!is_dir($dir)) {
            continue;
        }

        $suspects = [];

        foreach (scandir($dir) ?: [] as $entry) {
            if ('.' === $entry || '..' === $entry || 'index.php' === $entry) {
                continue;
            }

            $full = $dir . '/' . $entry;
            $reason = null;

            if (preg_match($pattern, $entry) || preg_match('/\.(zip|tar|gz|tgz|bak|old|orig)$/i', $entry)) {
                $reason = 'nom de copie ou d\'archive';
            } elseif ('plugins' === $kind && is_dir($full) && !has_plugin_header($full)) {
                $reason = 'dossier sans en-tête d\'extension';
            } elseif ('themes' === $kind && is_dir($full) && !is_file($full . '/style.css')) {
                $reason = 'dossier sans style.css';
            }

            if (null !== $reason) {
                $suspects[$entry] = ['path' => 'wp-content/' . $kind . '/' . $entry, 'bytes' => is_dir($full) ? 0 : (int) filesize($full), 'reason' => $reason];
            }
        }

        // One find for every suspect directory of this kind, sizes summed
        // per top-level entry: a du per entry was a process per leftover,
        // and a site with fifty of them spent the audit's budget on that.
        $dirs = [];

        foreach ($suspects as $entry => $suspect) {
            if (is_dir($dir . '/' . $entry)) {
                $dirs[] = $dir . '/' . $entry;
            }
        }

        foreach (tree_sizes($dirs, 60) as $top => $bytes) {
            $entry = basename($top);

            if (isset($suspects[$entry])) {
                $suspects[$entry]['bytes'] = $bytes;
            }
        }

        foreach ($suspects as $suspect) {
            $stale[] = $suspect;
        }
    }

    $upgrade = $path . '/wp-content/upgrade';
    $upgradeEntries = is_dir($upgrade) ? array_values(array_diff(scandir($upgrade) ?: [], ['.', '..', 'index.php'])) : [];
    $upgradeBytes = [] === $upgradeEntries ? 0 : (int) array_sum(tree_sizes([$upgrade], 30));

    return [
        'entries' => array_slice($stale, 0, 30),
        'count' => count($stale),
        'bytes' => array_sum(array_map(function ($e) { return (int) $e['bytes']; }, $stale)),
        'upgrade' => ['entries' => count($upgradeEntries), 'bytes' => $upgradeBytes, 'samples' => array_slice($upgradeEntries, 0, 5)],
    ];
}

/**
 * The size of each given directory, in one find over all of them: the
 * bytes of every regular file below, summed under the directory it
 * belongs to. Directories that hold nothing are absent from the result.
 *
 * @param string[] $dirs
 *
 * @return array<string, int>
 */
function tree_sizes(array $dirs, $timeout)
{
    if ([] === $dirs) {
        return [];
    }

    $result = run(array_merge(['find'], $dirs, ['-xdev', '-type', 'f', '-printf', '%s %p\n']), $timeout);
    $sizes = [];
    rsort($dirs);

    foreach (preg_split('/\R/', $result['stdout']) ?: [] as $line) {
        if ('' === $line || false === ($space = strpos($line, ' '))) {
            continue;
        }

        $file = substr($line, $space + 1);

        foreach ($dirs as $dir) {
            if (0 === strpos($file, $dir . '/')) {
                $sizes[$dir] = (isset($sizes[$dir]) ? $sizes[$dir] : 0) + (int) substr($line, 0, $space);
                break;
            }
        }
    }

    return $sizes;
}

function has_plugin_header($dir)
{
    foreach (glob($dir . '/*.php') ?: [] as $file) {
        if (false !== stripos((string) file_get_contents($file, false, null, 0, 8192), 'Plugin Name:')) {
            return true;
        }
    }

    return false;
}

// -------------------------------------------------------------- weblogs

/**
 * The web server's own logs, where the host leaves them readable: who
 * comes back too often, what they ask for, what fails. Read from the end,
 * a bounded slice, on the most recent file of each kind.
 *
 * @return array<string, mixed>
 */
function verb_weblogs(array $request, array $config)
{
    $path = site_path($request, false);
    $maxBytes = 24 * 1024 * 1024;
    $dirs = [];

    // The account's own logs, and those the host leaves next to the site:
    // what this account is meant to read. The system's log directories
    // hold every vhost of the machine, and are read only where the
    // configuration says weblogs=system.
    $candidates = log_directories($path);

    if ($config['weblogs_system']) {
        $candidates = array_merge($candidates, ['/var/log/apache2', '/var/log/nginx', '/var/log/httpd']);
    }

    foreach (array_unique(array_filter($candidates)) as $dir) {
        if (is_dir($dir) && is_readable($dir)) {
            $dirs[] = $dir;
        }
    }

    if ([] === $dirs) {
        return ['available' => false, 'reason' => 'aucun répertoire de logs lisible (~/logs, ~/log, ../logs, ../log' . ($config['weblogs_system'] ? ', /var/log/apache2, /var/log/nginx' : ' ; weblogs=system dans shell.conf pour lire /var/log') . ')', 'access' => null, 'error' => null];
    }

    $access = newest_log($dirs, '/access/i');
    $error = newest_log($dirs, '/error/i');

    // The machine talking to itself and Zenith knocking are not traffic:
    // its own addresses, plus whatever Zenith asks to leave out.
    $exclude = own_ips();

    foreach (isset($request['exclude_ips']) && is_array($request['exclude_ips']) ? $request['exclude_ips'] : [] as $ip) {
        if (is_string($ip) && false !== filter_var($ip, FILTER_VALIDATE_IP)) {
            $exclude[$ip] = true;
        }
    }

    // Where this site receives credentials, when its framework can say
    // (Symfony and Sulu declare it in their firewalls): counted as sign-in
    // attempts, next to the forms the shell knows by itself.
    $loginPaths = [];

    foreach (isset($request['login_paths']) && is_array($request['login_paths']) ? $request['login_paths'] : [] as $loginPath) {
        if (is_string($loginPath) && '' !== $loginPath && strlen($loginPath) <= 200 && count($loginPaths) < 20) {
            $loginPaths[] = $loginPath;
        }
    }

    return [
        'available' => null !== $access || null !== $error,
        'reason' => null === $access && null === $error ? 'aucun access.log ni error.log dans ' . implode(', ', $dirs) : null,
        'directories' => $dirs,
        'excluded_ips' => array_keys($exclude),
        'access' => null === $access ? null : access_log_stats($access, $maxBytes, $exclude, rotated_logs($access, time() - 86400), $loginPaths),
        'error' => null === $error ? null : error_log_stats($error, 4 * 1024 * 1024, $exclude),
    ];
}

/**
 * The addresses this machine answers on, loopback included.
 *
 * @return array<string, bool>
 */
function own_ips()
{
    $ips = ['127.0.0.1' => true, '::1' => true];
    $result = run(['hostname', '-I'], 5);

    if (0 === $result['exit']) {
        foreach (preg_split('/\s+/', trim($result['stdout'])) ?: [] as $ip) {
            if ('' !== $ip && false !== filter_var($ip, FILTER_VALIDATE_IP)) {
                $ips[$ip] = true;
            }
        }
    }

    return $ips;
}

/**
 * The most recently written, uncompressed file whose name matches.
 *
 * @param string[] $dirs
 */
function newest_log(array $dirs, $pattern)
{
    $best = null;
    $bestTime = 0;

    foreach ($dirs as $dir) {
        foreach (scandir($dir) ?: [] as $entry) {
            $file = $dir . '/' . $entry;

            if (!is_file($file) || !is_readable($file) || !preg_match($pattern, $entry) || preg_match('/\.(gz|zip|bz2|xz|\d+)$/', $entry) || filesize($file) < 1) {
                continue;
            }

            $time = (int) filemtime($file);

            if ($time > $bestTime) {
                $best = $file;
                $bestTime = $time;
            }
        }
    }

    return $best;
}

/**
 * A rotated log's name without what the rotation added to it:
 * access.log.1, access.log-20260930.gz and access-2026-09-30.log are all
 * « access.log ».
 */
function log_stem($name)
{
    $name = (string) preg_replace('/\.gz$/', '', $name);
    $name = (string) preg_replace('/[._-]\d{4}-?\d{2}-?\d{2}(?:[_-]?\d+)?/', '', $name);

    return (string) preg_replace('/\.\d+$/', '', $name);
}

/**
 * The rotations the host kept beside a log and that were still written
 * after $since, newest first. A log rotated at midnight and read at three
 * holds the quietest hours of the day — on a site nobody visits at night,
 * nothing but Zenith's own requests: the day is in the file before it.
 *
 * @return string[]
 */
function rotated_logs($file, $since)
{
    $dir = dirname($file);
    $stem = log_stem(basename($file));
    $found = [];

    foreach (scandir($dir) ?: [] as $entry) {
        $path = $dir . '/' . $entry;

        if ($path === $file || log_stem($entry) !== $stem || preg_match('/\.(zip|bz2|xz)$/', $entry) || !is_file($path) || !is_readable($path) || filesize($path) < 1) {
            continue;
        }

        if ((int) filemtime($path) >= $since) {
            $found[$path] = (int) filemtime($path);
        }
    }

    arsort($found);

    return array_slice(array_keys($found), 0, 3);
}

/**
 * A log opened on its last bytes, compressed or not: the handle, and how
 * many bytes lie ahead of it.
 *
 * @return array{0: resource, 1: int}|null
 */
function open_log_tail($file, $maxBytes)
{
    $compressed = (bool) preg_match('/\.gz$/', $file);

    if ($compressed && !in_array('compress.zlib', stream_get_wrappers(), true)) {
        return null;
    }

    $size = (int) filesize($file);

    // A gzip file ends on the size of what it holds: enough to skip to
    // its last bytes without keeping the rest.
    if ($compressed) {
        $raw = fopen($file, 'r');
        $tail = false !== $raw && 0 === fseek($raw, -4, SEEK_END) ? fread($raw, 4) : false;
        $size = is_string($tail) && 4 === strlen($tail) ? (int) unpack('V', $tail)[1] : 0;

        if (false !== $raw) {
            fclose($raw);
        }
    }

    $handle = fopen($compressed ? 'compress.zlib://' . $file : $file, 'r');

    if (false === $handle) {
        return null;
    }

    $start = max(0, $size - $maxBytes);

    if ($start > 0) {
        fseek($handle, $start);
        fgets($handle); // drop the partial first line
    }

    return [$handle, $size - $start];
}

/**
 * The regular expression that recognises a sign-in request: the forms every
 * framework is known for, plus the paths given — exact, trailing slash
 * optional, a `*` standing for one segment (a language or a parameter), a
 * `**` for none or several (Sulu's portal prefix: /**login is /login and
 * /fr/login).
 *
 * @param string[] $loginPaths
 */
function login_pattern(array $loginPaths)
{
    $alternatives = ['/wp-login\\.php$', '(?:^|/)user/login/?$'];

    foreach ($loginPaths as $path) {
        if (!is_string($path) || '' === $path || '/' === $path) {
            continue;
        }

        $quoted = str_replace(['\\*\\*', '\\*'], ['(?:[^/]+/)*', '[^/]+'], preg_quote('/' . trim($path, '/'), '#'));
        $alternatives[] = '^' . $quoted . '/?$';
    }

    return '#' . implode('|', $alternatives) . '#';
}

/**
 * @param string[] $rotated the rotations that may complete the last 24 hours, newest first
 *
 * @return array<string, mixed>
 */
/**
 * @param string[] $loginPaths the paths where the site receives credentials, as its
 *                             framework declares them (`*` for a route parameter) —
 *                             counted as sign-in attempts next to the forms every
 *                             framework is known for
 */
function access_log_stats($file, $maxBytes, array $exclude = [], array $rotated = [], array $loginPaths = [])
{
    $size = (int) filesize($file);
    $loginPattern = login_pattern($loginPaths);
    $opened = open_log_tail($file, $maxBytes);

    if (null === $opened) {
        return ['file' => $file, 'error' => 'illisible'];
    }

    $handle = $opened[0];
    $readBytes = $opened[1];
    $files = [$file];
    // Lines of a rotation count from this instant on: the current file is
    // read whole, the ones before it only complete its last 24 hours.
    $since = null;

    $ips = [];
    $ipLogin = [];
    $ipXmlrpc = [];
    $ipErrors = [];
    $paths404 = [];
    $paths5xx = [];
    $agents = [];
    $statuses = ['2xx' => 0, '3xx' => 0, '4xx' => 0, '5xx' => 0];
    $hours = [];
    $requests = 0;
    $bytes = 0;
    $first = null;
    $last = null;
    $loginPosts = 0;
    $xmlrpc = 0;
    $unparsed = 0;
    $excluded = 0;
    $ipAgents = [];
    $ipSample = [];
    $months = ['Jan' => 1, 'Feb' => 2, 'Mar' => 3, 'Apr' => 4, 'May' => 5, 'Jun' => 6, 'Jul' => 7, 'Aug' => 8, 'Sep' => 9, 'Oct' => 10, 'Nov' => 11, 'Dec' => 12];

    while (true) {
        $line = fgets($handle);

        if (false === $line) {
            fclose($handle);
            $handle = null;

            // The file before this one, when the lines read so far do not
            // reach back 24 hours and the bytes allowed are not spent.
            $next = array_shift($rotated);
            $since = time() - 86400;

            if (null === $next || $readBytes >= $maxBytes || (null !== $first && $first <= $since)) {
                break;
            }

            $opened = open_log_tail($next, $maxBytes - $readBytes);

            if (null === $opened) {
                break;
            }

            $handle = $opened[0];
            $readBytes += $opened[1];
            $files[] = $next;

            continue;
        }

        // Combined format, with or without a leading vhost: the IP is the
        // first dotted or colon-separated token, the date is bracketed.
        if (!preg_match('/(?:^|\s)(\d{1,3}(?:\.\d{1,3}){3}|[0-9a-f:]{3,39})\s+\S+\s+\S+\s+\[(\d{2})\/([A-Za-z]{3})\/(\d{4}):(\d{2}):(\d{2}):\d{2}(?:\s+([+-]\d{4}))?[^\]]*\]\s+"([A-Z]+)\s+([^"\s]*)[^"]*"\s+(\d{3})\s+(\S+)(?:\s+"[^"]*"\s+"([^"]*)")?/', $line, $m)) {
            ++$unparsed;
            continue;
        }

        // The server writes its own clock and says how far it is from UTC.
        $stamp = isset($months[$m[3]]) ? gmmktime((int) $m[5], (int) $m[6], 0, $months[$m[3]], (int) $m[2], (int) $m[4]) : null;

        if (null !== $stamp && '' !== $m[7]) {
            $stamp -= ('-' === $m[7][0] ? -1 : 1) * ((int) substr($m[7], 1, 2) * 3600 + (int) substr($m[7], 3, 2) * 60);
        }

        if (null !== $since && (null === $stamp || $stamp < $since)) {
            continue;
        }

        $ip = $m[1];

        if (isset($exclude[$ip])) {
            ++$excluded;
            continue;
        }

        ++$requests;
        $method = $m[8];
        $pathOnly = strtok($m[9], '?') ?: '/';
        $status = (int) $m[10];
        $agent = isset($m[12]) ? $m[12] : '';

        if (null !== $stamp) {
            $first = null === $first ? $stamp : min($first, $stamp);
            $last = null === $last ? $stamp : max($last, $stamp);
            $hour = gmdate('Y-m-d H:00', $stamp);
            $hours[$hour] = isset($hours[$hour]) ? $hours[$hour] + 1 : 1;
        }

        $bytes += is_numeric($m[11]) ? (int) $m[11] : 0;
        $ips[$ip] = isset($ips[$ip]) ? $ips[$ip] + 1 : 1;
        $bucket = $status >= 500 ? '5xx' : ($status >= 400 ? '4xx' : ($status >= 300 ? '3xx' : '2xx'));
        ++$statuses[$bucket];

        if (404 === $status) {
            $paths404[$pathOnly] = isset($paths404[$pathOnly]) ? $paths404[$pathOnly] + 1 : 1;
        }

        if ($status >= 500) {
            $paths5xx[$pathOnly] = isset($paths5xx[$pathOnly]) ? $paths5xx[$pathOnly] + 1 : 1;
        }

        if ($status >= 400) {
            $ipErrors[$ip] = isset($ipErrors[$ip]) ? $ipErrors[$ip] + 1 : 1;
        }

        // A sign-in attempt, wherever the framework puts its form:
        // wp-login.php, Drupal's /user/login (with or without a language
        // prefix), or the paths a Symfony application's firewalls declare.
        if ('POST' === $method && preg_match($loginPattern, $pathOnly)) {
            ++$loginPosts;
            $ipLogin[$ip] = isset($ipLogin[$ip]) ? $ipLogin[$ip] + 1 : 1;
        }

        if (preg_match('#/xmlrpc\.php$#', $pathOnly)) {
            ++$xmlrpc;
            $ipXmlrpc[$ip] = isset($ipXmlrpc[$ip]) ? $ipXmlrpc[$ip] + 1 : 1;
        }

        if ('' !== $agent) {
            $family = agent_family($agent);
            $agents[$family] = isset($agents[$family]) ? $agents[$family] + 1 : 1;
            $ipAgents[$ip][$family] = isset($ipAgents[$ip][$family]) ? $ipAgents[$ip][$family] + 1 : 1;

            if (!isset($ipSample[$ip])) {
                $ipSample[$ip] = str_cut($agent, 0, 200);
            }
        }
    }

    arsort($ips);
    arsort($ipLogin);
    arsort($ipXmlrpc);
    arsort($ipErrors);
    arsort($paths404);
    arsort($paths5xx);
    arsort($agents);
    ksort($hours);

    $window = null !== $first && null !== $last ? max(1, $last - $first) : null;
    $top = function (array $counts, $n) { $out = []; foreach (array_slice($counts, 0, $n, true) as $k => $v) { $out[] = ['key' => (string) $k, 'count' => (int) $v]; } return $out; };

    // The same rows, each address with the user agent it mostly came with:
    // a crawler names itself, an attack tool rarely bothers.
    $withAgent = function (array $rows) use ($ipAgents, $ipSample) {
        foreach ($rows as &$row) {
            $families = isset($ipAgents[$row['key']]) ? $ipAgents[$row['key']] : [];
            arsort($families);
            $row['agent'] = [] === $families ? null : (string) key($families);
            $row['agent_raw'] = isset($ipSample[$row['key']]) ? $ipSample[$row['key']] : null;
        }

        return $rows;
    };

    return [
        'file' => $file,
        'files' => $files,
        'size_bytes' => $size,
        'read_bytes' => $readBytes,
        'modified_at' => gmdate('Y-m-d H:i:s', (int) filemtime($file)),
        'from' => null === $first ? null : gmdate('Y-m-d H:i:s', $first),
        'to' => null === $last ? null : gmdate('Y-m-d H:i:s', $last),
        'window_seconds' => $window,
        'requests' => $requests,
        'excluded' => $excluded,
        'unparsed' => $unparsed,
        'bytes_sent' => $bytes,
        'unique_ips' => count($ips),
        'statuses' => $statuses,
        'top_ips' => $withAgent($top($ips, 10)),
        'top_error_ips' => $withAgent($top($ipErrors, 5)),
        'login_posts' => $loginPosts,
        'login_paths' => array_values($loginPaths),
        'top_login_ips' => $withAgent($top($ipLogin, 5)),
        'xmlrpc_requests' => $xmlrpc,
        'top_xmlrpc_ips' => $withAgent($top($ipXmlrpc, 5)),
        'top_404' => $top($paths404, 8),
        'top_5xx' => $top($paths5xx, 8),
        'agents' => $top($agents, 8),
        'busiest_hours' => $top(array_slice(arsort_copy($hours), 0, 3, true), 3),
        'hours_covered' => count($hours),
    ];
}

function arsort_copy(array $a)
{
    arsort($a);

    return $a;
}

/**
 * A user agent reduced to its family, so that ten thousand Chrome builds
 * count as one and the crawlers stand out.
 */
function agent_family($agent)
{
    $known = ['Googlebot', 'bingbot', 'AhrefsBot', 'SemrushBot', 'MJ12bot', 'DotBot', 'PetalBot', 'YandexBot', 'Applebot', 'facebookexternalhit', 'GPTBot', 'ClaudeBot', 'CCBot', 'Bytespider', 'DuckDuckBot', 'WordPress', 'wp-cron', 'curl', 'python-requests', 'Go-http-client', 'Java', 'Scrapy', 'HeadlessChrome', 'Lighthouse', 'UptimeRobot', 'Pingdom', 'Zenith'];

    foreach ($known as $name) {
        if (false !== stripos($agent, $name)) {
            return $name;
        }
    }

    if (preg_match('/bot|crawl|spider|scan/i', $agent)) {
        return 'autre robot';
    }

    foreach (['Edg' => 'Edge', 'OPR' => 'Opera', 'Firefox' => 'Firefox', 'Chrome' => 'Chrome', 'Safari' => 'Safari', 'MSIE' => 'Internet Explorer', 'Trident' => 'Internet Explorer'] as $needle => $family) {
        if (false !== strpos($agent, $needle)) {
            return $family;
        }
    }

    return '-' === $agent ? 'sans user-agent' : 'autre';
}

/**
 * @return array<string, mixed>
 */
function error_log_stats($file, $maxBytes, array $exclude = [])
{
    $tail = tail_lines($file, 6000, $maxBytes) ?: [];
    $levels = [];
    $messages = [];
    $clients = [];
    $recent = [];
    $ignored = ['denied' => 0, 'not_found' => 0, 'excluded' => 0];

    foreach ($tail as $line) {
        $level = preg_match('/\[(?:[a-z_]+:)?(emerg|alert|crit|error|warn|notice|info|debug)\]/i', $line, $m) ? strtolower($m[1]) : 'autre';

        if (preg_match('/\[client ([^\]:\s]+)/', $line, $c) && isset($exclude[$c[1]])) {
            ++$ignored['excluded'];
            continue;
        }

        // Access refused and files not found are the access log's business,
        // already counted there as 4xx: here only what broke is kept.
        if (preg_match('/client denied by server configuration|AH01797|AH01630|AH01276|user .* not found|authentication failure|password mismatch/i', $line)) {
            ++$ignored['denied'];
            continue;
        }

        if (preg_match('/File does not exist|AH00128|script .* not found or unable to stat/i', $line)) {
            ++$ignored['not_found'];
            continue;
        }

        $levels[$level] = isset($levels[$level]) ? $levels[$level] + 1 : 1;

        if (preg_match('/\[client ([^\]:\s]+)/', $line, $c)) {
            $clients[$c[1]] = isset($clients[$c[1]]) ? $clients[$c[1]] + 1 : 1;
        }

        // The message without what varies: timestamp, client, pid, paths
        // ending in numbers, so the same fault counts as one.
        $message = preg_replace(['/^\[[^\]]+\]\s*/', '/\[[a-z_]+:[a-z]+\]\s*/i', '/\[pid \d+[^\]]*\]\s*/', '/\[client [^\]]+\]\s*/', '/\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}[^ ]*/', '/, referer: .*$/', '/\d+/'], ['', '', '', '', '', '', '#'], $line);
        $message = str_cut(trim((string) $message), 0, 160);

        if ('' !== $message) {
            $messages[$message] = isset($messages[$message]) ? $messages[$message] + 1 : 1;
        }
    }

    arsort($messages);
    arsort($clients);
    arsort($levels);

    foreach (array_reverse($tail) as $line) {
        if (count($recent) >= 5) {
            break;
        }

        if (!preg_match('/client denied by server configuration|AH01797|AH01630|File does not exist|AH00128/i', $line)) {
            $recent[] = str_cut($line, 0, 300);
        }
    }

    $top = function (array $counts, $n) { $out = []; foreach (array_slice($counts, 0, $n, true) as $k => $v) { $out[] = ['key' => (string) $k, 'count' => (int) $v]; } return $out; };

    return [
        'file' => $file,
        'size_bytes' => (int) filesize($file),
        'modified_at' => gmdate('Y-m-d H:i:s', (int) filemtime($file)),
        'lines_read' => count($tail),
        'ignored' => $ignored,
        'levels' => $levels,
        'top_messages' => $top($messages, 8),
        'top_clients' => $top($clients, 5),
        'recent' => $recent,
    ];
}

// ------------------------------------------------------ file transfer

/**
 * One piece of a file Zenith is bringing over, appended under ~/.zenith/
 * incoming: the way a plugin archive crosses a channel that only carries
 * one command argument at a time. The last piece names the digest the
 * whole must match.
 *
 * @return array<string, mixed>
 */
function verb_put(array $request, array $config)
{
    // self_update=yes opens install_shell, which is nothing without the
    // file it installs: the one transfer it lets through is the shell's
    // own copy. Before 1.8.3 the gate below stopped every piece, and the
    // key route of deploy-shell never worked.
    $shellCopy = isset($request['name']) && 'zenith-shell' === $request['name'] && $config['self_update'];

    if (!$config['control'] && !$shellCopy) {
        throw new RuntimeException('transfert refusé : control=no dans la configuration de zenith-shell' . ($config['self_update'] ? '' : ' (self_update=yes ouvrirait le seul transfert de zenith-shell)'));
    }

    $name = isset($request['name']) && is_string($request['name']) && preg_match('/^[A-Za-z0-9_][A-Za-z0-9._-]{0,79}$/', $request['name']) ? $request['name'] : null;
    $transfer = isset($request['transfer']) && is_string($request['transfer']) && preg_match('/^[A-Za-z0-9]{8,32}$/', $request['transfer']) ? $request['transfer'] : null;
    $index = isset($request['index']) && is_int($request['index']) ? $request['index'] : -1;
    $total = isset($request['total']) && is_int($request['total']) ? $request['total'] : 0;
    $chunk = isset($request['chunk']) && is_string($request['chunk']) && strlen($request['chunk']) <= ZENITH_PUT_CHUNK_MAX_BYTES * 2 ? base64_decode($request['chunk'], true) : false;

    if (null === $name || null === $transfer || $index < 0 || $index >= $total || false === $chunk) {
        throw new RuntimeException('morceau invalide');
    }

    if ($total > ZENITH_PUT_MAX_CHUNKS) {
        throw new RuntimeException(sprintf('transfert refusé : %d morceaux, %d au plus', $total, ZENITH_PUT_MAX_CHUNKS));
    }

    if (strlen($chunk) > ZENITH_PUT_CHUNK_MAX_BYTES) {
        throw new RuntimeException(sprintf('morceau trop grand : %d octets, %d au plus', strlen($chunk), ZENITH_PUT_CHUNK_MAX_BYTES));
    }

    $dir = incoming_dir();
    sweep_incoming($dir);

    // The transfer's own identifier is part of the file name: two
    // transfers of the same archive, from two scans or two operators,
    // never append into each other's file.
    $basename = $transfer . '-' . $name;
    $file = $dir . '/' . $basename;

    if (0 === $index) {
        @unlink($file);
    } elseif (!is_file($file)) {
        throw new RuntimeException('transfert interrompu : recommencer au premier morceau');
    }

    $size = is_file($file) ? (int) filesize($file) : 0;

    if ($size + strlen($chunk) > ZENITH_PUT_MAX_BYTES) {
        @unlink($file);

        throw new RuntimeException(sprintf('transfert refusé : plus de %d Mo', (int) (ZENITH_PUT_MAX_BYTES / 1048576)));
    }

    if (false === file_put_contents($file, $chunk, FILE_APPEND)) {
        throw new RuntimeException(sprintf('impossible d\'écrire %s', $file));
    }

    $done = $index === $total - 1;
    $size = (int) filesize($file);

    if ($done) {
        $expected = isset($request['sha256']) && is_string($request['sha256']) ? strtolower($request['sha256']) : '';

        if (!preg_match('/^[a-f0-9]{64}$/', $expected) || !hash_equals($expected, (string) hash_file('sha256', $file))) {
            @unlink($file);

            throw new RuntimeException('empreinte du fichier reçu incorrecte : transfert rejeté');
        }
    }

    return ['name' => $name, 'transfer' => $transfer, 'received' => $index + 1, 'total' => $total, 'bytes' => $size, 'complete' => $done, 'file' => $done ? $basename : null];
}

function incoming_dir()
{
    $dir = zenith_home() . '/.zenith/incoming';

    if (!is_dir($dir) && !@mkdir($dir, 0700, true)) {
        throw new RuntimeException(sprintf('impossible de créer %s', $dir));
    }

    return $dir;
}

/**
 * Drops what an interrupted transfer left behind more than an hour ago:
 * the incoming directory holds pieces in transit, never an archive.
 */
function sweep_incoming($dir)
{
    foreach (glob($dir . '/*') ?: [] as $file) {
        if (is_file($file) && filemtime($file) < time() - ZENITH_PUT_STALE_SECONDS) {
            @unlink($file);
        }
    }
}

/**
 * The completed transfer a control action names, as verb_put returned
 * it: a base name under the incoming directory, nothing else. Absent or
 * unfinished, the action stops here.
 */
function incoming_file(array $request, $key = 'file')
{
    $name = isset($request[$key]) && is_string($request[$key]) && preg_match('/^[A-Za-z0-9]{8,32}-[A-Za-z0-9_][A-Za-z0-9._-]{0,79}$/', $request[$key]) ? $request[$key] : null;
    $file = null === $name ? null : incoming_dir() . '/' . $name;

    if (null === $file || !is_file($file)) {
        throw new RuntimeException('fichier transféré absent : transfert incomplet ou expiré');
    }

    return $file;
}

/**
 * Installs, or reinstalls, the Zenith plugin from an archive brought over
 * by verb_put, activates it, and sets the options Zenith hands along —
 * only the plugin's own, by name.
 *
 * @return array<string, mixed>
 */
function control_install_agent($path, array $request, $actor, $host, array $config)
{
    if (!is_wordpress($path)) {
        throw new RuntimeException(sprintf('aucun WordPress dans %s', $path));
    }

    $archive = incoming_file($request, 'file');

    if (!class_exists('ZipArchive')) {
        throw new RuntimeException('extension zip absente : impossible de décompresser le plugin');
    }

    $zip = new ZipArchive();

    if (true !== $zip->open($archive)) {
        throw new RuntimeException('archive du plugin illisible');
    }

    // Every entry must live under the plugin's own directory: nothing
    // else in wp-content/plugins is touched.
    for ($i = 0; $i < $zip->numFiles; ++$i) {
        $entry = (string) $zip->getNameIndex($i);

        if (0 !== strpos($entry, 'zenith-wordpress/') || false !== strpos($entry, '..')) {
            $zip->close();

            throw new RuntimeException(sprintf('entrée inattendue dans l\'archive : %s', $entry));
        }
    }

    $pluginsDir = $path . '/wp-content/plugins';
    $current = $pluginsDir . '/zenith-wordpress';
    $aside = $pluginsDir . '/.zenith-wordpress.zenith-aside';
    $had = is_dir($current);

    if (is_dir($aside)) {
        run(['rm', '-rf', '--', $aside], 60);
    }

    if ($had && !@rename($current, $aside)) {
        $zip->close();

        throw new RuntimeException('impossible de mettre de côté le plugin en place');
    }

    $extracted = $zip->extractTo($pluginsDir);
    $zip->close();

    if (!$extracted || !is_file($current . '/zenith-wordpress.php')) {
        run(['rm', '-rf', '--', $current], 60);

        if ($had) {
            @rename($aside, $current);
        }

        throw new RuntimeException('extraction du plugin en échec');
    }

    if ($had) {
        run(['rm', '-rf', '--', $aside], 60);
    }

    @unlink($archive);

    $options = [];

    foreach (isset($request['options']) && is_array($request['options']) ? $request['options'] : [] as $key => $value) {
        if (is_string($key) && preg_match('/^zenith_[a-z_]{1,60}$/', $key) && (is_scalar($value) || null === $value)) {
            $options[$key] = $value;
        }
    }

    // Since 1.12 the plugin enrols itself from the command line: wp zenith
    // setup validates as the settings screen does, writes network-wide on
    // a multisite, and refuses what wp-config.php froze. Taken whenever
    // the machine has wp-cli, the plugin is recent enough, and the three
    // secrets are given — setup would otherwise draw the missing ones and
    // print them once, where Zenith is not listening.
    $version = plugin_version($current);
    $wp = wp_binary($config, $path);
    $secretsGiven = true;

    foreach (['zenith_api_key', 'zenith_update_token', 'zenith_push_secret'] as $secret) {
        $secretsGiven = $secretsGiven && isset($options[$secret]) && '' !== (string) $options[$secret];
    }

    if (null !== $wp && 'unknown' !== $version && version_compare($version, '1.12', '>=') && $secretsGiven) {
        $setup = install_agent_by_cli($path, $wp, $options, $version, $had);

        if (null !== $setup) {
            wp_bootstrap($path, $host, '$result = ["status" => "ok"];' . journal_snippet('install_agent', $actor, ['setup' => 'wp zenith setup']) . ' echo "\n{}\n";', $config, 30);

            return $setup;
        }
    }

    // The plugin's own writer once it is loaded — activate_plugin() includes
    // its file — so a multisite gets network options; a setting frozen by
    // a wp-config.php constant is left alone and named in the answer.
    $code = 'require_once ABSPATH . "wp-admin/includes/plugin.php";'
        . ' $r = is_plugin_active("zenith-wordpress/zenith-wordpress.php") ? true : activate_plugin("zenith-wordpress/zenith-wordpress.php");'
        . ' $options = ' . var_export($options, true) . '; $set = []; $locked = [];'
        . ' foreach ($options as $key => $value) { if (null === $value || "" === $value) { continue; } $name = substr($key, 7);'
        . '   if (function_exists("zenith_setting_locked") && zenith_setting_locked($name)) { $locked[] = $name; continue; }'
        . '   if (function_exists("zenith_option_update")) { zenith_option_update($key, $value); } else { update_option($key, $value); } $set[] = $key; }'
        . ' $result = ["status" => is_wp_error($r) ? "failed" : "ok", "message" => is_wp_error($r) ? $r->get_error_message() : null, "activated" => !is_wp_error($r), "options_set" => $set, "options_locked" => $locked, "version" => defined("ZENITH_VERSION") ? ZENITH_VERSION : null];';
    $code .= journal_snippet('install_agent', $actor, ['setup' => 'options']);
    $code .= ' echo "\n", json_encode($result), "\n";';

    $result = wp_bootstrap($path, $host, $code, $config, 120);

    if (!$result['ok']) {
        return ['status' => 'partial', 'message' => sprintf('fichiers en place, mais WordPress n\'a pas pu activer le plugin : %s', $result['error']), 'activated' => false, 'reinstalled' => $had];
    }

    $data = is_array($result['json']) ? $result['json'] : [];
    $data['reinstalled'] = $had;
    $data['message'] = isset($data['message']) && null !== $data['message'] ? $data['message'] : sprintf('Plugin Zenith %s%s et activé.', isset($data['version']) ? $data['version'] : '', $had ? ' réinstallé' : ' installé');

    return $data;
}

/**
 * Drupal, driven for a campaign (1.11.0). A Drupal site is updated by
 * Composer: the inventory is what `composer update` would do within the
 * constraints of composer.json, an item is one package (with what it
 * needs), the core is its family of packages moved together, and what is
 * left — the libraries no line of composer.json names — is one lot. Each
 * update is followed by the database updates and a cache rebuild, and by
 * a configuration export when the configuration was in sync before: the
 * commit then carries what the update changed in it.
 */
function drupal_tools(array $config, $root)
{
    $project = drupal_project_root($root);
    $composer = null;
    $candidates = [];
    $found = which('composer');

    if (null !== $found) {
        $candidates[] = $found;
    }

    $home = getenv('HOME');

    foreach ([$project, dirname($project)] as $dir) {
        $candidates[] = $dir . '/composer.phar';
    }

    if (is_string($home) && '' !== $home) {
        $candidates[] = $home . '/composer.phar';
        $candidates[] = $home . '/bin/composer.phar';
        $candidates[] = $home . '/bin/composer';
    }

    foreach ($candidates as $candidate) {
        if (is_file($candidate)) {
            // Through the PHP the shell was told to use: the vendor tree of
            // a recent Drupal refuses an older one at its first require.
            $composer = [$config['php'], $candidate];
            break;
        }
    }

    $drush = null;

    foreach ([$project . '/vendor/drush/drush/drush.php', $project . '/vendor/bin/drush.php'] as $candidate) {
        if (is_file($candidate)) {
            $drush = [$config['php'], $candidate];
            break;
        }
    }

    return ['project' => $project, 'composer' => $composer, 'drush' => $drush];
}

/**
 * The environment Composer and drush run in: the configured PHP first in
 * the PATH, since both start children of their own (`php` by name), and
 * nothing asked on a terminal nobody holds.
 *
 * @return array<string, string>
 */
function drupal_env(array $config)
{
    $path = getenv('PATH');
    $path = is_string($path) && '' !== $path ? $path : '/usr/local/bin:/usr/bin:/bin';
    $home = getenv('HOME');
    $php = $config['php'];

    if (is_string($home) && '' !== $home && is_string($php) && '/' === substr($php, 0, 1) && is_file($php)) {
        $shim = $home . '/.config/zenith/bin';

        if (is_dir($shim) || @mkdir($shim, 0700, true)) {
            $link = $shim . '/php';

            if (!is_link($link) || @readlink($link) !== $php) {
                @unlink($link);
                @symlink($php, $link);
            }

            if (is_link($link)) {
                $path = $shim . ':' . $path;
            }
        }
    }

    return ['PATH' => $path, 'COMPOSER_NO_INTERACTION' => '1', 'COMPOSER_MEMORY_LIMIT' => '-1', 'COMPOSER_ALLOW_SUPERUSER' => '0'];
}

/**
 * @param array<string, mixed> $tools
 * @param string[]             $args
 */
function drupal_drush(array $tools, $root, $host, array $args, array $config, $timeout = 300)
{
    if (null === $tools['drush']) {
        return ['exit' => 127, 'stdout' => '', 'stderr' => 'drush introuvable dans vendor/ : il fait partie des dépendances du projet', 'seconds' => 0.0, 'timeout' => false];
    }

    return run(array_merge($tools['drush'], ['--root=' . $root, '--uri=https://' . $host, '--no-ansi'], $args), $timeout, $tools['project'], null, drupal_env($config));
}

/**
 * @param array<string, mixed> $tools
 * @param string[]             $args
 */
function drupal_composer(array $tools, array $args, array $config, $timeout = 600)
{
    if (null === $tools['composer']) {
        return ['exit' => 127, 'stdout' => '', 'stderr' => 'composer introuvable sur cette machine', 'seconds' => 0.0, 'timeout' => false];
    }

    return run(array_merge($tools['composer'], $args, ['--no-interaction', '--no-ansi']), $timeout, $tools['project'], null, drupal_env($config));
}

/**
 * What composer.lock holds: name => version.
 *
 * @return array<string, string>
 */
function drupal_lock($project)
{
    $lock = json_decode((string) @file_get_contents($project . '/composer.lock'), true);
    $versions = [];

    foreach (['packages', 'packages-dev'] as $key) {
        foreach (is_array($lock) && isset($lock[$key]) && is_array($lock[$key]) ? $lock[$key] : [] as $package) {
            if (is_array($package) && isset($package['name'], $package['version']) && is_string($package['name'])) {
                $versions[strtolower($package['name'])] = ltrim((string) $package['version'], 'v');
            }
        }
    }

    return $versions;
}

/**
 * What composer.json asks for by name: name => constraint.
 *
 * @return array<string, string>
 */
function drupal_requirements($project)
{
    $json = json_decode((string) @file_get_contents($project . '/composer.json'), true);
    $direct = [];

    foreach (['require', 'require-dev'] as $key) {
        foreach (is_array($json) && isset($json[$key]) && is_array($json[$key]) ? $json[$key] : [] as $name => $constraint) {
            if (is_string($name) && false !== strpos($name, '/')) {
                $direct[strtolower($name)] = (string) $constraint;
            }
        }
    }

    return $direct;
}

function drupal_is_core_package($name)
{
    return 'drupal/core' === $name || 0 === strpos($name, 'drupal/core-');
}

function drupal_is_package_name($name)
{
    return is_string($name) && strlen($name) <= 120 && 1 === preg_match('#^[a-z0-9]([a-z0-9._-]*[a-z0-9])?/[a-z0-9]([a-z0-9._-]*[a-z0-9])?$#', $name);
}

/**
 * What Composer says it would do, read from its own lines:
 * « - Upgrading vendor/name (1.0.0 => 1.0.1) ».
 *
 * @return array<string, array{from: string, to: string}>
 */
function drupal_planned_changes($text)
{
    $changes = [];

    if (preg_match_all('#^\s*-\s+(?:Upgrading|Downgrading)\s+([a-z0-9._/-]+)\s+\((\S+)\s+=>\s+(\S+)\)#mi', (string) $text, $matches, PREG_SET_ORDER)) {
        foreach ($matches as $m) {
            $changes[strtolower($m[1])] = ['from' => ltrim($m[2], 'v'), 'to' => ltrim($m[3], 'v')];
        }
    }

    return $changes;
}

/**
 * The releases of the core the site could move to: the latest stable one
 * of its own major, and the latest of a later major when there is one.
 *
 * @param array<string, mixed> $tools
 *
 * @return array{minor: ?string, major: ?string, error: ?string}
 */
function drupal_core_targets(array $tools, $current, array $config)
{
    $show = drupal_composer($tools, ['show', 'drupal/core', '--all', '--format=json'], $config, 180);
    $json = json_decode(trim($show['stdout']), true);
    $versions = is_array($json) && isset($json['versions']) && is_array($json['versions']) ? $json['versions'] : null;

    if (0 !== $show['exit'] || null === $versions || !is_string($current)) {
        return ['minor' => null, 'major' => null, 'error' => 'cœur : ' . last_error_line($show['stderr'] ?: ($show['stdout'] ?: 'composer show drupal/core a échoué'))];
    }

    $own = (int) $current;
    $minor = null;
    $major = null;

    foreach ($versions as $version) {
        $version = ltrim((string) $version, 'v');

        if (1 !== preg_match('/^\d+\.\d+\.\d+$/', $version) || version_compare($version, $current, '<=')) {
            continue;
        }

        if ((int) $version === $own) {
            $minor = null === $minor || version_compare($version, $minor, '>') ? $version : $minor;
        } else {
            $major = null === $major || version_compare($version, $major, '>') ? $version : $major;
        }
    }

    return ['minor' => $minor, 'major' => $major, 'error' => null];
}

/**
 * The same answer as WordPress's `updates`, from Composer: the core, the
 * packages composer.json names (in the place of the plugins), the
 * libraries behind them as one lot, the worktree, the disk, the tools.
 *
 * @return array<string, mixed>
 */
function drupal_updates(array $request, array $config)
{
    $path = site_path($request);
    $root = drupal_root_or_fail($path);
    $tools = drupal_tools($config, $root);
    $project = $tools['project'];
    $out = ['framework' => 'drupal', 'core' => null, 'plugins' => [], 'themes' => [], 'translations' => [], 'dependencies' => [], 'errors' => []];

    if (null === $tools['composer']) {
        throw new RuntimeException('composer introuvable sur cette machine : l\'inventaire des mises à jour de Drupal passe par lui');
    }

    $lock = drupal_lock($project);
    $direct = drupal_requirements($project);
    $current = isset($lock['drupal/core']) ? $lock['drupal/core'] : drupal_core_version($root);
    $targets = drupal_core_targets($tools, $current, $config);
    $out['core'] = ['title' => 'Drupal', 'current' => $current, 'minor' => $targets['minor'], 'major' => $targets['major']];

    if (null !== $targets['error']) {
        $out['errors'][] = $targets['error'];
    }

    // What an update would do today, constraints respected.
    $dry = drupal_composer($tools, ['update', '--dry-run', '--with-all-dependencies', '--no-scripts', '--no-plugins'], $config, 600);
    $planned = drupal_planned_changes($dry['stdout'] . "\n" . $dry['stderr']);

    if (0 !== $dry['exit']) {
        $out['errors'][] = 'composer update --dry-run : ' . last_error_line($dry['stderr'] ?: $dry['stdout']);
    }

    // What is published beyond the constraints, for the packages named.
    $outdated = drupal_composer($tools, ['outdated', '--direct', '--format=json', '--no-plugins'], $config, 300);
    $rows = json_decode(trim($outdated['stdout']), true);
    $latest = [];

    foreach (is_array($rows) && isset($rows['installed']) && is_array($rows['installed']) ? $rows['installed'] : [] as $row) {
        if (is_array($row) && isset($row['name'], $row['latest'])) {
            $latest[strtolower((string) $row['name'])] = ltrim((string) $row['latest'], 'v');
        }
    }

    ksort($direct);

    foreach ($direct as $name => $constraint) {
        if (drupal_is_core_package($name) || !drupal_is_package_name($name) || !isset($lock[$name])) {
            continue;
        }

        $row = ['name' => $name, 'title' => $name, 'status' => 'active', 'version' => $lock[$name], 'update' => 'none', 'update_version' => null, 'constraint' => $constraint];

        if (isset($planned[$name])) {
            $row['update'] = 'available';
            $row['update_version'] = $planned[$name]['to'];
        } elseif (isset($latest[$name]) && 1 === preg_match('/^\d/', $latest[$name]) && version_compare($latest[$name], $lock[$name], '>')) {
            $row['update'] = 'unavailable';
            $row['update_version'] = $latest[$name];
            $row['held_reason'] = sprintf('hors de la contrainte de composer.json (%s) : montée à décider par une personne', $constraint);
        }

        $out['plugins'][] = $row;
    }

    foreach ($planned as $name => $change) {
        if (!isset($direct[$name]) && !drupal_is_core_package($name)) {
            $out['dependencies'][] = ['name' => $name, 'from' => $change['from'], 'to' => $change['to']];
        }
    }

    $out['git'] = git_status($path);
    $out['disk'] = ['free_bytes' => @disk_free_space($path) ?: null, 'total_bytes' => @disk_total_space($path) ?: null];
    $out['tools'] = ['wp' => null, 'composer' => implode(' ', $tools['composer']), 'drush' => null === $tools['drush'] ? null : implode(' ', $tools['drush']), 'git' => which('git'), 'mysqldump' => which('mysqldump') ?: which('mariadb-dump'), 'gzip' => which('gzip')];

    return $out;
}

/**
 * Whether the active configuration and the exported one say the same.
 * Null when drush could not tell.
 *
 * @param array<string, mixed> $tools
 */
function drupal_config_in_sync(array $tools, $root, $host, array $config)
{
    $status = drupal_drush($tools, $root, $host, ['config:status', '--format=json'], $config, 180);

    if (0 !== $status['exit']) {
        return null;
    }

    $rows = json_decode(trim($status['stdout']), true);

    return is_array($rows) ? [] === $rows : (false !== stripos($status['stdout'] . $status['stderr'], 'No differences'));
}

/**
 * One update, the way a campaign asks for it: the core, one package, or
 * the libraries left. The same rows as WordPress's `update`.
 *
 * @return array<string, mixed>
 */
function drupal_update(array $request, array $config)
{
    $path = site_path($request);
    $root = drupal_root_or_fail($path);
    $host = site_host($request);
    $tools = drupal_tools($config, $root);
    $project = $tools['project'];

    if (null === $tools['composer'] || null === $tools['drush']) {
        throw new RuntimeException(null === $tools['composer'] ? 'composer introuvable sur cette machine : les mises à jour de Drupal passent par lui' : 'drush introuvable dans vendor/ : les mises à jour de base passent par lui');
    }

    $core = isset($request['core']) && true === $request['core'];
    $dependencies = isset($request['dependencies']) && true === $request['dependencies'];
    $allowMajor = isset($request['allow_major']) && true === $request['allow_major'];
    $dryRun = isset($request['dry_run']) && true === $request['dry_run'];
    $names = isset($request['items']) && is_array($request['items']) ? $request['items'] : [];
    $results = [];
    $changed = false;
    $inSync = $dryRun ? null : drupal_config_in_sync($tools, $root, $host, $config);
    $flags = $dryRun ? ['--dry-run', '--no-scripts', '--no-plugins'] : [];

    $attempt = function ($label, array $args, $watch) use ($tools, $project, $config, $dryRun, $flags, &$results, &$changed) {
        $before = drupal_lock($project);
        $run = drupal_composer($tools, array_merge(['update'], $args, ['--with-all-dependencies'], $flags), $config, 900);
        $said = str_cut(last_error_line($run['stderr'] ?: $run['stdout']), 0, 200);

        if ($dryRun) {
            $planned = drupal_planned_changes($run['stdout'] . "\n" . $run['stderr']);
            $results[] = ['item' => $label, 'status' => 0 === $run['exit'] ? 'planned' : 'failed', 'message' => 0 === $run['exit'] ? sprintf('%d paquet(s) seraient mis à jour', count($planned)) : $said, 'would_update' => [] !== $planned];

            return;
        }

        $after = drupal_lock($project);
        $moved = [];

        foreach ($after as $name => $version) {
            if (!isset($before[$name]) || $before[$name] !== $version) {
                $moved[] = $name;
            }
        }

        $row = [
            'item' => $label,
            'status' => 0 !== $run['exit'] ? 'failed' : ([] === $moved ? 'unchanged' : 'updated'),
            'message' => 0 !== $run['exit'] ? $said : ([] === $moved ? 'composer.lock identique avant et après : Composer n\'a rien installé' : sprintf('%d paquet(s) mis à jour : %s', count($moved), str_cut(implode(', ', $moved), 0, 160))),
            'version_before' => null !== $watch && isset($before[$watch]) ? $before[$watch] : null,
            'version_after' => null !== $watch && isset($after[$watch]) ? $after[$watch] : null,
            'packages' => array_slice($moved, 0, 60),
        ];
        $changed = $changed || [] !== $moved;
        $results[] = $row;
    };

    if ($core) {
        $lock = drupal_lock($project);
        $current = isset($lock['drupal/core']) ? $lock['drupal/core'] : drupal_core_version($root);
        $targets = drupal_core_targets($tools, $current, $config);
        $target = $allowMajor && null !== $targets['major'] ? $targets['major'] : $targets['minor'];

        if (null === $target) {
            $results[] = ['item' => 'core', 'status' => 'skipped', 'message' => null !== $targets['major'] ? sprintf('montée majeure %s disponible, non autorisée', $targets['major']) : (null !== $targets['error'] ? $targets['error'] : 'déjà à jour')];
        } else {
            // The lines of composer.json that pin the core to one release
            // move to the target; the ranges stay as written, unless the
            // target is another major.
            $family = [];

            foreach (drupal_requirements($project) as $name => $constraint) {
                if (!drupal_is_core_package($name)) {
                    continue;
                }

                if (1 === preg_match('/^v?\d+\.\d+\.\d+$/', trim($constraint))) {
                    $family[] = $name . ':' . $target;
                } elseif ((int) $target !== (int) $current) {
                    $family[] = $name . ':^' . (int) $target;
                }
            }

            $pinned = null;

            if ([] !== $family && !$dryRun) {
                $pinned = drupal_composer($tools, array_merge(['require', '--no-update'], $family), $config, 120);
            }

            if (null !== $pinned && 0 !== $pinned['exit']) {
                $results[] = ['item' => 'core', 'status' => 'failed', 'message' => 'composer require --no-update : ' . str_cut(last_error_line($pinned['stderr'] ?: $pinned['stdout']), 0, 200)];
            } else {
                $attempt('core', ['drupal/core', 'drupal/core-*'], 'drupal/core');
            }
        }
    }

    foreach ($names as $name) {
        $name = is_string($name) ? strtolower($name) : '';

        if (!drupal_is_package_name($name) || drupal_is_core_package($name)) {
            $results[] = ['item' => $name, 'status' => 'failed', 'message' => 'nom de paquet invalide'];
            continue;
        }

        $attempt($name, [$name], $name);
    }

    if ($dependencies) {
        $attempt('dependencies', [], null);
    }

    $after = [];

    if ($changed) {
        // The database follows the code, then the caches; the configuration
        // is exported again only when it said the same as its export before.
        $updb = drupal_drush($tools, $root, $host, ['updatedb', '-y'], $config, 900);
        $after['updb'] = ['status' => 0 === $updb['exit'] ? 'ok' : 'failed', 'message' => str_cut(last_error_line($updb['stderr'] ?: $updb['stdout']), 0, 200)];
        $rebuild = drupal_drush($tools, $root, $host, ['cache:rebuild'], $config, 300);
        $after['cache'] = ['status' => 0 === $rebuild['exit'] ? 'ok' : 'failed'];

        if (0 === $updb['exit'] && true === $inSync) {
            $export = drupal_drush($tools, $root, $host, ['config:export', '-y'], $config, 300);
            $after['config_export'] = ['status' => 0 === $export['exit'] ? 'ok' : 'failed', 'message' => str_cut(last_error_line($export['stderr'] ?: $export['stdout']), 0, 200)];
        } else {
            $after['config_export'] = ['status' => 'skipped', 'message' => true === $inSync ? 'mises à jour de base en échec' : 'configuration active différente de son export avant la mise à jour : export laissé à une personne'];
        }

        if (0 !== $updb['exit']) {
            foreach ($results as $i => $row) {
                if ('updated' === $row['status']) {
                    $results[$i]['status'] = 'failed';
                    $results[$i]['message'] = 'drush updatedb : ' . $after['updb']['message'];
                }
            }
        }
    }

    $failed = count(array_filter($results, function ($r) { return 'failed' === $r['status']; }));

    return ['status' => $dryRun ? 'planned' : (0 === $failed ? 'ok' : ($failed === count($results) ? 'failed' : 'partial')), 'dry_run' => $dryRun, 'results' => $results, 'after' => $after];
}

/**
 * vendor/ brought back to what composer.lock says, after Git moved the
 * lock under it: a branch left, a worktree put back, a merge pulled. The
 * code Git does not carry would otherwise stay one update ahead of the
 * rest.
 *
 * @return array<string, mixed>
 */
function drupal_sync_vendor(array $request, array $config)
{
    $path = site_path($request);
    $root = drupal_root($path);

    if (null === $root) {
        return ['status' => 'skipped', 'message' => 'aucun Drupal sous ce chemin'];
    }

    $tools = drupal_tools($config, $root);

    if (null === $tools['composer']) {
        return ['status' => 'skipped', 'message' => 'composer introuvable'];
    }

    $install = drupal_composer($tools, ['install'], $config, 900);
    $rebuild = 0 === $install['exit'] ? drupal_drush($tools, $root, site_host($request), ['cache:rebuild'], $config, 300) : null;

    return [
        'status' => 0 === $install['exit'] ? 'ok' : 'failed',
        'message' => 0 === $install['exit'] ? null : str_cut(last_error_line($install['stderr'] ?: $install['stdout']), 0, 200),
        'cache' => null === $rebuild ? null : (0 === $rebuild['exit'] ? 'ok' : 'failed'),
        'seconds' => $install['seconds'],
    ];
}

/**
 * The restore point of a Drupal campaign, through drush: the same
 * actions, the same answers as WordPress's.
 *
 * @return array<string, mixed>
 */
function drupal_db(array $request, array $config)
{
    if (!$config['update']) {
        throw new RuntimeException('point de reprise refusé : update=no dans la configuration de zenith-shell');
    }

    $action = isset($request['action']) && is_string($request['action']) ? $request['action'] : 'list';
    $folder = restore_folder($config);

    if ('list' === $action) {
        return ['status' => 'ok', 'folder' => $folder, 'files' => restore_files($folder)];
    }

    $path = site_path($request);
    $root = drupal_root_or_fail($path);
    $host = site_host($request);
    $tools = drupal_tools($config, $root);

    if (null === $tools['drush']) {
        throw new RuntimeException('drush introuvable dans vendor/ : le point de reprise passe par lui');
    }

    switch ($action) {
        case 'dump':
            if (!is_dir($folder) && !@mkdir($folder, 0700, true)) {
                throw new RuntimeException('dossier de reprise non créé : ' . $folder);
            }

            @chmod($folder, 0700);
            $file = $folder . '/' . gmdate('Ymd-His') . '.sql';
            $dump = drupal_drush($tools, $root, $host, ['sql:dump', '--result-file=' . $file], $config, 900);

            if (0 !== $dump['exit'] || !is_file($file)) {
                @unlink($file);

                return ['status' => 'failed', 'message' => 'drush sql:dump : ' . last_error_line($dump['stderr'] ?: $dump['stdout'])];
            }

            $size = (int) filesize($file);

            if (null !== which('gzip')) {
                $zip = run(['gzip', '-f', $file], 300);

                if (0 === $zip['exit'] && is_file($file . '.gz')) {
                    $file .= '.gz';
                }
            }

            @chmod($file, 0600);

            return ['status' => 'ok', 'file' => basename($file), 'folder' => $folder, 'bytes' => (int) filesize($file), 'sql_bytes' => $size, 'seconds' => $dump['seconds']];

        case 'restore':
            $file = restore_file($folder, $request);
            // The tables an update created are not in the dump: the base
            // is emptied first, or they would outlive the way back.
            $drop = drupal_drush($tools, $root, $host, ['sql:drop', '-y'], $config, 300);

            if (0 !== $drop['exit']) {
                return ['status' => 'failed', 'message' => 'drush sql:drop : ' . last_error_line($drop['stderr'] ?: $drop['stdout'])];
            }

            $cli = implode(' ', array_map('escapeshellarg', array_merge($tools['drush'], ['--root=' . $root, '--uri=https://' . $host, '--no-ansi', 'sql:cli'])));
            $import = run(['sh', '-c', ('.gz' === substr($file, -3) ? 'gunzip -c "$0"' : 'cat "$0"') . ' | ' . $cli, $file], 900, $tools['project'], null, drupal_env($config));

            if (0 !== $import['exit']) {
                return ['status' => 'failed', 'message' => 'drush sql:cli : ' . last_error_line($import['stderr'] ?: $import['stdout'])];
            }

            drupal_drush($tools, $root, $host, ['cache:rebuild'], $config, 300);

            return ['status' => 'ok', 'file' => basename($file), 'seconds' => $import['seconds']];

        case 'delete':
            $file = restore_file($folder, $request);
            @unlink($file);

            return ['status' => is_file($file) ? 'failed' : 'ok', 'file' => basename($file)];

        case 'verify':
            $file = restore_file($folder, $request);
            $gz = '.gz' === substr($file, -3);
            $gzipOk = true;

            if ($gz) {
                $test = run(['gzip', '-t', $file], 300);
                $gzipOk = 0 === $test['exit'];
            }

            $count = $gz
                ? run(['sh', '-c', 'gunzip -c "$0" | grep -c "^CREATE TABLE"', $file], 300)
                : run(['grep', '-c', '^CREATE TABLE', $file], 300);
            $inDump = is_numeric(trim($count['stdout'])) ? (int) trim($count['stdout']) : 0;
            $tail = $gz
                ? run(['sh', '-c', 'gunzip -c "$0" | tail -c 400', $file], 300)
                : run(['tail', '-c', '400', $file], 60);
            $complete = false !== strpos($tail['stdout'], 'Dump completed');
            $live = drupal_table_count($tools, $root, $host, $config);
            $ok = $gzipOk && $complete && $inDump > 0 && (null === $live || $inDump >= $live);
            $why = [];

            if (!$gzipOk) {
                $why[] = 'archive gzip illisible';
            }

            if (!$complete) {
                $why[] = 'dump sans ligne de fin (tronqué ?)';
            }

            if (null !== $live && $inDump < $live) {
                $why[] = sprintf('%d table(s) dans le dump, %d dans la base', $inDump, $live);
            }

            return ['status' => $ok ? 'ok' : 'failed', 'file' => basename($file), 'bytes' => (int) filesize($file), 'gzip_ok' => $gzipOk, 'complete' => $complete, 'tables_in_dump' => $inDump, 'tables_live' => $live, 'message' => [] === $why ? null : implode(' ; ', $why)];

        default:
            throw new RuntimeException(sprintf('action db inconnue : %s', $action));
    }
}

/**
 * @param array<string, mixed> $tools
 */
function drupal_table_count(array $tools, $root, $host, array $config)
{
    $tables = drupal_drush($tools, $root, $host, ['sql:query', 'SHOW TABLES'], $config, 120);

    if (0 !== $tables['exit']) {
        return null;
    }

    return count(array_filter(array_map('trim', preg_split('/\R/', trim($tables['stdout'])) ?: []), 'strlen'));
}

/**
 * What a campaign checks around a Drupal update, in the shape WordPress
 * answers: the modules enabled in the place of the active plugins, the
 * default theme, the settings an update should never move, the tables,
 * and whether database updates wait.
 *
 * @return array<string, mixed>
 */
function drupal_verify(array $request, array $config)
{
    $action = isset($request['action']) && is_string($request['action']) ? $request['action'] : 'state';
    $path = site_path($request);
    $root = drupal_root_or_fail($path);
    $host = site_host($request);
    $tools = drupal_tools($config, $root);

    if (null === $tools['drush']) {
        throw new RuntimeException('drush introuvable dans vendor/ : la vérification passe par lui');
    }

    switch ($action) {
        case 'state':
            $list = drupal_drush($tools, $root, $host, ['pm:list', '--status=enabled', '--format=json'], $config, 180);
            $rows = json_decode(trim($list['stdout']), true);

            if (0 !== $list['exit'] || !is_array($rows)) {
                return ['status' => 'failed', 'message' => 'drush pm:list : ' . last_error_line($list['stderr'] ?: ($list['stdout'] ?: 'sans réponse'))];
            }

            $modules = [];
            $themes = [];

            foreach ($rows as $name => $row) {
                if (!is_string($name) || !is_array($row) || !is_clean_slug($name, 120)) {
                    continue;
                }

                $entry = ['status' => 'active', 'version' => isset($row['version']) && is_scalar($row['version']) ? (string) $row['version'] : null];

                if (isset($row['type']) && false !== stripos((string) $row['type'], 'theme')) {
                    $themes[$name] = $entry;
                } else {
                    $modules[$name] = $entry;
                }
            }

            $read = function ($name) use ($tools, $root, $host, $config) {
                $get = drupal_drush($tools, $root, $host, ['config:get', $name, '--format=json'], $config, 120);
                $json = json_decode(trim($get['stdout']), true);

                return 0 === $get['exit'] && is_array($json) ? $json : [];
            };
            $theme = $read('system.theme');
            $site = $read('system.site');
            $users = $read('user.settings');
            $pending = drupal_drush($tools, $root, $host, ['updatedb:status', '--format=json'], $config, 180);
            $waiting = json_decode(trim($pending['stdout']), true);
            $default = isset($theme['default']) && is_string($theme['default']) ? $theme['default'] : '';

            return [
                'status' => 'ok',
                'framework' => 'drupal',
                'active_plugins' => array_keys($modules),
                'network_plugins' => [],
                'plugins' => $modules,
                'themes' => $themes,
                'options' => [
                    'template' => $default,
                    'stylesheet' => $default,
                    'siteurl' => 'https://' . $host,
                    // Only the settings that mean the same thing on both
                    // sides are answered: the others stay empty, so that a
                    // WordPress word is never put on a Drupal change.
                    'home' => 'https://' . $host,
                    'permalink_structure' => '',
                    'blog_public' => '',
                    'users_can_register' => isset($users['register']) && is_string($users['register']) ? $users['register'] : '',
                    'default_role' => '',
                    'WPLANG' => isset($site['default_langcode']) && is_string($site['default_langcode']) ? $site['default_langcode'] : '',
                    'front_page' => isset($site['page']['front']) && is_string($site['page']['front']) ? $site['page']['front'] : '',
                    'admin_theme' => isset($theme['admin']) && is_string($theme['admin']) ? $theme['admin'] : '',
                ],
                'tables' => drupal_table_count($tools, $root, $host, $config),
                'db_upgrade_needed' => 0 === $pending['exit'] && is_array($waiting) && [] !== $waiting,
                'plugin_list_ok' => true,
            ];

        case 'checksums':
            // drupal.org publishes no checksums; the files come from
            // Composer, which checks each archive against its lock.
            $none = ['status' => 'unknown', 'files' => [], 'message' => 'drupal.org ne publie pas d\'empreintes ; archives vérifiées par Composer contre composer.lock'];
            $out = ['status' => 'ok', 'core' => isset($request['core']) && true === $request['core'] ? $none : null, 'plugins' => []];

            foreach (isset($request['plugins']) && is_array($request['plugins']) ? $request['plugins'] : [] as $name) {
                if (is_string($name)) {
                    $out['plugins'][$name] = $none;
                }
            }

            return $out;

        case 'update_db':
            if (!$config['update']) {
                throw new RuntimeException('update-db refusé : update=no dans la configuration de zenith-shell');
            }

            $run = drupal_drush($tools, $root, $host, ['updatedb', '-y'], $config, 900);
            $message = trim($run['stdout'] . "\n" . $run['stderr']);

            return ['status' => 0 === $run['exit'] ? 'ok' : 'failed', 'message' => str_cut(last_error_line($message) ?: $message, 0, 200), 'already' => false !== stripos($message, 'No pending updates')];

        default:
            throw new RuntimeException(sprintf('action verify inconnue : %s', $action));
    }
}

/**
 * A Symfony application, and Sulu which is one, driven for a campaign
 * (1.12.0): the same answers as WordPress and Drupal, through Composer
 * and the application's own console. The packages of one vendor that
 * composer.json names together (symfony/*, doctrine/*, scheb/*) move as
 * one item — they are released together, and a campaign that read the
 * site again after each of forty packages would never end. On Sulu the
 * core is sulu/sulu; on a plain Symfony application it is symfony/*.
 */
function is_symfony_request(array $request)
{
    return isset($request['framework']) && is_string($request['framework']) && in_array(strtolower($request['framework']), ['symfony', 'sulu'], true);
}

/**
 * @return array<string, mixed>
 */
function symfony_tools(array $request, array $config)
{
    $path = site_path($request);
    $project = null;

    foreach ([$path, dirname($path)] as $dir) {
        if (is_file($dir . '/composer.json') && is_dir($dir . '/vendor')) {
            $project = $dir;
            break;
        }
    }

    if (null === $project) {
        throw new RuntimeException(sprintf('aucun projet Composer installé dans %s (composer.json et vendor/ attendus)', $path));
    }

    $sulu = 'sulu' === strtolower((string) $request['framework']);
    $console = null;

    foreach ($sulu ? ['/bin/adminconsole', '/bin/console'] : ['/bin/console'] as $candidate) {
        if (is_file($project . $candidate)) {
            $console = [$config['php'], $project . $candidate];
            break;
        }
    }

    $tools = drupal_tools($config, $project);

    return ['project' => $project, 'composer' => $tools['composer'], 'drush' => null, 'console' => $console, 'sulu' => $sulu, 'core' => $sulu ? 'sulu/sulu' : 'symfony/*', 'title' => $sulu ? 'Sulu' : 'Symfony'];
}

/**
 * @param array<string, mixed> $tools
 * @param string[]             $args
 */
function symfony_console(array $tools, array $args, array $config, $timeout = 300)
{
    if (null === $tools['console']) {
        return ['exit' => 127, 'stdout' => '', 'stderr' => 'bin/console introuvable dans le projet', 'seconds' => 0.0, 'timeout' => false];
    }

    return run(array_merge($tools['console'], $args, ['--no-interaction', '--no-ansi']), $timeout, $tools['project'], null, drupal_env($config) + ['APP_DEBUG' => '0']);
}

/**
 * Whether the console knows a command: an application carries the
 * migrations it chose to, and nothing is run on a guess.
 *
 * @param array<string, mixed> $tools
 */
function symfony_has_command(array $tools, $name, array $config)
{
    static $known = null;

    if (null === $known) {
        $list = symfony_console($tools, ['list', '--raw'], $config, 120);
        $known = [];

        foreach (preg_split('/\R/', $list['stdout']) ?: [] as $line) {
            $word = strtok(trim($line), " \t");

            if (is_string($word) && '' !== $word) {
                $known[$word] = true;
            }
        }
    }

    return isset($known[$name]);
}

function symfony_group($name)
{
    return substr($name, 0, (int) strpos($name, '/')) . '/*';
}

function symfony_is_item_name($name)
{
    return is_string($name) && strlen($name) <= 120 && (drupal_is_package_name($name) || 1 === preg_match('#^[a-z0-9]([a-z0-9._-]*[a-z0-9])?/\*$#', $name));
}

/**
 * The next generation of a Symfony application (1.13.0): the next
 * long-term release of Symfony (X.4) and, on Sulu, the next major of
 * sulu/sulu. Neither is taken on its word. composer.json is rewritten in
 * a copy — the symfony/* lines released together with the framework, the
 * branch Flex is held to (extra.symfony.require), the `conflict` entries
 * that fence the next major off, the line of sulu/sulu — and Composer is
 * asked to resolve it without installing anything. A generation is
 * « ready » the day that resolution passes: every bundle of the project
 * accepts it. Until then it is named, with what Composer answered.
 *
 * Only a long-term release of Symfony is a target (8.4, never 8.0 to
 * 8.3): an application held on the LTS goes from one to the next.
 *
 * @param array<string, mixed>  $tools
 * @param array<string, string> $lock
 *
 * @return array{candidate: ?string, ready: bool, target: ?string, label: ?string, rewrite: ?array<string, mixed>, blocked: ?string}
 */
function symfony_major_plan(array $tools, array $lock, array $config)
{
    $none = ['candidate' => null, 'ready' => false, 'target' => null, 'label' => null, 'rewrite' => null, 'blocked' => null];
    $project = $tools['project'];
    $json = json_decode((string) @file_get_contents($project . '/composer.json'));

    if (!is_object($json)) {
        return $none;
    }

    $stable = function ($package) use ($tools, $config) {
        $show = drupal_composer($tools, ['show', $package, '--all', '--format=json'], $config, 180);
        $data = json_decode(trim($show['stdout']), true);
        $out = [];

        foreach (is_array($data) && isset($data['versions']) && is_array($data['versions']) ? $data['versions'] : [] as $version) {
            $version = ltrim((string) $version, 'v');

            if (1 === preg_match('/^\d+\.\d+\.\d+$/', $version)) {
                $out[] = $version;
            }
        }

        return $out;
    };

    // The next long-term release of Symfony, if one is published.
    $lts = null;
    $framework = isset($lock['symfony/framework-bundle']) ? $lock['symfony/framework-bundle'] : null;

    if (is_string($framework) && 1 === preg_match('/^(\d+)\.(\d+)\./', $framework, $now)) {
        foreach ($stable('symfony/framework-bundle') as $version) {
            if (1 === preg_match('/^(\d+)\.4\.\d+$/', $version, $m) && (int) $m[1] > (int) $now[1] && (null === $lts || (int) $m[1] > (int) $lts)) {
                $lts = $m[1] . '.4';
            }
        }
    }

    // The next major of Sulu, on a Sulu project.
    $sulu = null;

    if ($tools['sulu'] && isset($lock['sulu/sulu'])) {
        foreach ($stable('sulu/sulu') as $version) {
            if ((int) $version > (int) $lock['sulu/sulu'] && (null === $sulu || (int) $version > $sulu)) {
                $sulu = (int) $version;
            }
        }
    }

    if (null === $lts && null === $sulu) {
        return $none;
    }

    $rewrite = function ($withLts, $withSulu) use ($json, $lock, $framework, $lts, $sulu) {
        $copy = unserialize(serialize($json));
        $changes = [];

        if ($withLts) {
            $branch = substr($framework, 0, (int) strrpos($framework, '.'));
            $next = (int) $framework + 1;

            foreach (['require', 'require-dev'] as $section) {
                foreach (isset($copy->{$section}) && is_object($copy->{$section}) ? get_object_vars($copy->{$section}) : [] as $name => $constraint) {
                    $key = strtolower($name);

                    // The components released with the framework, at its
                    // very branch: Flex, the polyfills, the UX packages and
                    // the bundles with a life of their own stay as written.
                    if (0 === strpos($key, 'symfony/') && isset($lock[$key]) && 0 === strpos($lock[$key], $branch . '.') && $constraint !== $lts . '.*') {
                        $copy->{$section}->{$name} = $lts . '.*';
                        $changes[] = sprintf('%s %s → %s.*', $name, $constraint, $lts);
                    }
                }
            }

            if (isset($copy->extra->symfony->require) && is_string($copy->extra->symfony->require)) {
                $changes[] = sprintf('extra.symfony.require %s → %s.*', $copy->extra->symfony->require, $lts);
                $copy->extra->symfony->require = $lts . '.*';
            }

            // A `conflict` block that fences the next major off (>=8.0)
            // moves its fence past the new branch (>=9.0).
            $moved = 0;

            foreach (isset($copy->conflict) && is_object($copy->conflict) ? get_object_vars($copy->conflict) : [] as $name => $constraint) {
                if (0 === strpos(strtolower($name), 'symfony/') && 1 === preg_match('/^>=\s*' . $next . '(\.0)*$/', trim((string) $constraint))) {
                    $copy->conflict->{$name} = '>=' . ((int) $lts + 1) . '.0';
                    ++$moved;
                }
            }

            if ($moved > 0) {
                $changes[] = sprintf('conflict : %d composant(s) symfony/* de >=%d.0 à >=%d.0', $moved, $next, (int) $lts + 1);
            }
        }

        if ($withSulu) {
            foreach (['require', 'require-dev'] as $section) {
                foreach (isset($copy->{$section}) && is_object($copy->{$section}) ? get_object_vars($copy->{$section}) : [] as $name => $constraint) {
                    if ('sulu/sulu' === strtolower($name)) {
                        $copy->{$section}->{$name} = '^' . $sulu . '.0';
                        $changes[] = sprintf('sulu/sulu %s → ^%d.0', $constraint, $sulu);
                    }
                }
            }
        }

        return [$copy, $changes];
    };

    // Together first — a major of Sulu usually comes with its Symfony —
    // then each alone.
    $attempts = [];

    if (null !== $lts && null !== $sulu) {
        $attempts[] = [true, true, sprintf('Sulu %d et Symfony %s (LTS)', $sulu, $lts)];
    }

    if (null !== $sulu) {
        $attempts[] = [false, true, sprintf('Sulu %d', $sulu)];
    }

    if (null !== $lts) {
        $attempts[] = [true, false, sprintf('Symfony %s (LTS)', $lts)];
    }

    $candidate = $attempts[0][2];
    $blocked = null;

    foreach ($attempts as $attempt) {
        list($copy, $changes) = $rewrite($attempt[0], $attempt[1]);

        if ([] === $changes) {
            $blocked = null === $blocked ? sprintf('%s : aucune ligne de composer.json à déplacer', $attempt[2]) : $blocked;
            continue;
        }

        $probe = symfony_major_probe($tools, $copy, $config);

        if ($probe['ok']) {
            $lead = $attempt[1] ? 'sulu/sulu' : 'symfony/framework-bundle';
            $target = isset($probe['planned'][$lead]) ? $probe['planned'][$lead]['to'] : null;

            if (null !== $target) {
                return ['candidate' => $attempt[2], 'ready' => true, 'target' => $target, 'label' => $attempt[2], 'rewrite' => ['json' => $copy, 'changes' => $changes, 'lead' => $lead], 'blocked' => null];
            }

            $blocked = null === $blocked ? sprintf('%s : Composer résout sans déplacer %s', $attempt[2], $lead) : $blocked;
            continue;
        }

        $blocked = null === $blocked ? sprintf('%s : %s', $attempt[2], $probe['error']) : $blocked;
    }

    return ['candidate' => $candidate, 'ready' => false, 'target' => null, 'label' => null, 'rewrite' => null, 'blocked' => $blocked];
}

/**
 * composer.json as Composer writes it: four spaces, slashes and accents
 * left alone, empty objects kept as objects.
 */
function symfony_composer_json($json)
{
    return json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n";
}

/**
 * Whether Composer resolves a rewritten composer.json: the file and the
 * lock in a directory of their own, `update --dry-run`, nothing installed
 * and nothing of the project touched. Without vendor/ no plugin runs —
 * the lines were rewritten so that none is needed.
 *
 * @param array<string, mixed> $tools
 *
 * @return array{ok: bool, error: ?string, planned: array<string, array{from: string, to: string}>}
 */
function symfony_major_probe(array $tools, $json, array $config)
{
    $dir = sys_get_temp_dir() . '/zenith-major-' . bin2hex(random_bytes(6));

    if (!@mkdir($dir, 0700)) {
        return ['ok' => false, 'error' => 'dossier temporaire refusé pour l\'essai de résolution', 'planned' => []];
    }

    @file_put_contents($dir . '/composer.json', symfony_composer_json($json));
    @copy($tools['project'] . '/composer.lock', $dir . '/composer.lock');
    $run = run(array_merge($tools['composer'], ['update', '--dry-run', '--with-all-dependencies', '--no-scripts', '--no-plugins', '--no-interaction', '--no-ansi']), 420, $dir, null, drupal_env($config));
    @unlink($dir . '/composer.json');
    @unlink($dir . '/composer.lock');
    @rmdir($dir);

    if (0 !== $run['exit']) {
        // Composer names the package that refuses a few lines after
        // « Your requirements could not be resolved » : that line says more
        // than the last one.
        $text = $run['stderr'] . "\n" . $run['stdout'];
        $why = 1 === preg_match('/Problem 1\s*\R\s*-\s*(.+)/', $text, $m) ? trim($m[1]) : last_error_line($run['stderr'] ?: $run['stdout']);

        return ['ok' => false, 'error' => $run['timeout'] ? 'résolution Composer trop longue' : str_cut($why, 0, 260), 'planned' => []];
    }

    return ['ok' => true, 'error' => null, 'planned' => drupal_planned_changes($run['stdout'] . "\n" . $run['stderr'])];
}

/**
 * @return array<string, mixed>
 */
function symfony_updates(array $request, array $config)
{
    $tools = symfony_tools($request, $config);
    $project = $tools['project'];
    $out = ['framework' => strtolower((string) $request['framework']), 'core' => null, 'plugins' => [], 'themes' => [], 'translations' => [], 'dependencies' => [], 'errors' => []];

    if (null === $tools['composer']) {
        throw new RuntimeException('composer introuvable sur cette machine : l\'inventaire des mises à jour passe par lui');
    }

    $lock = drupal_lock($project);
    $direct = drupal_requirements($project);
    // Composer's plugins stay on: Symfony Flex is one, and it is what
    // keeps every symfony/* package on the branch composer.json names
    // (extra.symfony.require). Without it the rehearsal announces a
    // Symfony the real update would never install.
    $dry = drupal_composer($tools, ['update', '--dry-run', '--with-all-dependencies', '--no-scripts'], $config, 600);
    $planned = drupal_planned_changes($dry['stdout'] . "\n" . $dry['stderr']);

    if (0 !== $dry['exit']) {
        $out['errors'][] = 'composer update --dry-run : ' . last_error_line($dry['stderr'] ?: $dry['stdout']);
    }

    $outdated = drupal_composer($tools, ['outdated', '--direct', '--format=json'], $config, 300);
    $rows = json_decode(trim($outdated['stdout']), true);
    $latest = [];

    foreach (is_array($rows) && isset($rows['installed']) && is_array($rows['installed']) ? $rows['installed'] : [] as $row) {
        if (is_array($row) && isset($row['name'], $row['latest'])) {
            $latest[strtolower((string) $row['name'])] = ltrim((string) $row['latest'], 'v');
        }
    }

    // The packages named, gathered by vendor when a vendor has several.
    $vendors = [];

    foreach ($direct as $name => $constraint) {
        if (drupal_is_package_name($name) && isset($lock[$name])) {
            $vendors[symfony_group($name)][] = $name;
        }
    }

    $items = [];

    foreach ($vendors as $group => $names) {
        if (count($names) > 1 && $group !== symfony_group($tools['core']) . '') {
            $items[$group] = $names;
        } else {
            foreach ($names as $name) {
                $items[$name] = [$name];
            }
        }
    }

    // The core: one package on Sulu, the whole vendor on Symfony.
    $coreNames = [];

    if ('symfony/*' === $tools['core']) {
        $coreNames = isset($vendors['symfony/*']) ? $vendors['symfony/*'] : [];
        unset($items['symfony/*']);

        foreach ($coreNames as $name) {
            unset($items[$name]);
        }
    } elseif (isset($lock[$tools['core']])) {
        $coreNames = [$tools['core']];
        unset($items[$tools['core']]);
    }

    $lead = function (array $names) use ($lock, $planned) {
        // The package that speaks for a group: the first one that moves,
        // the framework bundle before the others.
        usort($names, function ($a, $b) {
            return (false !== strpos($b, 'framework-bundle')) - (false !== strpos($a, 'framework-bundle')) ?: strcmp($a, $b);
        });

        foreach ($names as $name) {
            if (isset($planned[$name])) {
                return [$name, $planned[$name]['from'], $planned[$name]['to']];
            }
        }

        return [$names[0], isset($lock[$names[0]]) ? $lock[$names[0]] : null, null];
    };

    if ([] !== $coreNames) {
        $spoken = $lead($coreNames);
        $major = null;

        // A release of another major is named, never crossed here: it
        // changes composer.json, the configuration and often the code.
        foreach ($coreNames as $name) {
            if (isset($latest[$name], $lock[$name]) && 1 === preg_match('/^\d/', $latest[$name]) && (int) $latest[$name] > (int) $lock[$name]) {
                $major = $latest[$name];
                break;
            }
        }

        $out['core'] = ['title' => $tools['title'], 'current' => $spoken[1], 'minor' => $spoken[2], 'major' => null, 'beyond' => $major];
    }

    // The next generation (1.13.0), tried only when the tool says the
    // site may cross it: the trial is a full resolution by Composer.
    if (null !== $out['core'] && isset($request['probe_major']) && true === $request['probe_major']) {
        $plan = symfony_major_plan($tools, $lock, $config);
        $out['core']['major_candidate'] = $plan['candidate'];
        $out['core']['major_blocked'] = $plan['blocked'];

        if ($plan['ready']) {
            $out['core']['major'] = $plan['target'];
            $out['core']['major_label'] = $plan['label'];
            $out['core']['major_from'] = isset($lock[$plan['rewrite']['lead']]) ? $lock[$plan['rewrite']['lead']] : null;
            $out['core']['major_changes'] = $plan['rewrite']['changes'];
        }
    }

    ksort($items);

    foreach ($items as $item => $names) {
        $spoken = $lead($names);
        $row = ['name' => $item, 'title' => $item, 'status' => 'active', 'version' => $spoken[1], 'update' => 'none', 'update_version' => null, 'packages' => count($names)];

        if (null !== $spoken[2]) {
            $row['update'] = 'available';
            $row['update_version'] = $spoken[2];
        } else {
            foreach ($names as $name) {
                if (isset($latest[$name], $lock[$name]) && 1 === preg_match('/^\d/', $latest[$name]) && version_compare($latest[$name], $lock[$name], '>')) {
                    $row['update'] = 'unavailable';
                    $row['version'] = $lock[$name];
                    $row['update_version'] = $latest[$name];
                    $row['held_reason'] = sprintf('%s hors de la contrainte de composer.json (%s) : montée à décider par une personne', $name, $direct[$name]);
                    break;
                }
            }
        }

        $out['plugins'][] = $row;
    }

    foreach ($planned as $name => $change) {
        if (!isset($direct[$name])) {
            $out['dependencies'][] = ['name' => $name, 'from' => $change['from'], 'to' => $change['to']];
        }
    }

    $out['git'] = git_status($project);
    $out['disk'] = ['free_bytes' => @disk_free_space($project) ?: null, 'total_bytes' => @disk_total_space($project) ?: null];
    $out['tools'] = ['wp' => null, 'composer' => implode(' ', $tools['composer']), 'console' => null === $tools['console'] ? null : implode(' ', $tools['console']), 'git' => which('git'), 'mysqldump' => which('mysqldump') ?: which('mariadb-dump'), 'gzip' => which('gzip')];

    return $out;
}

/**
 * What follows a change of code on a Symfony application: the content
 * repository and the database migrations the application carries, each
 * only if its console knows the command. Doctrine's schema is compared,
 * never forced: an application without migrations is one whose schema a
 * person moves.
 *
 * @param array<string, mixed> $tools
 *
 * @return array<string, mixed>
 */
function symfony_migrate(array $tools, array $config)
{
    $after = [];
    $ok = true;

    foreach (['phpcr:migrations:migrate' => [], 'doctrine:migrations:migrate' => ['--allow-no-migration']] as $command => $args) {
        if (!symfony_has_command($tools, $command, $config)) {
            continue;
        }

        $run = symfony_console($tools, array_merge([$command], $args), $config, 900);
        $after[$command] = ['status' => 0 === $run['exit'] ? 'ok' : 'failed', 'message' => str_cut(last_error_line($run['stderr'] ?: $run['stdout']), 0, 200)];
        $ok = $ok && 0 === $run['exit'];
    }

    if (symfony_has_command($tools, 'doctrine:schema:update', $config)) {
        $diff = symfony_console($tools, ['doctrine:schema:update', '--dump-sql'], $config, 300);
        $queries = preg_match_all('/;\s*$/m', $diff['stdout']);
        $after['schema'] = ['status' => 0 !== $diff['exit'] ? 'unknown' : (0 === $queries ? 'ok' : 'pending'), 'queries' => (int) $queries, 'message' => 0 === $queries ? null : sprintf('%d requête(s) de schéma en attente (doctrine:schema:update), laissées à une personne', $queries)];
    }

    return ['ok' => $ok, 'steps' => $after];
}

/**
 * @return array<string, mixed>
 */
function symfony_update(array $request, array $config)
{
    if (!$config['update']) {
        throw new RuntimeException('mise à jour refusée : update=no dans la configuration de zenith-shell');
    }

    $tools = symfony_tools($request, $config);
    $project = $tools['project'];

    if (null === $tools['composer'] || null === $tools['console']) {
        throw new RuntimeException(null === $tools['composer'] ? 'composer introuvable sur cette machine : les mises à jour passent par lui' : 'bin/console introuvable dans le projet : les suites d\'une mise à jour passent par lui');
    }

    $core = isset($request['core']) && true === $request['core'];
    $dependencies = isset($request['dependencies']) && true === $request['dependencies'];
    $dryRun = isset($request['dry_run']) && true === $request['dry_run'];
    $names = isset($request['items']) && is_array($request['items']) ? $request['items'] : [];
    $results = [];
    $changed = false;
    $coreMoved = false;
    $flags = $dryRun ? ['--dry-run', '--no-scripts'] : [];

    $attempt = function ($label, array $args, $watch) use ($tools, $project, $config, $dryRun, $flags, &$results, &$changed) {
        $before = drupal_lock($project);
        $run = drupal_composer($tools, array_merge(['update'], $args, ['--with-all-dependencies'], $flags), $config, 900);
        $said = str_cut(last_error_line($run['stderr'] ?: $run['stdout']), 0, 200);

        if ($dryRun) {
            $planned = drupal_planned_changes($run['stdout'] . "\n" . $run['stderr']);
            $results[] = ['item' => $label, 'status' => 0 === $run['exit'] ? 'planned' : 'failed', 'message' => 0 === $run['exit'] ? sprintf('%d paquet(s) seraient mis à jour', count($planned)) : $said, 'would_update' => [] !== $planned];

            return false;
        }

        $after = drupal_lock($project);
        $moved = [];

        foreach ($after as $name => $version) {
            if (!isset($before[$name]) || $before[$name] !== $version) {
                $moved[] = $name;
            }
        }

        $results[] = [
            'item' => $label,
            'status' => 0 !== $run['exit'] ? 'failed' : ([] === $moved ? 'unchanged' : 'updated'),
            'message' => 0 !== $run['exit'] ? $said : ([] === $moved ? 'composer.lock identique avant et après : Composer n\'a rien installé' : sprintf('%d paquet(s) mis à jour : %s', count($moved), str_cut(implode(', ', $moved), 0, 160))),
            'version_before' => null !== $watch && isset($before[$watch]) ? $before[$watch] : null,
            'version_after' => null !== $watch && isset($after[$watch]) ? $after[$watch] : null,
            'packages' => array_slice($moved, 0, 60),
        ];
        $changed = $changed || [] !== $moved;

        return [] !== $moved;
    };

    if ($core && isset($request['allow_major']) && true === $request['allow_major']) {
        // The next generation (1.13.0): composer.json is rewritten as the
        // trial rewrote it, and everything moves in one resolution. A
        // refusal puts composer.json and its lock back as they were:
        // Composer installs nothing it could not resolve.
        $plan = symfony_major_plan($tools, drupal_lock($project), $config);

        if (!$plan['ready']) {
            $results[] = ['item' => 'core', 'status' => 'skipped', 'message' => null === $plan['candidate'] ? 'aucune version majeure publiée' : sprintf('montée majeure pas encore prête — %s', (string) $plan['blocked'])];
        } elseif ($dryRun) {
            $results[] = ['item' => 'core', 'status' => 'planned', 'message' => sprintf('%s : %s', $plan['label'], implode(' ; ', array_slice($plan['rewrite']['changes'], 0, 6))), 'would_update' => true];
        } else {
            $files = [$project . '/composer.json' => @file_get_contents($project . '/composer.json'), $project . '/composer.lock' => @file_get_contents($project . '/composer.lock')];
            $before = drupal_lock($project);
            $lead = $plan['rewrite']['lead'];
            $written = false !== $files[$project . '/composer.json'] && false !== @file_put_contents($project . '/composer.json', symfony_composer_json($plan['rewrite']['json']));
            $run = $written ? drupal_composer($tools, ['update', '--with-all-dependencies'], $config, 1500) : ['exit' => 1, 'stdout' => '', 'stderr' => 'composer.json non inscriptible'];
            $after = drupal_lock($project);
            $crossed = 0 === $run['exit'] && isset($before[$lead], $after[$lead]) && (int) $after[$lead] > (int) $before[$lead];

            if (!$crossed) {
                $restored = true;

                foreach ($files as $file => $content) {
                    $restored = false !== $content && false !== @file_put_contents($file, $content) && $restored;
                }

                // vendor/ back to what the lock says, whatever Composer had
                // begun to install.
                $resync = drupal_composer($tools, ['install', '--no-scripts'], $config, 900);
                $results[] = ['item' => 'core', 'status' => 'failed', 'message' => str_cut(sprintf('%s : %s — composer.json et son verrou %s', $plan['label'], 0 !== $run['exit'] ? last_error_line($run['stderr'] ?: $run['stdout']) : $lead . ' n\'a pas changé de majeure', $restored && 0 === $resync['exit'] ? 'remis en place' : 'À REMETTRE EN PLACE À LA MAIN'), 0, 300), 'version_before' => isset($before[$lead]) ? $before[$lead] : null, 'version_after' => isset($before[$lead]) ? $before[$lead] : null];
            } else {
                $moved = [];

                foreach ($after as $name => $version) {
                    if (!isset($before[$name]) || $before[$name] !== $version) {
                        $moved[] = $name;
                    }
                }

                $results[] = ['item' => 'core', 'status' => 'updated', 'message' => sprintf('%s : %d paquet(s) mis à jour ; %s', $plan['label'], count($moved), str_cut(implode(' ; ', $plan['rewrite']['changes']), 0, 200)), 'version_before' => $before[$lead], 'version_after' => $after[$lead], 'packages' => array_slice($moved, 0, 60), 'major' => true];
                $changed = true;
                $coreMoved = isset($before['sulu/sulu'], $after['sulu/sulu']) && $before['sulu/sulu'] !== $after['sulu/sulu'];
            }
        }
    } elseif ($core) {
        $coreMoved = $attempt('core', [$tools['core']], 'symfony/*' === $tools['core'] ? 'symfony/framework-bundle' : $tools['core']);
    }

    foreach ($names as $name) {
        $name = is_string($name) ? strtolower($name) : '';

        if (!symfony_is_item_name($name)) {
            $results[] = ['item' => $name, 'status' => 'failed', 'message' => 'nom de paquet invalide'];
            continue;
        }

        $attempt($name, [$name], '*' === substr($name, -1) ? null : $name);
    }

    if ($dependencies) {
        $attempt('dependencies', [], null);
    }

    $after = [];

    if ($changed) {
        $migrated = symfony_migrate($tools, $config);
        $after = $migrated['steps'];

        // Sulu's administration is a JavaScript build that goes with the
        // version of sulu/sulu: fetched again when the core moved.
        if ($tools['sulu'] && true === $coreMoved && symfony_has_command($tools, 'sulu:admin:download-build', $config)) {
            $build = symfony_console($tools, ['sulu:admin:download-build'], $config, 600);
            $after['admin_build'] = ['status' => 0 === $build['exit'] ? 'ok' : 'failed', 'message' => str_cut(last_error_line($build['stderr'] ?: $build['stdout']), 0, 200)];
        }

        if (!$migrated['ok']) {
            foreach ($results as $i => $row) {
                if ('updated' === $row['status']) {
                    $results[$i]['status'] = 'failed';
                    $results[$i]['message'] = 'migrations en échec après la mise à jour : ' . json_encode($after, JSON_UNESCAPED_UNICODE);
                }
            }
        }
    }

    $failed = count(array_filter($results, function ($r) { return 'failed' === $r['status']; }));

    return ['status' => $dryRun ? 'planned' : (0 === $failed ? 'ok' : ($failed === count($results) ? 'failed' : 'partial')), 'dry_run' => $dryRun, 'results' => $results, 'after' => $after];
}

/**
 * The caches of the application, cleared by its own console: both
 * contexts on Sulu, whose administration and website each keep theirs.
 * The OPcache of the web server is not this process's to empty; a
 * production that never revalidates its files needs its own reload.
 *
 * @return array<string, mixed>
 */
function symfony_cache_flush(array $request, array $config)
{
    $tools = symfony_tools($request, $config);
    $project = $tools['project'];
    $consoles = $tools['sulu'] ? ['bin/adminconsole', 'bin/websiteconsole'] : ['bin/console'];
    $cleared = [];
    $ok = true;

    foreach ($consoles as $console) {
        if (!is_file($project . '/' . $console)) {
            continue;
        }

        $run = run([$config['php'], $project . '/' . $console, 'cache:clear', '--no-interaction', '--no-ansi'], 300, $project, null, drupal_env($config) + ['APP_DEBUG' => '0']);
        $cleared[$console] = 0 === $run['exit'];
        $ok = $ok && 0 === $run['exit'];
    }

    return ['status' => $ok && [] !== $cleared ? 'ok' : 'failed', 'flushed' => ['object_cache' => $ok ? true : null, 'opcache' => null, 'transients' => null, 'page_cache' => []], 'consoles' => $cleared];
}

/**
 * vendor/ brought back to composer.lock after Git moved it; Composer's
 * own scripts clear the caches of the application.
 *
 * @return array<string, mixed>
 */
function symfony_sync_vendor(array $request, array $config)
{
    try {
        $tools = symfony_tools($request, $config);
    } catch (RuntimeException $e) {
        return ['status' => 'skipped', 'message' => $e->getMessage()];
    }

    if (null === $tools['composer']) {
        return ['status' => 'skipped', 'message' => 'composer introuvable'];
    }

    $install = drupal_composer($tools, ['install'], $config, 900);

    return ['status' => 0 === $install['exit'] ? 'ok' : 'failed', 'message' => 0 === $install['exit'] ? null : str_cut(last_error_line($install['stderr'] ?: $install['stdout']), 0, 200), 'seconds' => $install['seconds']];
}

/**
 * DATABASE_URL as the application reads it (.env, .env.local, the
 * environment): "" when it declares none — an application without a
 * database (1.12.1) —, null when it could not be read at all.
 *
 * @param array<string, mixed> $tools
 *
 * @return string|null
 */
function symfony_database_url(array $tools, array $config)
{
    $code = 'require "vendor/autoload.php"; if (class_exists("Symfony\\\\Component\\\\Dotenv\\\\Dotenv") && is_file(".env")) { (new Symfony\\Component\\Dotenv\\Dotenv())->bootEnv(".env"); } $u = isset($_SERVER["DATABASE_URL"]) ? $_SERVER["DATABASE_URL"] : (getenv("DATABASE_URL") ?: ""); echo json_encode(["url" => $u]);';
    $read = run([$config['php'], '-r', $code], 60, $tools['project'], null, drupal_env($config));
    $json = json_decode(trim($read['stdout']), true);

    return is_array($json) && isset($json['url']) && is_string($json['url']) ? $json['url'] : null;
}

/**
 * The connection of the application, as a client file mysqldump reads.
 *
 * @param array<string, mixed> $tools
 *
 * @return array{file: string, database: string}
 */
function symfony_database(array $tools, array $config, $folder)
{
    $url = (string) symfony_database_url($tools, $config);
    $parts = '' === $url ? false : parse_url($url);

    if (!is_array($parts) || !isset($parts['scheme'], $parts['path']) || !in_array(strtolower($parts['scheme']), ['mysql', 'mariadb', 'pdo-mysql', 'mysqli'], true)) {
        throw new RuntimeException('DATABASE_URL illisible ou hors MySQL/MariaDB : le point de reprise ne sait lire que ces bases');
    }

    if (!is_dir($folder) && !@mkdir($folder, 0700, true)) {
        throw new RuntimeException('dossier de reprise non créé : ' . $folder);
    }

    @chmod($folder, 0700);
    $file = $folder . '/.my-' . getmypid() . '.cnf';
    $quote = function ($value) {
        return '"' . str_replace(['\\', '"'], ['\\\\', '\\"'], (string) $value) . '"';
    };
    $lines = ['[client]', 'user=' . $quote(isset($parts['user']) ? rawurldecode($parts['user']) : ''), 'password=' . $quote(isset($parts['pass']) ? rawurldecode($parts['pass']) : ''), 'host=' . $quote(isset($parts['host']) ? $parts['host'] : 'localhost')];

    if (isset($parts['port'])) {
        $lines[] = 'port=' . (int) $parts['port'];
    }

    $old = umask(0077);
    file_put_contents($file, implode("\n", $lines) . "\n");
    umask($old);
    register_shutdown_function(function () use ($file) {
        @unlink($file);
    });

    return ['file' => $file, 'database' => rawurldecode(ltrim($parts['path'], '/'))];
}

/**
 * @return array<string, mixed>
 */
function symfony_db(array $request, array $config)
{
    if (!$config['update']) {
        throw new RuntimeException('point de reprise refusé : update=no dans la configuration de zenith-shell');
    }

    $action = isset($request['action']) && is_string($request['action']) ? $request['action'] : 'list';
    $folder = restore_folder($config);

    if ('list' === $action) {
        return ['status' => 'ok', 'folder' => $folder, 'files' => restore_files($folder)];
    }

    if ('delete' === $action) {
        $file = restore_file($folder, $request);
        @unlink($file);

        return ['status' => is_file($file) ? 'failed' : 'ok', 'file' => basename($file)];
    }

    $tools = symfony_tools($request, $config);

    // An application that declares no database has nothing to dump: said
    // as such, so that a campaign goes on with Git as its only way back
    // rather than refusing for want of a restore point (1.12.1).
    if ('dump' === $action && '' === symfony_database_url($tools, $config)) {
        return ['status' => 'ok', 'none' => true, 'file' => null, 'folder' => $folder, 'bytes' => 0, 'message' => 'aucune base de données déclarée (DATABASE_URL absent)'];
    }

    $db = symfony_database($tools, $config, $folder);
    $dumper = which('mysqldump') ?: which('mariadb-dump');
    $client = which('mysql') ?: which('mariadb');

    if (null === $dumper || null === $client) {
        throw new RuntimeException('mysqldump ou mysql introuvable : le point de reprise passe par eux');
    }

    $tables = function () use ($client, $db) {
        $list = run([$client, '--defaults-extra-file=' . $db['file'], '-N', '-e', 'SHOW TABLES', $db['database']], 120);

        return 0 === $list['exit'] ? array_values(array_filter(array_map('trim', preg_split('/\R/', trim($list['stdout'])) ?: []), 'strlen')) : null;
    };

    switch ($action) {
        case 'dump':
            $file = $folder . '/' . gmdate('Ymd-His') . '.sql';
            $dump = run([$dumper, '--defaults-extra-file=' . $db['file'], '--single-transaction', '--quick', '--add-drop-table', '--routines', '--result-file=' . $file, $db['database']], 900);

            if (0 !== $dump['exit'] || !is_file($file)) {
                @unlink($file);

                return ['status' => 'failed', 'message' => 'mysqldump : ' . last_error_line($dump['stderr'] ?: $dump['stdout'])];
            }

            $size = (int) filesize($file);

            if (null !== which('gzip')) {
                $zip = run(['gzip', '-f', $file], 300);

                if (0 === $zip['exit'] && is_file($file . '.gz')) {
                    $file .= '.gz';
                }
            }

            @chmod($file, 0600);

            return ['status' => 'ok', 'file' => basename($file), 'folder' => $folder, 'bytes' => (int) filesize($file), 'sql_bytes' => $size, 'seconds' => $dump['seconds']];

        case 'restore':
            $file = restore_file($folder, $request);
            // The tables an update created are not in the dump: dropped
            // first, or they would outlive the way back.
            $live = $tables();

            if (is_array($live) && [] !== $live) {
                $names = implode(', ', array_map(function ($t) { return '`' . str_replace('`', '``', $t) . '`'; }, $live));
                $drop = run([$client, '--defaults-extra-file=' . $db['file'], '-e', 'SET FOREIGN_KEY_CHECKS=0; DROP TABLE IF EXISTS ' . $names . ';', $db['database']], 300);

                if (0 !== $drop['exit']) {
                    return ['status' => 'failed', 'message' => 'vidage de la base : ' . last_error_line($drop['stderr'] ?: $drop['stdout'])];
                }
            }

            $cli = implode(' ', array_map('escapeshellarg', [$client, '--defaults-extra-file=' . $db['file'], $db['database']]));
            $import = run(['sh', '-c', ('.gz' === substr($file, -3) ? 'gunzip -c "$0"' : 'cat "$0"') . ' | ' . $cli, $file], 900);

            if (0 !== $import['exit']) {
                return ['status' => 'failed', 'message' => 'mysql : ' . last_error_line($import['stderr'] ?: $import['stdout'])];
            }

            return ['status' => 'ok', 'file' => basename($file), 'seconds' => $import['seconds']];

        case 'verify':
            $file = restore_file($folder, $request);
            $gz = '.gz' === substr($file, -3);
            $gzipOk = true;

            if ($gz) {
                $test = run(['gzip', '-t', $file], 300);
                $gzipOk = 0 === $test['exit'];
            }

            $count = $gz
                ? run(['sh', '-c', 'gunzip -c "$0" | grep -c "^CREATE TABLE"', $file], 300)
                : run(['grep', '-c', '^CREATE TABLE', $file], 300);
            $inDump = is_numeric(trim($count['stdout'])) ? (int) trim($count['stdout']) : 0;
            $tail = $gz
                ? run(['sh', '-c', 'gunzip -c "$0" | tail -c 400', $file], 300)
                : run(['tail', '-c', '400', $file], 60);
            $complete = false !== strpos($tail['stdout'], 'Dump completed');
            $names = $tables();
            $live = null === $names ? null : count($names);
            $ok = $gzipOk && $complete && $inDump > 0 && (null === $live || $inDump >= $live);
            $why = [];

            if (!$gzipOk) {
                $why[] = 'archive gzip illisible';
            }

            if (!$complete) {
                $why[] = 'dump sans ligne de fin (tronqué ?)';
            }

            if (null !== $live && $inDump < $live) {
                $why[] = sprintf('%d table(s) dans le dump, %d dans la base', $inDump, $live);
            }

            return ['status' => $ok ? 'ok' : 'failed', 'file' => basename($file), 'bytes' => (int) filesize($file), 'gzip_ok' => $gzipOk, 'complete' => $complete, 'tables_in_dump' => $inDump, 'tables_live' => $live, 'message' => [] === $why ? null : implode(' ; ', $why)];

        default:
            throw new RuntimeException(sprintf('action db inconnue : %s', $action));
    }
}

/**
 * The state of a Symfony application in the shape WordPress answers: the
 * bundles its kernel loads in the place of the active plugins. A kernel
 * that no longer boots answers an empty list — every bundle gone — which
 * is what a campaign must read as a regression.
 *
 * @return array<string, mixed>
 */
function symfony_verify(array $request, array $config)
{
    $action = isset($request['action']) && is_string($request['action']) ? $request['action'] : 'state';
    $tools = symfony_tools($request, $config);

    if (null === $tools['console']) {
        throw new RuntimeException('bin/console introuvable dans le projet : la vérification passe par lui');
    }

    switch ($action) {
        case 'state':
            $read = symfony_console($tools, ['debug:container', '--parameter=kernel.bundles', '--format=json'], $config, 180);
            $json = json_decode(trim($read['stdout']), true);
            $bundles = is_array($json) && isset($json['kernel.bundles']) && is_array($json['kernel.bundles']) ? $json['kernel.bundles'] : (is_array($json) ? $json : []);
            $booted = 0 === $read['exit'] && [] !== $bundles;
            $plugins = [];

            foreach ($bundles as $name => $class) {
                if (is_string($name) && is_clean_slug($name, 120)) {
                    $plugins[$name] = ['status' => 'active', 'version' => null];
                }
            }

            $host = site_host($request);
            $tables = null;

            try {
                $db = symfony_database($tools, $config, restore_folder($config));
                $client = which('mysql') ?: which('mariadb');

                if (null !== $client) {
                    $list = run([$client, '--defaults-extra-file=' . $db['file'], '-N', '-e', 'SHOW TABLES', $db['database']], 120);
                    $tables = 0 === $list['exit'] ? count(array_filter(array_map('trim', preg_split('/\R/', trim($list['stdout'])) ?: []), 'strlen')) : null;
                }
            } catch (RuntimeException $e) {
                $tables = null;
            }

            return [
                'status' => 'ok',
                'framework' => strtolower((string) $request['framework']),
                'active_plugins' => array_keys($plugins),
                'network_plugins' => [],
                'plugins' => $plugins,
                'themes' => [],
                'options' => ['template' => '', 'stylesheet' => $tools['title'], 'siteurl' => 'https://' . $host, 'home' => 'https://' . $host, 'permalink_structure' => '', 'blog_public' => '', 'users_can_register' => '', 'default_role' => '', 'WPLANG' => ''],
                'tables' => $tables,
                'db_upgrade_needed' => false,
                'plugin_list_ok' => $booted,
                'message' => $booted ? null : 'le noyau ne démarre plus : ' . str_cut(last_error_line($read['stderr'] ?: $read['stdout']), 0, 200),
            ];

        case 'checksums':
            $none = ['status' => 'unknown', 'files' => [], 'message' => 'archives vérifiées par Composer contre composer.lock'];
            $out = ['status' => 'ok', 'core' => isset($request['core']) && true === $request['core'] ? $none : null, 'plugins' => []];

            foreach (isset($request['plugins']) && is_array($request['plugins']) ? $request['plugins'] : [] as $name) {
                if (is_string($name)) {
                    $out['plugins'][$name] = $none;
                }
            }

            return $out;

        case 'update_db':
            if (!$config['update']) {
                throw new RuntimeException('update-db refusé : update=no dans la configuration de zenith-shell');
            }

            $migrated = symfony_migrate($tools, $config);
            $pending = isset($migrated['steps']['schema']['message']) && is_string($migrated['steps']['schema']['message']) ? $migrated['steps']['schema']['message'] : null;

            return ['status' => $migrated['ok'] ? 'ok' : 'failed', 'message' => null !== $pending ? $pending : ($migrated['ok'] ? 'migrations à jour' : json_encode($migrated['steps'], JSON_UNESCAPED_UNICODE)), 'already' => $migrated['ok'] && null === $pending, 'steps' => $migrated['steps']];

        default:
            throw new RuntimeException(sprintf('action verify inconnue : %s', $action));
    }
}

/**
 * The enrolment handed to wp zenith setup: the plugin activated by wp-cli,
 * the settings frozen by wp-config.php asked of the plugin and left out,
 * the rest passed as options. Every value is held to the plugin's own
 * rule before it reaches the command line, where it travels as one
 * argument behind its option name. Null when wp-cli could not do it, so
 * that the option path takes over.
 *
 * @param string[]             $wp
 * @param array<string, mixed> $options
 *
 * @return array<string, mixed>|null
 */
function install_agent_by_cli($path, array $wp, array $options, $version, $had)
{
    $base = array_merge($wp, ['--path=' . $path, '--skip-themes', '--no-color']);
    $activate = run(array_merge($base, ['plugin', 'activate', 'zenith-wordpress']), 120, $path);

    if (0 !== $activate['exit']) {
        return null;
    }

    // The code is this script's, not the request's: only its answer varies.
    $probe = run(array_merge($base, ['eval', 'echo json_encode(function_exists("zenith_setting_locked") ? array_values(array_filter(zenith_setting_constant_names(), "zenith_setting_locked")) : []);']), 60, $path);
    $locked = 0 === $probe['exit'] ? json_decode(trim($probe['stdout']), true) : null;

    if (!is_array($locked)) {
        return null;
    }

    $rules = [
        'zenith_api_key' => ['api-key', '/^[A-Za-z0-9_\-]{16,255}$/'],
        'zenith_update_token' => ['update-token', '/^[A-Za-z0-9_\-]{16,255}$/'],
        'zenith_push_secret' => ['push-secret', '/^[A-Za-z0-9_\-]{16,255}$/'],
        'zenith_push_url' => ['push-url', '#^https?://[A-Za-z0-9._~%:/?\#\[\]@!$&\'()*+,;=\-]{1,500}$#'],
        'zenith_write_ip_allowlist' => ['ip-allowlist', '/^[0-9A-Fa-f.:\/,\s]{1,500}$/'],
        'zenith_github_token' => ['github-token', '/^[A-Za-z0-9_\-.]{1,255}$/'],
    ];
    $args = [];
    $set = [];
    $skipped = [];

    foreach ($rules as $option => $rule) {
        if (!isset($options[$option]) || '' === (string) $options[$option]) {
            continue;
        }

        $name = substr($option, 7);

        if (in_array($name, $locked, true)) {
            $skipped[] = $name;
            continue;
        }

        $value = (string) $options[$option];

        if (!preg_match($rule[1], $value)) {
            return null;
        }

        $args[] = '--' . $rule[0] . '=' . ('ip-allowlist' === $rule[0] ? implode(',', array_filter(preg_split('/[\s,]+/', $value) ?: [], 'strlen')) : $value);
        $set[] = $option;
    }

    if (isset($options['zenith_write_require_signature']) && is_yes($options['zenith_write_require_signature'])) {
        $args[] = '--require-signature';
        $set[] = 'zenith_write_require_signature';
    }

    // Both endpoints open unless told otherwise: setup's own default, and
    // what a site under supervision is enrolled for.
    foreach (['zenith_updates_enabled' => '--no-update', 'zenith_control_enabled' => '--no-control'] as $option => $flag) {
        if (isset($options[$option]) && !is_yes($options[$option])) {
            $args[] = $flag;
        }

        $set[] = $option;
    }

    $setup = run(array_merge($base, ['zenith', 'setup', '--format=json'], $args), 120, $path);

    if (0 !== $setup['exit']) {
        return null;
    }

    return [
        'status' => 'ok',
        'activated' => true,
        'version' => $version,
        'options_set' => $set,
        'options_locked' => $skipped,
        'setup' => 'wp zenith setup',
        'reinstalled' => $had,
        'message' => sprintf('Plugin Zenith %s %s, activé et configuré par wp zenith setup.', $version, $had ? 'réinstallé' : 'installé'),
    ];
}

/* ---------------------------------------------------------------------------
 * Drupal
 *
 * Everything below reads or drives a Drupal site. Nothing above calls into
 * it except through the switch at the top of each verb, so a WordPress
 * request runs exactly the code it ran before this block existed.
 * ------------------------------------------------------------------------- */

function is_drupal_request(array $request)
{
    return isset($request['framework']) && is_string($request['framework']) && 'drupal' === strtolower($request['framework']);
}

/**
 * The web root of the Drupal under a path: the path itself, or the usual
 * public directory of a Composer project when the path names the project.
 */
function drupal_root($path)
{
    if (null === $path) {
        return null;
    }

    foreach (['', '/web', '/docroot', '/public', '/html', '/public_html', '/app'] as $sub) {
        if (is_file($path . $sub . '/core/lib/Drupal.php') && is_file($path . $sub . '/index.php')) {
            return $path . $sub;
        }
    }

    return null;
}

function drupal_root_or_fail($path)
{
    $root = drupal_root($path);

    if (null === $root) {
        throw new RuntimeException(sprintf('aucun Drupal dans %s', $path));
    }

    return $root;
}

/**
 * Where Composer keeps the project: next to the web root, or one level up.
 */
function drupal_project_root($root)
{
    foreach ([$root, dirname($root)] as $dir) {
        if (is_file($dir . '/composer.json') && is_dir($dir . '/vendor')) {
            return $dir;
        }
    }

    return is_dir($root . '/vendor') ? $root : (is_dir(dirname($root) . '/vendor') ? dirname($root) : $root);
}

function drupal_core_version($root)
{
    $file = $root . '/core/lib/Drupal.php';

    return is_readable($file) && preg_match('/const\s+VERSION\s*=\s*\'([^\']+)\'/', (string) file_get_contents($file, false, null, 0, 16384), $m) ? $m[1] : null;
}

function drush_version(array $config, $path)
{
    $root = drupal_root($path);

    if (null === $root) {
        return null;
    }

    // Read from Composer's own record rather than by running drush: drush
    // boots slowly, wants a home directory and a terminal of its liking, and
    // a jailed account does not always give it either.
    $installed = drupal_project_root($root) . '/vendor/composer/installed.json';

    if (!is_readable($installed) || filesize($installed) > 8 * 1024 * 1024) {
        return null;
    }

    $data = json_decode((string) file_get_contents($installed), true);
    $packages = is_array($data) && isset($data['packages']) && is_array($data['packages']) ? $data['packages'] : (is_array($data) ? $data : []);

    foreach ($packages as $package) {
        if (is_array($package) && isset($package['name'], $package['version']) && 'drush/drush' === $package['name']) {
            return ltrim((string) $package['version'], 'v');
        }
    }

    return null;
}

/**
 * The site directory a host name selects: sites/<host> when it holds a
 * settings.php, sites/default otherwise. sites.php is not read: it is PHP,
 * and nothing of the site runs inside this process.
 */
function drupal_site_dir($root, $host = null)
{
    if (null !== $host && is_file($root . '/sites/' . $host . '/settings.php')) {
        return 'sites/' . $host;
    }

    return 'sites/default';
}

/**
 * settings.php and the directory that holds it, seen from the file system:
 * who may read the database password, who may replace the file.
 *
 * @return array<string, mixed>
 */
function drupal_settings_status($path)
{
    $root = drupal_root($path);

    if (null === $root) {
        return ['found' => false];
    }

    $site = drupal_site_dir($root);
    $file = $root . '/' . $site . '/settings.php';
    $perms = is_file($file) ? fileperms($file) : false;
    $dirPerms = fileperms($root . '/' . $site);
    $owner = is_file($file) ? fileowner($file) : false;
    $me = function_exists('posix_geteuid') ? posix_geteuid() : null;

    return [
        'found' => true,
        'root' => $root,
        'project_root' => drupal_project_root($root),
        'core_version' => drupal_core_version($root),
        'site_dir' => $site,
        'settings_file' => is_file($file) ? $file : null,
        'mode' => false === $perms ? null : substr(sprintf('%o', $perms), -4),
        'world_readable' => false === $perms ? null : (bool) ($perms & 0004),
        'group_writable' => false === $perms ? null : (bool) ($perms & 0020),
        'world_writable' => false === $perms ? null : (bool) ($perms & 0002),
        'writable_by_me' => is_file($file) ? is_writable($file) : null,
        'owned_by_me' => false === $owner || null === $me ? null : $owner === $me,
        'site_dir_mode' => false === $dirPerms ? null : substr(sprintf('%o', $dirPerms), -4),
        'site_dir_writable_by_me' => is_writable($root . '/' . $site),
        'settings_local_present' => is_file($root . '/' . $site . '/settings.local.php'),
        'services_yml_present' => is_file($root . '/' . $site . '/services.yml'),
        'vendor_inside_docroot' => is_dir($root . '/vendor'),
    ];
}

/**
 * The database settings of the site, under the names mysql_status() and the
 * diagnostic already read. settings.php is PHP: it is included in a process
 * of its own, which prints the connection and nothing else, so whatever the
 * file does stays out of this one.
 *
 * @return array<string, string>
 */
function drupal_database_constants($path, array $config, $host = null)
{
    $root = drupal_root($path);

    if (null === $root) {
        return [];
    }

    $site = drupal_site_dir($root, $host);
    $script = '<?php error_reporting(0); ini_set("display_errors", "0");'
        . ' $app_root = ' . var_export($root, true) . '; $site_path = ' . var_export($site, true) . ';'
        . ' chdir($app_root); if (is_file($app_root . "/autoload.php")) { $class_loader = require $app_root . "/autoload.php"; }'
        . ' $databases = []; $settings = []; $config = [];'
        . ' ob_start(); include $app_root . "/" . $site_path . "/settings.php"; ob_end_clean();'
        . ' $db = isset($databases["default"]["default"]) && is_array($databases["default"]["default"]) ? $databases["default"]["default"] : [];'
        . ' echo "\n", json_encode(array_intersect_key($db, array_flip(["driver", "host", "port", "unix_socket", "username", "password", "database", "prefix"]))), "\n";';
    $result = run([$config['php']], 20, $root, $script);
    $start = strrpos($result['stdout'], "\n{");
    $db = false === $start ? null : json_decode(trim(substr($result['stdout'], $start + 1)), true);

    if (!is_array($db) || !isset($db['database'], $db['username']) || (isset($db['driver']) && !in_array($db['driver'], ['mysql', 'mysqli'], true))) {
        return [];
    }

    $dbHost = isset($db['host']) && '' !== $db['host'] ? (string) $db['host'] : 'localhost';

    if (isset($db['unix_socket']) && '' !== $db['unix_socket']) {
        $dbHost = 'localhost:' . $db['unix_socket'];
    } elseif (isset($db['port']) && '' !== (string) $db['port']) {
        $dbHost .= ':' . (int) $db['port'];
    }

    return ['DB_HOST' => $dbHost, 'DB_USER' => (string) $db['username'], 'DB_PASSWORD' => isset($db['password']) ? (string) $db['password'] : '', 'DB_NAME' => (string) $db['database']];
}

/**
 * Who owns what, on the paths a Drupal site is made of.
 *
 * @return array<string, mixed>
 */
function drupal_ownership_status($path)
{
    $root = drupal_root($path);
    $base = null === $root ? $path : $root;
    $site = null === $root ? 'sites/default' : drupal_site_dir($root);
    $project = null === $root ? $base : drupal_project_root($root);
    $me = function_exists('posix_geteuid') ? posix_geteuid() : null;
    $entries = [];

    foreach (['root' => $base, 'settings' => $base . '/' . $site . '/settings.php', 'site_dir' => $base . '/' . $site, 'files' => $base . '/' . $site . '/files', 'modules' => $base . '/modules', 'themes' => $base . '/themes', 'core' => $base . '/core', 'vendor' => $project . '/vendor'] as $key => $file) {
        if (!file_exists($file)) {
            $entries[$key] = null;
            continue;
        }

        $uid = fileowner($file);
        $gid = filegroup($file);
        $perms = fileperms($file);

        $entries[$key] = [
            'path' => $file,
            'owner' => false !== $uid && function_exists('posix_getpwuid') ? (posix_getpwuid($uid)['name'] ?? (string) $uid) : (string) $uid,
            'group' => false !== $gid && function_exists('posix_getgrgid') ? (posix_getgrgid($gid)['name'] ?? (string) $gid) : (string) $gid,
            'mode' => false === $perms ? null : substr(sprintf('%o', $perms), -4),
            'mine' => null !== $me && false !== $uid ? $uid === $me : null,
            'writable_by_me' => is_writable($file),
            'group_writable' => false === $perms ? null : (bool) ($perms & 0020),
            'world_writable' => false === $perms ? null : (bool) ($perms & 0002),
        ];
    }

    return ['user' => null !== $me && function_exists('posix_getpwuid') ? (posix_getpwuid($me)['name'] ?? (string) $me) : get_current_user(), 'entries' => $entries];
}

/**
 * Runs a snippet inside the site: the kernel is booted the way index.php
 * boots it, for the host Zenith names, without drush and without HTTP. The
 * snippet finds $kernel and $request, and prints one JSON document last.
 *
 * @return array{ok: bool, output: string, error: ?string, seconds: float, json: mixed}
 */
function drupal_bootstrap($root, $host, $code, array $config, $timeout = 90)
{
    $uri = isset($GLOBALS['zenith_site_uri']) && is_string($GLOBALS['zenith_site_uri']) ? $GLOBALS['zenith_site_uri'] : '/';

    $script = '<?php'
        . ' error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED); ini_set("display_errors", "stderr");'
        . ' define("ZENITH_SSH", true);'
        . ' $_SERVER["HTTP_HOST"] = ' . var_export($host, true) . '; $_SERVER["SERVER_NAME"] = ' . var_export($host, true) . ';'
        . ' $_SERVER["REQUEST_URI"] = ' . var_export($uri, true) . '; $_SERVER["SCRIPT_NAME"] = "/index.php"; $_SERVER["SCRIPT_FILENAME"] = ' . var_export($root . '/index.php', true) . '; $_SERVER["PHP_SELF"] = "/index.php";'
        . ' $_SERVER["REQUEST_METHOD"] = "GET"; $_SERVER["SERVER_PORT"] = 443; $_SERVER["HTTPS"] = "on"; $_SERVER["REMOTE_ADDR"] = "127.0.0.1"; $_SERVER["HTTP_USER_AGENT"] = "zenith-shell"; $_SERVER["SERVER_SOFTWARE"] = "zenith-shell";'
        . ' chdir(' . var_export($root, true) . ');'
        . ' $autoloader = require ' . var_export($root . '/autoload.php', true) . ';'
        . ' $request = \Symfony\Component\HttpFoundation\Request::createFromGlobals();'
        . ' $kernel = \Drupal\Core\DrupalKernel::createFromRequest($request, $autoloader, "prod");'
        . ' $kernel->boot(); $kernel->preHandle($request);'
        . ' ' . $code;

    $result = run([$config['php'], '-d', 'memory_limit=512M', '-d', 'max_execution_time=0'], $timeout, $root, $script);
    $output = trim($result['stdout']);
    $error = trim($result['stderr']);
    $json = null;
    $start = strrpos($output, "\n{");
    $candidate = false === $start ? $output : substr($output, $start + 1);

    if ('' !== $candidate && '{' === $candidate[0]) {
        $json = json_decode($candidate, true);
    }

    $failure = null;

    if ($result['timeout']) {
        $failure = sprintf('Drupal ne s\'est pas chargé en %d s', $timeout);
    } elseif (0 !== $result['exit'] || null === $json) {
        if ('' !== $error) {
            $failure = drupal_error_line($error);
        } elseif ('' !== $output) {
            $failure = drupal_error_line(strip_tags($output));
        } else {
            $failure = sprintf('sortie %d sans réponse', $result['exit']);
        }
    }

    return ['ok' => null === $failure, 'output' => $output, 'error' => $failure, 'seconds' => $result['seconds'], 'json' => $json];
}

/**
 * The line that names the failure. Drupal prints the exception first and its
 * stack after: the last line of the output is a frame number, the first one
 * that is not a frame is the message. Site paths are cut out of it.
 */
function drupal_error_line($text)
{
    foreach (preg_split('/\R/', trim($text)) ?: [] as $line) {
        $line = trim($line);

        if ('' === $line || '#' === $line[0] || 0 === stripos($line, 'Stack trace') || 0 === stripos($line, 'thrown in')) {
            continue;
        }

        $line = (string) preg_replace('/^PHP\s+/', '', $line);
        $line = (string) preg_replace('/\s+\[Tip:.*$/s', '', $line);

        return str_cut($line, 0, 300);
    }

    return str_cut(trim($text), 0, 300);
}

/**
 * The agent's own reading, asked from inside: the kernel handles the very
 * request Zenith sends over HTTP, with the key the site holds. What the
 * module answers is what comes back, whatever its version.
 *
 * @return array<string, mixed>
 */
function drupal_inventory(array $request, array $config)
{
    $root = drupal_root_or_fail(site_path($request));
    $checks = isset($request['checks']) && is_string($request['checks']) && preg_match('/^[a-z_,]+$/', $request['checks']) ? $request['checks'] : 'all';

    $code = 'if (!\Drupal::moduleHandler()->moduleExists("zenith")) { fwrite(STDERR, "module Zenith absent ou désactivé\n"); exit(3); }'
        . ' $settings = \Drupal::service("Drupal\\\\zenith\\\\ZenithSettings");'
        . ' $sub = \Symfony\Component\HttpFoundation\Request::create("/zenith/v1/data", "GET", ["checks" => ' . var_export($checks, true) . '], [], [], $request->server->all());'
        . ' $sub->headers->set("X-Zenith-Token", $settings->secret("api_key"));'
        . ' $response = $kernel->handle($sub, \Symfony\Component\HttpKernel\HttpKernelInterface::MAIN_REQUEST, false);'
        . ' if (200 !== $response->getStatusCode()) { fwrite(STDERR, "le module a répondu HTTP " . $response->getStatusCode() . "\n"); exit(4); }'
        . ' echo "\n", $response->getContent(), "\n";';

    $result = drupal_bootstrap($root, site_host($request), $code, $config, 240);

    if (!$result['ok']) {
        throw new RuntimeException(sprintf('inventaire impossible : %s', $result['error']));
    }

    return is_array($result['json']) ? $result['json'] : [];
}

/**
 * The site from inside the machine when nothing answers from outside: does
 * the database connect, does Drupal boot, what do the logs say last, and
 * does the web server answer on the machine itself.
 *
 * @return array<string, mixed>
 */
function drupal_diagnostic(array $request, array $config)
{
    $path = site_path($request);
    $root = drupal_root($path);
    $host = site_host($request);
    $constants = null === $root ? [] : drupal_database_constants($path, $config, $host);
    $free = @disk_free_space($path);
    $total = @disk_total_space($path);

    $diagnostic = [
        'at' => gmdate('Y-m-d H:i:s'),
        'path' => $path,
        'root' => $root,
        'php' => ['version' => PHP_VERSION, 'binary' => $config['php']],
        'site_found' => null !== $root,
        'bootstrap' => null,
        'database' => null,
        'drupal' => null,
        'maintenance' => null,
        'disk' => ['free_bytes' => false === $free ? null : (int) $free, 'total_bytes' => false === $total ? null : (int) $total],
        'load' => is_readable('/proc/loadavg') ? array_map('floatval', array_slice(explode(' ', trim((string) file_get_contents('/proc/loadavg'))), 0, 3)) : null,
        'memory' => meminfo(),
        'logs' => [],
        'http_local' => null,
    ];

    // The database on its own first: a Drupal that dies on boot usually
    // dies there, and the answer must come whatever the kernel does next.
    if (isset($constants['DB_HOST']) && function_exists('mysqli_init')) {
        $hostParts = explode(':', $constants['DB_HOST'], 2);
        $socket = isset($hostParts[1]) && !is_numeric($hostParts[1]) ? $hostParts[1] : null;
        $port = isset($hostParts[1]) && is_numeric($hostParts[1]) ? (int) $hostParts[1] : 3306;
        mysqli_report(MYSQLI_REPORT_OFF);
        $mysqli = mysqli_init();
        $mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
        $connected = @$mysqli->real_connect($hostParts[0], $constants['DB_USER'], $constants['DB_PASSWORD'], $constants['DB_NAME'], $port, $socket);
        $diagnostic['database'] = ['ok' => (bool) $connected, 'host' => $constants['DB_HOST'], 'error' => $connected ? null : str_cut((string) $mysqli->connect_error, 0, 200)];

        if ($connected) {
            $mysqli->close();
        }
    } elseif (null !== $root) {
        $diagnostic['database'] = ['ok' => null, 'host' => null, 'error' => 'settings.php illisible, ou base autre que MySQL'];
    }

    if (null !== $root) {
        $code = '$modules = array_keys(\Drupal::moduleHandler()->getModuleList());'
            . ' $dbOk = null; try { \Drupal::database()->query("SELECT 1")->fetchField(); $dbOk = true; } catch (\Throwable $e) { $dbOk = false; }'
            . ' $cron = (int) \Drupal::state()->get("system.cron_last", 0);'
            . ' echo "\n", json_encode(['
            . '   "version" => \Drupal::VERSION,'
            . '   "db_ok" => $dbOk,'
            . '   "modules" => count($modules),'
            . '   "zenith_enabled" => in_array("zenith", $modules, true),'
            . '   "zenith_module" => in_array("zenith", $modules, true) && class_exists("Drupal\\\\zenith\\\\ZenithSettings") ? \Drupal\zenith\ZenithSettings::VERSION : null,'
            . '   "maintenance_mode" => (bool) \Drupal::state()->get("system.maintenance_mode", false),'
            . '   "default_theme" => \Drupal::config("system.theme")->get("default"),'
            . '   "install_profile" => \Drupal::installProfile(),'
            . '   "cron_last_run_at" => $cron > 0 ? gmdate("Y-m-d H:i:s", $cron) : null,'
            . '   "namespace_registered" => isset($kernel->getContainer()->getParameter("container.namespaces")["Drupal\\\\zenith"]),'
            . ' ]), "\n";';

        $result = drupal_bootstrap($root, $host, $code, $config, 90);
        $diagnostic['bootstrap'] = ['ok' => $result['ok'], 'seconds' => $result['seconds'], 'error' => $result['error']];
        $diagnostic['drupal'] = $result['ok'] ? $result['json'] : null;
        $diagnostic['maintenance'] = $result['ok'] && is_array($result['json']) ? (bool) $result['json']['maintenance_mode'] : null;
    }

    foreach (log_candidates($path, []) as $file) {
        $tail = tail_lines($file, 30);

        if (null === $tail) {
            continue;
        }

        $diagnostic['logs'][] = ['path' => $file, 'size_bytes' => (int) filesize($file), 'modified_at' => gmdate('Y-m-d H:i:s', (int) filemtime($file)), 'tail' => $tail, 'last_fatal' => last_fatal($tail)];
    }

    $diagnostic['http_local'] = local_http($host, site_uri($request));

    return $diagnostic;
}

/**
 * The tree of a Drupal site as find walks it, in the shape the WordPress
 * audit answers so Zenith reads both alike: what anyone may write, what
 * runs where only media should, what changed lately, what carries the
 * constructs malware is made of, and what a deploy left lying around.
 *
 * @return array<string, mixed>
 */
function drupal_audit(array $request, array $config)
{
    $path = site_path($request);
    $root = drupal_root_or_fail($path);
    $started = microtime(true);
    $me = function_exists('posix_geteuid') && function_exists('posix_getpwuid') ? (posix_getpwuid(posix_geteuid())['name'] ?? get_current_user()) : get_current_user();
    $site = drupal_site_dir($root, site_host($request));
    $files = $root . '/' . $site . '/files';
    $prune = ['-not', '-path', '*/node_modules/*', '-not', '-path', $files . '/php/*', '-not', '-path', $files . '/css/*', '-not', '-path', $files . '/js/*', '-not', '-path', $files . '/styles/*'];

    // Public files are meant to be writable by the web server, not by
    // everyone: they are walked like the rest.
    $worldWritable = find_list(array_merge([$root, '-xdev', '(', '-type', 'f', '-o', '-type', 'd', ')', '-perm', '-o+w'], $prune), 180);
    $otherOwner = find_list(array_merge([$root, '-xdev', '-not', '-user', $me], $prune), 180);
    $phpInFiles = is_dir($files) ? find_list([$files, '-type', 'f', '(', '-iname', '*.php', '-o', '-iname', '*.phtml', '-o', '-iname', '*.php5', '-o', '-iname', '*.php7', '-o', '-iname', '*.phar', '-o', '-iname', '*.phps', ')', '-not', '-path', $files . '/php/*'], 120) : ['count' => 0, 'samples' => [], 'truncated' => false, 'error' => null];
    $recentPhp = recent_outside_git(find_list(array_merge([$root, '-xdev', '-type', 'f', '(', '-name', '*.php', '-o', '-name', '*.module', '-o', '-name', '*.inc', '-o', '-name', '*.install', '-o', '-name', '*.theme', ')', '-mtime', '-2'], $prune), 180, '%TY-%Tm-%Td %TH:%TM %p\n', true), $root);

    // Custom and contributed code, and the site directory: the core and
    // vendor come from Composer and are judged by the lock, not by grep.
    $signatures = ['count' => 0, 'samples' => [], 'details' => [], 'truncated' => false, 'error' => null, 'scanned' => []];

    foreach ([$root . '/modules', $root . '/themes', $root . '/profiles', $root . '/sites'] as $dir) {
        if (!is_dir($dir) || out_of_time()) {
            continue;
        }

        // Drupal keeps PHP under its own extensions.
        $found = signature_scan($dir, 200, ['*.module', '*.install', '*.theme', '*.profile', '*.engine']);
        $signatures['count'] += isset($found['count']) ? (int) $found['count'] : 0;
        $signatures['samples'] = array_slice(array_merge($signatures['samples'], isset($found['samples']) && is_array($found['samples']) ? $found['samples'] : []), 0, 60);
        $signatures['details'] = array_slice(array_merge($signatures['details'], isset($found['details']) && is_array($found['details']) ? $found['details'] : []), 0, 20);
        $signatures['truncated'] = $signatures['truncated'] || !empty($found['truncated']);
        $signatures['error'] = isset($found['error']) && null !== $found['error'] ? $found['error'] : $signatures['error'];
        $signatures['scanned'][] = substr($dir, strlen($root) + 1);
    }

    $exposure = [];
    $seen = [];

    foreach (array_unique([dirname($root), dirname(dirname($root)), (string) getenv('HOME'), $root]) as $dir) {
        if ('' === $dir || !is_dir($dir) || isset($seen[$dir])) {
            continue;
        }

        $seen[$dir] = true;
        $found = find_list([$dir, '-maxdepth', 2, '-type', 'f', '(', '-iname', '*.sql', '-o', '-iname', '*.sql.gz', '-o', '-iname', '*.sql.zip', '-o', '-iname', '*.zip', '-o', '-iname', '*.tar', '-o', '-iname', '*.tar.gz', '-o', '-iname', '*.tgz', '-o', '-name', '.env', '-o', '-name', '.env.*', '-o', '-iname', '*.bak', '-o', '-iname', '*.old', '-o', '-iname', '*.orig', '-o', '-iname', 'settings.php.*', '-o', '-iname', 'settings.local.php.*', ')', '-size', '+0', '-not', '-path', '*/node_modules/*', '-not', '-path', '*/.zenith/*', '-not', '-path', '*/.ssh/*', '-not', '-path', '*/vendor/*', '-not', '-path', '*/core/*'], 60, '%s %p\n');

        foreach ($found['samples'] as $line) {
            list($size, $file) = array_pad(explode(' ', $line, 2), 2, '');
            $exposure[$file] = ['file' => $file, 'size_bytes' => (int) $size, 'in_docroot' => 0 === strpos($file, $root . '/')];
        }
    }

    $bigFiles = [];

    foreach (array_unique([$root, dirname($root), dirname(dirname($root)), (string) getenv('HOME')]) as $dir) {
        if ('' === $dir || !is_dir($dir)) {
            continue;
        }

        $args = $dir === $root
            ? [$dir, '-xdev', '-type', 'f', '-size', '+50M', '-not', '-path', $files . '/*']
            : [$dir, '-maxdepth', 2, '-xdev', '-type', 'f', '-size', '+50M', '-not', '-path', $root . '/*'];
        $found = find_list($args, 60, '%s %p\n');

        foreach ($found['samples'] as $line) {
            list($size, $file) = array_pad(explode(' ', $line, 2), 2, '');
            $bigFiles[$file] = ['file' => $file, 'size_bytes' => (int) $size, 'in_docroot' => 0 === strpos($file, $root . '/')];
        }
    }

    usort($bigFiles, function ($a, $b) { return $b['size_bytes'] - $a['size_bytes']; });

    $generated = 0;

    foreach (['php', 'css', 'js'] as $sub) {
        $generated += is_dir($files . '/' . $sub) ? dir_bytes($files . '/' . $sub) : 0;
    }

    return [
        'at' => gmdate('Y-m-d H:i:s'),
        'framework' => 'drupal',
        'path' => $path,
        'root' => $root,
        'user' => $me,
        'disk_usage' => disk_usage($root),
        'stale' => null,
        'big_files' => array_slice(array_values($bigFiles), 0, 20),
        'cache_bytes' => $generated,
        'deadline_reached' => out_of_time(),
        'filesystem' => [
            'world_writable' => $worldWritable,
            'other_owner' => $otherOwner,
            'php_in_uploads' => $phpInFiles,
            'recent_php' => $recentPhp,
            'signatures' => $signatures,
            'uploads_htaccess' => is_file($files . '/.htaccess'),
            'settings' => drupal_settings_status($path),
        ],
        'exposure' => array_slice(array_values($exposure), 0, 40),
        'uploads' => null,
        'duration_seconds' => round(microtime(true) - $started, 2),
    ];
}

/**
 * The three actions a Drupal site is driven with from here, each through
 * Drupal's own services, and each written in the module's journal when the
 * module is there to keep one.
 *
 * @return array<string, mixed>
 */
function drupal_control($action, $path, array $request, $actor, array $config)
{
    $root = drupal_root_or_fail($path);
    $params = [];

    switch ($action) {
        case 'cache_flush':
            // The caches in base and the compiled container are rebuilt. The
            // web server's own memory (APCu, OPcache) belongs to another
            // process and cannot be reached from the command line.
            $code = 'drupal_flush_all_caches();'
                . ' $result = ["status" => "ok", "flushed" => ["drupal" => true, "opcache_cli" => function_exists("opcache_reset") ? @opcache_reset() : null, "web_process_memory" => false], "message" => "Caches de Drupal reconstruits. APCu et OPcache du serveur web ne sont pas atteints depuis la ligne de commande."];';
            break;
        case 'cron_run':
            $code = '$before = (int) \Drupal::state()->get("system.cron_last", 0); $started = microtime(true);'
                . ' $ok = (bool) \Drupal::service("cron")->run();'
                . ' $after = (int) \Drupal::state()->get("system.cron_last", 0);'
                . ' $result = $ok ? ["status" => "ok", "seconds" => round(microtime(true) - $started, 1), "cron_last_run_at" => gmdate("Y-m-d H:i:s", $after)]'
                . '   : ["status" => "failed", "refused" => true, "message" => "le cron de Drupal est déjà en cours (verrou cron), ou a refusé de partir"];';
            break;
        // Both names: the shell's own, and the one the Drupal agent gives
        // the same action over HTTP, so Zenith asks alike on either channel.
        case 'maintenance_set':
        case 'maintenance_mode':
            $enabled = isset($request['enabled']) && true === $request['enabled'];
            $params = ['enabled' => $enabled];
            $code = '$was = (bool) \Drupal::state()->get("system.maintenance_mode", false);'
                . ' \Drupal::state()->set("system.maintenance_mode", ' . var_export($enabled, true) . ');'
                . ' \Drupal::service("cache.render")->invalidateAll(); \Drupal::service("page_cache_kill_switch")->trigger(); if (\Drupal::hasService("cache.page")) { \Drupal::service("cache.page")->invalidateAll(); }'
                . ' $result = ["status" => "ok", "maintenance" => ' . var_export($enabled, true) . ', "changed" => $was !== ' . var_export($enabled, true) . ', "until" => null, "message" => ' . var_export($enabled ? 'Mode maintenance de Drupal activé. Il ne se lève pas seul : le remettre en ligne depuis Zenith ou par drush.' : 'Mode maintenance de Drupal levé.', true) . '];';
            break;
        default:
            throw new RuntimeException(sprintf('action non prise en charge pour Drupal par zenith-shell : %s', $action));
    }

    // The module's journal, by its own recorder: same type as the entries
    // it writes for its /control route, marked as coming over SSH. As on
    // that route, a cron that ran without trouble leaves no line.
    $code .= ' try { if (' . ('cron_run' === $action ? '"ok" !== $result["status"] && ' : '') . '\Drupal::hasService("zenith.events")) { \Drupal::service("zenith.events")->record("zenith.control", ["action" => ' . var_export($action, true) . ', "params" => ' . var_export($params, true) . ', "status" => $result["status"], "message" => isset($result["message"]) ? $result["message"] : null, "via" => "ssh", "requested_by" => ' . var_export(null === $actor ? 'zenith' : $actor, true) . '], "warning"); } } catch (\Throwable $e) {}';
    $code .= ' echo "\n", json_encode($result), "\n";';

    $result = drupal_bootstrap($root, site_host($request), $code, $config, 'cron_run' === $action ? 300 : 180);

    if (!$result['ok']) {
        throw new RuntimeException(sprintf('%s : %s', $action, $result['error']));
    }

    $answer = is_array($result['json']) ? $result['json'] : ['status' => 'failed', 'message' => 'réponse illisible'];

    if (isset($answer['refused']) && true === $answer['refused']) {
        throw new RuntimeException(isset($answer['message']) && is_string($answer['message']) ? $answer['message'] : sprintf('%s refusé', $action));
    }

    return $answer;
}

/* ---------------------------------------------------------------------------
 * Composer applications: Symfony, Sulu, Laravel — and a PHP project without
 * a framework (1.8.9), which Composer still built.
 *
 * The shell boots none of them: their inventory and their diagnostic are the
 * agent's. What it reads here is what find and stat say of a tree, which an
 * application cannot say of itself under an open_basedir — and what stays
 * readable when the application no longer answers.
 * ------------------------------------------------------------------------- */

function is_composer_app_request(array $request)
{
    return isset($request['framework']) && is_string($request['framework']) && in_array(strtolower($request['framework']), ['symfony', 'sulu', 'laravel', 'php'], true);
}

/**
 * The project under a path: the path itself, or its parent when the path
 * names the public directory the web server is pointed at. A console marks
 * a Symfony or Laravel application; a project without a framework has only
 * its composer.json and what Composer installed.
 */
function composer_app_root($path)
{
    if (null === $path) {
        return null;
    }

    foreach ([$path, dirname($path)] as $dir) {
        if (is_file($dir . '/composer.json') && (is_file($dir . '/bin/console') || is_file($dir . '/artisan') || is_dir($dir . '/vendor'))) {
            return $dir;
        }
    }

    return null;
}

/**
 * The directories an application is made of, by what they are for: Laravel
 * keeps its code in app/ and what it writes in storage/, Symfony in src/ and
 * var/. The public directory is the one composer.json declares; a project
 * without a framework keeps it where it likes, or serves its root.
 *
 * @return array{root: string, public: string, code: string, runtime: string, laravel: bool, php: bool}
 */
function composer_app_layout($root)
{
    $json = is_readable($root . '/composer.json') ? json_decode((string) file_get_contents($root . '/composer.json'), true) : null;
    $declared = is_array($json) && isset($json['extra']['public-dir']) && is_string($json['extra']['public-dir']) && '' !== trim($json['extra']['public-dir'], '/') ? trim($json['extra']['public-dir'], '/') : null;
    $laravel = is_file($root . '/artisan');
    $console = $laravel || is_file($root . '/bin/console');
    $public = null !== $declared ? $root . '/' . $declared : null;

    if (null === $public && $console) {
        $public = $root . '/public';
    }

    if (null === $public) {
        foreach (['public', 'public_html', 'web', 'htdocs', 'www', 'html', 'dist'] as $candidate) {
            if (is_dir($root . '/' . $candidate)) {
                $public = $root . '/' . $candidate;
                break;
            }
        }
    }

    return [
        'root' => $root,
        'public' => null === $public ? $root : $public,
        'code' => $root . ($laravel ? '/app' : '/src'),
        'runtime' => $root . ($laravel ? '/storage' : '/var'),
        'laravel' => $laravel,
        'php' => !$console,
    ];
}

/**
 * Who owns what, on the paths an application is made of.
 *
 * @return array<string, mixed>
 */
function composer_app_ownership_status($path, array $request)
{
    $root = composer_app_root($path);
    $layout = composer_app_layout(null === $root ? $path : $root);
    $me = function_exists('posix_geteuid') ? posix_geteuid() : null;
    $entries = [];

    foreach (['root' => $layout['root'], 'env' => $layout['root'] . '/.env', 'public' => $layout['public'], 'code' => $layout['code'], 'config' => $layout['root'] . '/config', 'vendor' => $layout['root'] . '/vendor', 'runtime' => $layout['runtime']] as $key => $file) {
        if (!file_exists($file)) {
            $entries[$key] = null;
            continue;
        }

        $uid = fileowner($file);
        $gid = filegroup($file);
        $perms = fileperms($file);

        $entries[$key] = [
            'path' => $file,
            'owner' => false !== $uid && function_exists('posix_getpwuid') ? (posix_getpwuid($uid)['name'] ?? (string) $uid) : (string) $uid,
            'group' => false !== $gid && function_exists('posix_getgrgid') ? (posix_getgrgid($gid)['name'] ?? (string) $gid) : (string) $gid,
            'mode' => false === $perms ? null : substr(sprintf('%o', $perms), -4),
            'mine' => null !== $me && false !== $uid ? $uid === $me : null,
            'writable_by_me' => is_writable($file),
            'group_writable' => false === $perms ? null : (bool) ($perms & 0020),
            'world_writable' => false === $perms ? null : (bool) ($perms & 0002),
            'world_readable' => false === $perms ? null : (bool) ($perms & 0004),
        ];
    }

    return ['user' => null !== $me && function_exists('posix_getpwuid') ? (posix_getpwuid($me)['name'] ?? (string) $me) : get_current_user(), 'layout' => $layout['laravel'] ? 'laravel' : ($layout['php'] ? 'php' : 'symfony'), 'entries' => $entries];
}

/**
 * The tree of an application as find walks it, in the shape the WordPress
 * and Drupal audits answer so Zenith reads the three alike: what anyone may
 * write, what runs under the public directory besides the front controller,
 * what changed lately, what carries the constructs malware is made of, and
 * what a deploy left lying around.
 *
 * @return array<string, mixed>
 */
function composer_app_audit(array $request, array $config)
{
    $path = site_path($request);
    $root = composer_app_root($path);

    if (null === $root) {
        throw new RuntimeException(sprintf('aucune application Composer (Symfony, Laravel, projet PHP) dans %s', $path));
    }

    $started = microtime(true);
    $layout = composer_app_layout($root);
    $public = $layout['public'];
    $me = function_exists('posix_geteuid') && function_exists('posix_getpwuid') ? (posix_getpwuid(posix_geteuid())['name'] ?? get_current_user()) : get_current_user();
    // What the application rewrites by itself: compiled caches, sessions.
    $generated = $layout['laravel'] ? [$root . '/storage/framework', $root . '/bootstrap/cache'] : [$root . '/var/cache'];
    $prune = ['-not', '-path', '*/node_modules/*', '-not', '-path', '*/.git/*'];

    foreach ($generated as $dir) {
        $prune[] = '-not';
        $prune[] = '-path';
        $prune[] = $dir . '/*';
    }

    $worldWritable = find_list(array_merge([$root, '-xdev', '(', '-type', 'f', '-o', '-type', 'd', ')', '-perm', '-o+w'], $prune), 180);
    $otherOwner = find_list(array_merge([$root, '-xdev', '-not', '-user', $me], $prune), 180);
    // Under the public directory the front controller is the only script
    // (Sulu ships its maintenance page next to it): anything else is an
    // entry point the application does not know. Links are not followed:
    // the assets of the bundles are not dropped code.
    // A project without a framework may serve its root: vendor and the
    // agent's own entry script (zenith-agent.php) are not dropped code.
    $phpInPublic = is_dir($public)
        ? find_list([$public, '-type', 'f', '(', '-iname', '*.php', '-o', '-iname', '*.phtml', '-o', '-iname', '*.php5', '-o', '-iname', '*.php7', '-o', '-iname', '*.phar', '-o', '-iname', '*.phps', ')', '-not', '-path', $public . '/index.php', '-not', '-path', $public . '/maintenance.php', '-not', '-path', $public . '/zenith-agent.php', '-not', '-path', '*/node_modules/*', '-not', '-path', '*/vendor/*', '-not', '-path', '*/.git/*'], 120)
        : ['count' => 0, 'samples' => [], 'truncated' => false, 'error' => null];
    $recentPhp = recent_outside_git(find_list(array_merge([$root, '-xdev', '-type', 'f', '-name', '*.php', '-mtime', '-2'], $prune), 180, '%TY-%Tm-%Td %TH:%TM %p\n', true), $root);

    // The project's own code and what it serves: vendor comes from Composer
    // and is judged by the agent against its install, not by grep.
    $signatures = ['count' => 0, 'samples' => [], 'details' => [], 'truncated' => false, 'error' => null, 'scanned' => []];

    // A project without a framework keeps its code where it likes: the usual
    // places are tried, and a public directory that is the project itself is
    // not walked whole (vendor would be).
    $codeDirs = $layout['php']
        ? [$layout['code'], $root . '/includes', $root . '/inc', $root . '/lib', $root . '/app', $root . '/classes', $public === $root ? null : $public, $root . '/config', $root . '/templates']
        : [$layout['code'], $public, $root . '/config', $root . '/templates', $root . '/resources', $root . '/routes'];

    foreach (array_filter($codeDirs) as $dir) {
        if (!is_dir($dir) || out_of_time()) {
            continue;
        }

        $found = signature_scan($dir, 200, ['*.twig']);
        $signatures['count'] += isset($found['count']) ? (int) $found['count'] : 0;
        $signatures['samples'] = array_slice(array_merge($signatures['samples'], isset($found['samples']) && is_array($found['samples']) ? $found['samples'] : []), 0, 60);
        $signatures['details'] = array_slice(array_merge($signatures['details'], isset($found['details']) && is_array($found['details']) ? $found['details'] : []), 0, 20);
        $signatures['truncated'] = $signatures['truncated'] || !empty($found['truncated']);
        $signatures['error'] = isset($found['error']) && null !== $found['error'] ? $found['error'] : $signatures['error'];
        $signatures['scanned'][] = substr($dir, strlen($root) + 1);
    }

    $exposure = [];
    $seen = [];

    foreach (array_unique([dirname($root), (string) getenv('HOME'), $root, $public]) as $dir) {
        if ('' === $dir || !is_dir($dir) || isset($seen[$dir])) {
            continue;
        }

        $seen[$dir] = true;
        // The project's own .env files are where they belong at its root:
        // only their copies count there, and any of them under public/.
        $names = ['(', '-iname', '*.sql', '-o', '-iname', '*.sql.gz', '-o', '-iname', '*.sql.zip', '-o', '-iname', '*.zip', '-o', '-iname', '*.tar', '-o', '-iname', '*.tar.gz', '-o', '-iname', '*.tgz', '-o', '-iname', '*.bak', '-o', '-iname', '*.old', '-o', '-iname', '*.orig', '-o', '-iname', '.env.*.bak', '-o', '-iname', '.env.save'];

        if ($dir !== $root) {
            $names = array_merge($names, ['-o', '-name', '.env', '-o', '-name', '.env.*']);
        }

        $names[] = ')';
        $found = find_list(array_merge([$dir, '-maxdepth', 2, '-type', 'f'], $names, ['-size', '+0', '-not', '-path', '*/node_modules/*', '-not', '-path', '*/.zenith/*', '-not', '-path', '*/.ssh/*', '-not', '-path', '*/vendor/*', '-not', '-path', $layout['runtime'] . '/*']), 60, '%s %p\n');

        foreach ($found['samples'] as $line) {
            list($size, $file) = array_pad(explode(' ', $line, 2), 2, '');

            // From the parent or the home, the project's own .env files are
            // met again one level down: they are not leftovers.
            if (dirname($file) === $root && 1 === preg_match('/^\.env(\.[a-z]+)?(\.local)?$/', basename($file))) {
                continue;
            }

            $exposure[$file] = ['file' => $file, 'size_bytes' => (int) $size, 'in_docroot' => 0 === strpos($file, $public . '/')];
        }
    }

    $bigFiles = [];

    foreach (array_unique([$root, dirname($root), (string) getenv('HOME')]) as $dir) {
        if ('' === $dir || !is_dir($dir)) {
            continue;
        }

        $args = $dir === $root
            ? [$dir, '-xdev', '-type', 'f', '-size', '+50M', '-not', '-path', '*/.git/*']
            : [$dir, '-maxdepth', 2, '-xdev', '-type', 'f', '-size', '+50M', '-not', '-path', $root . '/*'];
        $found = find_list($args, 60, '%s %p\n');

        foreach ($found['samples'] as $line) {
            list($size, $file) = array_pad(explode(' ', $line, 2), 2, '');
            $bigFiles[$file] = ['file' => $file, 'size_bytes' => (int) $size, 'in_docroot' => 0 === strpos($file, $public . '/')];
        }
    }

    usort($bigFiles, function ($a, $b) { return $b['size_bytes'] - $a['size_bytes']; });

    $cache = 0;

    foreach ($generated as $dir) {
        $cache += is_dir($dir) ? (int) dir_bytes($dir) : 0;
    }

    return [
        'at' => gmdate('Y-m-d H:i:s'),
        'framework' => strtolower($request['framework']),
        'path' => $path,
        'root' => $root,
        'public' => substr($public, strlen($root) + 1),
        'user' => $me,
        'disk_usage' => disk_usage($root),
        'stale' => null,
        'big_files' => array_slice(array_values($bigFiles), 0, 20),
        'cache_bytes' => $cache,
        'deadline_reached' => out_of_time(),
        'filesystem' => [
            'world_writable' => $worldWritable,
            'other_owner' => $otherOwner,
            'php_in_uploads' => $phpInPublic,
            'recent_php' => $recentPhp,
            'signatures' => $signatures,
            'uploads_htaccess' => null,
        ],
        'exposure' => array_slice(array_values($exposure), 0, 40),
        'uploads' => null,
        'duration_seconds' => round(microtime(true) - $started, 2),
    ];
}
