manage-backup.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. <?php
  2. // Backups: collecting sources, writing the archive, local retention and the
  3. // upload to the Manage server.
  4. //
  5. // The source list is not hardcoded — it comes from MANAGE_BACKUP_SOURCES in
  6. // config.php, which for this shop is data/*.json plus assets/images/.
  7. //
  8. // There is deliberately no restore: archives are created and transferred, never
  9. // played back. Restoring is manual work, see docs/BACKUP_UPDATE.md.
  10. declare(strict_types=1);
  11. function manageBackupDir(): string
  12. {
  13. return rtrim((string) MANAGE_BACKUP_DIR, '/\\') . DIRECTORY_SEPARATOR;
  14. }
  15. function manageBackupIndexFile(): string
  16. {
  17. return manageBackupDir() . 'backup-index.json';
  18. }
  19. function manageBackupLockFile(): string
  20. {
  21. return manageBackupDir() . '.backup.lock';
  22. }
  23. // ---------------------------------------------------------------------------
  24. // Source collection
  25. // ---------------------------------------------------------------------------
  26. // Recursively lists readable files below $dir, mapped to $entryPrefix.
  27. function manageBackupCollectDirectory(string $dir, string $entryPrefix, array &$files): void
  28. {
  29. if (!is_dir($dir)) {
  30. return;
  31. }
  32. $base = rtrim($dir, '/\\') . DIRECTORY_SEPARATOR;
  33. $items = new RecursiveIteratorIterator(
  34. new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS),
  35. RecursiveIteratorIterator::LEAVES_ONLY
  36. );
  37. foreach ($items as $item) {
  38. if (!$item->isFile() || !$item->isReadable()) {
  39. continue;
  40. }
  41. $path = $item->getPathname();
  42. if (manageIsTemporaryFile($path)) {
  43. continue;
  44. }
  45. $relative = ltrim(manageClientNormalizePath(substr($path, strlen($base))), '/');
  46. if ($relative === '' || str_contains($relative, "\0")) {
  47. continue;
  48. }
  49. $files[] = [
  50. 'path' => $path,
  51. 'name' => trim($entryPrefix . '/' . $relative, '/'),
  52. ];
  53. }
  54. }
  55. /**
  56. * Resolves MANAGE_BACKUP_SOURCES into a flat list of archive entries.
  57. *
  58. * Each source entry supports one of:
  59. * 'glob' => 'data/*.json' non-recursive shell glob
  60. * 'dir' => 'assets/images' recursive directory
  61. * 'file' => 'settings.ini' single file
  62. * plus an optional 'as' prefix for the path inside the archive.
  63. */
  64. function manageBackupCollectSources(): array
  65. {
  66. $root = manageClientAppRoot();
  67. $sources = is_array(MANAGE_BACKUP_SOURCES) ? MANAGE_BACKUP_SOURCES : [];
  68. $files = [];
  69. foreach ($sources as $source) {
  70. if (!is_array($source)) {
  71. continue;
  72. }
  73. $prefix = trim((string) ($source['as'] ?? ''), '/');
  74. if (isset($source['glob'])) {
  75. $pattern = $root . DIRECTORY_SEPARATOR . ltrim((string) $source['glob'], '/\\');
  76. foreach (glob($pattern) ?: [] as $path) {
  77. if (!is_file($path) || !is_readable($path) || manageIsTemporaryFile($path)) {
  78. continue;
  79. }
  80. $files[] = [
  81. 'path' => $path,
  82. 'name' => trim($prefix . '/' . basename($path), '/'),
  83. ];
  84. }
  85. continue;
  86. }
  87. if (isset($source['dir'])) {
  88. $dir = $root . DIRECTORY_SEPARATOR . ltrim((string) $source['dir'], '/\\');
  89. manageBackupCollectDirectory($dir, $prefix !== '' ? $prefix : basename($dir), $files);
  90. continue;
  91. }
  92. if (isset($source['file'])) {
  93. $path = $root . DIRECTORY_SEPARATOR . ltrim((string) $source['file'], '/\\');
  94. if (is_file($path) && is_readable($path)) {
  95. $files[] = [
  96. 'path' => $path,
  97. 'name' => trim($prefix . '/' . basename($path), '/'),
  98. ];
  99. }
  100. }
  101. }
  102. // Two sources may resolve to the same archive entry; the first one wins so
  103. // the ZIP can never contain a duplicate name.
  104. $unique = [];
  105. foreach ($files as $file) {
  106. $unique[$file['name']] = $file;
  107. }
  108. $files = array_values($unique);
  109. usort($files, function ($left, $right) {
  110. return strcmp($left['name'], $right['name']);
  111. });
  112. return $files;
  113. }
  114. // ---------------------------------------------------------------------------
  115. // Index
  116. // ---------------------------------------------------------------------------
  117. function manageBackupReadIndex(): array
  118. {
  119. $index = manageReadJson(manageBackupIndexFile());
  120. $records = isset($index['backups']) && is_array($index['backups'])
  121. ? $index['backups']
  122. : [];
  123. return ['backups' => array_values($records)];
  124. }
  125. function manageBackupWriteIndex(array $records): void
  126. {
  127. manageWriteJson(manageBackupIndexFile(), ['backups' => array_values($records)]);
  128. }
  129. /**
  130. * Local backups, newest first. Self-healing: index records whose file is gone
  131. * are dropped and sizes are refreshed from disk.
  132. */
  133. function manageBackupList(): array
  134. {
  135. $dir = manageBackupDir();
  136. $existing = [];
  137. foreach (manageBackupReadIndex()['backups'] as $record) {
  138. if (!is_array($record)) {
  139. continue;
  140. }
  141. $filename = basename((string) ($record['filename'] ?? ''));
  142. if ($filename === '' || !is_file($dir . $filename)) {
  143. continue;
  144. }
  145. $record['filename'] = $filename;
  146. $record['size'] = (int) (filesize($dir . $filename) ?: ($record['size'] ?? 0));
  147. $existing[] = $record;
  148. }
  149. usort($existing, function ($left, $right) {
  150. return strcmp((string) ($right['created_at'] ?? ''), (string) ($left['created_at'] ?? ''));
  151. });
  152. return $existing;
  153. }
  154. function manageBackupRetentionLimit(): int
  155. {
  156. return max(1, (int) MANAGE_BACKUP_LOCAL_RETENTION);
  157. }
  158. function manageBackupApplyRetention(): void
  159. {
  160. $records = manageBackupList();
  161. $keep = manageBackupRetentionLimit();
  162. $dir = manageBackupDir();
  163. foreach (array_slice($records, $keep) as $record) {
  164. $filename = basename((string) ($record['filename'] ?? ''));
  165. if ($filename !== '' && is_file($dir . $filename)) {
  166. @unlink($dir . $filename);
  167. }
  168. }
  169. manageBackupWriteIndex(array_slice(manageBackupList(), 0, $keep));
  170. }
  171. // Absolute path of a local archive. Validates the filename strictly, so the
  172. // download form on the settings page cannot be made to serve another path.
  173. function manageBackupPath(string $filename): string
  174. {
  175. $filename = basename($filename);
  176. if (preg_match('/^backup-\d{8}-\d{6}(?:-\d+)?\.zip$/', $filename) !== 1) {
  177. throw new RuntimeException('Ungültiger Backup-Dateiname: ' . $filename);
  178. }
  179. $path = manageBackupDir() . $filename;
  180. if (!is_file($path)) {
  181. throw new RuntimeException('Backup wurde nicht gefunden: ' . $filename);
  182. }
  183. return $path;
  184. }
  185. // ---------------------------------------------------------------------------
  186. // Upload to the Manage server
  187. // ---------------------------------------------------------------------------
  188. function manageBackupBuildMultipartBody(
  189. array $fields,
  190. string $fileField,
  191. string $filePath,
  192. string $fileName,
  193. string $boundary
  194. ): string {
  195. $body = '';
  196. foreach ($fields as $name => $value) {
  197. $body .= '--' . $boundary . "\r\n";
  198. $body .= 'Content-Disposition: form-data; name="' . addcslashes((string) $name, "\"\\") . "\"\r\n\r\n";
  199. $body .= (string) $value . "\r\n";
  200. }
  201. $payload = file_get_contents($filePath);
  202. if ($payload === false) {
  203. throw new RuntimeException('Das Backup-ZIP konnte für den Upload nicht gelesen werden.');
  204. }
  205. $body .= '--' . $boundary . "\r\n";
  206. $body .=
  207. 'Content-Disposition: form-data; name="' . addcslashes($fileField, "\"\\") .
  208. '"; filename="' . addcslashes($fileName, "\"\\") . "\"\r\n";
  209. $body .= "Content-Type: application/zip\r\n\r\n";
  210. $body .= $payload . "\r\n";
  211. $body .= '--' . $boundary . "--\r\n";
  212. return $body;
  213. }
  214. /**
  215. * Uploads one archive to the Manage server.
  216. *
  217. * @param array $meta trigger, file_count, source_bytes, sha256
  218. */
  219. function manageBackupUpload(string $archivePath, array $meta = []): array
  220. {
  221. manageClientRequireConfigured();
  222. if (!is_file($archivePath)) {
  223. throw new RuntimeException('Die Backup-Datei existiert nicht: ' . $archivePath);
  224. }
  225. $filename = basename($archivePath);
  226. $sha256 = strtolower(trim((string) ($meta['sha256'] ?? '')));
  227. if (preg_match('/^[a-f0-9]{64}$/', $sha256) !== 1) {
  228. $sha256 = strtolower(hash_file('sha256', $archivePath) ?: '');
  229. }
  230. if (preg_match('/^[a-f0-9]{64}$/', $sha256) !== 1) {
  231. throw new RuntimeException('Die Prüfsumme des Backups konnte nicht berechnet werden.');
  232. }
  233. $metaPayload = json_encode([
  234. 'trigger' => (string) ($meta['trigger'] ?? 'manual'),
  235. 'file_count' => (int) ($meta['file_count'] ?? 0),
  236. 'source_bytes' => (int) ($meta['source_bytes'] ?? 0),
  237. 'app_version' => manageClientVersion(),
  238. ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  239. $boundary = '----manage-client-' . bin2hex(random_bytes(12));
  240. $body = manageBackupBuildMultipartBody(
  241. [
  242. 'filename' => $filename,
  243. 'sha256' => $sha256,
  244. 'meta' => $metaPayload === false ? '{}' : $metaPayload,
  245. ],
  246. 'backup',
  247. $archivePath,
  248. $filename,
  249. $boundary
  250. );
  251. $response = manageClientRequest(
  252. 'POST',
  253. 'backup.php',
  254. $body,
  255. 'multipart/form-data; boundary=' . $boundary,
  256. (int) MANAGE_HTTP_TIMEOUT_LONG
  257. );
  258. if ($response['status'] < 200 || $response['status'] >= 300) {
  259. throw new ManageRemoteUploadException(
  260. manageClientErrorMessage($response['status'], $response['body']),
  261. [
  262. 'http_status' => $response['status'],
  263. 'response_excerpt' => manageResponseExcerpt($response['body']),
  264. 'filename' => $filename,
  265. ]
  266. );
  267. }
  268. $decoded = json_decode($response['body'], true);
  269. if (!is_array($decoded) || empty($decoded['success'])) {
  270. $error = is_array($decoded) ? trim((string) ($decoded['error'] ?? '')) : '';
  271. throw new ManageRemoteUploadException(
  272. 'Der Manage-Server hat das Backup abgelehnt' . ($error !== '' ? ': ' . $error : '.'),
  273. [
  274. 'http_status' => $response['status'],
  275. 'response_excerpt' => manageResponseExcerpt($response['body']),
  276. 'filename' => $filename,
  277. ]
  278. );
  279. }
  280. return [
  281. 'target' => 'Manage-Server',
  282. 'type' => 'manage',
  283. 'success' => true,
  284. 'uploaded_at' => date(DATE_ATOM),
  285. 'server_filename' => (string) ($decoded['filename'] ?? ''),
  286. 'remote_path' => manageClientEndpoint('backup.php'),
  287. ];
  288. }
  289. // ---------------------------------------------------------------------------
  290. // Creating a backup
  291. // ---------------------------------------------------------------------------
  292. /**
  293. * Creates a local archive and, unless disabled, uploads it.
  294. *
  295. * A failed upload never invalidates the local archive: the error is stored in
  296. * the index record and logged, and the function returns normally. If it does
  297. * throw, the archive itself never came into being.
  298. *
  299. * @param string $trigger manual | automatic | update
  300. */
  301. function manageBackupCreate(string $trigger = 'manual'): array
  302. {
  303. $dir = manageBackupDir();
  304. manageEnsureDir($dir);
  305. $lockHandle = fopen(manageBackupLockFile(), 'c+');
  306. if ($lockHandle === false) {
  307. throw new RuntimeException('Die Backup-Sperrdatei konnte nicht geöffnet werden.');
  308. }
  309. // Two admins pressing the button at the same time must not interleave.
  310. if (!flock($lockHandle, LOCK_EX | LOCK_NB)) {
  311. fclose($lockHandle);
  312. throw new RuntimeException('Es läuft bereits ein Backup.');
  313. }
  314. try {
  315. $baseName = 'backup-' . date('Ymd-His');
  316. $filename = $baseName . '.zip';
  317. $counter = 2;
  318. while (file_exists($dir . $filename)) {
  319. $filename = $baseName . '-' . $counter . '.zip';
  320. $counter++;
  321. }
  322. $tmpFile = $dir . '.' . $filename . '.tmp';
  323. $archivePath = $dir . $filename;
  324. $createdAt = date(DATE_ATOM);
  325. $files = manageBackupCollectSources();
  326. $zipStats = manageZipWrite($tmpFile, $files);
  327. if (!rename($tmpFile, $archivePath)) {
  328. @unlink($tmpFile);
  329. throw new RuntimeException('Das Backup-ZIP konnte nicht finalisiert werden.');
  330. }
  331. @chmod($archivePath, 0660);
  332. $metadata = [
  333. 'filename' => $filename,
  334. 'created_at' => $createdAt,
  335. 'trigger' => $trigger,
  336. 'sha256' => $zipStats['sha256'],
  337. 'file_count' => $zipStats['file_count'],
  338. 'source_bytes' => $zipStats['source_bytes'],
  339. ];
  340. $uploads = [];
  341. if (MANAGE_BACKUP_UPLOAD === true && manageClientConfigured()) {
  342. try {
  343. $uploads[] = manageBackupUpload($archivePath, $metadata);
  344. } catch (Throwable $exception) {
  345. $debugContext = $exception instanceof ManageRemoteUploadException
  346. ? $exception->getDebugContext()
  347. : [];
  348. $uploads[] = [
  349. 'target' => 'Manage-Server',
  350. 'type' => 'manage',
  351. 'success' => false,
  352. 'error' => $exception->getMessage(),
  353. 'debug' => $debugContext,
  354. ];
  355. manageClientLog('ERROR', 'Backup upload to manage server failed', [
  356. 'filename' => $filename,
  357. 'error' => $exception->getMessage(),
  358. 'debug' => $debugContext,
  359. ]);
  360. }
  361. }
  362. $record = [
  363. 'filename' => $filename,
  364. 'created_at' => $createdAt,
  365. 'trigger' => $trigger,
  366. 'size' => (int) (filesize($archivePath) ?: $zipStats['archive_bytes']),
  367. 'file_count' => $zipStats['file_count'],
  368. 'source_bytes' => $zipStats['source_bytes'],
  369. 'sha256' => $zipStats['sha256'],
  370. 'app_version' => manageClientVersion(),
  371. 'remote_uploads' => $uploads,
  372. ];
  373. $records = manageBackupList();
  374. array_unshift($records, $record);
  375. manageBackupWriteIndex($records);
  376. manageBackupApplyRetention();
  377. manageClientLog('INFO', 'Backup created', [
  378. 'filename' => $filename,
  379. 'trigger' => $trigger,
  380. 'file_count' => $record['file_count'],
  381. 'size' => $record['size'],
  382. ]);
  383. return $record;
  384. } catch (Throwable $exception) {
  385. manageClientLog('ERROR', 'Backup failed', [
  386. 'trigger' => $trigger,
  387. 'error' => $exception->getMessage(),
  388. ]);
  389. throw $exception;
  390. } finally {
  391. flock($lockHandle, LOCK_UN);
  392. fclose($lockHandle);
  393. }
  394. }
  395. // ---------------------------------------------------------------------------
  396. // Automatic scheduling — this host has no cron
  397. // ---------------------------------------------------------------------------
  398. function manageBackupLastAutomaticAt(): int
  399. {
  400. foreach (manageBackupList() as $record) {
  401. if ((string) ($record['trigger'] ?? '') !== 'automatic') {
  402. continue;
  403. }
  404. $timestamp = strtotime((string) ($record['created_at'] ?? ''));
  405. if ($timestamp !== false) {
  406. return $timestamp;
  407. }
  408. }
  409. return 0;
  410. }
  411. function manageBackupIsAutomaticDue(): bool
  412. {
  413. $interval = (int) MANAGE_BACKUP_AUTO_INTERVAL_SECONDS;
  414. if ($interval < 1) {
  415. return false;
  416. }
  417. return time() - manageBackupLastAutomaticAt() >= $interval;
  418. }
  419. /**
  420. * Creates an automatic backup once the interval has elapsed, otherwise returns
  421. * null immediately. Called from admin/index.php, which is the rarely loaded
  422. * page this is meant for — a backup takes a few seconds.
  423. */
  424. function manageBackupCreateAutomaticIfDue(): ?array
  425. {
  426. if (!manageBackupIsAutomaticDue()) {
  427. return null;
  428. }
  429. return manageBackupCreate('automatic');
  430. }