| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447 |
- <?php
- /**
- * Maintenance: backups and software updates, both driven by the manage client
- * in manage-client/ (reference: https://manage.med0.de/client-docs/).
- *
- * The page holds no update or backup logic of its own — every button calls the
- * same documented function the CLI calls, so `php manage-client/bin/manage-client.php
- * backup` and the button below do exactly the same thing. The client ships a
- * drop-in panel of its own; this page replaces it so the backoffice keeps one
- * look, one login and one CSRF token.
- *
- * Results are rendered on the POST itself rather than after a redirect: an
- * update reports several lines (files copied, migrations run, backup location)
- * and a flash message holds one.
- */
- require dirname(__DIR__) . '/app/bootstrap.php';
- auth_require();
- // An installation may legitimately not carry the client — it is one folder,
- // and deploying by FTP works without it. Say so instead of dying on a require.
- if (!is_file(APP_ROOT . '/manage-client/lib/client.php')) {
- admin_header('Maintenance', 'maintenance');
- echo '<h1>Maintenance</h1><div class="card"><p class="help" style="margin:0">'
- . 'The backup and update client is not installed: <code>manage-client/</code> '
- . 'is missing. See <code>docs/SETUP.md</code>, section 5a.</p></div>';
- admin_footer();
- exit;
- }
- require_once APP_ROOT . '/manage-client/lib/client.php';
- $messages = [];
- $errors = [];
- if ($_SERVER['REQUEST_METHOD'] === 'POST') {
- csrf_verify();
- // Archiving media/ and uploading it runs well past the default limit.
- @set_time_limit(0);
- $action = (string)($_POST['action'] ?? '');
- try {
- if ($action === 'download') {
- // Validates the filename itself and throws on anything that is not
- // a backup of this installation.
- $path = manageBackupPath((string)($_POST['filename'] ?? ''));
- $size = filesize($path);
- $fh = fopen($path, 'rb');
- if ($size === false || $fh === false) {
- throw new RuntimeException('Backup file could not be opened.');
- }
- header('Content-Type: application/zip');
- header('Content-Disposition: attachment; filename="' . addcslashes(basename($path), '"\\') . '"');
- header('Content-Length: ' . $size);
- header('Cache-Control: private, no-store');
- header('X-Content-Type-Options: nosniff');
- fpassthru($fh);
- fclose($fh);
- exit;
- }
- if ($action === 'backup') {
- $messages = array_merge($messages, maintenance_backup('manual'));
- manageHeartbeatSendQuietly();
- } elseif ($action === 'update') {
- // Deliberately a line here rather than a feature of the client: it
- // stays visible that the update takes a backup first, and the
- // update stops if that backup cannot be written.
- if (!empty($_POST['backup_first'])) {
- $messages = array_merge($messages, maintenance_backup('update'));
- }
- $result = manageUpdateApply(['force' => !empty($_POST['force'])]);
- $messages[] = sprintf(
- 'Update deployed: %s → %s. %d files copied, %d replaced files saved to %s.',
- $result['from_version'] !== '' ? $result['from_version'] : 'unknown',
- $result['to_version'],
- $result['copied'],
- $result['backed_up'],
- $result['backup_dir'],
- );
- // Files are deployed even when the hook failed; that difference is
- // the whole point of reporting it separately.
- $hook = is_array($result['hook'] ?? null) ? $result['hook'] : [];
- $applied = $hook['migrations']['applied'] ?? [];
- if ($applied !== []) {
- $messages[] = 'Migrations run: ' . implode(', ', $applied);
- }
- if ($hook !== [] && empty($hook['success'])) {
- $errors[] = empty($hook['failed_migration'])
- ? 'The files are deployed, but the post-update step failed: '
- . (string)($hook['error'] ?? 'unknown')
- : 'The files are deployed, but migration "' . (string)$hook['failed_migration']
- . '" failed: ' . (string)($hook['error'] ?? 'unknown')
- . ' Remaining migrations were not attempted — fix the cause, then use "Run migrations" below.';
- }
- manageHeartbeatSendQuietly();
- } elseif ($action === 'migrate') {
- $report = manageUpdateRunMigrations();
- if ($report['applied'] !== []) {
- $messages[] = 'Migrations run: ' . implode(', ', $report['applied']);
- }
- if (!$report['success']) {
- $errors[] = 'Migration "' . (string)$report['failed'] . '" failed: ' . (string)$report['error'];
- } elseif ($report['applied'] === []) {
- $messages[] = 'No pending migrations.';
- }
- } elseif ($action === 'heartbeat') {
- $result = manageHeartbeatSend();
- $messages[] = 'Status reported. Current release: '
- . (($result['latest'] ?? '') !== '' ? (string)$result['latest'] : 'none') . '.';
- }
- } catch (Throwable $e) {
- $errors[] = $e->getMessage();
- }
- }
- /**
- * One backup, reported as message lines. A failed upload is a warning, not a
- * failure: the archive exists locally either way.
- */
- function maintenance_backup(string $trigger): array
- {
- $record = manageBackupCreate($trigger);
- $lines = [sprintf(
- 'Backup created: %s — %d files, %s.',
- $record['filename'],
- $record['file_count'],
- manageFormatBytes((int)$record['size']),
- )];
- foreach ($record['remote_uploads'] as $upload) {
- if (empty($upload['success'])) {
- $lines[] = 'Upload to ' . (string)$upload['target'] . ' failed: '
- . (string)($upload['error'] ?? 'unknown') . ' The local copy is intact.';
- }
- }
- return $lines;
- }
- /** An interval as something readable: 604800 -> "every 7 days". */
- function maintenance_interval_text(int $seconds): string
- {
- if ($seconds % 86400 === 0) {
- $days = intdiv($seconds, 86400);
- return $days === 1 ? 'daily' : 'every ' . $days . ' days';
- }
- if ($seconds % 3600 === 0) {
- $hours = intdiv($seconds, 3600);
- return $hours === 1 ? 'hourly' : 'every ' . $hours . ' hours';
- }
- return 'every ' . max(1, intdiv($seconds, 60)) . ' minutes';
- }
- // The one place that asks the manage server whether a release is waiting: it is
- // a network round trip, so it happens when this page is opened and nowhere else.
- // Never throws — an unreachable server still renders the page.
- $status = manageClientStatus();
- // State of the schedule in app/manage.php.
- $autoInterval = (int)MANAGE_BACKUP_AUTO_INTERVAL_SECONDS;
- $due = manage_due();
- $lastAutoBackup = 0;
- foreach ($status['backups'] as $backup) {
- if (in_array($backup['trigger'] ?? '', ['automatic', 'cron'], true)) {
- $lastAutoBackup = max($lastAutoBackup, strtotime((string)($backup['created_at'] ?? '')) ?: 0);
- }
- }
- $lastHeartbeat = (int)(json_read(manage_state_file())['heartbeat_at'] ?? 0);
- // An instance whose server has no release yet answers the manifest with 404.
- // That is a normal state — a new project, nothing published — and reads far
- // too much like a broken connection when it is shown as a failed check.
- $noReleaseYet = $status['update_error'] !== null
- && str_contains($status['update_error'], 'HTTP 404');
- $update = $status['update'];
- $capabilities = manageRemoteCapabilities();
- admin_header('Maintenance', 'maintenance');
- flash_render();
- ?>
- <h1>Maintenance</h1>
- <?php foreach ($messages as $line): ?>
- <div class="flash flash-ok"><?= e($line) ?></div>
- <?php endforeach; ?>
- <?php foreach ($errors as $line): ?>
- <div class="flash flash-error"><?= e($line) ?></div>
- <?php endforeach; ?>
- <?php if (!$status['configured']): ?>
- <div class="flash flash-error">
- Not connected to the manage server. Create an instance there, then fill in
- <code>MANAGE_INSTANCE</code> and <code>MANAGE_TOKEN</code> in
- <code>manage-client/config.php</code>. Backups can still be made locally.
- </div>
- <?php endif; ?>
- <div class="card">
- <table>
- <tr>
- <td>Installed version</td>
- <td><?= e($status['version'] !== '' ? $status['version'] : 'unknown') ?></td>
- <td class="help" style="margin:0">PHP <?= e($status['php_version']) ?></td>
- </tr>
- <tr>
- <td>Current release</td>
- <td>
- <?php if ($update !== null && $update['available']): ?>
- <span class="tag tag-lock"><?= e($update['latest']) ?> available</span>
- <?php elseif ($update !== null): ?>
- <?= e($update['latest'] !== '' ? $update['latest'] : '—') ?>
- <?php else: ?>
- —
- <?php endif; ?>
- </td>
- <td class="help" style="margin:0">
- <?php if ($noReleaseYet): ?>
- No release has been published on the manage server yet.
- <?php elseif ($status['update_error'] !== null): ?>
- Check failed: <?= e($status['update_error']) ?>
- <?php elseif ($update !== null && $update['available']): ?>
- Back up first, then deploy.
- <?php elseif ($update !== null): ?>
- Up to date.
- <?php else: ?>
- <?= e($status['instance'] !== '' ? $status['instance'] : 'no instance configured') ?>
- <?php endif; ?>
- </td>
- </tr>
- <tr>
- <td>Last backup</td>
- <td><?= e($status['last_backup_at'] ?? 'never') ?></td>
- <td class="help" style="margin:0"><?= count($status['backups']) ?> kept locally</td>
- </tr>
- <tr>
- <td>Release migrations</td>
- <td><?= count($status['pending_migrations']) ?> pending</td>
- <td class="help" style="margin:0">
- <?= $status['pending_migrations'] === []
- ? 'Nothing to run.'
- : e(implode(', ', array_column($status['pending_migrations'], 'id'))) ?>
- </td>
- </tr>
- </table>
- </div>
- <h2>Backup</h2>
- <div class="card">
- <p class="help" style="margin-top:0">
- Archives <code>data/</code> and <code>media/</code> — galleries, showreel,
- front page, settings — and uploads it to the manage server. Gallery photos
- are not included: they live in the S3 bucket, which is their own backup.
- Nor are <code>config/</code> credentials, because a backup can be
- downloaded again from the server.
- </p>
- <form method="post">
- <?= csrf_field() ?>
- <input type="hidden" name="action" value="backup">
- <button type="submit" style="margin:0">Back up now</button>
- </form>
- </div>
- <h2>Schedule</h2>
- <div class="card">
- <p class="help" style="margin-top:0">
- This host is assumed to have no cron, so the backoffice drives both jobs:
- opening any admin page past the interval starts them in the background
- (<code>manage-worker.php</code>). Updates are never part of that, and the
- release check runs only when this page is opened.
- </p>
- <table>
- <tr>
- <td>Automatic backup</td>
- <td><?= $autoInterval > 0 ? e(maintenance_interval_text($autoInterval)) : 'off' ?></td>
- <td class="help" style="margin:0">
- <?php if ($autoInterval <= 0): ?>
- <code>MANAGE_BACKUP_AUTO_INTERVAL_SECONDS</code> is 0 — only cron or the button above make backups.
- <?php elseif (in_array('backup', $due, true)): ?>
- Due now — starts on the next admin page load.
- <?php else: ?>
- Next <?= e(date('Y-m-d H:i', $lastAutoBackup + $autoInterval)) ?>.
- <?php endif; ?>
- </td>
- </tr>
- <tr>
- <td>Heartbeat</td>
- <td><?= e(maintenance_interval_text(manage_heartbeat_interval())) ?></td>
- <td class="help" style="margin:0">
- <?php if ($lastHeartbeat === 0): ?>
- Not sent yet.
- <?php else: ?>
- Last <?= e(date('Y-m-d H:i', $lastHeartbeat)) ?>.
- <?php endif; ?>
- </td>
- </tr>
- </table>
- <p class="help">
- If the host does offer cron, point it at
- <code>manage-worker.php?key=…</code> every 15 minutes instead — the key
- is in <code>data/worker-key.json</code>, and the jobs are the same code
- either way. See <code>scripts/manage-client.cron</code>.
- </p>
- </div>
- <h2>Update</h2>
- <div class="card">
- <?php if ($update !== null && $update['available']): ?>
- <p style="margin-top:0">
- Version <strong><?= e($update['latest']) ?></strong> is ready
- <?php if (!empty($update['manifest']['published_at'])): ?>
- (published <?= e($update['manifest']['published_at']) ?>)
- <?php endif; ?>.
- </p>
- <?php endif; ?>
- <p class="help" style="margin-top:0">
- Files are replaced while the site stays online, and there is no rollback:
- the replaced files are copied to <code>data/manage/updates/</code> for
- manual recovery. <code>config/</code>, <code>data/</code> and
- <code>media/</code> are never touched. Deleted files are not removed —
- an update overlays what is there.
- <?php if ($status['pending_migrations'] === []): ?>
- Afterwards, check <a href="migrate.php">Data migration</a>.
- <?php endif; ?>
- </p>
- <form method="post" onsubmit="return confirm('Deploy the update now? Files will be overwritten.');">
- <?= csrf_field() ?>
- <input type="hidden" name="action" value="update">
- <p class="help" style="margin-bottom:.4rem"><label style="display:inline;text-transform:none;letter-spacing:0">
- <input type="checkbox" name="backup_first" value="1" checked>
- Create a backup first
- </label></p>
- <p class="help" style="margin-bottom:.4rem"><label style="display:inline;text-transform:none;letter-spacing:0">
- <input type="checkbox" name="force" value="1">
- Deploy even if no newer version is offered
- </label></p>
- <button type="submit" style="margin-top:1rem"
- <?= $update !== null && !$update['available'] ? 'class="btn-ghost"' : '' ?>>
- Deploy update
- </button>
- </form>
- </div>
- <?php if ($status['pending_migrations'] !== []): ?>
- <h2>Pending release migrations</h2>
- <div class="card">
- <p class="help" style="margin-top:0">
- Shipped with a release and normally run by the update itself. These are
- left over — usually because one failed, or because the update ran with
- migrations skipped.
- </p>
- <table style="margin-bottom:1rem">
- <?php foreach ($status['pending_migrations'] as $migration): ?>
- <tr><td><?= e($migration['id']) ?></td></tr>
- <?php endforeach; ?>
- </table>
- <form method="post">
- <?= csrf_field() ?>
- <input type="hidden" name="action" value="migrate">
- <button type="submit" style="margin:0">Run migrations</button>
- </form>
- </div>
- <?php endif; ?>
- <h2>Local backups</h2>
- <div class="card">
- <?php if ($status['backups'] === []): ?>
- <p class="help" style="margin:0">No backup has been made yet.</p>
- <?php else: ?>
- <table>
- <tr>
- <th>File</th><th>Created</th><th>Trigger</th>
- <th>Files</th><th>Size</th><th>Upload</th><th></th>
- </tr>
- <?php foreach ($status['backups'] as $backup): ?>
- <tr>
- <td><?= e((string)($backup['filename'] ?? '')) ?></td>
- <td><?= e((string)($backup['created_at'] ?? '')) ?></td>
- <td><?= e((string)($backup['trigger'] ?? '')) ?></td>
- <td><?= (int)($backup['file_count'] ?? 0) ?></td>
- <td><?= e(manageFormatBytes((int)($backup['size'] ?? 0))) ?></td>
- <td>
- <?php $uploads = is_array($backup['remote_uploads'] ?? null) ? $backup['remote_uploads'] : []; ?>
- <?php if ($uploads === []): ?>
- —
- <?php else: foreach ($uploads as $upload): ?>
- <span class="tag <?= empty($upload['success']) ? 'tag-expired' : 'tag-lock' ?>">
- <?= e((string)($upload['target'] ?? '?')) ?><?= empty($upload['success']) ? ' failed' : '' ?>
- </span>
- <?php endforeach; endif; ?>
- </td>
- <td>
- <form method="post">
- <?= csrf_field() ?>
- <input type="hidden" name="action" value="download">
- <input type="hidden" name="filename" value="<?= e((string)($backup['filename'] ?? '')) ?>">
- <button type="submit" class="btn-ghost" style="margin:0;padding:.4rem 1rem">Download</button>
- </form>
- </td>
- </tr>
- <?php endforeach; ?>
- </table>
- <?php endif; ?>
- <p class="help">
- Kept locally: <?= (int)MANAGE_BACKUP_LOCAL_RETENTION ?>. Older ones are
- deleted here after each new backup; the manage server keeps its own,
- longer history.
- </p>
- </div>
- <?php
- $unsupported = [];
- foreach ($capabilities as $type => $capability) {
- if ($capability['configured'] && !$capability['available']) {
- $unsupported[] = $type;
- }
- }
- ?>
- <?php if ($unsupported !== []): ?>
- <div class="flash flash-error">
- Configured backup targets this server cannot use:
- <?= e(implode(', ', $unsupported)) ?>. Those uploads will fail.
- </div>
- <?php endif; ?>
- <?php foreach ($status['errors'] as $line): ?>
- <div class="flash flash-error"><?= e($line) ?></div>
- <?php endforeach; ?>
- <div class="card">
- <h2 style="margin-top:0">Report status</h2>
- <p class="help" style="margin-top:0">
- Sends version, PHP version, free disk space and the time of the last
- backup to the manage server. Normally an hourly cron job; this is the
- manual version of it.
- </p>
- <form method="post">
- <?= csrf_field() ?>
- <input type="hidden" name="action" value="heartbeat">
- <button type="submit" class="btn-ghost" style="margin:0">Send heartbeat</button>
- </form>
- </div>
- <p class="help">
- Same operations from the shell:
- <code>php manage-client/bin/manage-client.php status|check|backup|update|migrate|heartbeat</code>.
- See <code>docs/SETUP.md</code>.
- </p>
- <?php admin_footer(); ?>
|