From 952a2874b0b63a1d5f18cc45dce9af457195b30c Mon Sep 17 00:00:00 2001 From: torsten Date: Mon, 30 Nov 2026 16:11:36 +0100 Subject: [PATCH] feat(backup): Sicherungen von Datenbank und Dateien mit Restore MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - app/backup.php: ein tar.gz-Archiv aus manifest.json (Format, Zeilen- und Dateizahl, SHA-256 des Dumps), database.sql (DROP/CREATE/INSERT) und allen Dateien aus storage/ ohne backups/ und logs/; Aufbewahrung app.backup_keep, eigener SQL-Splitter fürs Einspielen, Rechte 0600/0700 - Verwaltung → Sicherungen (/admin/backups): anlegen, herunterladen, hochladen (mit Prüfsummen- und Formatprüfung), einspielen (Datenbank und/oder Dateien, Bestätigungswort, automatische Sicherheitskopie, alte Dateien beiseitegelegt), löschen - tools/backup.php (create/list/restore/rotate/delete) und /cron/backup?token=… für Hosting ohne SSH - Bedienungsanleitung um Admin-Abschnitt „Sicherungen“ erweitert, README, ROADMAP (Feature 19), DSGVO-Hinweis, Deploy-Manifest um tools/backup.php --- README.md | 55 +++ ROADMAP.md | 6 + app/admin.php | 118 +++++++ app/backup.php | 761 ++++++++++++++++++++++++++++++++++++++++ app/bootstrap.php | 1 + app/config.example.php | 6 + app/pages.php | 41 +++ docs/dsgvo.md | 5 +- tools/backup.php | 164 +++++++++ tools/deploy.sh | 1 + views/_admin_nav.php | 1 + views/admin_backups.php | 201 +++++++++++ views/layout.php | 1 + views/manual.php | 34 +- 14 files changed, 1393 insertions(+), 2 deletions(-) create mode 100644 app/backup.php create mode 100644 tools/backup.php create mode 100644 views/admin_backups.php diff --git a/README.md b/README.md index c64612c..5a8c450 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,12 @@ Die Anforderungen stammen aus (wird beim Scrollen per CSS invertiert). PWA-Icons liegen unter `web/assets/icons/`. +- **Sicherungen**: Unter **Verwaltung → Sicherungen** legt der Admin mit einem + Klick ein Archiv aus Datenbank und allen abgelegten Dateien an, lädt es + herunter, spielt einen früheren Stand wieder ein (mit automatischer + Sicherheitskopie vorher) oder übernimmt ein extern aufbewahrtes Archiv. + Details: siehe *Sicherungen in der App* weiter unten. + - **Buchungsunterlagen**: In jeder Buchung erzeugt die App den **Mietvertrag** (Varianten *Mit Lieferung*, *Selbstabholer*, *Truhe*, passend zur Buchung vorbelegt) und die **Auftragsbestätigung** als PDF – ohne externe Bibliothek @@ -46,6 +52,8 @@ Die Anforderungen stammen aus Buchungsunterlagen: Mietvertrag in den drei Varianten erzeugen, vom Kunden auf dem Tablet unterschreiben lassen oder den Unterschriftslink mailen, drucken, Auftragsbestätigung und Lexware-Rechnung ablegen (`views/manual.php`). + Nur für Admins erscheint dort zusätzlich der Abschnitt **Sicherungen** + (Archiv erstellen, herunterladen, einspielen, aufräumen). - **Kalender** mit Tages-, 4-Wochen- und Monatsansicht (4 Kalenderwochen sind Standard und starten mit der aktuellen KW). Alle Anhänger haben eine eigene Zeile und sind immer gleichzeitig sichtbar. Jeder Termin ist ein durchgehender, farbiger Balken in der Farbe des Anhängers. Gesetzliche @@ -285,6 +293,53 @@ Zurückspielen (Vorsicht: der Dump enthält `DROP TABLE`/`CREATE TABLE`): mysql -h -u -p < tools/dumps/drink-it-cold_live_<...>.sql ``` +## Sicherungen in der App (Backup & Restore) + +Unter **Verwaltung → Sicherungen** (`/admin/backups`, nur für Administratoren) +sichert die App die Datenbank **und** alle abgelegten Dateien in einem Archiv: + +- **Inhalt:** `manifest.json` (Format, Zeitpunkt, Zeilen- und Dateizahl, + SHA-256 des Dumps), `database.sql` (alle Tabellen mit `DROP`/`CREATE`/`INSERT`) + und `files/…` – das ist alles unter `storage/` **außer** `backups/` und + `logs/`, also Buchungsunterlagen und Unterschriften. +- **Ablage:** `storage/backups` (Verzeichnis `0700`, Dateien `0600`, + konfigurierbar über `app.backup_path`). Die Archive enthalten + personenbezogene Daten; zur Aufbewahrung außerhalb des Servers herunterladen. +- **Aufräumen:** Standardmäßig bleiben die letzten 14 Sicherungen + (`app.backup_keep`, `0` = nichts löschen). Sicherheitskopien vor einem + Restore werden getrennt behandelt (maximal drei). +- **Einspielen:** In der Liste „Einspielen…“ wählen, Datenbank und/oder Dateien + anhaken und zur Bestätigung `WIEDERHERSTELLEN` eintippen. Vorher legt die App + automatisch eine Sicherheitskopie des aktuellen Stands an; die alten Dateien + werden als `storage/backups/files-vor-restore-` beiseitegelegt (die + letzten zwei bleiben). Nach dem Einspielen kann eine erneute Anmeldung nötig + sein, wenn sich der Benutzerstand geändert hat. +- **Upload:** Ein extern aufbewahrtes Archiv (`*.tar.gz`) lässt sich hochladen + (bis `app.backup_max_mb`, Standard 200 MB); die Prüfsumme des Dumps wird + geprüft, fremde Dateien werden abgewiesen. + +Per Kommandozeile (Cron auf Servern mit Shell): + +```bash +php tools/backup.php create # Sicherung anlegen, danach aufräumen +php tools/backup.php list # vorhandene Archive +php tools/backup.php restore # einspielen (vorher automatisch sichern) +php tools/backup.php restore --db-only # nur die Datenbank +php tools/backup.php rotate --keep 30 # Aufbewahrung ändern +php tools/backup.php delete +``` + +Ohne SSH (netcup-Webhosting) stößt ein Cronjob im Hosting-Panel die Sicherung +per HTTP an – Tokens wie beim Erinnerungslauf (`app.cron_token`): + +``` +30 4 * * * curl -sS "https://drinkitcold.com/cron/backup?token=" >/dev/null +``` + +Die Antwort listet Archivname, Zeilen- und Dateizahl. Der ältere Weg über +`tools/dump_drink_it_cold.py` (nur Datenbank, Ablage `tools/dumps/`) bleibt +unverändert nutzbar. + ## Erinnerungen: Push, E-Mail und Cron Die Erinnerungen sind immer in der App sichtbar. Zusätzlich gibt es zwei diff --git a/ROADMAP.md b/ROADMAP.md index 33e2b28..7f87781 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -82,6 +82,12 @@ - **Umsetzung:** `next_booking_start()` liefert die nächste Buchung; `page_dashboard()` gibt `free_until` (Tag vor Mietbeginn) je Anhänger mit, `views/dashboard.php` zeigt „Frei bis – neue Buchung möglich“. - **Prüfung:** Anhänger mit Buchung in 10 Tagen zeigt „Frei bis “, Anhänger ohne Buchung den bisherigen Text, Anhänger mit heutiger Buchung unverändert. +## Betriebssicherheit (30.11.2026) + +- [x] **Feature 19: Sicherungen (Backup & Restore)** + - **Umsetzung:** `app/backup.php` packt Datenbank-Dump (`SHOW CREATE TABLE` + `INSERT`-Blöcke, eigener SQL-Splitter für Restore) und alle Dateien aus `storage/` (ohne `backups/`, `logs/`) in ein `tar.gz` mit `manifest.json` inkl. SHA-256; Ablage `storage/backups` (0600, Aufbewahrung `app.backup_keep`). Admin-Seite `/admin/backups` zum Anlegen, Herunterladen, Hochladen (mit Prüfsumme), Löschen und Einspielen (Datenbank/Dateien wählbar, Bestätigungswort, automatische Sicherheitskopie vorher), CLI `tools/backup.php`, Cron `/cron/backup?token=…`. + - **Prüfung:** Sicherung erstellen – Archiv enthält `manifest.json`, `database.sql` und alle Unterlagen; Buchung anlegen, Sicherung einspielen – Buchung ist wieder weg, Unterlagen im alten Stand; Sicherheitskopie erscheint in der Liste; falsches Bestätigungswort und manipuliertes/fremdes Archiv werden abgewiesen; alte Archive verschwinden nach `app.backup_keep`. + ## Kundenwunsch vom 30.11.2026 - [x] **Feature 18: Kundenrundmail (Dankeschön zum Jahresende)** diff --git a/app/admin.php b/app/admin.php index 0cef977..d79a114 100644 --- a/app/admin.php +++ b/app/admin.php @@ -46,6 +46,14 @@ function admin_handle(string $path, array $user): void admin_mailings($user); return; } + if ($path === '/admin/backups') { + admin_backups($user); + return; + } + if (preg_match('#^/admin/backups/(backup_[A-Za-z0-9_.-]+\.tar\.gz)/download$#', $path, $m) === 1) { + admin_backup_download($m[1]); + return; + } if (preg_match('#^/admin/mailings/(\d+)$#', $path, $m) === 1) { admin_mailing_detail((int) $m[1]); return; @@ -718,3 +726,113 @@ function admin_mailings(array $user): void 'batchSize' => MAILING_BATCH_DEFAULT, ], 'Kundenrundmail'); } + +/* ------------------------------------------------------------ Sicherungen */ + +function admin_backups(array $user): void +{ + $errors = []; + + if (is_post()) { + require_post(); + $action = post_string('action'); + try { + if ($action === 'create') { + $backup = backup_create('manuell'); + $rotation = backup_rotate(); + flash('success', sprintf( + 'Sicherung %s erstellt: %d Zeilen, %d Dateien, %s%s.', + $backup['name'], + $backup['rows'], + $backup['files'], + backup_human_size($backup['size']), + $rotation['deleted'] !== [] ? ', ' . count($rotation['deleted']) . ' alte entfernt' : '' + )); + redirect('/admin/backups'); + } + if ($action === 'delete') { + $name = post_string('name'); + if (backup_delete($name)) { + flash('success', 'Sicherung ' . $name . ' gelöscht.'); + } else { + flash('error', 'Diese Sicherung gibt es nicht (mehr).'); + } + redirect('/admin/backups'); + } + if ($action === 'upload') { + $import = backup_import($_FILES['archive'] ?? []); + backup_rotate(); + flash('success', sprintf( + 'Sicherung übernommen: %s (Stand %s, %d Dateien, %s).', + $import['name'], + (string) fmt_datetime($import['created_at']), + (int) ($import['files'] ?? 0), + backup_human_size($import['size']) + )); + redirect('/admin/backups'); + } + if ($action === 'restore') { + admin_backup_restore($user); + } + } catch (Throwable $error) { + error_log('Sicherung: ' . $error->getMessage()); + $errors['general'] = $error->getMessage(); + } + } + + $restoreResult = $_SESSION['backup_restore_result'] ?? null; + unset($_SESSION['backup_restore_result']); + + render_page('admin_backups', [ + 'backups' => backup_list(), + 'keep' => backup_keep(), + 'errors' => $errors, + 'restoreResult' => is_array($restoreResult) ? $restoreResult : null, + 'directory' => backup_root(), + 'maxMb' => (int) config('app.backup_max_mb', 200), + 'available' => class_exists('PharData'), + ], 'Sicherungen'); +} + +function admin_backup_restore(array $user): never +{ + $name = post_string('name'); + if (post_string('confirm') !== 'WIEDERHERSTELLEN') { + throw new RuntimeException('Bitte zur Bestätigung WIEDERHERSTELLEN in das Textfeld schreiben.'); + } + $database = post_string('restore_database') === '1'; + $files = post_string('restore_files') === '1'; + if (!$database && !$files) { + throw new RuntimeException('Bitte auswählen, was eingespielt werden soll.'); + } + + $result = backup_restore($name, ['database' => $database, 'files' => $files, 'safety' => true]); + error_log(sprintf( + 'Restore durch Benutzer %d (%s %s): %s – %d Anweisungen, %d Dateien, Sicherheitskopie %s', + (int) $user['id'], + (string) $user['first_name'], + (string) $user['last_name'], + $name, + $result['statements'], + $result['files'], + (string) $result['safety'] + )); + + $_SESSION['backup_restore_result'] = $result; + flash('success', 'Sicherung ' . $name . ' wurde eingespielt.'); + redirect('/admin/backups'); +} + +function admin_backup_download(string $name): void +{ + $path = backup_path_for($name); + if ($path === null) { + abort_page(404, 'Diese Sicherung gibt es nicht (mehr).'); + } + header('Content-Type: application/gzip'); + header('Content-Length: ' . (string) filesize($path)); + header('Content-Disposition: attachment; filename="' . $name . '"'); + header('Cache-Control: private, no-store'); + readfile($path); + exit; +} diff --git a/app/backup.php b/app/backup.php new file mode 100644 index 0000000..8e7b7b4 --- /dev/null +++ b/app/backup.php @@ -0,0 +1,761 @@ +|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]; +} diff --git a/app/bootstrap.php b/app/bootstrap.php index 037f65f..5299c4d 100644 --- a/app/bootstrap.php +++ b/app/bootstrap.php @@ -41,6 +41,7 @@ require DIC_APP . '/mailing.php'; require DIC_APP . '/inquiry.php'; require DIC_APP . '/invite.php'; require DIC_APP . '/privacy.php'; +require DIC_APP . '/backup.php'; require DIC_APP . '/pages.php'; require DIC_APP . '/admin.php'; diff --git a/app/config.example.php b/app/config.example.php index 08ce7d2..33d46d0 100644 --- a/app/config.example.php +++ b/app/config.example.php @@ -49,6 +49,12 @@ return [ 'document_deposit_cents' => 10000, // Maximale Größe einer hochgeladenen Rechnung (PDF aus Lexware). 'document_max_mb' => 10, + // Sicherungen: Archiv aus Datenbank-Dump und allen abgelegten Dateien + // unter storage/ (ohne backups/ und logs/). Verwaltung → Sicherungen. + 'backup_path' => dirname(__DIR__) . '/storage/backups', + 'backup_keep' => 14, + // Maximale Größe einer hochgeladenen Sicherung (MB). + 'backup_max_mb' => 200, ], // Optional: Angaben für Impressum und Datenschutz überschreiben. Die // Standardwerte stehen in app/legal.php. Hinweis: tools/deploy.sh erzeugt diff --git a/app/pages.php b/app/pages.php index 82dc797..d444f38 100644 --- a/app/pages.php +++ b/app/pages.php @@ -50,6 +50,10 @@ function page_handle(string $method, string $path): void cron_reminders(); return; } + if ($path === '/cron/backup') { + cron_backup(); + return; + } if ($path === '/login') { page_login($method); return; @@ -272,6 +276,43 @@ function cron_reminders(): void } } +/** + * Sicherung per HTTP anstoßen (Token = app.cron_token). + * + * Auf dem Webhosting gibt es kein SSH/Cron für CLI-Skripte; dieser Aufruf + * ersetzt `php tools/backup.php create`. + */ +function cron_backup(): void +{ + header('Content-Type: text/plain; charset=utf-8'); + header('Cache-Control: no-store'); + $expected = trim((string) config('app.cron_token', '')); + $token = query_string('token'); + if ($expected === '' || $token === '' || !hash_equals($expected, $token)) { + http_response_code(403); + echo "Kein Zugriff.\n"; + return; + } + try { + $backup = backup_create('cron'); + $rotation = backup_rotate(); + echo sprintf( + "Sicherung %s erstellt: %d Zeilen, %d Dateien, %d Byte.\n", + $backup['name'], + $backup['rows'], + $backup['files'], + $backup['size'] + ); + echo $rotation['deleted'] === [] + ? "Aufgeräumt: nichts zu löschen.\n" + : 'Aufgeräumt: ' . implode(', ', $rotation['deleted']) . " entfernt.\n"; + } catch (Throwable $error) { + error_log('Cron-Sicherung: ' . $error->getMessage()); + http_response_code(500); + echo "Fehler: Sicherung konnte nicht erstellt werden.\n"; + } +} + /** * Schema-Migrationen per HTTP anstoßen (Token = app.cron_token). * diff --git a/docs/dsgvo.md b/docs/dsgvo.md index 0af88cf..5fef71b 100644 --- a/docs/dsgvo.md +++ b/docs/dsgvo.md @@ -129,7 +129,10 @@ Meldung an die Aufsichtsbehörde innerhalb von 72 Stunden erfolgen ohne Aufbewahrungsgrund löschen. - [ ] Datensicherung: Aufbewahrungsdauer festlegen und dokumentieren (die Datenschutzerklärung nennt nur „so lange wie für die Wiederherstellung - erforderlich“). + erforderlich“). Technisch umgesetzt in **Verwaltung → Sicherungen** + (`app.backup_keep`, Standard 14 Archive, plus max. drei Sicherheitskopien + vor einem Restore); die Archive liegen in `storage/backups` (0600) und + werden nur bei Bedarf außerhalb des Servers aufbewahrt. - [ ] Mitarbeiter auf Vertraulichkeit und Datenschutz verpflichten und ihnen diese Datenschutzerklärung zugänglich machen. - [ ] Datenschutzhinweise in Mietanfrage/Mietvertrag aufnehmen, damit Kunden diff --git a/tools/backup.php b/tools/backup.php new file mode 100644 index 0000000..b73c424 --- /dev/null +++ b/tools/backup.php @@ -0,0 +1,164 @@ + [--db-only|--files-only] [--force] + * php tools/backup.php rotate [--keep 14] + * php tools/backup.php delete + * + * Die Archive liegen in app.backup_path (Standard: storage/backups) und + * enthalten personenbezogene Daten – Ablage mit 0600, Transfer verschlüsselt. + * Dieselbe Funktion gibt es in der Verwaltung (/admin/backups) und per + * Cron (/cron/backup?token=…). + */ + +if (PHP_SAPI !== 'cli') { + http_response_code(403); + exit("Nur per CLI.\n"); +} + +require __DIR__ . '/../app/bootstrap.php'; + +/** @return list */ +function backup_cli_args(): array +{ + global $argv; + return array_slice($argv, 1); +} + +function backup_cli_option(array $args, string $name, ?string $default = null): ?string +{ + foreach ($args as $index => $arg) { + if ($arg === '--' . $name) { + return $args[$index + 1] ?? $default; + } + if (str_starts_with($arg, '--' . $name . '=')) { + return substr($arg, strlen($name) + 3); + } + } + return $default; +} + +function backup_cli_flag(array $args, string $name): bool +{ + return in_array('--' . $name, $args, true); +} + +/** @return list */ +function backup_cli_positional(array $args): array +{ + $out = []; + foreach ($args as $arg) { + if (!str_starts_with($arg, '--')) { + $out[] = $arg; + } + } + return $out; +} + +$args = backup_cli_args(); +$command = backup_cli_positional($args)[0] ?? 'help'; + +try { + switch ($command) { + case 'create': + $reason = (string) backup_cli_option($args, 'reason', 'cli'); + $backup = backup_create($reason); + $rotation = backup_rotate(); + echo sprintf( + "Sicherung %s erstellt: %d Zeilen aus %d Tabellen, %d Dateien, %s.\n", + $backup['name'], + $backup['rows'], + $backup['tables'], + $backup['files'], + backup_human_size($backup['size']) + ); + echo 'Ablage: ' . $backup['path'] . "\n"; + if ($rotation['deleted'] !== []) { + echo 'Aufgeräumt: ' . implode(', ', $rotation['deleted']) . "\n"; + } + break; + + case 'list': + $items = backup_list(); + if ($items === []) { + echo "Keine Sicherungen vorhanden (" . backup_root() . ").\n"; + break; + } + foreach ($items as $item) { + echo sprintf( + "%-46s %s %s %s\n", + $item['name'], + gmdate('d.m.Y H:i', strtotime($item['created_at'] . ' UTC') ?: time()), + backup_human_size($item['size']), + $item['rows'] === null ? '' : $item['rows'] . ' Zeilen / ' . (int) ($item['files'] ?? 0) . ' Dateien' + ); + } + echo count($items) . " Sicherung(en) in " . backup_root() . "\n"; + break; + + case 'restore': + $archive = backup_cli_positional($args)[1] ?? ''; + if ($archive === '') { + fwrite(STDERR, "Bitte ein Archiv angeben (siehe: php tools/backup.php list).\n"); + exit(1); + } + $dbOnly = backup_cli_flag($args, 'db-only'); + $filesOnly = backup_cli_flag($args, 'files-only'); + if ($dbOnly && $filesOnly) { + fwrite(STDERR, "--db-only und --files-only schließen sich aus.\n"); + exit(1); + } + $result = backup_restore($archive, [ + 'database' => !$filesOnly, + 'files' => !$dbOnly, + 'safety' => !backup_cli_flag($args, 'no-safety'), + ]); + echo sprintf( + "Sicherung %s eingespielt: %d Anweisungen, %d Dateien.\n", + $result['archive'], + $result['statements'], + $result['files'] + ); + if ($result['safety'] !== null) { + echo 'Sicherheitskopie des alten Stands: ' . $result['safety'] . "\n"; + } + foreach ($result['warnings'] as $warning) { + echo 'Hinweis: ' . $warning . "\n"; + } + break; + + case 'rotate': + $keep = backup_cli_option($args, 'keep'); + $rotation = backup_rotate($keep === null ? null : (int) $keep); + echo $rotation['deleted'] === [] + ? "Nichts zu löschen.\n" + : 'Entfernt: ' . implode(', ', $rotation['deleted']) . "\n"; + break; + + case 'delete': + $archive = backup_cli_positional($args)[1] ?? ''; + if ($archive === '') { + fwrite(STDERR, "Bitte ein Archiv angeben.\n"); + exit(1); + } + echo backup_delete($archive) ? "Gelöscht: $archive\n" : "Nicht gefunden: $archive\n"; + break; + + default: + echo "Sicherungen von Drink it cold\n\n" + . " php tools/backup.php create [--reason text]\n" + . " php tools/backup.php list\n" + . " php tools/backup.php restore [--db-only|--files-only] [--no-safety]\n" + . " php tools/backup.php rotate [--keep N]\n" + . " php tools/backup.php delete \n"; + break; + } +} catch (Throwable $error) { + fwrite(STDERR, 'Fehler: ' . $error->getMessage() . "\n"); + exit(1); +} diff --git a/tools/deploy.sh b/tools/deploy.sh index acf0e51..bad8aa8 100755 --- a/tools/deploy.sh +++ b/tools/deploy.sh @@ -342,6 +342,7 @@ do_sync() { echo "Lade Cron-Skript und Konfiguration hoch …" printf '%s\t%s\t\n' "$REPO_ROOT/tools/send_reminders.php" "tools/send_reminders.php" >> "$manifest" printf '%s\t%s\t\n' "$REPO_ROOT/tools/migrate.php" "tools/migrate.php" >> "$manifest" + printf '%s\t%s\t\n' "$REPO_ROOT/tools/backup.php" "tools/backup.php" >> "$manifest" printf '%s\t%s\t\n' "$REPO_ROOT/tools/.htaccess" "tools/.htaccess" >> "$manifest" printf '%s\t%s\t%s\n' "$TMP_DIR/config.local.php" "app/config.local.php" 600 >> "$manifest" diff --git a/views/_admin_nav.php b/views/_admin_nav.php index bf59449..d4d115c 100644 --- a/views/_admin_nav.php +++ b/views/_admin_nav.php @@ -5,6 +5,7 @@ $items = [ '/admin/employees' => ['label' => 'Mitarbeiter', 'icon' => 'i-users'], '/admin/trailers' => ['label' => 'Anhänger', 'icon' => 'i-truck'], '/admin/mailings' => ['label' => 'Rundmail', 'icon' => 'i-mail'], + '/admin/backups' => ['label' => 'Sicherungen', 'icon' => 'i-database'], ]; ?>