Upload via GUI (267 Dateien)
This commit is contained in:
@@ -22,9 +22,18 @@ function backup_excluded_fragments(): array
|
||||
* @param string|null $rootDir Ordner, dessen Dateien gesichert werden (Standard: DeskHub-Hauptordner)
|
||||
* @param string|null $backupDir Zielordner (Standard: backups/ im Hauptordner)
|
||||
* @param PDO|null $pdo Datenbankverbindung (Standard: get_db())
|
||||
* @param array $options Optional: 'with_database' (bool, Standard true), 'with_files' (bool, Standard true),
|
||||
* 'only' (Liste von Pfaden relativ zum Hauptordner, nur diese Dateien/Ordner sichern),
|
||||
* 'exclude' (Liste von Pfaden relativ zum Hauptordner, die nicht gesichert werden),
|
||||
* 'verify' (bool, Standard true: Backup sofort automatisch auf Wiederherstellbarkeit prüfen und das Ergebnis merken)
|
||||
*/
|
||||
function create_backup(?string $rootDir = null, ?string $backupDir = null, ?PDO $pdo = null): array
|
||||
function create_backup(?string $rootDir = null, ?string $backupDir = null, ?PDO $pdo = null, array $options = []): array
|
||||
{
|
||||
$withDb = $options['with_database'] ?? true;
|
||||
$withFiles = $options['with_files'] ?? true;
|
||||
$norm = fn(string $p) => trim(str_replace(chr(92), '/', $p), '/');
|
||||
$onlyRel = array_values(array_filter(array_map($norm, (array) ($options['only'] ?? []))));
|
||||
$excludeRel = array_values(array_filter(array_map($norm, (array) ($options['exclude'] ?? []))));
|
||||
$rootDir = realpath($rootDir ?? __DIR__ . '/..');
|
||||
$backupDir = $backupDir ?? $rootDir . '/backups';
|
||||
$pdo = $pdo ?? get_db();
|
||||
@@ -93,7 +102,7 @@ Deny from all
|
||||
);
|
||||
|
||||
$files = [];
|
||||
foreach ($iter as $file) {
|
||||
foreach ($withFiles ? $iter : [] as $file) {
|
||||
if (!$file->isFile()) continue;
|
||||
$filePath = $file->getRealPath();
|
||||
$norm = str_replace('\\', '/', $filePath);
|
||||
@@ -106,7 +115,18 @@ Deny from all
|
||||
}
|
||||
if ($liveDb && ($filePath === $liveDb || $filePath === $liveDb . '-wal' || $filePath === $liveDb . '-shm' || $filePath === $liveDb . '-journal')) $skip = true;
|
||||
if ($skip) continue;
|
||||
$files[$filePath] = str_replace(chr(92), '/', substr($filePath, strlen($rootDir) + 1)); // im ZIP immer mit /
|
||||
$rel = str_replace(chr(92), '/', substr($filePath, strlen($rootDir) + 1)); // im ZIP immer mit /
|
||||
// Auswahl und Ausschlüsse (relativ zum Hauptordner, ganze Ordner oder einzelne Dateien)
|
||||
$under = fn(array $list) => (bool) array_filter($list, fn($p) => $rel === $p || str_starts_with($rel, $p . '/'));
|
||||
if ($onlyRel && !$under($onlyRel)) continue;
|
||||
if ($excludeRel && $under($excludeRel)) continue;
|
||||
$files[$filePath] = $rel;
|
||||
}
|
||||
|
||||
// Dateien, die der Webserver-Benutzer nicht lesen kann (fremde Besitzer/Rechte), würden das ganze Backup scheitern lassen: überspringen und melden
|
||||
$skipped = [];
|
||||
foreach ($files as $filePath => $relativePath) {
|
||||
if (!is_readable($filePath)) { $skipped[] = $relativePath; unset($files[$filePath]); }
|
||||
}
|
||||
|
||||
// Abzug erzeugen
|
||||
@@ -116,7 +136,7 @@ Deny from all
|
||||
$tableCount = 0;
|
||||
$dbError = null;
|
||||
|
||||
if ($driver === 'sqlite') {
|
||||
if ($withDb && $driver === 'sqlite') {
|
||||
$snapshot = tempnam(sys_get_temp_dir(), 'dhbk');
|
||||
@unlink($snapshot);
|
||||
try {
|
||||
@@ -130,7 +150,7 @@ Deny from all
|
||||
if ($sqliteSnapshot) {
|
||||
$tableCount = (int) $pdo->query("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")->fetchColumn();
|
||||
}
|
||||
} elseif ($driver === 'mysql') {
|
||||
} elseif ($withDb && $driver === 'mysql') {
|
||||
try {
|
||||
$dbName = (string) $pdo->query('SELECT DATABASE()')->fetchColumn();
|
||||
$dump = "-- DeskHub MySQL Backup\n-- Erstellt: " . date('Y-m-d H:i:s') . "\n-- Datenbank: " . $dbName . "\n\nSET FOREIGN_KEY_CHECKS=0;\n\n";
|
||||
@@ -175,7 +195,7 @@ Deny from all
|
||||
|
||||
$manifest = json_encode([
|
||||
'created' => date('Y-m-d H:i:s'), 'driver' => $driver, 'version' => defined('DESKHUB_VERSION') ? DESKHUB_VERSION : null,
|
||||
'database' => $sqliteSnapshot ? 'database_backup.sqlite' : $sqlFile, 'tables' => $tableCount, 'files' => count($files),
|
||||
'database' => $sqliteSnapshot ? 'database_backup.sqlite' : $sqlFile, 'tables' => $tableCount, 'files' => count($files), 'skipped' => array_slice($skipped, 0, 50),
|
||||
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
|
||||
|
||||
// ZIP erstellen – ZipArchive wenn verfügbar, sonst eigene Implementierung
|
||||
@@ -191,7 +211,32 @@ Deny from all
|
||||
if ($sqlDump && $sqlFile) $zip->addFromString($sqlFile, $sqlDump);
|
||||
if ($sqliteSnapshot) $zip->addFile($sqliteSnapshot, 'database_backup.sqlite');
|
||||
$zip->addFromString('backup_manifest.json', $manifest);
|
||||
$zip->close();
|
||||
$closed = @$zip->close();
|
||||
if (!$closed || !file_exists($backupPath)) {
|
||||
$zipReason = trim((string) $zip->getStatusString());
|
||||
// Zweiter Versuch: nur Dateien, die sich wirklich öffnen lassen
|
||||
@unlink($backupPath);
|
||||
$retry = new ZipArchive();
|
||||
if ($retry->open($backupPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
|
||||
foreach ($files as $filePath => $relativePath) {
|
||||
$h = @fopen($filePath, 'rb');
|
||||
if ($h === false) { $skipped[] = $relativePath; continue; }
|
||||
fclose($h);
|
||||
$retry->addFile($filePath, $relativePath);
|
||||
}
|
||||
if ($sqlDump && $sqlFile) $retry->addFromString($sqlFile, $sqlDump);
|
||||
if ($sqliteSnapshot) $retry->addFile($sqliteSnapshot, 'database_backup.sqlite');
|
||||
$retry->addFromString('backup_manifest.json', json_encode(['created' => date('Y-m-d H:i:s'), 'driver' => $driver, 'version' => defined('DESKHUB_VERSION') ? DESKHUB_VERSION : null, 'database' => $sqliteSnapshot ? 'database_backup.sqlite' : $sqlFile, 'tables' => $tableCount, 'files' => count($files) - count($skipped), 'skipped' => array_slice($skipped, 0, 50)], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
|
||||
@$retry->close();
|
||||
if (!file_exists($backupPath)) $zipReason = trim($zipReason . ' ' . $retry->getStatusString());
|
||||
}
|
||||
if (!file_exists($backupPath)) {
|
||||
if ($sqliteSnapshot) @unlink($sqliteSnapshot);
|
||||
$free = @disk_free_space($backupDir);
|
||||
return ['ok' => false, 'error' => 'Backup-Datei wurde nicht erstellt' . ($zipReason !== '' ? ' (' . $zipReason . ')' : '')
|
||||
. '. Prüfen: Ist der Ordner „' . basename($backupDir) . '“ beschreibbar' . ($free !== false ? ' und ist genug Speicherplatz frei (aktuell ' . round($free / 1048576) . ' MB)' : '') . '?'];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Eigene ZIP-Implementierung (kein php_zip nötig)
|
||||
$zip = new SimpleZip($backupPath);
|
||||
@@ -213,11 +258,21 @@ Deny from all
|
||||
return ['ok' => false, 'error' => 'Backup-Datei wurde nicht erstellt.'];
|
||||
}
|
||||
|
||||
// Automatische Prüfung: Ein Backup, das sich nicht wiederherstellen lässt, ist wertlos. Das Ergebnis steht in der Liste und im Hinweis im System.
|
||||
// (Backups ohne Datenbank, zum Beispiel reine Datei-Sicherungen von Plugins, lassen sich so nicht prüfen und werden hier ausgelassen.)
|
||||
$verify = null;
|
||||
if ($withDb && ($options['verify'] ?? true)) {
|
||||
if (!function_exists('backup_verify_and_record')) require_once __DIR__ . '/backup_restore.php';
|
||||
$verify = backup_verify_and_record($backupPath);
|
||||
}
|
||||
|
||||
return [
|
||||
'ok' => true,
|
||||
'filename' => $backupName,
|
||||
'path' => $backupPath,
|
||||
'files' => count($files),
|
||||
'skipped' => $skipped,
|
||||
'verify' => $verify,
|
||||
'size' => round(filesize($backupPath) / 1024 / 1024, 2),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1,298 +1,343 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Backups prüfen und wiederherstellen (Gegenstück zu create_backup in includes/backup.php).
|
||||
*
|
||||
* backup_verify($zip) prüft, ob ein Backup vollständig und lesbar ist, ohne etwas zu verändern
|
||||
* backup_restore($pdo, $zip, …) stellt Datenbank und (wählbar) Dateien wieder her; vorher wird ein Sicherheits-Backup erstellt
|
||||
*
|
||||
* Programmdateien (includes/, staff/, config/ …) werden nie überschrieben: Dafür gibt es das System-Update. Wiederhergestellt werden
|
||||
* die Datenbank sowie die Ordner uploads/, plugins/ und app_downloads/.
|
||||
*/
|
||||
require_once __DIR__ . '/backup.php';
|
||||
|
||||
/** Ordner im Backup, die beim Wiederherstellen zurückgespielt werden dürfen. */
|
||||
function backup_restorable_dirs(): array
|
||||
{
|
||||
return ['uploads' => 'Hochgeladene Dateien (Anhänge)', 'plugins' => 'Plugins', 'app_downloads' => 'App-Dateien'];
|
||||
}
|
||||
|
||||
/** Ist der Eintragsname im ZIP unbedenklich (keine .., keine absoluten Pfade)? */
|
||||
function backup_entry_name_ok(string $name): bool
|
||||
{
|
||||
$n = str_replace('\\', '/', $name);
|
||||
return $n !== '' && $n[0] !== '/' && !str_contains($n, "\0") && !preg_match('#(^|/)\.\.(/|$)#', $n) && !preg_match('#^[A-Za-z]:#', $n);
|
||||
}
|
||||
|
||||
/** Zerlegt einen SQL-Dump in Anweisungen (Zeilenweise, mit Beachtung von Zeichenketten). */
|
||||
function backup_sql_statements(string $file): Generator
|
||||
{
|
||||
$fh = fopen($file, 'rb');
|
||||
$buf = '';
|
||||
$inQuote = false;
|
||||
while (($line = fgets($fh)) !== false) {
|
||||
if (!$inQuote && $buf === '' && (trim($line) === '' || str_starts_with($line, '--'))) continue;
|
||||
$buf .= $line;
|
||||
// Anführungszeichen-Zustand über die Zeile fortschreiben
|
||||
$n = strlen($line);
|
||||
for ($i = 0; $i < $n; $i++) {
|
||||
$c = $line[$i];
|
||||
if ($inQuote) {
|
||||
if ($c === '\\') { $i++; continue; }
|
||||
if ($c === "'") $inQuote = false;
|
||||
} elseif ($c === "'") {
|
||||
$inQuote = true;
|
||||
}
|
||||
}
|
||||
if (!$inQuote && substr(rtrim($line), -1) === ';') {
|
||||
yield trim($buf);
|
||||
$buf = '';
|
||||
}
|
||||
}
|
||||
if (trim($buf) !== '') yield trim($buf);
|
||||
fclose($fh);
|
||||
}
|
||||
|
||||
/** Entpackt einen Eintrag in eine temporäre Datei (Streaming, auch für große Dateien). */
|
||||
function backup_extract_entry(ZipArchive $zip, string $name): ?string
|
||||
{
|
||||
$in = $zip->getStream($name);
|
||||
if (!$in) return null;
|
||||
$tmp = tempnam(sys_get_temp_dir(), 'dhrs');
|
||||
$out = fopen($tmp, 'wb');
|
||||
stream_copy_to_stream($in, $out);
|
||||
fclose($in);
|
||||
fclose($out);
|
||||
return $tmp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft ein Backup, ohne etwas zu verändern.
|
||||
*
|
||||
* @return array{ok:bool, errors:string[], warnings:string[], info:array}
|
||||
*/
|
||||
function backup_verify(string $zipPath): array
|
||||
{
|
||||
$r = ['ok' => false, 'errors' => [], 'warnings' => [], 'info' => []];
|
||||
if (!class_exists('ZipArchive')) { $r['errors'][] = 'Die PHP-Erweiterung zip fehlt.'; return $r; }
|
||||
if (!is_file($zipPath) || filesize($zipPath) < 100) { $r['errors'][] = 'Die Backup-Datei fehlt oder ist leer.'; return $r; }
|
||||
$zip = new ZipArchive();
|
||||
if ($zip->open($zipPath, ZipArchive::CHECKCONS) !== true) { $r['errors'][] = 'Die ZIP-Datei ist beschädigt oder unvollständig.'; return $r; }
|
||||
|
||||
$names = [];
|
||||
for ($i = 0; $i < $zip->numFiles; $i++) {
|
||||
$n = (string) $zip->getNameIndex($i);
|
||||
if (!backup_entry_name_ok($n)) { $zip->close(); $r['errors'][] = "Unzulässiger Pfad im Backup: {$n}"; return $r; }
|
||||
$names[$n] = true;
|
||||
}
|
||||
$r['info']['files'] = count($names);
|
||||
|
||||
$manifest = null;
|
||||
if (isset($names['backup_manifest.json'])) {
|
||||
$manifest = json_decode((string) $zip->getFromName('backup_manifest.json'), true);
|
||||
if (!is_array($manifest)) { $r['errors'][] = 'Das Manifest im Backup ist unlesbar.'; $manifest = null; }
|
||||
}
|
||||
$r['info']['created'] = $manifest['created'] ?? null;
|
||||
$r['info']['version'] = $manifest['version'] ?? null;
|
||||
|
||||
$key = ['tickets', 'users', 'staff', 'settings'];
|
||||
if (isset($names['database_backup.sqlite'])) {
|
||||
$r['info']['driver'] = 'sqlite';
|
||||
$tmp = backup_extract_entry($zip, 'database_backup.sqlite');
|
||||
if (!$tmp || (string) @file_get_contents($tmp, false, null, 0, 15) !== 'SQLite format 3') {
|
||||
$r['errors'][] = 'Der Datenbank-Abzug im Backup ist keine gültige SQLite-Datenbank.';
|
||||
} else {
|
||||
try {
|
||||
$db = new PDO('sqlite:' . $tmp);
|
||||
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
$integrity = $db->query('PRAGMA integrity_check')->fetchColumn();
|
||||
if ($integrity !== 'ok') $r['errors'][] = 'Die Datenbank im Backup ist beschädigt: ' . $integrity;
|
||||
$tables = $db->query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")->fetchAll(PDO::FETCH_COLUMN);
|
||||
$r['info']['tables'] = count($tables);
|
||||
foreach ($key as $t) if (!in_array($t, $tables, true)) $r['errors'][] = "In der Datenbank des Backups fehlt die Tabelle \"{$t}\".";
|
||||
foreach (['tickets', 'users', 'staff'] as $t) if (in_array($t, $tables, true)) $r['info'][$t] = (int) $db->query("SELECT COUNT(*) FROM {$t}")->fetchColumn();
|
||||
} catch (Throwable $e) {
|
||||
$r['errors'][] = 'Die Datenbank im Backup lässt sich nicht lesen: ' . $e->getMessage();
|
||||
}
|
||||
$db = null;
|
||||
}
|
||||
if ($tmp) @unlink($tmp);
|
||||
} elseif (isset($names['database_backup.sql'])) {
|
||||
$r['info']['driver'] = 'mysql';
|
||||
$tmp = backup_extract_entry($zip, 'database_backup.sql');
|
||||
if (!$tmp) {
|
||||
$r['errors'][] = 'Der Datenbank-Abzug im Backup ist nicht lesbar.';
|
||||
} else {
|
||||
$creates = [];
|
||||
$count = 0;
|
||||
$last = '';
|
||||
foreach (backup_sql_statements($tmp) as $stmt) {
|
||||
$count++;
|
||||
$last = $stmt;
|
||||
if (preg_match('/^CREATE TABLE `?([A-Za-z0-9_]+)`?/i', $stmt, $m)) $creates[$m[1]] = true;
|
||||
}
|
||||
$r['info']['tables'] = count($creates);
|
||||
$r['info']['statements'] = $count;
|
||||
foreach ($key as $t) if (!isset($creates[$t])) $r['errors'][] = "Im Datenbank-Abzug fehlt die Tabelle \"{$t}\".";
|
||||
if (stripos($last, 'FOREIGN_KEY_CHECKS=1') === false) $r['errors'][] = 'Der Datenbank-Abzug ist unvollständig (das Ende fehlt).';
|
||||
@unlink($tmp);
|
||||
}
|
||||
} elseif (isset($names['database/deskhub.sqlite'])) {
|
||||
// Ältere Backups enthalten die laufende SQLite-Datei als Kopie
|
||||
$r['info']['driver'] = 'sqlite';
|
||||
$r['warnings'][] = 'Dieses ältere Backup enthält eine Kopie der laufenden Datenbankdatei. Sie lässt sich nicht garantiert fehlerfrei wiederherstellen.';
|
||||
$tmp = backup_extract_entry($zip, 'database/deskhub.sqlite');
|
||||
if (!$tmp || (string) @file_get_contents($tmp, false, null, 0, 15) !== 'SQLite format 3') $r['errors'][] = 'Die Datenbankkopie im Backup ist keine gültige SQLite-Datenbank.';
|
||||
else $r['errors'][] = 'Backups im alten Format können nicht automatisch wiederhergestellt werden. Bitte ein neues Backup erstellen.';
|
||||
if ($tmp) @unlink($tmp);
|
||||
} else {
|
||||
$r['errors'][] = 'Im Backup fehlt der Datenbank-Abzug.';
|
||||
}
|
||||
$zip->close();
|
||||
$r['ok'] = !$r['errors'];
|
||||
return $r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stellt ein Backup wieder her.
|
||||
*
|
||||
* Optionen: database (Standard true), dirs (Liste aus backup_restorable_dirs(), Standard alle),
|
||||
* root (Zielordner für Dateien), backup_dir (Zielordner des Sicherheits-Backups), safety_backup (Standard true).
|
||||
*
|
||||
* @return array{ok:bool, error?:string, tables?:int, rows?:int, files?:int, safety?:string, notes?:string[]}
|
||||
*/
|
||||
function backup_restore(PDO $pdo, string $zipPath, array $options = []): array
|
||||
{
|
||||
@set_time_limit(600);
|
||||
$check = backup_verify($zipPath);
|
||||
if (!$check['ok']) return ['ok' => false, 'error' => 'Das Backup ist nicht wiederherstellbar: ' . implode(' ', $check['errors'])];
|
||||
$driver = $pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
|
||||
if (($check['info']['driver'] ?? '') !== $driver) {
|
||||
return ['ok' => false, 'error' => 'Das Backup stammt aus einer ' . strtoupper((string) $check['info']['driver']) . '-Datenbank, dieses System nutzt ' . strtoupper($driver) . '. Eine Wiederherstellung ist nur auf demselben Datenbanktyp möglich.'];
|
||||
}
|
||||
$root = realpath($options['root'] ?? __DIR__ . '/..');
|
||||
$result = ['ok' => true, 'tables' => 0, 'rows' => 0, 'files' => 0, 'notes' => []];
|
||||
|
||||
if (($options['safety_backup'] ?? true)) {
|
||||
$safety = create_backup($root, $options['backup_dir'] ?? null, $pdo);
|
||||
if (!$safety['ok']) return ['ok' => false, 'error' => 'Das Sicherheits-Backup vor der Wiederherstellung ist fehlgeschlagen, es wurde nichts verändert: ' . $safety['error']];
|
||||
$result['safety'] = $safety['filename'];
|
||||
}
|
||||
$zip = new ZipArchive();
|
||||
$zip->open($zipPath);
|
||||
|
||||
try {
|
||||
if ($options['database'] ?? true) {
|
||||
$db = $driver === 'sqlite' ? backup_restore_sqlite($pdo, $zip) : backup_restore_mysql($pdo, $zip);
|
||||
$result['tables'] = $db['tables'];
|
||||
$result['rows'] = $db['rows'];
|
||||
$result['notes'] = array_merge($result['notes'], $db['notes']);
|
||||
}
|
||||
$dirs = array_values(array_intersect(array_keys(backup_restorable_dirs()), (array) ($options['dirs'] ?? array_keys(backup_restorable_dirs()))));
|
||||
for ($i = 0; $i < $zip->numFiles; $i++) {
|
||||
$name = str_replace('\\', '/', (string) $zip->getNameIndex($i));
|
||||
if (substr($name, -1) === '/' || !backup_entry_name_ok($name)) continue;
|
||||
$top = explode('/', $name, 2)[0];
|
||||
if (!in_array($top, $dirs, true)) continue;
|
||||
$dest = $root . '/' . $name;
|
||||
if (!is_dir(dirname($dest))) @mkdir(dirname($dest), 0755, true);
|
||||
$in = $zip->getStream($zip->getNameIndex($i));
|
||||
if (!$in) continue;
|
||||
$out = fopen($dest, 'wb');
|
||||
if (!$out) { fclose($in); $result['notes'][] = "Datei nicht beschreibbar: {$name}"; continue; }
|
||||
stream_copy_to_stream($in, $out);
|
||||
fclose($in);
|
||||
fclose($out);
|
||||
$result['files']++;
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
$zip->close();
|
||||
return ['ok' => false, 'error' => 'Wiederherstellung abgebrochen: ' . $e->getMessage() . (isset($result['safety']) ? ' Der Stand von vorher steht im Sicherheits-Backup ' . $result['safety'] . '.' : '')];
|
||||
}
|
||||
$zip->close();
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** SQLite: Inhalte aller Tabellen des Backups in die laufende Datenbank übernehmen (Spalten, die es in beiden gibt). */
|
||||
function backup_restore_sqlite(PDO $pdo, ZipArchive $zip): array
|
||||
{
|
||||
$tmp = backup_extract_entry($zip, 'database_backup.sqlite');
|
||||
if (!$tmp) throw new RuntimeException('Der Datenbank-Abzug konnte nicht entpackt werden.');
|
||||
$out = ['tables' => 0, 'rows' => 0, 'notes' => []];
|
||||
$pdo->exec('PRAGMA foreign_keys = OFF'); // außerhalb einer Transaktion
|
||||
try {
|
||||
$pdo->exec('ATTACH DATABASE ' . $pdo->quote($tmp) . ' AS bk');
|
||||
$pdo->beginTransaction();
|
||||
$bkTables = $pdo->query("SELECT name FROM bk.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")->fetchAll(PDO::FETCH_COLUMN);
|
||||
$liveTables = $pdo->query("SELECT name FROM main.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")->fetchAll(PDO::FETCH_COLUMN);
|
||||
$cols = fn(string $schema, string $t) => array_column($pdo->query("PRAGMA {$schema}.table_info(\"{$t}\")")->fetchAll(PDO::FETCH_ASSOC), 'name');
|
||||
$missing = [];
|
||||
foreach ($liveTables as $t) {
|
||||
if (!in_array($t, $bkTables, true)) { $missing[] = $t; continue; }
|
||||
$common = array_values(array_intersect($cols('main', $t), $cols('bk', $t)));
|
||||
$pdo->exec("DELETE FROM main.\"{$t}\"");
|
||||
if ($common) {
|
||||
$list = '"' . implode('","', $common) . '"';
|
||||
$pdo->exec("INSERT INTO main.\"{$t}\" ({$list}) SELECT {$list} FROM bk.\"{$t}\"");
|
||||
}
|
||||
$out['tables']++;
|
||||
$out['rows'] += (int) $pdo->query("SELECT COUNT(*) FROM main.\"{$t}\"")->fetchColumn();
|
||||
}
|
||||
// Zähler der automatischen Nummern übernehmen, damit neue Datensätze nicht alte Nummern wiederverwenden
|
||||
$hasSeq = (bool) $pdo->query("SELECT 1 FROM bk.sqlite_master WHERE name = 'sqlite_sequence'")->fetchColumn();
|
||||
if ($hasSeq) {
|
||||
$pdo->exec('DELETE FROM main.sqlite_sequence');
|
||||
$pdo->exec('INSERT INTO main.sqlite_sequence (name, seq) SELECT name, seq FROM bk.sqlite_sequence');
|
||||
}
|
||||
$pdo->commit();
|
||||
if ($missing) $out['notes'][] = 'Tabellen, die es im Backup noch nicht gab, blieben unverändert: ' . implode(', ', $missing) . '. Danach unter System-Update „Datenbank aktualisieren“ ausführen.';
|
||||
} catch (Throwable $e) {
|
||||
if ($pdo->inTransaction()) $pdo->rollBack();
|
||||
throw $e;
|
||||
} finally {
|
||||
try { $pdo->exec('DETACH DATABASE bk'); } catch (Throwable $e) {}
|
||||
$pdo->exec('PRAGMA foreign_keys = ON');
|
||||
@unlink($tmp);
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** MySQL: den SQL-Abzug Anweisung für Anweisung einspielen. */
|
||||
function backup_restore_mysql(PDO $pdo, ZipArchive $zip): array
|
||||
{
|
||||
$tmp = backup_extract_entry($zip, 'database_backup.sql');
|
||||
if (!$tmp) throw new RuntimeException('Der Datenbank-Abzug konnte nicht entpackt werden.');
|
||||
$out = ['tables' => 0, 'rows' => 0, 'notes' => []];
|
||||
try {
|
||||
foreach (backup_sql_statements($tmp) as $stmt) {
|
||||
$pdo->exec($stmt);
|
||||
if (preg_match('/^CREATE TABLE/i', $stmt)) $out['tables']++;
|
||||
if (preg_match('/^INSERT INTO/i', $stmt)) $out['rows'] += max(1, substr_count($stmt, "),\n(") + 1);
|
||||
}
|
||||
} finally {
|
||||
@unlink($tmp);
|
||||
}
|
||||
$out['notes'][] = 'Danach unter System-Update „Datenbank aktualisieren“ ausführen, falls das Backup von einer älteren Version stammt.';
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** Pfad eines Backups im backups-Ordner anhand des Dateinamens (nur echte Backups, sonst null). */
|
||||
function backup_path_for(string $filename, ?string $backupDir = null): ?string
|
||||
{
|
||||
$dir = realpath($backupDir ?? __DIR__ . '/../backups');
|
||||
$file = basename($filename);
|
||||
if (!$dir || !preg_match('/^backup_[\d\-_a-f]+\.zip$/', $file) || !is_file($dir . '/' . $file)) return null;
|
||||
return $dir . '/' . $file;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft ein Backup und merkt sich das Ergebnis (für die Anzeige und den Hinweis im System). Ein Backup, das sich nicht
|
||||
* wiederherstellen lässt, ist wertlos: Das soll auffallen, bevor man es braucht.
|
||||
*/
|
||||
function backup_verify_and_record(string $zipPath): array
|
||||
{
|
||||
$r = backup_verify($zipPath);
|
||||
set_setting('backup_last_check', json_encode(['file' => basename($zipPath), 'at' => date('Y-m-d H:i:s'), 'ok' => $r['ok'], 'errors' => $r['errors'], 'info' => $r['info']], JSON_UNESCAPED_UNICODE));
|
||||
return $r;
|
||||
}
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Backups prüfen und wiederherstellen (Gegenstück zu create_backup in includes/backup.php).
|
||||
*
|
||||
* backup_verify($zip) prüft, ob ein Backup vollständig und lesbar ist, ohne etwas zu verändern
|
||||
* backup_restore($pdo, $zip, …) stellt Datenbank und (wählbar) Dateien wieder her; vorher wird ein Sicherheits-Backup erstellt
|
||||
*
|
||||
* Programmdateien (includes/, staff/, config/ …) werden nie überschrieben: Dafür gibt es das System-Update. Wiederhergestellt werden
|
||||
* die Datenbank sowie die Ordner uploads/, plugins/ und app_downloads/.
|
||||
*/
|
||||
require_once __DIR__ . '/backup.php';
|
||||
|
||||
/** Ordner im Backup, die beim Wiederherstellen zurückgespielt werden dürfen. */
|
||||
function backup_restorable_dirs(): array
|
||||
{
|
||||
return ['uploads' => 'Hochgeladene Dateien (Anhänge)', 'plugins' => 'Plugins', 'app_downloads' => 'App-Dateien'];
|
||||
}
|
||||
|
||||
/** Ist der Eintragsname im ZIP unbedenklich (keine .., keine absoluten Pfade)? */
|
||||
function backup_entry_name_ok(string $name): bool
|
||||
{
|
||||
$n = str_replace('\\', '/', $name);
|
||||
return $n !== '' && $n[0] !== '/' && !str_contains($n, "\0") && !preg_match('#(^|/)\.\.(/|$)#', $n) && !preg_match('#^[A-Za-z]:#', $n);
|
||||
}
|
||||
|
||||
/** Zerlegt einen SQL-Dump in Anweisungen (Zeilenweise, mit Beachtung von Zeichenketten). */
|
||||
function backup_sql_statements(string $file): Generator
|
||||
{
|
||||
$fh = fopen($file, 'rb');
|
||||
$buf = '';
|
||||
$inQuote = false;
|
||||
while (($line = fgets($fh)) !== false) {
|
||||
if (!$inQuote && $buf === '' && (trim($line) === '' || str_starts_with($line, '--'))) continue;
|
||||
$buf .= $line;
|
||||
// Anführungszeichen-Zustand über die Zeile fortschreiben
|
||||
$n = strlen($line);
|
||||
for ($i = 0; $i < $n; $i++) {
|
||||
$c = $line[$i];
|
||||
if ($inQuote) {
|
||||
if ($c === '\\') { $i++; continue; }
|
||||
if ($c === "'") $inQuote = false;
|
||||
} elseif ($c === "'") {
|
||||
$inQuote = true;
|
||||
}
|
||||
}
|
||||
if (!$inQuote && substr(rtrim($line), -1) === ';') {
|
||||
yield trim($buf);
|
||||
$buf = '';
|
||||
}
|
||||
}
|
||||
if (trim($buf) !== '') yield trim($buf);
|
||||
fclose($fh);
|
||||
}
|
||||
|
||||
/** Entpackt einen Eintrag in eine temporäre Datei (Streaming, auch für große Dateien). */
|
||||
function backup_extract_entry(ZipArchive $zip, string $name): ?string
|
||||
{
|
||||
$in = $zip->getStream($name);
|
||||
if (!$in) return null;
|
||||
$tmp = tempnam(sys_get_temp_dir(), 'dhrs');
|
||||
$out = fopen($tmp, 'wb');
|
||||
stream_copy_to_stream($in, $out);
|
||||
fclose($in);
|
||||
fclose($out);
|
||||
return $tmp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft ein Backup, ohne etwas zu verändern.
|
||||
*
|
||||
* @return array{ok:bool, errors:string[], warnings:string[], info:array}
|
||||
*/
|
||||
function backup_verify(string $zipPath): array
|
||||
{
|
||||
$r = ['ok' => false, 'errors' => [], 'warnings' => [], 'info' => []];
|
||||
if (!class_exists('ZipArchive')) { $r['errors'][] = 'Die PHP-Erweiterung zip fehlt.'; return $r; }
|
||||
if (!is_file($zipPath) || filesize($zipPath) < 100) { $r['errors'][] = 'Die Backup-Datei fehlt oder ist leer.'; return $r; }
|
||||
$zip = new ZipArchive();
|
||||
if ($zip->open($zipPath, ZipArchive::CHECKCONS) !== true) { $r['errors'][] = 'Die ZIP-Datei ist beschädigt oder unvollständig.'; return $r; }
|
||||
|
||||
$names = [];
|
||||
for ($i = 0; $i < $zip->numFiles; $i++) {
|
||||
$n = (string) $zip->getNameIndex($i);
|
||||
if (!backup_entry_name_ok($n)) { $zip->close(); $r['errors'][] = "Unzulässiger Pfad im Backup: {$n}"; return $r; }
|
||||
$names[$n] = true;
|
||||
}
|
||||
$r['info']['files'] = count($names);
|
||||
|
||||
$manifest = null;
|
||||
if (isset($names['backup_manifest.json'])) {
|
||||
$manifest = json_decode((string) $zip->getFromName('backup_manifest.json'), true);
|
||||
if (!is_array($manifest)) { $r['errors'][] = 'Das Manifest im Backup ist unlesbar.'; $manifest = null; }
|
||||
}
|
||||
$r['info']['created'] = $manifest['created'] ?? null;
|
||||
$r['info']['version'] = $manifest['version'] ?? null;
|
||||
|
||||
$key = ['tickets', 'users', 'staff', 'settings'];
|
||||
if (isset($names['database_backup.sqlite'])) {
|
||||
$r['info']['driver'] = 'sqlite';
|
||||
$tmp = backup_extract_entry($zip, 'database_backup.sqlite');
|
||||
if (!$tmp || (string) @file_get_contents($tmp, false, null, 0, 15) !== 'SQLite format 3') {
|
||||
$r['errors'][] = 'Der Datenbank-Abzug im Backup ist keine gültige SQLite-Datenbank.';
|
||||
} else {
|
||||
try {
|
||||
$db = new PDO('sqlite:' . $tmp);
|
||||
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
$integrity = $db->query('PRAGMA integrity_check')->fetchColumn();
|
||||
if ($integrity !== 'ok') $r['errors'][] = 'Die Datenbank im Backup ist beschädigt: ' . $integrity;
|
||||
$tables = $db->query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")->fetchAll(PDO::FETCH_COLUMN);
|
||||
$r['info']['tables'] = count($tables);
|
||||
foreach ($key as $t) if (!in_array($t, $tables, true)) $r['errors'][] = "In der Datenbank des Backups fehlt die Tabelle \"{$t}\".";
|
||||
foreach (['tickets', 'users', 'staff'] as $t) if (in_array($t, $tables, true)) $r['info'][$t] = (int) $db->query("SELECT COUNT(*) FROM {$t}")->fetchColumn();
|
||||
} catch (Throwable $e) {
|
||||
$r['errors'][] = 'Die Datenbank im Backup lässt sich nicht lesen: ' . $e->getMessage();
|
||||
}
|
||||
$db = null;
|
||||
}
|
||||
if ($tmp) @unlink($tmp);
|
||||
} elseif (isset($names['database_backup.sql'])) {
|
||||
$r['info']['driver'] = 'mysql';
|
||||
$tmp = backup_extract_entry($zip, 'database_backup.sql');
|
||||
if (!$tmp) {
|
||||
$r['errors'][] = 'Der Datenbank-Abzug im Backup ist nicht lesbar.';
|
||||
} else {
|
||||
$creates = [];
|
||||
$count = 0;
|
||||
$last = '';
|
||||
foreach (backup_sql_statements($tmp) as $stmt) {
|
||||
$count++;
|
||||
$last = $stmt;
|
||||
if (preg_match('/^CREATE TABLE `?([A-Za-z0-9_]+)`?/i', $stmt, $m)) $creates[$m[1]] = true;
|
||||
}
|
||||
$r['info']['tables'] = count($creates);
|
||||
$r['info']['statements'] = $count;
|
||||
foreach ($key as $t) if (!isset($creates[$t])) $r['errors'][] = "Im Datenbank-Abzug fehlt die Tabelle \"{$t}\".";
|
||||
if (stripos($last, 'FOREIGN_KEY_CHECKS=1') === false) $r['errors'][] = 'Der Datenbank-Abzug ist unvollständig (das Ende fehlt).';
|
||||
@unlink($tmp);
|
||||
}
|
||||
} elseif (isset($names['database/deskhub.sqlite'])) {
|
||||
// Ältere Backups enthalten die laufende SQLite-Datei als Kopie
|
||||
$r['info']['driver'] = 'sqlite';
|
||||
$r['warnings'][] = 'Dieses ältere Backup enthält eine Kopie der laufenden Datenbankdatei. Sie lässt sich nicht garantiert fehlerfrei wiederherstellen.';
|
||||
$tmp = backup_extract_entry($zip, 'database/deskhub.sqlite');
|
||||
if (!$tmp || (string) @file_get_contents($tmp, false, null, 0, 15) !== 'SQLite format 3') $r['errors'][] = 'Die Datenbankkopie im Backup ist keine gültige SQLite-Datenbank.';
|
||||
else $r['errors'][] = 'Backups im alten Format können nicht automatisch wiederhergestellt werden. Bitte ein neues Backup erstellen.';
|
||||
if ($tmp) @unlink($tmp);
|
||||
} else {
|
||||
$r['errors'][] = 'Im Backup fehlt der Datenbank-Abzug.';
|
||||
}
|
||||
$zip->close();
|
||||
$r['ok'] = !$r['errors'];
|
||||
return $r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stellt ein Backup wieder her.
|
||||
*
|
||||
* Optionen: database (Standard true), dirs (Liste aus backup_restorable_dirs(), Standard alle),
|
||||
* root (Zielordner für Dateien), backup_dir (Zielordner des Sicherheits-Backups), safety_backup (Standard true).
|
||||
*
|
||||
* @return array{ok:bool, error?:string, tables?:int, rows?:int, files?:int, safety?:string, notes?:string[]}
|
||||
*/
|
||||
function backup_restore(PDO $pdo, string $zipPath, array $options = []): array
|
||||
{
|
||||
@set_time_limit(600);
|
||||
$check = backup_verify($zipPath);
|
||||
if (!$check['ok']) return ['ok' => false, 'error' => 'Das Backup ist nicht wiederherstellbar: ' . implode(' ', $check['errors'])];
|
||||
$driver = $pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
|
||||
if (($check['info']['driver'] ?? '') !== $driver) {
|
||||
return ['ok' => false, 'error' => 'Das Backup stammt aus einer ' . strtoupper((string) $check['info']['driver']) . '-Datenbank, dieses System nutzt ' . strtoupper($driver) . '. Eine Wiederherstellung ist nur auf demselben Datenbanktyp möglich.'];
|
||||
}
|
||||
$root = realpath($options['root'] ?? __DIR__ . '/..');
|
||||
$result = ['ok' => true, 'tables' => 0, 'rows' => 0, 'files' => 0, 'notes' => []];
|
||||
|
||||
if (($options['safety_backup'] ?? true)) {
|
||||
$safety = create_backup($root, $options['backup_dir'] ?? null, $pdo);
|
||||
if (!$safety['ok']) return ['ok' => false, 'error' => 'Das Sicherheits-Backup vor der Wiederherstellung ist fehlgeschlagen, es wurde nichts verändert: ' . $safety['error']];
|
||||
$result['safety'] = $safety['filename'];
|
||||
}
|
||||
$zip = new ZipArchive();
|
||||
$zip->open($zipPath);
|
||||
|
||||
try {
|
||||
if ($options['database'] ?? true) {
|
||||
$db = $driver === 'sqlite' ? backup_restore_sqlite($pdo, $zip) : backup_restore_mysql($pdo, $zip);
|
||||
$result['tables'] = $db['tables'];
|
||||
$result['rows'] = $db['rows'];
|
||||
$result['notes'] = array_merge($result['notes'], $db['notes']);
|
||||
}
|
||||
$dirs = array_values(array_intersect(array_keys(backup_restorable_dirs()), (array) ($options['dirs'] ?? array_keys(backup_restorable_dirs()))));
|
||||
for ($i = 0; $i < $zip->numFiles; $i++) {
|
||||
$name = str_replace('\\', '/', (string) $zip->getNameIndex($i));
|
||||
if (substr($name, -1) === '/' || !backup_entry_name_ok($name)) continue;
|
||||
$top = explode('/', $name, 2)[0];
|
||||
if (!in_array($top, $dirs, true)) continue;
|
||||
$dest = $root . '/' . $name;
|
||||
if (!is_dir(dirname($dest))) @mkdir(dirname($dest), 0755, true);
|
||||
$in = $zip->getStream($zip->getNameIndex($i));
|
||||
if (!$in) continue;
|
||||
$out = fopen($dest, 'wb');
|
||||
if (!$out) { fclose($in); $result['notes'][] = "Datei nicht beschreibbar: {$name}"; continue; }
|
||||
stream_copy_to_stream($in, $out);
|
||||
fclose($in);
|
||||
fclose($out);
|
||||
$result['files']++;
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
$zip->close();
|
||||
return ['ok' => false, 'error' => 'Wiederherstellung abgebrochen: ' . $e->getMessage() . (isset($result['safety']) ? ' Der Stand von vorher steht im Sicherheits-Backup ' . $result['safety'] . '.' : '')];
|
||||
}
|
||||
$zip->close();
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** SQLite: Inhalte aller Tabellen des Backups in die laufende Datenbank übernehmen (Spalten, die es in beiden gibt). */
|
||||
function backup_restore_sqlite(PDO $pdo, ZipArchive $zip): array
|
||||
{
|
||||
$tmp = backup_extract_entry($zip, 'database_backup.sqlite');
|
||||
if (!$tmp) throw new RuntimeException('Der Datenbank-Abzug konnte nicht entpackt werden.');
|
||||
$out = ['tables' => 0, 'rows' => 0, 'notes' => []];
|
||||
$pdo->exec('PRAGMA foreign_keys = OFF'); // außerhalb einer Transaktion
|
||||
try {
|
||||
$pdo->exec('ATTACH DATABASE ' . $pdo->quote($tmp) . ' AS bk');
|
||||
$pdo->beginTransaction();
|
||||
$bkTables = $pdo->query("SELECT name FROM bk.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")->fetchAll(PDO::FETCH_COLUMN);
|
||||
$liveTables = $pdo->query("SELECT name FROM main.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")->fetchAll(PDO::FETCH_COLUMN);
|
||||
$cols = fn(string $schema, string $t) => array_column($pdo->query("PRAGMA {$schema}.table_info(\"{$t}\")")->fetchAll(PDO::FETCH_ASSOC), 'name');
|
||||
$missing = [];
|
||||
foreach ($liveTables as $t) {
|
||||
if (!in_array($t, $bkTables, true)) { $missing[] = $t; continue; }
|
||||
$common = array_values(array_intersect($cols('main', $t), $cols('bk', $t)));
|
||||
$pdo->exec("DELETE FROM main.\"{$t}\"");
|
||||
if ($common) {
|
||||
$list = '"' . implode('","', $common) . '"';
|
||||
$pdo->exec("INSERT INTO main.\"{$t}\" ({$list}) SELECT {$list} FROM bk.\"{$t}\"");
|
||||
}
|
||||
$out['tables']++;
|
||||
$out['rows'] += (int) $pdo->query("SELECT COUNT(*) FROM main.\"{$t}\"")->fetchColumn();
|
||||
}
|
||||
// Zähler der automatischen Nummern übernehmen, damit neue Datensätze nicht alte Nummern wiederverwenden
|
||||
$hasSeq = (bool) $pdo->query("SELECT 1 FROM bk.sqlite_master WHERE name = 'sqlite_sequence'")->fetchColumn();
|
||||
if ($hasSeq) {
|
||||
$pdo->exec('DELETE FROM main.sqlite_sequence');
|
||||
$pdo->exec('INSERT INTO main.sqlite_sequence (name, seq) SELECT name, seq FROM bk.sqlite_sequence');
|
||||
}
|
||||
$pdo->commit();
|
||||
if ($missing) $out['notes'][] = 'Tabellen, die es im Backup noch nicht gab, blieben unverändert: ' . implode(', ', $missing) . '. Danach unter System-Update „Datenbank aktualisieren“ ausführen.';
|
||||
} catch (Throwable $e) {
|
||||
if ($pdo->inTransaction()) $pdo->rollBack();
|
||||
throw $e;
|
||||
} finally {
|
||||
try { $pdo->exec('DETACH DATABASE bk'); } catch (Throwable $e) {}
|
||||
$pdo->exec('PRAGMA foreign_keys = ON');
|
||||
@unlink($tmp);
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** MySQL: den SQL-Abzug Anweisung für Anweisung einspielen. */
|
||||
function backup_restore_mysql(PDO $pdo, ZipArchive $zip): array
|
||||
{
|
||||
$tmp = backup_extract_entry($zip, 'database_backup.sql');
|
||||
if (!$tmp) throw new RuntimeException('Der Datenbank-Abzug konnte nicht entpackt werden.');
|
||||
$out = ['tables' => 0, 'rows' => 0, 'notes' => []];
|
||||
try {
|
||||
foreach (backup_sql_statements($tmp) as $stmt) {
|
||||
$pdo->exec($stmt);
|
||||
if (preg_match('/^CREATE TABLE/i', $stmt)) $out['tables']++;
|
||||
if (preg_match('/^INSERT INTO/i', $stmt)) $out['rows'] += max(1, substr_count($stmt, "),\n(") + 1);
|
||||
}
|
||||
} finally {
|
||||
@unlink($tmp);
|
||||
}
|
||||
$out['notes'][] = 'Danach unter System-Update „Datenbank aktualisieren“ ausführen, falls das Backup von einer älteren Version stammt.';
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** Pfad eines Backups im backups-Ordner anhand des Dateinamens (nur echte Backups, sonst null). */
|
||||
function backup_path_for(string $filename, ?string $backupDir = null): ?string
|
||||
{
|
||||
$dir = realpath($backupDir ?? __DIR__ . '/../backups');
|
||||
$file = basename($filename);
|
||||
if (!$dir || !preg_match('/^backup_[\d\-_a-f]+\.zip$/', $file) || !is_file($dir . '/' . $file)) return null;
|
||||
return $dir . '/' . $file;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft ein Backup und merkt sich das Ergebnis (für die Anzeige und den Hinweis im System). Ein Backup, das sich nicht
|
||||
* wiederherstellen lässt, ist wertlos: Das soll auffallen, bevor man es braucht.
|
||||
*/
|
||||
function backup_verify_and_record(string $zipPath): array
|
||||
{
|
||||
$r = backup_verify($zipPath);
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$wasNotified = !empty((json_decode((string) get_setting('backup_check_map', ''), true) ?: [])[basename($zipPath)]['notified']);
|
||||
set_setting('backup_last_check', json_encode(['file' => basename($zipPath), 'at' => $now, 'ok' => $r['ok'], 'errors' => $r['errors'], 'info' => $r['info']], JSON_UNESCAPED_UNICODE));
|
||||
// Ergebnis je Datei (für die Liste auf der Backup-Seite), nur die letzten 40
|
||||
$map = json_decode((string) get_setting('backup_check_map', ''), true);
|
||||
$map = is_array($map) ? $map : [];
|
||||
$map[basename($zipPath)] = ['ok' => (bool) $r['ok'], 'at' => $now, 'notified' => $wasNotified];
|
||||
// Defektes Backup: Administrator einmal per E-Mail warnen
|
||||
if (!$r['ok'] && !$wasNotified && function_exists('send_mail')) {
|
||||
$to = (string) (get_setting('admin_email', '') ?: (config()['site']['admin_email'] ?? ''));
|
||||
if ($to !== '') {
|
||||
$map[basename($zipPath)]['notified'] = true;
|
||||
@send_mail($to, 'DeskHub: Backup nicht wiederherstellbar', '<p>Die automatische Prüfung hat ein Problem gefunden:</p><p><strong>' . htmlspecialchars(basename($zipPath)) . '</strong></p><p>' . htmlspecialchars(implode(' ', (array) $r['errors'])) . '</p><p>Erstelle ein neues Backup und prüfe die Einstellungen unter Adminportal → Backup.</p>');
|
||||
}
|
||||
}
|
||||
if (count($map) > 40) $map = array_slice($map, -40, null, true);
|
||||
set_setting('backup_check_map', json_encode($map));
|
||||
return $r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft Backups automatisch nach: solche, die noch nie geprüft wurden, und solche, deren letzte Prüfung über $maxAgeDays Tage her ist
|
||||
* (um spätere Beschädigungen zu bemerken). Pro Aufruf höchstens $limit Backups, neueste zuerst.
|
||||
*
|
||||
* @return array{checked:int,bad:int}
|
||||
*/
|
||||
function backup_verify_pending(int $limit = 2, int $maxAgeDays = 7, ?string $backupDir = null): array
|
||||
{
|
||||
$dir = realpath($backupDir ?? __DIR__ . '/../backups');
|
||||
$out = ['checked' => 0, 'bad' => 0];
|
||||
if (!$dir) return $out;
|
||||
$map = json_decode((string) get_setting('backup_check_map', ''), true);
|
||||
$map = is_array($map) ? $map : [];
|
||||
$files = glob($dir . '/backup_*.zip') ?: [];
|
||||
usort($files, fn($a, $b) => filemtime($b) <=> filemtime($a));
|
||||
$stale = time() - $maxAgeDays * 86400;
|
||||
foreach ($files as $f) {
|
||||
if ($out['checked'] >= $limit) break;
|
||||
$name = basename($f);
|
||||
if (!preg_match('/^backup_[\d\-_a-f]+\.zip$/', $name)) continue;
|
||||
$entry = $map[$name] ?? null;
|
||||
if ($entry && strtotime((string) $entry['at']) > $stale && strtotime((string) $entry['at']) >= filemtime($f)) continue; // frisch geprüft
|
||||
$r = backup_verify_and_record($f);
|
||||
$out['checked']++;
|
||||
if (empty($r['ok'])) $out['bad']++;
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
@@ -15,10 +15,38 @@ function config(): array
|
||||
if (getenv('DESKHUB_TESTING') === '1' && ($extra = json_decode((string) getenv('DESKHUB_CONFIG_JSON'), true)) && is_array($extra)) {
|
||||
$config = array_replace_recursive($config, $extra);
|
||||
}
|
||||
// Nur für die Testläufe (tests/run_all.php setzt DESKHUB_TESTS_FORCE_SQLITE): nie die in config/config.php eingetragene Datenbank
|
||||
// (zum Beispiel die Produktiv-MySQL) benutzen, sondern SQLite. In Test-Webservern nur mit einer vom Test gesetzten Datenbankdatei.
|
||||
if (getenv('DESKHUB_TESTS_FORCE_SQLITE') === '1') {
|
||||
$testDb = getenv('DESKHUB_SQLITE_PATH');
|
||||
if (PHP_SAPI === 'cli' || ($testDb !== false && $testDb !== '' && $testDb !== ':memory:')) {
|
||||
$config['db']['driver'] = 'sqlite';
|
||||
$config['db']['sqlite_path'] = $testDb !== false && $testDb !== '' ? $testDb : ':memory:';
|
||||
}
|
||||
}
|
||||
}
|
||||
return $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Datenbank ist nicht eingerichtet: Mit vorhandenem Installer dorthin weiterleiten, sonst eine verständliche Meldung.
|
||||
* Auf der Kommandozeile (Cron, Skripte) wird ein Fehler geworfen.
|
||||
*/
|
||||
function app_not_installed(): never
|
||||
{
|
||||
$message = 'DeskHub ist noch nicht eingerichtet: Die Datenbank fehlt. Bitte die Installation unter /install/ abschließen.';
|
||||
if (PHP_SAPI === 'cli') throw new RuntimeException($message);
|
||||
$installerOpen = is_file(__DIR__ . '/../install/index.php') && !is_file(__DIR__ . '/../install/.installed');
|
||||
if ($installerOpen && !headers_sent()) {
|
||||
header('Location: /install/');
|
||||
exit;
|
||||
}
|
||||
http_response_code(503);
|
||||
header('Content-Type: text/plain; charset=utf-8');
|
||||
exit($message . "
|
||||
");
|
||||
}
|
||||
|
||||
function get_db(): PDO
|
||||
{
|
||||
static $pdo = null;
|
||||
@@ -32,6 +60,13 @@ function get_db(): PDO
|
||||
$dbPath = $cfg['sqlite_path'];
|
||||
$needInit = !file_exists($dbPath) || filesize($dbPath) === 0;
|
||||
|
||||
// Eine SQLite-Datenbank wird nie nebenbei angelegt (z. B. durch den ersten Seitenaufruf mit einer mitgelieferten Konfiguration):
|
||||
// Das macht allein der Installer, wenn SQLite gewählt wurde. Nur Tests und Entwickler, die den Pfad ausdrücklich per
|
||||
// DESKHUB_SQLITE_PATH angeben, dürfen eine neue Datenbank erzeugen lassen.
|
||||
if ($needInit && $dbPath !== ':memory:' && (string) getenv('DESKHUB_SQLITE_PATH') === '') {
|
||||
app_not_installed();
|
||||
}
|
||||
|
||||
$pdo = new PDO('sqlite:' . $dbPath);
|
||||
$pdo->exec('PRAGMA journal_mode = WAL;');
|
||||
$pdo->exec('PRAGMA foreign_keys = ON;');
|
||||
|
||||
+1917
-1702
File diff suppressed because it is too large
Load Diff
@@ -19,14 +19,11 @@ if (get_setting('helpdesk_status', 'online') === 'offline') {
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title><?= e($displayName) ?> – Wartungsmodus</title>
|
||||
<link rel="stylesheet" href="/assets/css/style.css?v=<?= @filemtime(__DIR__ . "/../assets/css/style.css") ?: time() ?>">
|
||||
<link rel="icon" href="/favicon.ico" sizes="any">
|
||||
<link rel="icon" href="/assets/icons/icon-192.png" type="image/png">
|
||||
<?= site_icon_links() ?>
|
||||
<link rel="manifest" href="/manifest.php">
|
||||
<meta name="theme-color" content="#0f6f6a">
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default">
|
||||
<link rel="apple-touch-icon" href="/assets/icons/icon-192.png">
|
||||
<?php if ($logo): ?><link rel="icon" href="<?= e($logo) ?>"><?php endif; ?>
|
||||
<script>
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.register('/sw.js').catch(function(){});
|
||||
@@ -66,8 +63,7 @@ if ('serviceWorker' in navigator) {
|
||||
<meta name="theme-color" content="#0f6f6a">
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default">
|
||||
<link rel="apple-touch-icon" href="/assets/icons/icon-192.png">
|
||||
<?php if ($logo): ?><link rel="icon" href="<?= e($logo) ?>"><?php endif; ?>
|
||||
<?= site_icon_links() ?>
|
||||
<script>
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.register('/sw.js').catch(function(){});
|
||||
@@ -115,7 +111,7 @@ if ('serviceWorker' in navigator) {
|
||||
<span class="text-brand">Desk<span>Hub</span></span>
|
||||
<?php endif; ?>
|
||||
</a>
|
||||
<?php if ($logo && $displayName): ?>
|
||||
<?php if ($logo && $displayName && get_setting('logo_hide_name', '0') !== '1'): ?>
|
||||
<span style="font-size:1.15rem; font-weight:700; color:var(--ink); letter-spacing:-.01em"><?= e($displayName) ?></span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
@@ -117,16 +117,19 @@ function public_ticket_create(PDO $pdo, array $in, string $clientIp): array
|
||||
}
|
||||
foreach ($ruleResult['add_tags'] as $tagName) apply_tag_to_ticket($pdo, $ticketId, $tagName);
|
||||
apply_auto_reply($pdo, $ticketId, $ruleResult['auto_reply']);
|
||||
$closedByRule = apply_rule_close($pdo, $ticketId, $ruleResult);
|
||||
|
||||
$d = $pdo->prepare('SELECT name, email FROM departments WHERE id = ?');
|
||||
$d->execute([$deptId]);
|
||||
$dept = $d->fetch();
|
||||
$forNotify = ['ticket_number' => $number, 'subject' => $subject, 'requester_name' => $name, 'requester_email' => $email,
|
||||
'department_id' => $deptId, 'department_name' => $dept['name'] ?? null];
|
||||
notify_new_ticket_channels($forNotify, $dept['email'] ?? null);
|
||||
notify_staff_new_ticket($forNotify);
|
||||
notify_customer_ticket_created($forNotify);
|
||||
webhook_dispatch($pdo, 'ticket.created', $ticketId);
|
||||
if (!$closedByRule) {
|
||||
notify_new_ticket_channels($forNotify, $dept['email'] ?? null);
|
||||
notify_staff_new_ticket($forNotify);
|
||||
notify_customer_ticket_created($forNotify);
|
||||
webhook_dispatch($pdo, 'ticket.created', $ticketId);
|
||||
}
|
||||
return ['number' => $number, 'id' => $ticketId];
|
||||
}
|
||||
|
||||
|
||||
@@ -127,6 +127,7 @@ function plugin_filter_permission(string $hook): ?string
|
||||
{
|
||||
if ($hook === 'ticket.view.sidebar') return 'ui.sidebar';
|
||||
if (str_starts_with($hook, 'ticket.')) return 'hooks.tickets';
|
||||
if ($hook === 'backup.list.rows') return 'ui.menu'; // wer einen Reiter unter „Backup“ anbieten darf, darf auch die Liste der Backups ergänzen
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -146,14 +147,18 @@ function plugin_add_filter(string $hook, callable $fn, int $priority = 10): void
|
||||
$state['filters'][$hook][$priority][] = ['fn' => $fn, 'plugin' => $state['current']];
|
||||
}
|
||||
|
||||
/** Menüpunkt im Mitarbeiterbereich. $page ist der Dateiname unter plugins/<slug>/pages/ (ohne .php). */
|
||||
function plugin_register_menu(string $label, string $page, ?string $permission = null): void
|
||||
/**
|
||||
* Menüpunkt im Mitarbeiterbereich. $page ist der Dateiname unter plugins/<slug>/pages/ (ohne .php).
|
||||
* Mit $belongsTo (zum Beispiel 'backup', siehe plugin_parent_pages()) erscheint kein eigener Eintrag in der Seitenleiste: Die Seite wird
|
||||
* stattdessen als Reiter innerhalb dieser Seite angeboten (zum Beispiel unter „Backup“). Dafür ist keine zusätzliche Berechtigung nötig (ui.menu genügt).
|
||||
*/
|
||||
function plugin_register_menu(string $label, string $page, ?string $permission = null, ?string $belongsTo = null): void
|
||||
{
|
||||
if (!plugin_permission_allowed('ui.menu')) return;
|
||||
$state = &plugin_state();
|
||||
$slug = $state['current'];
|
||||
if ($slug === null || !preg_match('/^[a-z0-9_-]+$/i', $page)) return;
|
||||
$state['menus'][] = ['plugin' => $slug, 'label' => mb_substr($label, 0, 60), 'page' => $page, 'permission' => $permission];
|
||||
$state['menus'][] = ['plugin' => $slug, 'label' => mb_substr($label, 0, 60), 'page' => $page, 'permission' => $permission, 'belongs_to' => ($belongsTo !== null && isset(plugin_parent_pages()[$belongsTo])) ? $belongsTo : null];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -306,11 +311,45 @@ function plugin_menu_items(?array $staff): array
|
||||
$items = [];
|
||||
foreach (plugin_state()['menus'] as $m) {
|
||||
if ($m['permission'] !== null && (!$staff || !has_permission($staff, $m['permission']))) continue;
|
||||
if (!empty($m['belongs_to'])) continue; // erscheint als Reiter in der übergeordneten Seite, nicht in der Seitenleiste
|
||||
$items[] = $m + ['url' => '/staff/plugin.php?p=' . rawurlencode($m['plugin']) . '&page=' . rawurlencode($m['page'])];
|
||||
}
|
||||
return $items;
|
||||
}
|
||||
|
||||
/** Seiten, unter denen Plugins Reiter anbieten dürfen: Schlüssel => [Bezeichnung des ersten Reiters, Adresse]. */
|
||||
function plugin_parent_pages(): array
|
||||
{
|
||||
return ['backup' => ['Backups', '/staff/backup.php']];
|
||||
}
|
||||
|
||||
/** Plugin-Seiten (mit Rechteprüfung), die als Reiter zu einer übergeordneten Seite gehören. */
|
||||
function plugin_subpages(string $parent, ?array $staff): array
|
||||
{
|
||||
$items = [];
|
||||
foreach (plugin_state()['menus'] as $m) {
|
||||
if (($m['belongs_to'] ?? null) !== $parent) continue;
|
||||
if ($m['permission'] !== null && (!$staff || !has_permission($staff, $m['permission']))) continue;
|
||||
$items[] = $m + ['url' => '/staff/plugin.php?p=' . rawurlencode($m['plugin']) . '&page=' . rawurlencode($m['page'])];
|
||||
}
|
||||
return $items;
|
||||
}
|
||||
|
||||
/** Reiterleiste einer übergeordneten Seite (leer, wenn kein Plugin Reiter anbietet). $active: 'parent' oder '<plugin>:<seite>'. */
|
||||
function plugin_subpage_tabs(string $parent, ?array $staff, string $active = 'parent'): string
|
||||
{
|
||||
$parents = plugin_parent_pages();
|
||||
$subs = plugin_subpages($parent, $staff);
|
||||
if (!$subs || !isset($parents[$parent])) return '';
|
||||
$tab = function (string $label, string $url, bool $on): string {
|
||||
return '<a href="' . htmlspecialchars($url, ENT_QUOTES) . '" style="padding:8px 16px;border-radius:8px 8px 0 0;text-decoration:none;font-size:.9rem;'
|
||||
. ($on ? 'background:var(--card-bg,#fff);border:1px solid var(--border);border-bottom-color:var(--card-bg,#fff);font-weight:600;color:inherit;position:relative;top:1px' : 'color:var(--muted);border:1px solid transparent') . '">' . htmlspecialchars($label) . '</a>';
|
||||
};
|
||||
$html = '<div class="plugin-tabs" style="display:flex;gap:4px;flex-wrap:wrap;border-bottom:1px solid var(--border);margin:0 0 18px">' . $tab($parents[$parent][0], $parents[$parent][1], $active === 'parent');
|
||||
foreach ($subs as $s) $html .= $tab($s['label'], $s['url'], $active === $s['plugin'] . ':' . $s['page']);
|
||||
return $html . '</div>';
|
||||
}
|
||||
|
||||
// ─── Verwaltung (Installieren, Aktivieren, Entfernen) ────────────────────────
|
||||
|
||||
function plugins_installed(PDO $pdo): array
|
||||
@@ -785,10 +824,13 @@ function plugin_run_migrations(PDO $pdo, string $slug): array
|
||||
if (in_array($key, $done, true)) continue;
|
||||
$sql = preg_replace('/^\s*--.*$/m', '', (string) file_get_contents($file));
|
||||
try {
|
||||
$pdo->beginTransaction();
|
||||
// SQLite kann Tabellen-Änderungen in einer Transaktion zurückrollen. MySQL beendet bei CREATE/ALTER TABLE jede offene
|
||||
// Transaktion von selbst ("There is no active transaction"), dort läuft die Datei deshalb ohne Transaktion.
|
||||
$useTransaction = $driver === 'sqlite';
|
||||
if ($useTransaction) $pdo->beginTransaction();
|
||||
foreach (array_filter(array_map('trim', explode(';', $sql))) as $stmt) $pdo->exec($stmt);
|
||||
$pdo->prepare('INSERT INTO schema_migrations (migration) VALUES (?)')->execute([$key]);
|
||||
$pdo->commit();
|
||||
if ($useTransaction && $pdo->inTransaction()) $pdo->commit();
|
||||
$applied++;
|
||||
} catch (Throwable $e) {
|
||||
if ($pdo->inTransaction()) $pdo->rollBack();
|
||||
|
||||
@@ -96,6 +96,16 @@ function pseudo_cron_dispatch(): void
|
||||
catalog_refresh_background();
|
||||
}
|
||||
|
||||
// Backups automatisch prüfen: neue/ungeprüfte sofort, geprüfte nach 7 Tagen erneut (höchstens alle 10 Minuten, 2 je Lauf)
|
||||
if (pseudo_cron_try_claim($pdo, 'cron_verify_backups_last_run', 600)) {
|
||||
try {
|
||||
if (!function_exists('backup_verify_pending')) require_once __DIR__ . '/backup_restore.php';
|
||||
backup_verify_pending(2);
|
||||
} catch (Throwable $e) {
|
||||
error_log('pseudo_cron [verify_backups]: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Plugins: wiederkehrende Aufgaben (höchstens alle 5 Minuten)
|
||||
if (pseudo_cron_try_claim($pdo, 'plugins_cron_last_run', 300)) {
|
||||
plugin_hook('cron.run', ['time' => time()]);
|
||||
|
||||
@@ -124,7 +124,7 @@ function security_check_settings(PDO $pdo): array
|
||||
|
||||
// Reverse-Proxy ohne Konfiguration: alle Besucher teilen sich eine IP (gemeinsame Login-Sperre)
|
||||
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && !request_from_trusted_proxy()) {
|
||||
$out[] = ['level' => 'warn', 'title' => 'Reverse-Proxy nicht eingetragen', 'detail' => 'Die Anfrage kam über einen Proxy (X-Forwarded-For), aber dessen Adresse ist nicht als vertrauenswürdig eingetragen. DeskHub sieht dadurch für alle Besucher dieselbe IP: Anmelde-Sperren treffen dann alle gleichzeitig. Eintragen unter site → trusted_proxies in config/config.php (Adresse oder Bereich des Proxys, z. B. \'172.16.0.0/12\').'];
|
||||
$out[] = ['level' => 'warn', 'title' => 'Reverse-Proxy nicht eingetragen', 'detail' => 'Die Anfrage kam über einen Proxy (X-Forwarded-For), aber dessen Adresse (' . e((string) ($_SERVER['REMOTE_ADDR'] ?? '?')) . ') ist nicht als vertrauenswürdig eingetragen. DeskHub sieht dadurch für alle Besucher dieselbe IP: Anmelde-Sperren treffen dann alle gleichzeitig. Eintragen unter site → trusted_proxies in config/config.php (Adresse oder Bereich des Proxys, z. B. \'172.16.0.0/12\').'];
|
||||
}
|
||||
|
||||
// Fehlerausgabe
|
||||
|
||||
@@ -59,9 +59,25 @@ function update_find_assets(array $release, string $tag): array
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zugangstoken für den Update-Server (nur nötig, wenn das Repository privat ist; Gitea antwortet sonst mit "404").
|
||||
* Quelle: config/config.php ('update' => ['token' => '…']) hat Vorrang, sonst das in den Einstellungen der Update-Seite
|
||||
* gespeicherte (verschlüsselt). Gibt [Token, Quelle] zurück, Quelle 'config', 'einstellungen' oder ''.
|
||||
*
|
||||
* @return array{0: string, 1: string}
|
||||
*/
|
||||
function update_token_info(): array
|
||||
{
|
||||
$fromConfig = trim((string) (config()['update']['token'] ?? ''));
|
||||
if ($fromConfig !== '') return [$fromConfig, 'config'];
|
||||
$stored = (string) get_setting('update_token', '');
|
||||
$fromSettings = $stored !== '' ? trim(decrypt_secret($stored)) : '';
|
||||
return $fromSettings !== '' ? [$fromSettings, 'einstellungen'] : ['', ''];
|
||||
}
|
||||
|
||||
/** Kopfzeilen für Abrufe beim Update-Server; ein Zugangstoken ist nur nötig, wenn das Repository nicht öffentlich ist. */
|
||||
function update_http_headers(): array
|
||||
{
|
||||
$token = (string) (config()['update']['token'] ?? '');
|
||||
[$token] = update_token_info();
|
||||
return $token !== '' ? ['Authorization: token ' . $token] : [];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user