maintenance.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. <?php
  2. /**
  3. * Maintenance: backups and software updates, both driven by the manage client
  4. * in manage-client/ (see client-package/docs/ for the full reference).
  5. *
  6. * The page holds no update or backup logic of its own — every button calls the
  7. * same documented function the CLI calls, so `php manage-client/bin/manage-client.php
  8. * backup` and the button below do exactly the same thing. The client ships a
  9. * drop-in panel of its own; this page replaces it so the backoffice keeps one
  10. * look, one login and one CSRF token.
  11. *
  12. * Results are rendered on the POST itself rather than after a redirect: an
  13. * update reports several lines (files copied, migrations run, backup location)
  14. * and a flash message holds one.
  15. */
  16. require dirname(__DIR__) . '/app/bootstrap.php';
  17. auth_require();
  18. // An installation may legitimately not carry the client — it is one folder,
  19. // and deploying by FTP works without it. Say so instead of dying on a require.
  20. if (!is_file(APP_ROOT . '/manage-client/lib/client.php')) {
  21. admin_header('Maintenance', 'maintenance');
  22. echo '<h1>Maintenance</h1><div class="card"><p class="help" style="margin:0">'
  23. . 'The backup and update client is not installed: <code>manage-client/</code> '
  24. . 'is missing. See <code>docs/SETUP.md</code>, section 5a.</p></div>';
  25. admin_footer();
  26. exit;
  27. }
  28. require_once APP_ROOT . '/manage-client/lib/client.php';
  29. $messages = [];
  30. $errors = [];
  31. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  32. csrf_verify();
  33. // Archiving media/ and uploading it runs well past the default limit.
  34. @set_time_limit(0);
  35. $action = (string)($_POST['action'] ?? '');
  36. try {
  37. if ($action === 'download') {
  38. // Validates the filename itself and throws on anything that is not
  39. // a backup of this installation.
  40. $path = manageBackupPath((string)($_POST['filename'] ?? ''));
  41. $size = filesize($path);
  42. $fh = fopen($path, 'rb');
  43. if ($size === false || $fh === false) {
  44. throw new RuntimeException('Backup file could not be opened.');
  45. }
  46. header('Content-Type: application/zip');
  47. header('Content-Disposition: attachment; filename="' . addcslashes(basename($path), '"\\') . '"');
  48. header('Content-Length: ' . $size);
  49. header('Cache-Control: private, no-store');
  50. header('X-Content-Type-Options: nosniff');
  51. fpassthru($fh);
  52. fclose($fh);
  53. exit;
  54. }
  55. if ($action === 'backup') {
  56. $messages = array_merge($messages, maintenance_backup('manual'));
  57. manageHeartbeatSendQuietly();
  58. } elseif ($action === 'update') {
  59. // Deliberately a line here rather than a feature of the client: it
  60. // stays visible that the update takes a backup first, and the
  61. // update stops if that backup cannot be written.
  62. if (!empty($_POST['backup_first'])) {
  63. $messages = array_merge($messages, maintenance_backup('update'));
  64. }
  65. $result = manageUpdateApply(['force' => !empty($_POST['force'])]);
  66. $messages[] = sprintf(
  67. 'Update deployed: %s → %s. %d files copied, %d replaced files saved to %s.',
  68. $result['from_version'] !== '' ? $result['from_version'] : 'unknown',
  69. $result['to_version'],
  70. $result['copied'],
  71. $result['backed_up'],
  72. $result['backup_dir'],
  73. );
  74. // Files are deployed even when the hook failed; that difference is
  75. // the whole point of reporting it separately.
  76. $hook = is_array($result['hook'] ?? null) ? $result['hook'] : [];
  77. $applied = $hook['migrations']['applied'] ?? [];
  78. if ($applied !== []) {
  79. $messages[] = 'Migrations run: ' . implode(', ', $applied);
  80. }
  81. if ($hook !== [] && empty($hook['success'])) {
  82. $errors[] = empty($hook['failed_migration'])
  83. ? 'The files are deployed, but the post-update step failed: '
  84. . (string)($hook['error'] ?? 'unknown')
  85. : 'The files are deployed, but migration "' . (string)$hook['failed_migration']
  86. . '" failed: ' . (string)($hook['error'] ?? 'unknown')
  87. . ' Remaining migrations were not attempted — fix the cause, then use "Run migrations" below.';
  88. }
  89. manageHeartbeatSendQuietly();
  90. } elseif ($action === 'migrate') {
  91. $report = manageUpdateRunMigrations();
  92. if ($report['applied'] !== []) {
  93. $messages[] = 'Migrations run: ' . implode(', ', $report['applied']);
  94. }
  95. if (!$report['success']) {
  96. $errors[] = 'Migration "' . (string)$report['failed'] . '" failed: ' . (string)$report['error'];
  97. } elseif ($report['applied'] === []) {
  98. $messages[] = 'No pending migrations.';
  99. }
  100. } elseif ($action === 'heartbeat') {
  101. $result = manageHeartbeatSend();
  102. $messages[] = 'Status reported. Current release: '
  103. . (($result['latest'] ?? '') !== '' ? (string)$result['latest'] : 'none') . '.';
  104. }
  105. } catch (Throwable $e) {
  106. $errors[] = $e->getMessage();
  107. }
  108. }
  109. /**
  110. * One backup, reported as message lines. A failed upload is a warning, not a
  111. * failure: the archive exists locally either way.
  112. */
  113. function maintenance_backup(string $trigger): array
  114. {
  115. $record = manageBackupCreate($trigger);
  116. $lines = [sprintf(
  117. 'Backup created: %s — %d files, %s.',
  118. $record['filename'],
  119. $record['file_count'],
  120. manageFormatBytes((int)$record['size']),
  121. )];
  122. foreach ($record['remote_uploads'] as $upload) {
  123. if (empty($upload['success'])) {
  124. $lines[] = 'Upload to ' . (string)$upload['target'] . ' failed: '
  125. . (string)($upload['error'] ?? 'unknown') . ' The local copy is intact.';
  126. }
  127. }
  128. return $lines;
  129. }
  130. // Never throws: an unreachable manage server still renders the page.
  131. $status = manageClientStatus();
  132. $update = $status['update'];
  133. $capabilities = manageRemoteCapabilities();
  134. admin_header('Maintenance', 'maintenance');
  135. flash_render();
  136. ?>
  137. <h1>Maintenance</h1>
  138. <?php foreach ($messages as $line): ?>
  139. <div class="flash flash-ok"><?= e($line) ?></div>
  140. <?php endforeach; ?>
  141. <?php foreach ($errors as $line): ?>
  142. <div class="flash flash-error"><?= e($line) ?></div>
  143. <?php endforeach; ?>
  144. <?php if (!$status['configured']): ?>
  145. <div class="flash flash-error">
  146. Not connected to the manage server. Create an instance there, then fill in
  147. <code>MANAGE_INSTANCE</code> and <code>MANAGE_TOKEN</code> in
  148. <code>manage-client/config.php</code>. Backups can still be made locally.
  149. </div>
  150. <?php endif; ?>
  151. <div class="card">
  152. <table>
  153. <tr>
  154. <td>Installed version</td>
  155. <td><?= e($status['version'] !== '' ? $status['version'] : 'unknown') ?></td>
  156. <td class="help" style="margin:0">PHP <?= e($status['php_version']) ?></td>
  157. </tr>
  158. <tr>
  159. <td>Current release</td>
  160. <td>
  161. <?php if ($update !== null && $update['available']): ?>
  162. <span class="tag tag-lock"><?= e($update['latest']) ?> available</span>
  163. <?php elseif ($update !== null): ?>
  164. <?= e($update['latest'] !== '' ? $update['latest'] : '—') ?>
  165. <?php else: ?>
  166. —
  167. <?php endif; ?>
  168. </td>
  169. <td class="help" style="margin:0">
  170. <?php if ($status['update_error'] !== null): ?>
  171. Check failed: <?= e($status['update_error']) ?>
  172. <?php elseif ($update !== null && $update['available']): ?>
  173. Back up first, then deploy.
  174. <?php elseif ($update !== null): ?>
  175. Up to date.
  176. <?php else: ?>
  177. <?= e($status['instance'] !== '' ? $status['instance'] : 'no instance configured') ?>
  178. <?php endif; ?>
  179. </td>
  180. </tr>
  181. <tr>
  182. <td>Last backup</td>
  183. <td><?= e($status['last_backup_at'] ?? 'never') ?></td>
  184. <td class="help" style="margin:0"><?= count($status['backups']) ?> kept locally</td>
  185. </tr>
  186. <tr>
  187. <td>Release migrations</td>
  188. <td><?= count($status['pending_migrations']) ?> pending</td>
  189. <td class="help" style="margin:0">
  190. <?= $status['pending_migrations'] === []
  191. ? 'Nothing to run.'
  192. : e(implode(', ', array_column($status['pending_migrations'], 'id'))) ?>
  193. </td>
  194. </tr>
  195. </table>
  196. </div>
  197. <h2>Backup</h2>
  198. <div class="card">
  199. <p class="help" style="margin-top:0">
  200. Archives <code>data/</code> and <code>media/</code> — galleries, showreel,
  201. front page, settings — and uploads it to the manage server. Gallery photos
  202. are not included: they live in the S3 bucket, which is their own backup.
  203. Nor are <code>config/</code> credentials, because a backup can be
  204. downloaded again from the server.
  205. </p>
  206. <form method="post">
  207. <?= csrf_field() ?>
  208. <input type="hidden" name="action" value="backup">
  209. <button type="submit" style="margin:0">Back up now</button>
  210. </form>
  211. </div>
  212. <h2>Update</h2>
  213. <div class="card">
  214. <?php if ($update !== null && $update['available']): ?>
  215. <p style="margin-top:0">
  216. Version <strong><?= e($update['latest']) ?></strong> is ready
  217. <?php if (!empty($update['manifest']['published_at'])): ?>
  218. (published <?= e($update['manifest']['published_at']) ?>)
  219. <?php endif; ?>.
  220. </p>
  221. <?php endif; ?>
  222. <p class="help" style="margin-top:0">
  223. Files are replaced while the site stays online, and there is no rollback:
  224. the replaced files are copied to <code>data/manage/updates/</code> for
  225. manual recovery. <code>config/</code>, <code>data/</code> and
  226. <code>media/</code> are never touched. Deleted files are not removed —
  227. an update overlays what is there.
  228. <?php if ($status['pending_migrations'] === []): ?>
  229. Afterwards, check <a href="migrate.php">Data migration</a>.
  230. <?php endif; ?>
  231. </p>
  232. <form method="post" onsubmit="return confirm('Deploy the update now? Files will be overwritten.');">
  233. <?= csrf_field() ?>
  234. <input type="hidden" name="action" value="update">
  235. <p class="help" style="margin-bottom:.4rem"><label style="display:inline;text-transform:none;letter-spacing:0">
  236. <input type="checkbox" name="backup_first" value="1" checked>
  237. Create a backup first
  238. </label></p>
  239. <p class="help" style="margin-bottom:.4rem"><label style="display:inline;text-transform:none;letter-spacing:0">
  240. <input type="checkbox" name="force" value="1">
  241. Deploy even if no newer version is offered
  242. </label></p>
  243. <button type="submit" style="margin-top:1rem"
  244. <?= $update !== null && !$update['available'] ? 'class="btn-ghost"' : '' ?>>
  245. Deploy update
  246. </button>
  247. </form>
  248. </div>
  249. <?php if ($status['pending_migrations'] !== []): ?>
  250. <h2>Pending release migrations</h2>
  251. <div class="card">
  252. <p class="help" style="margin-top:0">
  253. Shipped with a release and normally run by the update itself. These are
  254. left over — usually because one failed, or because the update ran with
  255. migrations skipped.
  256. </p>
  257. <table style="margin-bottom:1rem">
  258. <?php foreach ($status['pending_migrations'] as $migration): ?>
  259. <tr><td><?= e($migration['id']) ?></td></tr>
  260. <?php endforeach; ?>
  261. </table>
  262. <form method="post">
  263. <?= csrf_field() ?>
  264. <input type="hidden" name="action" value="migrate">
  265. <button type="submit" style="margin:0">Run migrations</button>
  266. </form>
  267. </div>
  268. <?php endif; ?>
  269. <h2>Local backups</h2>
  270. <div class="card">
  271. <?php if ($status['backups'] === []): ?>
  272. <p class="help" style="margin:0">No backup has been made yet.</p>
  273. <?php else: ?>
  274. <table>
  275. <tr>
  276. <th>File</th><th>Created</th><th>Trigger</th>
  277. <th>Files</th><th>Size</th><th>Upload</th><th></th>
  278. </tr>
  279. <?php foreach ($status['backups'] as $backup): ?>
  280. <tr>
  281. <td><?= e((string)($backup['filename'] ?? '')) ?></td>
  282. <td><?= e((string)($backup['created_at'] ?? '')) ?></td>
  283. <td><?= e((string)($backup['trigger'] ?? '')) ?></td>
  284. <td><?= (int)($backup['file_count'] ?? 0) ?></td>
  285. <td><?= e(manageFormatBytes((int)($backup['size'] ?? 0))) ?></td>
  286. <td>
  287. <?php $uploads = is_array($backup['remote_uploads'] ?? null) ? $backup['remote_uploads'] : []; ?>
  288. <?php if ($uploads === []): ?>
  289. —
  290. <?php else: foreach ($uploads as $upload): ?>
  291. <span class="tag <?= empty($upload['success']) ? 'tag-expired' : 'tag-lock' ?>">
  292. <?= e((string)($upload['target'] ?? '?')) ?><?= empty($upload['success']) ? ' failed' : '' ?>
  293. </span>
  294. <?php endforeach; endif; ?>
  295. </td>
  296. <td>
  297. <form method="post">
  298. <?= csrf_field() ?>
  299. <input type="hidden" name="action" value="download">
  300. <input type="hidden" name="filename" value="<?= e((string)($backup['filename'] ?? '')) ?>">
  301. <button type="submit" class="btn-ghost" style="margin:0;padding:.4rem 1rem">Download</button>
  302. </form>
  303. </td>
  304. </tr>
  305. <?php endforeach; ?>
  306. </table>
  307. <?php endif; ?>
  308. <p class="help">
  309. Kept locally: <?= (int)MANAGE_BACKUP_LOCAL_RETENTION ?>. Older ones are
  310. deleted here after each new backup; the manage server keeps its own,
  311. longer history.
  312. </p>
  313. </div>
  314. <?php
  315. $unsupported = [];
  316. foreach ($capabilities as $type => $capability) {
  317. if ($capability['configured'] && !$capability['available']) {
  318. $unsupported[] = $type;
  319. }
  320. }
  321. ?>
  322. <?php if ($unsupported !== []): ?>
  323. <div class="flash flash-error">
  324. Configured backup targets this server cannot use:
  325. <?= e(implode(', ', $unsupported)) ?>. Those uploads will fail.
  326. </div>
  327. <?php endif; ?>
  328. <?php foreach ($status['errors'] as $line): ?>
  329. <div class="flash flash-error"><?= e($line) ?></div>
  330. <?php endforeach; ?>
  331. <div class="card">
  332. <h2 style="margin-top:0">Report status</h2>
  333. <p class="help" style="margin-top:0">
  334. Sends version, PHP version, free disk space and the time of the last
  335. backup to the manage server. Normally an hourly cron job; this is the
  336. manual version of it.
  337. </p>
  338. <form method="post">
  339. <?= csrf_field() ?>
  340. <input type="hidden" name="action" value="heartbeat">
  341. <button type="submit" class="btn-ghost" style="margin:0">Send heartbeat</button>
  342. </form>
  343. </div>
  344. <p class="help">
  345. Same operations from the shell:
  346. <code>php manage-client/bin/manage-client.php status|check|backup|update|migrate|heartbeat</code>.
  347. See <code>docs/SETUP.md</code>.
  348. </p>
  349. <?php admin_footer(); ?>