Unifi-Voucher-Tool/admin/backup.php
Friederich Loheide dd8e805e27
All checks were successful
CI / PHP Lint (push) Successful in 34s
CI / PHP Lint-1 (push) Successful in 39s
CI / Unit Tests & Static Analysis (push) Successful in 38s
CI / PHP Lint (pull_request) Successful in 41s
CI / PHP Lint-1 (pull_request) Successful in 49s
CI / Unit Tests & Static Analysis (pull_request) Successful in 41s
Display-Seiten: Betriebszeiten, PIN, Gerätesperre, Sprache und Vorschau
Die Display-Seiten hängen an öffentlichen Links, deshalb bekommen sie
Regler, mit denen sich der Missbrauch begrenzen lässt, und ein paar
Komfortfunktionen für den Betrieb:

- Betriebszeiten je Seite (auch über Mitternacht hinweg); außerhalb
  zeigt die Seite einen Hinweis statt des Buttons
- Optionale PIN von der Rezeption, geprüft mit hash_equals
- Wartezeit je Gerät über ein Cookie, zusätzlich zum globalen Cooldown
- Feste Sprache je Seite, sonst Browsersprache; Gäste können unten
  umschalten
- Reporting zeigt die Ausgabe pro Display-Seite
- Vorschau der Seite direkt in der Administration
- Backup exportiert und importiert die neuen Felder mit

Migration 0007, 16 neue Sprachschlüssel, 7 zusätzliche Tests
(69 Tests, 152 Assertions).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-24 11:21:20 +00:00

213 lines
12 KiB
PHP
Raw 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
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, 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=?, is_active=?, public_access=? WHERE id=?",
[$s['unifi_controller_url'], $s['unifi_username'], $s['unifi_password'], (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, is_active, public_access) VALUES (?,?,?,?,?,?,?)",
[$s['name'], $s['site_id'], $s['unifi_controller_url'], $s['unifi_username'], $s['unifi_password'], (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>