Unifi-Voucher-Tool/admin/backup.php
Friederich Loheide 4c1e58e68f
All checks were successful
CI / PHP Lint (push) Successful in 36s
CI / PHP Lint-1 (push) Successful in 38s
CI / Unit Tests & Static Analysis (push) Successful in 42s
CI / PHP Lint (pull_request) Successful in 36s
CI / PHP Lint-1 (pull_request) Successful in 41s
CI / Unit Tests & Static Analysis (pull_request) Successful in 42s
Zertifikatsprüfung als Opt-in: pro Site und für SMTP
Übernommen aus dem alten Review-Branch
claude/tool-review-optimization-q9nyv5, neu gebaut auf dem aktuellen
Stand. Der Rest jenes Branches ist durch das Redesign überholt.

Bisher galt CURLOPT_SSL_VERIFYPEER => false für jede Verbindung zum
Controller, ohne Möglichkeit, das zu ändern. Wer den Controller unter
seinem echten Namen mit gültigem Zertifikat betreibt, kann die Prüfung
jetzt pro Site einschalten; Standard bleibt aus, weil UniFi-Geräte ab
Werk ein selbst signiertes Zertifikat liefern.

- Migration 0008, Spalte sites.ssl_verify (Default 0)
- UniFiController: fünfter Konstruktor-Parameter, steuert VERIFYPEER und
  VERIFYHOST; testConnection() ebenso. Alle acht Aufrufer geben den Wert
  der Site weiter, tolerant über "?? 0" für Alt-Installationen
- Site-Verwaltung: Schalter in beiden Modalen, Abzeichen auf der Karte
- Mailer: dasselbe über die Einstellung smtp_verify_ssl, Schalter im
  SMTP-Tab
- Backup nimmt die Spalte mit, Readme erklärt, wann man sie einschaltet
- 3 Tests auf den Durchgriff bis cURL (75 Tests, 178 Assertions)

Nebenbei: der Aufruf von openEditModal() hat fehlende Spalten bisher als
leeres Argument gerendert - jetzt über (int)(... ?? 0) abgesichert.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-25 05:12:28 +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, 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>