Unifi-Voucher-Tool/admin/backup.php
Friederich Loheide 25b8c51362
Some checks failed
CI / PHP Lint-1 (push) Successful in 43s
CI / PHP Lint (push) Successful in 45s
CI / PHP Lint (pull_request) Successful in 38s
CI / Unit Tests & Static Analysis (push) Failing after 43s
CI / PHP Lint-1 (pull_request) Successful in 40s
CI / Unit Tests & Static Analysis (pull_request) Failing after 41s
Selbst-Updater neu gebaut, Diagnoseseiten abgesichert
Aktualisierung per Klick im Administrationsbereich, ohne Zugang zum
Server. Der bisherige Updater lud ein ZIP und entpackte es ungeprüft über
die Produktion; das ist vollständig ersetzt.

Neu in updater/:

- Version: Release-Version als Konstante, installierter Commit-SHA in
  storage/.version (Datei, nicht Datenbank - der Updater muss den Stand
  auch bei hängender Datenbank lesen können)
- Progress: Fortschrittsdatei mit eigenem Fehlerzustand (pct = -1) und
  Verfallszeit, damit ein abgestürzter Lauf den nächsten nicht blockiert
- Maintenance: Wartungsmarkierung mit Ablauf, die sich beim Prüfen selbst
  aufräumt
- ProxyClient: nur HTTPS, Zertifikatsprüfung an, begrenzte
  Weiterleitungen, 503 mirror_pending/not_released als Bitte um Geduld
- Updater: Prüfsumme gegen X-Content-Sha256, zweistufiger ZIP-Slip-Schutz,
  geschützte Pfade, atomares Schreiben je Datei, nie löschen
- AutoMigrate: zieht Migrationen beim ersten Seitenaufruf nach, nur bei
  geändertem Fingerabdruck und mit Sperre gegen Parallellauf
- guard.php: Wartungs-Wächter für die Einstiegsseiten, JSON für die
  Schnittstellen; ausgenommen bleiben Update-Seite, Anmeldung und
  Health-Check
- Changelog: zerlegt CHANGELOG.md und rendert Markdown ohne unsichere Links

Oberfläche: Seite "Aktualisierung" mit Stand, Kanal, Suche, Fortschritt,
Migrationsliste und Versionsgeschichte. Der Datenschutzhinweis steht
dauerhaft neben der Schaltfläche, nicht in einem Dialog.

Fehlt changelog_preview in der Antwort, bleibt es bei "neue Fassung
verfügbar" - kein leerer Kasten, kein erfundener Ersatztext. Commit-Texte
werden nirgends angezeigt.

Außerdem (Punkt 2 der Liste):

- cron_test.php entfernt: ohne jede Anmeldung erreichbar, meldete
  Datenbankfehler samt Meldung und die Spalten der vouchers-Tabelle
- test.php verweigert ohne config.php die Auskunft; bisher lief die
  Diagnose auf einer frisch entpackten Installation ohne Anmeldung

PHPStan prüft jetzt den gesamten updater/-Ordner. 18 neue Tests
(93 Tests, 243 Assertions), Ablauf gegen den echten Update-Dienst
durchgespielt.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-25 19:49:59 +00:00

216 lines
12 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
require_once __DIR__ . '/../updater/guard.php';
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/Database.php';
require_once __DIR__ . '/../includes/Auth.php';
require_once __DIR__ . '/../includes/I18n.php';
require_once __DIR__ . '/../includes/Kiosk.php';
$auth = new Auth();
$auth->requireAdmin();
I18n::init();
$db = Database::getInstance();
$appTitle = $db->getSetting('app_title', 'UniFi Voucher System');
$error = '';
$success = '';
// Export: JSON-Download
if (isset($_GET['export']) && isset($_GET['token']) && $auth->validateCsrfToken($_GET['token'])) {
$export = [
'meta' => [
'app' => 'unifi-voucher-tool',
'version' => trim((string)@file_get_contents(dirname(__DIR__) . '/VERSION')),
'exported_at'=> date('c'),
'note' => 'Site-Passwörter sind mit dem APP_KEY dieser Installation verschlüsselt.',
],
'settings' => $db->fetchAll("SELECT setting_key, setting_value FROM settings"),
'sites' => $db->fetchAll("SELECT name, site_id, unifi_controller_url, unifi_username, unifi_password, ssl_verify, is_active, public_access FROM sites"),
'voucher_templates' => $db->fetchAll("SELECT name, max_uses, expire_minutes, description, qos_rate_max_down, qos_rate_max_up, qos_usage_quota, is_active FROM voucher_templates"),
// Display-Seiten samt Token: sonst zeigen aufgehängte QR-Codes nach
// einem Restore ins Leere. Site und Profil werden über den Namen
// verknüpft, weil die IDs auf der Zielinstallation andere sind.
'kiosks' => $db->fetchAll(
"SELECT k.name, k.token, k.headline, k.subline, k.logo_url, k.background_url,
k.bg_overlay, k.accent_color, k.card_style, k.daily_limit,
k.cooldown_seconds, k.display_seconds, k.active_from, k.active_to,
k.device_cooldown_seconds, k.pin, k.language, k.is_active,
s.name AS site_name, t.name AS template_name
FROM kiosks k
INNER JOIN sites s ON s.id = k.site_id
LEFT JOIN voucher_templates t ON t.id = k.template_id"
),
];
$auth->writeAuditLog($_SESSION['user_id'], 'config_export', 'config', null, 'Konfiguration exportiert');
header('Content-Type: application/json');
header('Content-Disposition: attachment; filename="voucher-config-' . date('Y-m-d') . '.json"');
echo json_encode($export, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
// Import
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import'])) {
if (!$auth->validateCsrfToken($_POST['csrf_token'] ?? '')) {
$error = __('error_csrf');
} elseif (empty($_FILES['backup']['tmp_name'])) {
$error = __('backup_choose_file');
} else {
$raw = file_get_contents($_FILES['backup']['tmp_name']);
$data = json_decode($raw, true);
if (!is_array($data) || ($data['meta']['app'] ?? '') !== 'unifi-voucher-tool') {
$error = __('backup_invalid_file');
} else {
$importSites = isset($_POST['import_sites']);
$importTemplates = isset($_POST['import_templates']);
$importSettings = isset($_POST['import_settings']);
$importKiosks = isset($_POST['import_kiosks']);
$counts = ['settings' => 0, 'sites' => 0, 'templates' => 0, 'kiosks' => 0];
try {
if ($importSettings && !empty($data['settings'])) {
foreach ($data['settings'] as $s) {
// Cron-Token NICHT überschreiben (Sicherheit der Ziel-Installation)
if (($s['setting_key'] ?? '') === 'cron_token') continue;
$db->setSetting($s['setting_key'], $s['setting_value']);
$counts['settings']++;
}
}
if ($importSites && !empty($data['sites'])) {
foreach ($data['sites'] as $s) {
$exists = $db->fetchOne("SELECT id FROM sites WHERE name = ? AND site_id = ?", [$s['name'], $s['site_id']]);
if ($exists) {
$db->query(
"UPDATE sites SET unifi_controller_url=?, unifi_username=?, unifi_password=?, ssl_verify=?, is_active=?, public_access=? WHERE id=?",
[$s['unifi_controller_url'], $s['unifi_username'], $s['unifi_password'], (int)($s['ssl_verify'] ?? 0), (int)$s['is_active'], (int)$s['public_access'], $exists['id']]
);
} else {
$db->query(
"INSERT INTO sites (name, site_id, unifi_controller_url, unifi_username, unifi_password, ssl_verify, is_active, public_access) VALUES (?,?,?,?,?,?,?,?)",
[$s['name'], $s['site_id'], $s['unifi_controller_url'], $s['unifi_username'], $s['unifi_password'], (int)($s['ssl_verify'] ?? 0), (int)$s['is_active'], (int)$s['public_access']]
);
}
$counts['sites']++;
}
}
if ($importTemplates && !empty($data['voucher_templates'])) {
foreach ($data['voucher_templates'] as $t) {
$exists = $db->fetchOne("SELECT id FROM voucher_templates WHERE name = ?", [$t['name']]);
if (!$exists) {
$db->query(
"INSERT INTO voucher_templates (name, max_uses, expire_minutes, description, qos_rate_max_down, qos_rate_max_up, qos_usage_quota, is_active) VALUES (?,?,?,?,?,?,?,?)",
[$t['name'], (int)$t['max_uses'], (int)$t['expire_minutes'], $t['description'] ?? null,
$t['qos_rate_max_down'] ?? null, $t['qos_rate_max_up'] ?? null, $t['qos_usage_quota'] ?? null, (int)($t['is_active'] ?? 1)]
);
$counts['templates']++;
}
}
}
if ($importKiosks && !empty($data['kiosks'])) {
foreach ($data['kiosks'] as $k) {
$site = $db->fetchOne("SELECT id FROM sites WHERE name = ?", [$k['site_name'] ?? '']);
if (!$site) {
continue; // ohne passende Site ergibt die Display-Seite keinen Sinn
}
$templateId = null;
if (!empty($k['template_name'])) {
$tpl = $db->fetchOne("SELECT id FROM voucher_templates WHERE name = ?", [$k['template_name']]);
$templateId = $tpl['id'] ?? null;
}
$exists = $db->fetchOne("SELECT id FROM kiosks WHERE token = ?", [$k['token'] ?? '']);
$values = [
(int)$site['id'], $templateId, $k['name'], $k['headline'] ?? null, $k['subline'] ?? null,
$k['logo_url'] ?? null, $k['background_url'] ?? null, (int)($k['bg_overlay'] ?? 45),
$k['accent_color'] ?? null, ($k['card_style'] ?? 'light') === 'dark' ? 'dark' : 'light',
(int)($k['daily_limit'] ?? 100), (int)($k['cooldown_seconds'] ?? 20),
(int)($k['display_seconds'] ?? 90),
$k['active_from'] ?? null, $k['active_to'] ?? null,
(int)($k['device_cooldown_seconds'] ?? 0),
$k['pin'] ?? null, $k['language'] ?? null,
(int)($k['is_active'] ?? 1),
];
if ($exists) {
$db->query(
"UPDATE kiosks SET site_id=?, template_id=?, name=?, headline=?, subline=?, logo_url=?,
background_url=?, bg_overlay=?, accent_color=?, card_style=?, daily_limit=?,
cooldown_seconds=?, display_seconds=?, active_from=?, active_to=?,
device_cooldown_seconds=?, pin=?, language=?, is_active=? WHERE id=?",
array_merge($values, [(int)$exists['id']])
);
} else {
$db->query(
"INSERT INTO kiosks (site_id, template_id, name, headline, subline, logo_url, background_url,
bg_overlay, accent_color, card_style, daily_limit, cooldown_seconds, display_seconds,
active_from, active_to, device_cooldown_seconds, pin, language,
is_active, token, created_by)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
array_merge($values, [$k['token'] ?? Kiosk::newToken(), $_SESSION['user_id'] ?? null])
);
}
$counts['kiosks']++;
}
}
$auth->writeAuditLog($_SESSION['user_id'], 'config_import', 'config', null, 'Konfiguration importiert');
$success = str_replace(['{settings}', '{sites}', '{templates}', '{kiosks}'],
[(string)$counts['settings'], (string)$counts['sites'], (string)$counts['templates'], (string)$counts['kiosks']],
__('backup_imported'));
} catch (Exception $e) {
$error = 'Import-Fehler: ' . $e->getMessage();
}
}
}
}
$csrf = $auth->getCsrfToken();
$currentPage = 'backup';
$adminBase = '';
?>
<!DOCTYPE html>
<html lang="<?= I18n::getLanguage() ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= __('backup_title') ?> – <?= htmlspecialchars($appTitle) ?></title>
<?php require __DIR__ . '/../includes/admin_nav.php'; ?>
<div class="page-header">
<div>
<h1 class="page-title"><?= __('backup_title') ?></h1>
<p class="page-subtitle"><?= __('backup_subtitle') ?></p>
</div>
</div>
<?php if ($error): ?><div class="alert alert-error"><?= htmlspecialchars($error) ?></div><?php endif; ?>
<?php if ($success): ?><div class="alert alert-ok"><?= htmlspecialchars($success) ?></div><?php endif; ?>
<div class="card">
<h2><?= __('backup_export') ?></h2>
<p class="muted"><?= __('backup_export_hint') ?> <code>APP_KEY</code> <?= __('backup_export_hint2') ?></p>
<a class="btn btn-primary" href="?export=1&token=<?= urlencode($csrf) ?>"><?= __('backup_export_btn') ?></a>
</div>
<div class="card">
<h2><?= __('backup_import') ?></h2>
<p class="muted"><?= __('backup_import_hint') ?></p>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
<input type="file" name="backup" accept="application/json,.json" required><br>
<label class="chk"><input type="checkbox" name="import_settings" checked> <?= __('backup_opt_settings') ?></label>
<label class="chk"><input type="checkbox" name="import_sites" checked> <?= __('backup_opt_sites') ?></label>
<label class="chk"><input type="checkbox" name="import_templates" checked> <?= __('backup_opt_templates') ?></label>
<label class="chk"><input type="checkbox" name="import_kiosks" checked> <?= __('backup_opt_kiosks') ?></label>
<button class="btn btn-primary" type="submit" name="import" style="margin-top:12px;" onclick="return confirm('<?= __('backup_import_confirm') ?>');"><?= __('import_submit') ?></button>
</form>
</div>
</main>
<script src="../assets/global.js"></script>
</body>
</html>