|null */ function backup_meta_read(string $path): ?array { $sidecar = $path . '.json'; if (!is_file($sidecar)) { return null; } $data = json_decode((string) @file_get_contents($sidecar), true); return is_array($data) ? $data : null; } /** @param array $meta */ function backup_meta_write(string $path, array $meta): void { @file_put_contents($path . '.json', json_encode($meta, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n"); @chmod($path . '.json', 0600); } /** * Vorhandene Sicherungen, neueste zuerst. * * @return list */ function backup_list(): array { $dir = backup_root(); $items = []; foreach (glob($dir . '/backup_*.tar.gz') ?: [] as $path) { $name = basename($path); if (!backup_is_archive_name($name)) { continue; } $meta = backup_meta_read($path); $mtime = (int) @filemtime($path); $items[] = [ 'name' => $name, 'size' => (int) @filesize($path), 'created_at' => (string) ($meta['created_at'] ?? gmdate('Y-m-d H:i:s', $mtime)), 'reason' => (string) ($meta['reason'] ?? ''), 'rows' => isset($meta['rows']) ? (int) $meta['rows'] : null, 'files' => isset($meta['files']) ? (int) $meta['files'] : null, 'files_bytes' => isset($meta['files_bytes']) ? (int) $meta['files_bytes'] : null, 'manual' => $meta !== null, ]; } usort($items, static fn (array $a, array $b): int => strcmp($b['name'], $a['name'])); return $items; } /** @return list Tabellen der aktuellen Datenbank (ohne Views). */ function backup_tables(): array { $stmt = db()->query("SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'"); $tables = []; foreach (($stmt !== false ? $stmt->fetchAll(PDO::FETCH_NUM) : []) as $row) { $tables[] = (string) $row[0]; } sort($tables, SORT_STRING); return $tables; } /** SQL-Literal für einen Wert; nicht-UTF-8 fällt auf ein Binärliteral zurück. */ function backup_sql_value(mixed $value): string { if ($value === null) { return 'NULL'; } if (is_bool($value)) { return $value ? '1' : '0'; } if (is_int($value) || is_float($value)) { return (string) $value; } $string = (string) $value; if ($string === '') { return "''"; } if (preg_match('//u', $string) !== 1) { return "X'" . bin2hex($string) . "'"; } $quoted = db()->quote($string); return $quoted === false ? "X'" . bin2hex($string) . "'" : $quoted; } /** * Vollständiger Dump der Datenbank. * * @return array{sql: string, rows: int, tables: int} */ function backup_db_dump(): array { $pdo = db(); $tables = backup_tables(); $out = []; $out[] = '-- Drink it cold – Datenbank-Dump'; $out[] = '-- Format: ' . backup_format(); $out[] = '-- Erstellt: ' . utc_now() . ' UTC'; $out[] = '-- Einspielen: Verwaltung → Sicherungen oder: php tools/backup.php restore '; $out[] = 'SET NAMES utf8mb4;'; $out[] = "SET time_zone = '+00:00';"; $out[] = 'SET FOREIGN_KEY_CHECKS = 0;'; $out[] = "SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO';"; $rows = 0; foreach ($tables as $table) { $create = $pdo->query('SHOW CREATE TABLE `' . $table . '`'); $definition = $create !== false ? $create->fetch(PDO::FETCH_NUM) : false; if (!is_array($definition) || !isset($definition[1])) { continue; } $out[] = ''; $out[] = 'DROP TABLE IF EXISTS `' . $table . '`;'; $out[] = (string) $definition[1] . ';'; $select = $pdo->query('SELECT * FROM `' . $table . '`'); if ($select === false) { continue; } $columns = null; $batch = []; while (($row = $select->fetch(PDO::FETCH_ASSOC)) !== false) { if ($columns === null) { $columns = array_map(static fn (string $column): string => '`' . $column . '`', array_keys($row)); } $values = []; foreach ($row as $value) { $values[] = backup_sql_value($value); } $batch[] = '(' . implode(', ', $values) . ')'; $rows++; if (count($batch) >= 100) { $out[] = 'INSERT INTO `' . $table . '` (' . implode(', ', (array) $columns) . ") VALUES\n" . implode(",\n", $batch) . ';'; $batch = []; } } if ($batch !== []) { $out[] = 'INSERT INTO `' . $table . '` (' . implode(', ', (array) $columns) . ") VALUES\n" . implode(",\n", $batch) . ';'; } } $out[] = ''; $out[] = 'SET FOREIGN_KEY_CHECKS = 1;'; $out[] = ''; return ['sql' => implode("\n", $out), 'rows' => $rows, 'tables' => count($tables)]; } /** Zerlegt einen Dump in einzelne Anweisungen (beachtet Quotes und Kommentare). */ function backup_split_sql(string $sql): array { $statements = []; $current = ''; $length = strlen($sql); $quote = null; $inLineComment = false; for ($i = 0; $i < $length; $i++) { $char = $sql[$i]; if ($inLineComment) { if ($char === "\n") { $inLineComment = false; $current .= $char; } continue; } if ($quote !== null) { $current .= $char; if ($char === '\\' && $quote !== '`' && $i + 1 < $length) { $current .= $sql[++$i]; continue; } if ($char === $quote) { if ($i + 1 < $length && $sql[$i + 1] === $quote) { $current .= $sql[++$i]; continue; } $quote = null; } continue; } if ($char === "'" || $char === '"' || $char === '`') { $quote = $char; $current .= $char; continue; } if (($char === '-' && substr($sql, $i, 3) === '-- ') || ($char === '-' && substr($sql, $i, 2) === "--" && ($i + 2 >= $length || $sql[$i + 2] === "\n")) || $char === '#' ) { $inLineComment = true; continue; } if ($char === '/' && substr($sql, $i, 2) === '/*') { $end = strpos($sql, '*/', $i + 2); $i = $end === false ? $length : $end + 1; continue; } if ($char === ';') { $statement = trim($current); if ($statement !== '') { $statements[] = $statement; } $current = ''; continue; } $current .= $char; } $statement = trim($current); if ($statement !== '') { $statements[] = $statement; } return $statements; } /** Führt einen Dump aus; gibt die Anzahl ausgeführter Anweisungen zurück. */ function backup_exec_sql(string $sql): int { $pdo = db(); $pdo->exec('SET FOREIGN_KEY_CHECKS = 0'); $count = 0; try { foreach (backup_split_sql($sql) as $statement) { $pdo->exec($statement); $count++; } } finally { $pdo->exec('SET FOREIGN_KEY_CHECKS = 1'); } return $count; } /** * Dateien aus storage/ (ohne backups/ und logs/). * * @return array relativer Pfad => absoluter Pfad */ function backup_collect_files(): array { $storage = rtrim((string) config('app.storage_path', DIC_ROOT . '/storage'), '/'); if (!is_dir($storage)) { return []; } $skip = ['backups', 'logs']; $files = []; $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($storage, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::LEAVES_ONLY ); foreach ($iterator as $file) { /** @var SplFileInfo $file */ if (!$file->isFile()) { continue; } $path = $file->getPathname(); $relative = str_replace('\\', '/', substr($path, strlen($storage) + 1)); if ($relative === '' || $relative === '.htaccess') { continue; } if (in_array(explode('/', $relative)[0], $skip, true)) { continue; } $files[$relative] = $path; } ksort($files); return $files; } /** * Legt eine Sicherung an. * * @return array{name: string, path: string, size: int, rows: int, tables: int, files: int, created_at: string} */ function backup_create(string $reason = 'manuell'): array { if (!class_exists('PharData') || !function_exists('gzencode')) { throw new RuntimeException('Die PHP-Erweiterung Phar/zlib fehlt – Sicherungen sind nicht möglich.'); } @set_time_limit(0); @ignore_user_abort(true); $dir = backup_root(); $stamp = gmdate('Y-m-d_His'); $slug = substr(trim((string) preg_replace('/[^a-z0-9]+/', '-', strtolower($reason)), '-'), 0, 24); $base = 'backup_' . $stamp . ($slug !== '' ? '_' . $slug : ''); $name = $base . '.tar.gz'; $counter = 1; while (is_file($dir . '/' . $name)) { $counter++; $name = $base . '-' . $counter . '.tar.gz'; } $path = $dir . '/' . $name; $dump = backup_db_dump(); $files = backup_collect_files(); $filesBytes = 0; foreach ($files as $absolute) { $filesBytes += max(0, (int) @filesize($absolute)); } $meta = [ 'format' => backup_format(), 'created_at' => utc_now(), 'reason' => $reason, 'tables' => $dump['tables'], 'rows' => $dump['rows'], 'files' => count($files), 'files_bytes' => $filesBytes, 'db_bytes' => strlen($dump['sql']), 'database_sha256' => hash('sha256', $dump['sql']), ]; $work = $dir . '/.work-' . bin2hex(random_bytes(6)); if (!@mkdir($work, 0700, true) && !is_dir($work)) { throw new RuntimeException('Temporäres Verzeichnis für die Sicherung fehlt.'); } try { $sqlFile = $work . '/database.sql'; if (@file_put_contents($sqlFile, $dump['sql']) === false) { throw new RuntimeException('Datenbank-Dump konnte nicht geschrieben werden.'); } $metaFile = $work . '/manifest.json'; if (@file_put_contents($metaFile, json_encode($meta, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n") === false) { throw new RuntimeException('Manifest konnte nicht geschrieben werden.'); } $tarPath = $work . '/backup.tar'; $tar = new PharData($tarPath); $tar->addFile($metaFile, 'manifest.json'); $tar->addFile($sqlFile, 'database.sql'); foreach ($files as $relative => $absolute) { $tar->addFile($absolute, 'files/' . $relative); } $tar->compress(Phar::GZ); unset($tar); $built = $tarPath . '.gz'; if (!is_file($built)) { throw new RuntimeException('Das Archiv konnte nicht gepackt werden.'); } if (!@rename($built, $path)) { if (!@copy($built, $path)) { throw new RuntimeException('Das Archiv konnte nicht abgelegt werden.'); } } @chmod($path, 0600); backup_meta_write($path, $meta); } finally { backup_remove_tree($work); } return [ 'name' => $name, 'path' => $path, 'size' => (int) @filesize($path), 'rows' => $dump['rows'], 'tables' => $dump['tables'], 'files' => count($files), 'created_at' => (string) $meta['created_at'], ]; } function backup_delete(string $name): bool { $path = backup_path_for($name); if ($path === null) { return false; } $ok = @unlink($path); @unlink($path . '.json'); return $ok; } /** * Räumt alte Sicherungen auf: die letzten app.backup_keep bleiben, von den * Sicherheitskopien vor einem Restore maximal drei. * * @return array{deleted: list, kept: int} */ function backup_rotate(?int $keep = null): array { $keep = $keep ?? backup_keep(); $items = backup_list(); if ($keep <= 0) { return ['deleted' => [], 'kept' => count($items)]; } $regular = array_values(array_filter($items, static fn (array $item): bool => $item['reason'] !== 'vor-restore')); $safety = array_values(array_filter($items, static fn (array $item): bool => $item['reason'] === 'vor-restore')); $deleted = []; foreach (array_slice($regular, $keep) as $item) { if (backup_delete($item['name'])) { $deleted[] = $item['name']; } } foreach (array_slice($safety, 3) as $item) { if (backup_delete($item['name'])) { $deleted[] = $item['name']; } } return ['deleted' => $deleted, 'kept' => min($keep, count($regular)) + min(3, count($safety))]; } function backup_remove_tree(string $dir): void { if (!is_dir($dir)) { return; } $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST ); foreach ($iterator as $entry) { /** @var SplFileInfo $entry */ if ($entry->isDir()) { @rmdir($entry->getPathname()); } else { @unlink($entry->getPathname()); } } @rmdir($dir); } /** Kopiert einen Baum und legt fehlende Zielordner an. */ function backup_copy_tree(string $from, string $to): int { if (!is_dir($from)) { return 0; } $count = 0; $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($from, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST ); foreach ($iterator as $entry) { /** @var SplFileInfo $entry */ $relative = str_replace('\\', '/', substr($entry->getPathname(), strlen($from) + 1)); $target = $to . '/' . $relative; if ($entry->isDir()) { if (!is_dir($target)) { @mkdir($target, 0775, true); } continue; } if (!is_dir(dirname($target))) { @mkdir(dirname($target), 0775, true); } if (@copy($entry->getPathname(), $target)) { @chmod($target, 0664); $count++; } } return $count; } /** * Entpackt ein Archiv in ein Zielverzeichnis (nur manifest.json, database.sql * und files/…). Pfade mit ".." werden übersprungen. * * @return array{manifest: ?array, sql: ?string, files: int} */ function backup_extract(string $archive, string $target): array { if (!class_exists('PharData')) { throw new RuntimeException('Die PHP-Erweiterung Phar fehlt – Sicherungen lassen sich nicht entpacken.'); } $files = 0; try { $phar = new PharData($archive); $iterator = new RecursiveIteratorIterator($phar, RecursiveIteratorIterator::LEAVES_ONLY); foreach ($iterator as $entry) { /** @var PharFileInfo $entry */ $relative = str_replace('\\', '/', ltrim($iterator->getSubPathname(), '/')); if ($relative === '' || str_contains($relative, '..') || !$entry->isFile()) { continue; } if ($relative !== 'manifest.json' && $relative !== 'database.sql' && !str_starts_with($relative, 'files/')) { continue; } $destination = $target . '/' . $relative; if (!is_dir(dirname($destination))) { @mkdir(dirname($destination), 0700, true); } if (!@copy($entry->getPathname(), $destination)) { throw new RuntimeException('Eintrag konnte nicht entpackt werden: ' . $relative); } $files++; } } catch (PharException|UnexpectedValueException $error) { error_log('Sicherung: Archiv nicht lesbar: ' . $error->getMessage()); throw new RuntimeException('Die Datei ist kein gültiges Sicherungsarchiv.'); } $manifest = null; $manifestFile = $target . '/manifest.json'; if (is_file($manifestFile)) { $decoded = json_decode((string) file_get_contents($manifestFile), true); if (!is_array($decoded) || ($decoded['format'] ?? '') !== backup_format()) { throw new RuntimeException('Das Archiv stammt nicht aus dieser Anwendung (Format unbekannt).'); } $manifest = $decoded; } return [ 'manifest' => $manifest, 'sql' => is_file($target . '/database.sql') ? (string) file_get_contents($target . '/database.sql') : null, 'files' => $files, ]; } /** * Spielt eine Sicherung ein. * * @param array{database?: bool, files?: bool, safety?: bool} $options * @return array{archive: string, statements: int, rows_before: int, files: int, safety: ?string, warnings: list} */ function backup_restore(string $name, array $options = []): array { $options = $options + ['database' => true, 'files' => true, 'safety' => true]; $path = backup_path_for($name); if ($path === null) { throw new RuntimeException('Sicherung nicht gefunden: ' . $name); } @set_time_limit(0); @ignore_user_abort(true); $dir = backup_root(); $storage = rtrim((string) config('app.storage_path', DIC_ROOT . '/storage'), '/'); $result = [ 'archive' => $name, 'statements' => 0, 'rows_before' => 0, 'files' => 0, 'safety' => null, 'warnings' => [], ]; // Sicherheitskopie des Ist-Zustands: ein Restore ist damit umkehrbar. if ($options['safety']) { $safetyBackup = backup_create('vor-restore'); $result['safety'] = $safetyBackup['name']; } $work = $dir . '/.restore-' . bin2hex(random_bytes(6)); if (!@mkdir($work, 0700, true) && !is_dir($work)) { throw new RuntimeException('Temporäres Verzeichnis für die Wiederherstellung fehlt.'); } try { $extracted = backup_extract($path, $work); $expected = (string) ($extracted['manifest']['database_sha256'] ?? ''); $sql = $extracted['sql']; if ($options['database']) { if ($sql === null) { $result['warnings'][] = 'Das Archiv enthält keinen Datenbank-Dump.'; } elseif ($expected !== '' && !hash_equals($expected, hash('sha256', $sql))) { throw new RuntimeException('Der Datenbank-Dump ist beschädigt (Prüfsumme weicht ab).'); } else { $result['rows_before'] = (int) db()->query('SELECT COUNT(*) FROM bookings')->fetchColumn(); $result['statements'] = backup_exec_sql($sql); } } if ($options['files'] && is_dir($work . '/files')) { $current = $storage . '/documents'; if (is_dir($current)) { $parked = $dir . '/files-vor-restore-' . gmdate('Y-m-d_His'); $suffix = 1; while (is_dir($parked)) { $suffix++; $parked = $dir . '/files-vor-restore-' . gmdate('Y-m-d_His') . '-' . $suffix; } if (!@rename($current, $parked)) { throw new RuntimeException('Die vorhandenen Dateien lassen sich nicht beiseitelegen.'); } } $result['files'] = backup_copy_tree($work . '/files', $storage); } } finally { backup_remove_tree($work); } backup_prune_parked_files($dir); return $result; } /** Hält von den vor einem Restore beiseitegelegten Dateibäumen nur die letzten zwei. */ function backup_prune_parked_files(string $dir): void { $parked = glob($dir . '/files-vor-restore-*') ?: []; sort($parked, SORT_STRING); foreach (array_slice($parked, 0, max(0, count($parked) - 2)) as $old) { backup_remove_tree($old); } } /** * Übernimmt ein hochgeladenes Archiv in das Sicherungsverzeichnis. * * @param array $upload Eintrag aus $_FILES * @return array{name: string, created_at: string, rows: ?int, files: ?int, size: int} */ function backup_import(array $upload): array { $error = (int) ($upload['error'] ?? UPLOAD_ERR_NO_FILE); if ($error === UPLOAD_ERR_NO_FILE) { throw new RuntimeException('Bitte eine Sicherungsdatei auswählen.'); } if ($error !== UPLOAD_ERR_OK) { throw new RuntimeException('Der Upload ist fehlgeschlagen (Code ' . $error . ').'); } $tmp = (string) ($upload['tmp_name'] ?? ''); $original = (string) ($upload['name'] ?? ''); if ($tmp === '' || !is_uploaded_file($tmp)) { throw new RuntimeException('Der Upload konnte nicht gelesen werden.'); } if (!preg_match('/\.tar\.gz$/i', $original)) { throw new RuntimeException('Erwartet wird ein Archiv aus dieser Anwendung (*.tar.gz).'); } $size = (int) @filesize($tmp); if ($size <= 0) { throw new RuntimeException('Die Datei ist leer.'); } if ($size > backup_max_bytes()) { throw new RuntimeException('Die Datei ist zu groß (Grenze: ' . (int) config('app.backup_max_mb', 200) . ' MB).'); } $dir = backup_root(); $probe = $dir . '/.import-' . bin2hex(random_bytes(6)); if (!@mkdir($probe, 0700, true) && !is_dir($probe)) { throw new RuntimeException('Temporäres Verzeichnis für den Upload fehlt.'); } $meta = null; try { $copy = $probe . '/upload.tar.gz'; if (!@copy($tmp, $copy)) { throw new RuntimeException('Die Datei konnte nicht zwischengespeichert werden.'); } $extracted = backup_extract($copy, $probe); $meta = $extracted['manifest']; if ($meta === null) { throw new RuntimeException('Im Archiv fehlt das Manifest – es stammt nicht aus dieser Anwendung.'); } $expected = (string) ($meta['database_sha256'] ?? ''); if ($extracted['sql'] !== null && $expected !== '' && !hash_equals($expected, hash('sha256', (string) $extracted['sql']))) { throw new RuntimeException('Der Datenbank-Dump im Archiv ist beschädigt (Prüfsumme weicht ab).'); } $stamp = strtotime(((string) ($meta['created_at'] ?? '')) . ' UTC') ?: time(); $name = 'backup_' . gmdate('Y-m-d_His', $stamp) . '_import.tar.gz'; $target = $dir . '/' . $name; $counter = 1; while (is_file($target)) { $counter++; $name = 'backup_' . gmdate('Y-m-d_His', $stamp) . '_import-' . $counter . '.tar.gz'; $target = $dir . '/' . $name; } if (!@rename($copy, $target) && !@copy($copy, $target)) { throw new RuntimeException('Die Sicherung konnte nicht abgelegt werden.'); } @chmod($target, 0600); $meta['reason'] = trim((string) ($meta['reason'] ?? 'import')) !== '' ? (string) $meta['reason'] : 'import'; $meta['imported_at'] = utc_now(); backup_meta_write($target, $meta); } finally { backup_remove_tree($probe); } return [ 'name' => $name, 'created_at' => (string) ($meta['created_at'] ?? ''), 'rows' => isset($meta['rows']) ? (int) $meta['rows'] : null, 'files' => isset($meta['files']) ? (int) $meta['files'] : null, 'size' => (int) @filesize($dir . '/' . $name), ]; } /** Menschenlesbare Größe (z. B. „4,3 MB“). */ function backup_human_size(int $bytes): string { if ($bytes < 1024) { return $bytes . ' B'; } $units = ['KB', 'MB', 'GB']; $value = $bytes / 1024; $unit = 0; while ($value >= 1024 && $unit < count($units) - 1) { $value /= 1024; $unit++; } return number_format($value, $value < 10 ? 1 : 0, ',', '.') . ' ' . $units[$unit]; }