feat(backup): Sicherungen von Datenbank und Dateien mit Restore

- 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
This commit is contained in:
torsten 2026-11-30 16:11:36 +01:00
parent fb98f9a355
commit 952a2874b0
14 changed files with 1393 additions and 2 deletions

View file

@ -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 <host> -u <user> -p <datenbank> < 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-<Zeit>` 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 <archiv> # einspielen (vorher automatisch sichern)
php tools/backup.php restore <archiv> --db-only # nur die Datenbank
php tools/backup.php rotate --keep 30 # Aufbewahrung ändern
php tools/backup.php delete <archiv>
```
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=<app.cron_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

View file

@ -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 <Datum> – neue Buchung möglich“.
- **Prüfung:** Anhänger mit Buchung in 10 Tagen zeigt „Frei bis <Datum vor Mietbeginn>“, 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)**

View file

@ -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;
}

761
app/backup.php Normal file
View file

@ -0,0 +1,761 @@
<?php
declare(strict_types=1);
/**
* Sicherungen (Backup) und Wiederherstellung (Restore).
*
* Eine Sicherung ist ein tar.gz-Archiv mit drei Teilen:
* manifest.json – Format, Zeitpunkt, Anzahl Zeilen/Dateien, SHA-256 des Dumps
* database.sql – Dump aller Tabellen (DROP + CREATE + INSERT)
* files/… – alle Dateien aus storage/ (ohne backups/ und logs/)
*
* Archive liegen in storage/backups (Verzeichnis 0700, Dateien 0600) und
* enthalten personenbezogene Daten. Die letzten app.backup_keep Sicherungen
* bleiben erhalten (0 = unbegrenzt).
*
* Ausgelöst wird das über Verwaltung → Sicherungen, per CLI (tools/backup.php)
* oder per Cron (/cron/backup?token=…).
*/
/** Kennung des Archivformats im manifest.json. */
function backup_format(): string
{
return 'dic-backup/1';
}
function backup_root(): string
{
$storage = rtrim((string) config('app.storage_path', DIC_ROOT . '/storage'), '/');
$dir = rtrim((string) config('app.backup_path', $storage . '/backups'), '/');
if (!is_dir($dir) && !@mkdir($dir, 0700, true) && !is_dir($dir)) {
throw new RuntimeException('Das Sicherungsverzeichnis lässt sich nicht anlegen: ' . $dir);
}
return $dir;
}
function backup_keep(): int
{
return max(0, (int) config('app.backup_keep', 14));
}
function backup_max_bytes(): int
{
return max(1, (int) config('app.backup_max_mb', 200)) * 1024 * 1024;
}
function backup_is_archive_name(string $name): bool
{
return $name !== ''
&& $name === basename($name)
&& !str_contains($name, '..')
&& preg_match('/^backup_[A-Za-z0-9_.-]+\.tar\.gz$/', $name) === 1;
}
/** Absoluter Pfad einer vorhandenen Sicherung oder null. */
function backup_path_for(string $name): ?string
{
if (!backup_is_archive_name($name)) {
return null;
}
$path = backup_root() . '/' . $name;
return is_file($path) ? $path : null;
}
/** @return array<string, mixed>|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<string, mixed> $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<array{name: string, size: int, created_at: string, reason: string, rows: ?int, files: ?int, files_bytes: ?int, manual: bool}>
*/
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<string> 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 <archiv>';
$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<string, string> 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<string>, 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<string, mixed>, 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<string>}
*/
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<string, mixed> $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];
}

View file

@ -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';

View file

@ -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

View file

@ -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).
*

View file

@ -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

164
tools/backup.php Normal file
View file

@ -0,0 +1,164 @@
<?php
declare(strict_types=1);
/**
* Sicherungen (Backup/Restore) von Datenbank und Dateien – CLI.
*
* php tools/backup.php create [--reason manuell]
* php tools/backup.php list
* php tools/backup.php restore <archiv> [--db-only|--files-only] [--force]
* php tools/backup.php rotate [--keep 14]
* php tools/backup.php delete <archiv>
*
* 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<string> */
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<string> */
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 <archiv> [--db-only|--files-only] [--no-safety]\n"
. " php tools/backup.php rotate [--keep N]\n"
. " php tools/backup.php delete <archiv>\n";
break;
}
} catch (Throwable $error) {
fwrite(STDERR, 'Fehler: ' . $error->getMessage() . "\n");
exit(1);
}

View file

@ -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"

View file

@ -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'],
];
?>
<nav class="admin-nav" aria-label="Verwaltung">

201
views/admin_backups.php Normal file
View file

@ -0,0 +1,201 @@
<?php
/** @var list<array{name: string, size: int, created_at: string, reason: string, rows: ?int, files: ?int, files_bytes: ?int, manual: bool}> $backups */
/** @var int $keep */
/** @var array<string, string> $errors */
/** @var array{archive: string, statements: int, rows_before: int, files: int, safety: ?string, warnings: list<string>}|null $restoreResult */
/** @var string $directory */
/** @var int $maxMb */
/** @var bool $available */
$error = static fn (string $key): string => (string) ($errors[$key] ?? '');
$totalSize = 0;
foreach ($backups as $item) {
$totalSize += $item['size'];
}
?>
<div class="page-head page-head--compact">
<div>
<p class="eyebrow">Verwaltung</p>
<h1>Sicherungen</h1>
<p class="page-head__lede">Eine Sicherung enthält die komplette Datenbank und alle abgelegten
Dateien (Buchungsunterlagen, Unterschriften) in einem Archiv. Sie können sie hier
herunterladen, eine fremde Sicherung hochladen und den Stand wieder einspielen.</p>
</div>
</div>
<?php require __DIR__ . '/_admin_nav.php'; ?>
<?php if ($error('general') !== ''): ?>
<div class="alert alert--error" role="alert">
<svg class="ico" aria-hidden="true"><use href="#i-alert"/></svg>
<div><strong>Das hat nicht geklappt.</strong><p><?= e($error('general')) ?></p></div>
</div>
<?php endif; ?>
<?php if (!$available): ?>
<div class="alert alert--error" role="alert">
<svg class="ico" aria-hidden="true"><use href="#i-alert"/></svg>
<div><strong>Die PHP-Erweiterung <code>Phar</code> fehlt.</strong>
<p>Ohne sie lassen sich keine Archive schreiben oder lesen. Sicherungen sind deshalb
gesperrt; bitte beim Hoster prüfen.</p>
</div>
</div>
<?php endif; ?>
<?php if ($restoreResult !== null): ?>
<section class="panel">
<div class="panel__head">
<div>
<h2>Wiederherstellung abgeschlossen</h2>
<p>Aus <code><?= e($restoreResult['archive']) ?></code> wurden
<?= (int) $restoreResult['statements'] ?> SQL-Anweisungen ausgeführt und
<?= (int) $restoreResult['files'] ?> Dateien übernommen.</p>
</div>
</div>
<p class="muted small">Vor dem Einspielen wurde automatisch eine Sicherheitskopie angelegt<?= $restoreResult['safety'] !== null ? ' (<code>' . e((string) $restoreResult['safety']) . '</code>)' : '' ?>.
Falls die Anmeldung nicht mehr gilt, hat sich der Benutzerstand geändert – dann bitte neu anmelden.</p>
<?php foreach ($restoreResult['warnings'] as $warning): ?>
<p class="muted small">Hinweis: <?= e($warning) ?></p>
<?php endforeach; ?>
</section>
<?php endif; ?>
<section class="panel">
<div class="panel__head">
<div>
<h2>Neue Sicherung</h2>
<p>Läuft im Hintergrund des Aufrufs und dauert je nach Datenmenge einige Sekunden.
Die letzten <?= (int) $keep ?> Sicherungen bleiben erhalten<?= $keep === 0 ? ' (Aufräumen ist ausgeschaltet)' : '' ?>.</p>
</div>
<div class="panel__actions">
<form method="post" action="<?= e(url('/admin/backups')) ?>">
<?= csrf_field() ?>
<input type="hidden" name="action" value="create">
<button class="btn primary" type="submit"<?= $available ? '' : ' disabled' ?>>
<svg class="ico" aria-hidden="true"><use href="#i-download"/></svg> Sicherung jetzt erstellen
</button>
</form>
</div>
</div>
<p class="muted small">Ablage: <code><?= e($directory) ?></code> ·
<?= count($backups) ?> Archiv<?= count($backups) === 1 ? '' : 'e' ?> ·
<?= e(backup_human_size($totalSize)) ?> belegt</p>
<details class="create-trailer">
<summary class="btn small create-trailer__summary">
<svg class="ico" aria-hidden="true"><use href="#i-plus"/></svg> Sicherung hochladen
</summary>
<div class="create-trailer__body">
<p class="muted small">Ein Archiv aus dieser Anwendung (<code>*.tar.gz</code>, höchstens
<?= (int) $maxMb ?> MB). Die Prüfsumme des Datenbank-Dumps wird beim Hochladen geprüft.</p>
<form method="post" action="<?= e(url('/admin/backups')) ?>" enctype="multipart/form-data" class="form-grid">
<?= csrf_field() ?>
<input type="hidden" name="action" value="upload">
<label class="field field--full">
<span>Archiv</span>
<input type="file" name="archive" accept=".gz,.tar.gz,application/gzip" required>
</label>
<div class="form-actions field--full">
<button class="btn" type="submit"<?= $available ? '' : ' disabled' ?>>Hochladen</button>
</div>
</form>
</div>
</details>
</section>
<section class="panel">
<div class="panel__head">
<div>
<h2>Vorhandene Sicherungen</h2>
<p>Neueste zuerst. Herunterladen zur Aufbewahrung außerhalb des Servers ist empfohlen –
ein Archiv enthält personenbezogene Daten.</p>
</div>
</div>
<?php if ($backups === []): ?>
<p class="muted">Noch keine Sicherung vorhanden.</p>
<?php else: ?>
<div class="table-wrap">
<table class="data-table">
<thead>
<tr>
<th>Archiv</th>
<th>Stand</th>
<th>Inhalt</th>
<th>Größe</th>
<th class="ta-right">Aktionen</th>
</tr>
</thead>
<tbody>
<?php foreach ($backups as $item): ?>
<tr>
<td>
<strong><?= e($item['name']) ?></strong>
<?php if ($item['reason'] !== ''): ?>
<small class="muted">
<?= $item['reason'] === 'vor-restore' ? 'Sicherheitskopie vor Wiederherstellung' : ($item['reason'] === 'cron' ? 'automatisch (Cron)' : e($item['reason'])) ?>
</small>
<?php endif; ?>
</td>
<td><?= e(fmt_datetime($item['created_at'])) ?></td>
<td class="small">
<?php if ($item['rows'] === null): ?>
<span class="muted">keine Angaben</span>
<?php else: ?>
<?= (int) $item['rows'] ?> Zeilen ·
<?= (int) ($item['files'] ?? 0) ?> Dateien
<?php endif; ?>
</td>
<td><?= e(backup_human_size($item['size'])) ?></td>
<td class="ta-right">
<div class="danger-actions">
<a class="btn small" href="<?= e(url('/admin/backups/' . rawurlencode($item['name']) . '/download')) ?>">
<svg class="ico" aria-hidden="true"><use href="#i-download"/></svg> Herunterladen
</a>
<details>
<summary class="btn small">Einspielen…</summary>
<form method="post" action="<?= e(url('/admin/backups')) ?>"
class="stack"
data-confirm="Sicherung „<?= e($item['name']) ?>“ wirklich einspielen? Der aktuelle Stand wird dabei überschrieben.">
<?= csrf_field() ?>
<input type="hidden" name="action" value="restore">
<input type="hidden" name="name" value="<?= e_attr($item['name']) ?>">
<label class="check">
<input type="checkbox" name="restore_database" value="1" checked>
<span>Datenbank</span>
</label>
<label class="check">
<input type="checkbox" name="restore_files" value="1" checked>
<span>Dateien</span>
</label>
<label class="field">
<span>Zur Bestätigung <code>WIEDERHERSTELLEN</code> eingeben</span>
<input type="text" name="confirm" value="" autocomplete="off" required>
</label>
<button class="btn small danger" type="submit">
<svg class="ico" aria-hidden="true"><use href="#i-return"/></svg> Jetzt einspielen
</button>
<p class="muted small">Vorher wird automatisch eine Sicherheitskopie des
aktuellen Stands angelegt.</p>
</form>
</details>
<form method="post" action="<?= e(url('/admin/backups')) ?>"
data-confirm="Sicherung „<?= e($item['name']) ?>“ endgültig löschen?">
<?= csrf_field() ?>
<input type="hidden" name="action" value="delete">
<input type="hidden" name="name" value="<?= e_attr($item['name']) ?>">
<button class="btn small danger-ghost" type="submit">
<svg class="ico" aria-hidden="true"><use href="#i-trash"/></svg> Löschen
</button>
</form>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
<p class="muted small">Auf der Kommandozeile: <code>php tools/backup.php create</code> ·
Automatisch per Cron: <code>/cron/backup?token=…</code> mit <code>app.cron_token</code>.</p>
</section>

View file

@ -74,6 +74,7 @@ $navActive = static function (string $area) use ($path): string {
<symbol id="i-snow" viewBox="0 0 24 24"><path d="M12 2v20M4.5 6.8l15 10.4M19.5 6.8 4.5 17.2M12 6.4 9.6 4M12 6.4 14.4 4M12 17.6 9.6 20M12 17.6l2.4 2.4"/></symbol>
<symbol id="i-sun" viewBox="0 0 24 24"><circle cx="12" cy="12" r="4"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9 7 7M17 17l2.1 2.1M19.1 4.9 17 7M7 17l-2.1 2.1"/></symbol>
<symbol id="i-download" viewBox="0 0 24 24"><path d="M12 3v12M7 10l5 5 5-5"/><path d="M5 20h14"/></symbol>
<symbol id="i-database" viewBox="0 0 24 24"><ellipse cx="12" cy="5.5" rx="8" ry="3"/><path d="M4 5.5v13c0 1.7 3.6 3 8 3s8-1.3 8-3v-13"/><path d="M4 12c0 1.7 3.6 3 8 3s8-1.3 8-3"/></symbol>
</defs>
</svg>

View file

@ -24,6 +24,7 @@ $sections = [
'erinnerungen' => 'Erinnerungen & Push',
'abwesenheiten' => 'Abwesenheiten',
'fristen' => 'Storno, Kaution, Aufbewahrung',
'sicherungen' => 'Sicherungen (Admin)',
'verwaltung' => 'Verwaltung (Admin)',
];
$admin = !empty($isAdmin);
@ -45,7 +46,7 @@ $admin = !empty($isAdmin);
<nav class="legal-toc" aria-label="Inhalt der Anleitung">
<ol>
<?php foreach ($sections as $id => $title): ?>
<?php if ($id === 'verwaltung' && !$admin) { continue; } ?>
<?php if (!$admin && in_array($id, ['sicherungen', 'verwaltung'], true)) { continue; } ?>
<li><a href="#<?= e($id) ?>"><?= e($title) ?></a></li>
<?php endforeach; ?>
</ol>
@ -290,6 +291,37 @@ $admin = !empty($isAdmin);
(<code>app.document_retention_days</code>), Vertragstexte je Variante (<code>documents.delivery|pickup|chest</code>).</li>
</ul>
</section>
<section class="legal-section" id="sicherungen">
<h2>16. Sicherungen: Datenbank und Dateien (nur Administrator)</h2>
<p>Unter <strong>Verwaltung → Sicherungen</strong> sichert die App mit einem Klick die komplette Datenbank
<em>und</em> alle abgelegten Dateien (Mietverträge, Auftragsbestätigungen, Rechnungen, Unterschriften)
in einem Archiv. Dasselbe Archiv ist auch die Wiederherstellung.</p>
<ol class="manual-steps">
<li><strong>Sicherung erstellen:</strong> „Sicherung jetzt erstellen“ antippen – das Archiv erscheint
anschließend in der Liste. Das dauert je nach Datenmenge einige Sekunden.</li>
<li><strong>Aufbewahren:</strong> „Herunterladen“ und außerhalb des Servers ablegen (z. B. auf einem
Firmenlaufwerk). Die Archive enthalten Namen, Adressen und Telefonnummern von Kunden und gehören
deshalb nicht in eine offene Ablage oder in eine private Cloud.</li>
<li><strong>Einspielen:</strong> in der Liste „Einspielen…“ öffnen, <em>Datenbank</em> und/oder
<em>Dateien</em> anhaken und zur Bestätigung <code>WIEDERHERSTELLEN</code> eintippen. Vorher legt die
App automatisch eine Sicherheitskopie des aktuellen Stands an – ein versehentliches Einspielen lässt
sich damit zurücknehmen.</li>
<li><strong>Fremdes Archiv übernehmen:</strong> „Sicherung hochladen“, wenn ein früher heruntergeladenes
Archiv zurück auf den Server soll. Die Prüfsumme wird geprüft, fremde Dateien lehnt die App ab.</li>
<li><strong>Nach dem Einspielen prüfen:</strong> Kalender und eine Buchung öffnen, Unterlagen ansehen.
Meldet die App beim nächsten Klick „Bitte anmelden“, hat sich der Benutzerstand geändert – einfach
neu anmelden.</li>
</ol>
<ul>
<li><strong>Aufräumen:</strong> die letzten 14 Archive bleiben stehen (<code>app.backup_keep</code>, zur
Not auf einen anderen Wert setzen); ältere entfernt die App beim nächsten Erstellen.</li>
<li><strong>Ablage:</strong> <code>storage/backups</code> – nicht von außen erreichbar. Vor einem Restore
beiseitegelegte Dateien liegen dort als <code>files-vor-restore-…</code>.</li>
<li><strong>Automatisch:</strong> Ein Cronjob im Hosting-Panel kann die Sicherung täglich auslösen:
<code>/cron/backup?token=…</code> (Token = <code>app.cron_token</code>).</li>
</ul>
</section>
<?php endif; ?>
<p class="manual-foot">