diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8c08ebc..e1b2a0c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -85,4 +85,4 @@ jobs: run: vendor/bin/phpunit - name: PHPStan - run: vendor/bin/phpstan analyse --no-progress + run: vendor/bin/phpstan analyse --no-progress --memory-limit=512M diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 41a564d..7b7f5c6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -79,6 +79,7 @@ jobs: unifi-voucher-tool/database.sql \ unifi-voucher-tool/LICENSE \ unifi-voucher-tool/THIRD-PARTY-NOTICES.md \ + unifi-voucher-tool/CHANGELOG.md \ unifi-voucher-tool/assets/global.css \ unifi-voucher-tool/assets/vendor/inter/inter.css \ unifi-voucher-tool/assets/vendor/inter/LICENSE.txt \ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..ec41bd7 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,30 @@ +# Änderungsprotokoll + +Neueste Fassung oben. Die Abschnittsüberschriften tragen die Versionsnummer, +denn genau daran liest der Update-Dienst ab, was seit einem Stand dazugekommen +ist. + +## 3.0.0 – 2026-09-25 + +- Selbst-Updater neu gebaut: Aktualisierung per Klick im Administrationsbereich, ohne Zugang zum Server +- Update-Paket wird gegen die vom Dienst genannte Prüfsumme abgeglichen +- Entpacken mit zweistufigem Schutz gegen Pfadausbrüche aus dem Archiv +- Dateien werden einzeln erst daneben geschrieben und dann umbenannt; geschützte Pfade bleiben unberührt +- Wartungsmodus läuft von allein aus, ein abgebrochener Lauf blockiert die Installation nicht mehr +- Migrationen ziehen nach einem Update beim ersten Seitenaufruf nach, abgesichert über Fingerabdruck und Sperre +- Datenschutzhinweis dauerhaft sichtbar an der Stelle, an der die Übertragung ausgelöst wird +- Diagnoseseite `cron_test.php` entfernt, `test.php` ist ohne Anmeldung nicht mehr erreichbar + +## 2.9.0 – 2026-09-24 + +- Display-Seiten: Betriebszeiten, PIN, Wartezeit je Gerät und feste Sprache je Seite +- Vorschau der Display-Seiten in der Administration, Auswertung je Seite im Reporting +- Zertifikatsprüfung pro Site und für den Mailversand einschaltbar +- Karte „Über diese Installation“ mit Version, Lizenz und den Komponenten Dritter +- Lizenzhinweise vervollständigt: `LICENSE`, `THIRD-PARTY-NOTICES.md` und die Lizenztexte der Bibliotheken + +## 2.8.0 – 2026-09-23 + +- Öffentliche Display-Seiten für Gäste, gestaltbar mit Logo, Hintergrund und Farben +- Tests für Anmeldung und Controller, PHP 8.1 als Mindestversion +- Backup umfasst die Display-Seiten diff --git a/Readme.md b/Readme.md index 86f54e5..f829230 100644 --- a/Readme.md +++ b/Readme.md @@ -10,7 +10,7 @@ Entwickelt von **[Loheide.eu](https://loheide.eu)** ![MySQL](https://img.shields.io/badge/MySQL-5.7%2B%20%2F%20MariaDB-4479A1?logo=mysql&logoColor=white) ![UniFi OS](https://img.shields.io/badge/UniFi%20OS-7.0%2B-0559C9?logo=ubiquiti&logoColor=white) ![License](https://img.shields.io/badge/Lizenz-MIT-green) -![Version](https://img.shields.io/badge/Version-2.9.0-blueviolet) +![Version](https://img.shields.io/badge/Version-3.0.0-blueviolet) [![CI](https://git.loheide.cloud/friloo/Unifi-Voucher-Tool/badges/workflows/ci.yml/badge.svg)](https://git.loheide.cloud/friloo/Unifi-Voucher-Tool/actions) [![Repository](https://img.shields.io/badge/Code-git.loheide.cloud-4b3ec4)](https://git.loheide.cloud/friloo/Unifi-Voucher-Tool) @@ -203,36 +203,63 @@ cd Unifi-Voucher-Tool --- -## 🔄 Auto-Updater +## 🔄 Selbst-Updater -Das System bringt einen vollständig integrierten Updater mit, der Quellcode und -Datenbank-Migrationen über einen zentralen Update-Proxy nachzieht – ganz ohne -SSH oder manuelles `git pull`. +Eine laufende Installation aktualisiert sich per Klick im Administrationsbereich +– **ohne SSH und ohne `git pull` auf dem Server**. Quellcode und +Datenbank-Migrationen kommen über einen Update-Dienst, der den aktuellen Stand +des Branches als ZIP bereitstellt. ``` -[diese Instanz] ←HTTPS→ [Update-Proxy] ←pull→ [Git-Repo] +[diese Installation] ←HTTPS→ [Update-Dienst] ←pull→ [Git-Repository] ``` -**Aufruf:** Administration → **System-Update** (`/admin/update.php`) +**Aufruf:** Administration → **Aktualisierung** (`/admin/update.php`) -- 🔍 **„Auf Updates prüfen"** zeigt verfügbare Versionen inkl. Changelog -- ⬇️ **„Update installieren"** spielt das Update ein – mit Wartungsseite, - geschützten Pfaden (`config.php`, Uploads, …), automatischen DB-Migrationen - und OPcache-Reset -- 🔀 **Channel-Auswahl** zwischen `stable` und `development` -- 📊 **Migrations-Status** in einem eigenen Tab – inkl. Button **„Ausstehende - Migrationen ausführen"** (legt z. B. neue Tabellen für bestehende - Installationen an, ohne dass ein Code-Update nötig ist) +- 🔍 **„Nach Updates suchen"** zeigt, ob eine neue Fassung da ist, welche Version + sie trägt und – sofern der Dienst etwas liefert – die Abschnitte aus dem + Änderungsprotokoll. Gibt es dazu nichts, bleibt es bei der schlichten Aussage + „neue Fassung verfügbar" +- ⬇️ **„Jetzt aktualisieren"** spielt sie ein: Wartungsseite, Prüfsumme, gesichertes + Entpacken, geschützte Pfade, Migrationen, Bytecode-Cache. Der Fortschritt wird + alle zwei Sekunden abgefragt; der Ablauf läuft serverseitig weiter, auch wenn + der Browser die Verbindung kappt +- 🔀 **Kanal** zwischen `stable` und `development` umschaltbar +- 📊 **Migrationen** mit Status je Datei und Schaltfläche zum Nachziehen +- 📜 **Änderungsprotokoll** aus der mitgelieferten `CHANGELOG.md` -Während eines Updates wird die Anwendung kurz in den **Wartungsmodus** versetzt: +Während eines Updates antwortet die Anwendung mit einer **Wartungsseite** (HTTP +503 samt `Retry-After`) – ausgenommen die Update-Endpunkte selbst, die +Anmeldeseite und der Health-Check, damit der Fortschritt sichtbar bleibt:
Wartungsmodus
-> Der Updater ist vollständig isoliert im Ordner [`updater/`](updater/) gekapselt. -> Details zur Architektur und eine Rückbau-Anleitung stehen in -> [`updater/README.md`](updater/README.md). +**Was dabei geschützt ist:** `config.php`, `uploads/`, `vendor/`, +`updater/storage/` und weitere Pfade werden nie überschrieben. Dateien werden +einzeln erst daneben geschrieben und dann umbenannt, damit ein Abbruch keine +halbe PHP-Datei hinterlässt. Gelöscht wird nichts. Das Paket wird gegen die vom +Dienst genannte SHA-256 geprüft, und beim Entpacken verhindern zwei +unabhängige Prüfungen, dass ein Archiv aus seinem Verzeichnis ausbricht. + +> **Datenschutz:** Die Update-Prüfung überträgt den installierten Stand sowie +> technisch bedingt IP-Adresse und Zeitpunkt an `update.loheide.cloud`. Inhalte +> aus dem Programm werden nicht übertragen. Der vollständige Hinweis steht +> dauerhaft auf der Seite „Aktualisierung", direkt neben der Schaltfläche. + +Architektur, Sicherheitseigenschaften und eine Rückbau-Anleitung stehen in +[`updater/README.md`](updater/README.md). + +### Eine neue Fassung veröffentlichen + +1. `CHANGELOG.md`: Abschnitt `## MAJOR.MINOR.PATCH – Datum` ergänzen +2. `Updater\Version::RELEASE` und die Datei `VERSION` anheben (Patch = + Fehlerbehebung, Minor = Funktion) – ein Test prüft, dass beide übereinstimmen +3. `composer test` und `composer stan` grün, kompilierte Assets mitversionieren + (beim Anwender läuft kein Build) +4. Merge nach `main` – sobald der Dienst den Stand gespiegelt hat, bieten ihn + alle Installationen an --- @@ -752,7 +779,7 @@ Lizenztexte.
-**Version 2.9.0** · Autor: **Friederich Loheide** · Lizenz: **MIT** +**Version 3.0.0** · Autor: **Friederich Loheide** · Lizenz: **MIT** Entwickelt von **[Loheide.eu](https://loheide.eu)** diff --git a/VERSION b/VERSION index c8e38b6..4a36342 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -2.9.0 +3.0.0 diff --git a/admin/api_keys.php b/admin/api_keys.php index 7c7fc9a..a08e9f7 100644 --- a/admin/api_keys.php +++ b/admin/api_keys.php @@ -1,4 +1,7 @@ requireAdmin(); +I18n::init(); $db = Database::getInstance(); +$appTitle = $db->getSetting('app_title', 'UniFi Voucher System'); -$controller = new \Updater\UpdateController($db, $auth); -$controller->handle(); +$channel = \Updater\UpdaterFactory::channel(); +$channelLabels = \Updater\UpdaterFactory::channelLabels(); +$installedSha = \Updater\Version::current(); +$release = \Updater\Version::RELEASE; +$migrations = []; +$migrationError = ''; + +try { + $migrations = \Updater\UpdaterFactory::create($db)->migrationStatus(); +} catch (Throwable $e) { + $migrationError = $e->getMessage(); +} +$openMigrations = count(array_filter($migrations, static fn ($m) => !$m['applied'])); + +$changelog = \Updater\Changelog::sections(); +$privacyUrl = trim((string)$db->getSetting('privacy_url', '')); +$csrf = $auth->getCsrfToken(); +$currentPage = 'update'; +$adminBase = ''; +?> + + + + + +<?= __('update_title') ?> – <?= htmlspecialchars($appTitle) ?> + + + +
+

+
+
+
' . htmlspecialchars(substr($installedSha, 0, 7)) . '' : '' ?>
+ +
+
+ + + + + +
+ +
+
+
+ +
+ + +
+ + +
+

+
+
+ +
+

+
+ + +
+ + + + + + +
+

+

+
    +
  • +
  • +
+

+

+

+ +

+ +
+
+ +
+

+ +
+ +

+ +

+
+ + + + + + + + + + + + + + + +
+ + + + + +
+
+ + + +
+ +
+

+ +

+ + +
+

+
+
+ + +
+ + + + + + diff --git a/admin/update_api.php b/admin/update_api.php new file mode 100644 index 0000000..ace68e9 --- /dev/null +++ b/admin/update_api.php @@ -0,0 +1,21 @@ +requireAdmin(); + +$controller = new \Updater\UpdateController(Database::getInstance(), $auth); +$controller->handle((string)($_GET['action'] ?? $_POST['action'] ?? '')); diff --git a/admin/users.php b/admin/users.php index b489447..4d62674 100644 --- a/admin/users.php +++ b/admin/users.php @@ -1,4 +1,7 @@ checkForUpdates(); + $updater = \Updater\UpdaterFactory::create($db, null); + $res = $updater->check(); if (!empty($res['has_update'])) { Notifier::updateAvailable($res['latest_sha'] ?? ''); } diff --git a/cron_test.php b/cron_test.php deleted file mode 100644 index ab6067a..0000000 --- a/cron_test.php +++ /dev/null @@ -1,72 +0,0 @@ - 1, 'message' => 'PHP läuft']); - -// Test 1: Config laden -try { - require_once __DIR__ . '/config.php'; - echo "\n" . json_encode(['step' => 2, 'message' => 'Config geladen']); -} catch (Exception $e) { - echo "\n" . json_encode(['step' => 2, 'error' => $e->getMessage()]); - exit; -} - -// Test 2: Database laden -try { - require_once __DIR__ . '/includes/Database.php'; - echo "\n" . json_encode(['step' => 3, 'message' => 'Database.php geladen']); -} catch (Exception $e) { - echo "\n" . json_encode(['step' => 3, 'error' => $e->getMessage()]); - exit; -} - -// Test 3: DB-Verbindung -try { - $db = Database::getInstance(); - echo "\n" . json_encode(['step' => 4, 'message' => 'DB-Verbindung OK']); -} catch (Exception $e) { - echo "\n" . json_encode(['step' => 4, 'error' => $e->getMessage()]); - exit; -} - -// Test 4: UniFiController laden -try { - require_once __DIR__ . '/includes/UniFiController.php'; - echo "\n" . json_encode(['step' => 5, 'message' => 'UniFiController.php geladen']); -} catch (Exception $e) { - echo "\n" . json_encode(['step' => 5, 'error' => $e->getMessage()]); - exit; -} - -// Test 5: Spalten prüfen -try { - $columns = $db->fetchAll("SHOW COLUMNS FROM vouchers"); - $columnNames = array_column($columns, 'Field'); - echo "\n" . json_encode(['step' => 6, 'message' => 'Voucher-Spalten', 'columns' => $columnNames]); - - // Prüfen ob neue Spalten existieren - $required = ['status', 'used_count', 'expires_at', 'synced_from_unifi', 'last_sync']; - $missing = array_diff($required, $columnNames); - - if (!empty($missing)) { - echo "\n" . json_encode(['step' => 7, 'warning' => 'Fehlende Spalten', 'missing' => array_values($missing)]); - } else { - echo "\n" . json_encode(['step' => 7, 'message' => 'Alle Spalten vorhanden']); - } -} catch (Exception $e) { - echo "\n" . json_encode(['step' => 6, 'error' => $e->getMessage()]); - exit; -} - -// Test 6: Token prüfen -try { - $token = $db->getSetting('cron_token', ''); - echo "\n" . json_encode(['step' => 8, 'message' => 'Token Status', 'has_token' => !empty($token)]); -} catch (Exception $e) { - echo "\n" . json_encode(['step' => 8, 'error' => $e->getMessage()]); - exit; -} - -echo "\n" . json_encode(['final' => 'Alle Tests erfolgreich!']); diff --git a/docs/screenshots/admin-dashboard-dark.png b/docs/screenshots/admin-dashboard-dark.png index effa5ff..58181d8 100644 Binary files a/docs/screenshots/admin-dashboard-dark.png and b/docs/screenshots/admin-dashboard-dark.png differ diff --git a/docs/screenshots/admin-dashboard.png b/docs/screenshots/admin-dashboard.png index 1c06c88..0b5e065 100644 Binary files a/docs/screenshots/admin-dashboard.png and b/docs/screenshots/admin-dashboard.png differ diff --git a/docs/screenshots/api-keys.png b/docs/screenshots/api-keys.png index 2053175..3a86c44 100644 Binary files a/docs/screenshots/api-keys.png and b/docs/screenshots/api-keys.png differ diff --git a/docs/screenshots/bulk-vouchers.png b/docs/screenshots/bulk-vouchers.png index 4ceb658..e273f3f 100644 Binary files a/docs/screenshots/bulk-vouchers.png and b/docs/screenshots/bulk-vouchers.png differ diff --git a/docs/screenshots/integrations.png b/docs/screenshots/integrations.png index 78d18b8..6a50699 100644 Binary files a/docs/screenshots/integrations.png and b/docs/screenshots/integrations.png differ diff --git a/docs/screenshots/kiosk-branded.png b/docs/screenshots/kiosk-branded.png index 4fd41bc..9fd3435 100644 Binary files a/docs/screenshots/kiosk-branded.png and b/docs/screenshots/kiosk-branded.png differ diff --git a/docs/screenshots/kiosk-code.png b/docs/screenshots/kiosk-code.png index 4a6d7a8..bd03a36 100644 Binary files a/docs/screenshots/kiosk-code.png and b/docs/screenshots/kiosk-code.png differ diff --git a/docs/screenshots/kiosk-display.png b/docs/screenshots/kiosk-display.png index 2b984ca..f290ac4 100644 Binary files a/docs/screenshots/kiosk-display.png and b/docs/screenshots/kiosk-display.png differ diff --git a/docs/screenshots/kiosks-admin.png b/docs/screenshots/kiosks-admin.png index 1d793e3..5bbe14a 100644 Binary files a/docs/screenshots/kiosks-admin.png and b/docs/screenshots/kiosks-admin.png differ diff --git a/docs/screenshots/kiosks-form.png b/docs/screenshots/kiosks-form.png index 2121081..471bd42 100644 Binary files a/docs/screenshots/kiosks-form.png and b/docs/screenshots/kiosks-form.png differ diff --git a/docs/screenshots/login-branding.png b/docs/screenshots/login-branding.png index 799d8a9..18143c5 100644 Binary files a/docs/screenshots/login-branding.png and b/docs/screenshots/login-branding.png differ diff --git a/docs/screenshots/login.png b/docs/screenshots/login.png index 133e8f0..e5cd21a 100644 Binary files a/docs/screenshots/login.png and b/docs/screenshots/login.png differ diff --git a/docs/screenshots/maintenance.png b/docs/screenshots/maintenance.png index 55d6e4d..0bb19eb 100644 Binary files a/docs/screenshots/maintenance.png and b/docs/screenshots/maintenance.png differ diff --git a/docs/screenshots/mobile-vouchers.png b/docs/screenshots/mobile-vouchers.png index bc29c3c..a248f1d 100644 Binary files a/docs/screenshots/mobile-vouchers.png and b/docs/screenshots/mobile-vouchers.png differ diff --git a/docs/screenshots/settings-branding.png b/docs/screenshots/settings-branding.png index 0bdd9a3..dcd7e09 100644 Binary files a/docs/screenshots/settings-branding.png and b/docs/screenshots/settings-branding.png differ diff --git a/docs/screenshots/settings-login.png b/docs/screenshots/settings-login.png index af8de26..195a296 100644 Binary files a/docs/screenshots/settings-login.png and b/docs/screenshots/settings-login.png differ diff --git a/docs/screenshots/settings.png b/docs/screenshots/settings.png index 04299ec..a39bff9 100644 Binary files a/docs/screenshots/settings.png and b/docs/screenshots/settings.png differ diff --git a/docs/screenshots/two-factor.png b/docs/screenshots/two-factor.png index 0754713..e0ded5b 100644 Binary files a/docs/screenshots/two-factor.png and b/docs/screenshots/two-factor.png differ diff --git a/docs/screenshots/updater-available.png b/docs/screenshots/updater-available.png index 1ee6cd6..794fe85 100644 Binary files a/docs/screenshots/updater-available.png and b/docs/screenshots/updater-available.png differ diff --git a/docs/screenshots/updater.png b/docs/screenshots/updater.png index 1ee6cd6..18e4d35 100644 Binary files a/docs/screenshots/updater.png and b/docs/screenshots/updater.png differ diff --git a/docs/screenshots/voucher-form.png b/docs/screenshots/voucher-form.png index 776bbf5..b705f62 100644 Binary files a/docs/screenshots/voucher-form.png and b/docs/screenshots/voucher-form.png differ diff --git a/docs/screenshots/voucher-result.png b/docs/screenshots/voucher-result.png index 7119d7d..9445225 100644 Binary files a/docs/screenshots/voucher-result.png and b/docs/screenshots/voucher-result.png differ diff --git a/docs/screenshots/vouchers.png b/docs/screenshots/vouchers.png index 6f8204c..174594b 100644 Binary files a/docs/screenshots/vouchers.png and b/docs/screenshots/vouchers.png differ diff --git a/forgot_password.php b/forgot_password.php index de98f60..0fb25e9 100644 --- a/forgot_password.php +++ b/forgot_password.php @@ -1,4 +1,7 @@ 'Sicherheit (2FA)', 'nav_integrations' => 'Integration & Wartung', 'nav_backup' => 'Backup & Restore', - 'nav_update' => 'System-Update', + 'nav_update' => 'Aktualisierung', 'nav_back' => 'Zurück zur Startseite', 'nav_administration'=> 'Administration', @@ -667,4 +667,48 @@ return [ 'never' => 'Noch nie', 'unknown' => 'Unbekannt', 'or' => 'oder', + + // Selbst-Updater + 'update_title' => 'Aktualisierung', + 'update_subtitle' => 'Neue Fassungen prüfen und ohne Serverzugang einspielen.', + 'update_installed' => 'Installierter Stand', + 'update_version' => 'Version', + 'update_state' => 'Stand', + 'update_state_unknown' => 'Noch nicht ermittelt – einmal nach Updates suchen.', + 'update_channel' => 'Kanal', + 'update_channel_change' => 'Kanal wechseln', + 'update_channel_save' => 'Kanal übernehmen', + 'update_channel_hint' => 'Der Entwicklungskanal führt Vorabfassungen. Für den laufenden Betrieb ist „Stabil“ die richtige Wahl.', + 'update_search' => 'Nach Updates suchen', + 'update_search_btn' => 'Nach Updates suchen', + 'update_install_btn' => 'Jetzt aktualisieren', + 'update_migrations' => 'Datenbank-Migrationen', + 'update_migrations_hint' => '{total} Migrationen insgesamt, davon {open} offen.', + 'update_migrations_btn' => 'Migrationen ausführen', + 'update_migration_file' => 'Datei', + 'update_migration_state' => 'Status', + 'update_migration_applied' => 'Angewendet', + 'update_migration_open' => 'Offen', + 'update_history' => 'Änderungsprotokoll', + 'update_history_empty' => 'Für diese Fassung liegt kein Änderungsprotokoll bei.', + 'update_privacy_title' => 'Datenschutzhinweis', + 'update_privacy_intro' => 'Bei der Suche nach Updates und beim Herunterladen einer neuen Fassung werden Daten an update.loheide.cloud übertragen. Übermittelt werden:', + 'update_privacy_item_state' => 'der bei Ihnen installierte Stand, damit die Gegenstelle weiß, was neu ist', + 'update_privacy_item_tech' => 'technisch bedingt: Ihre IP-Adresse, Datum und Uhrzeit des Abrufs', + 'update_privacy_purpose' => 'Zweck: Bereitstellung der Aktualisierung.', + 'update_privacy_not' => 'Nicht übertragen werden Inhalte aus diesem Programm: keine Dokumente, keine Datenbank, keine Eingaben. Die Verbindung ist verschlüsselt.', + 'update_privacy_retention' => 'Zugriffe auf die Update-Endpunkte werden serverseitig 400 Tage aufbewahrt, danach gelöscht.', + 'update_privacy_link' => 'Datenschutzerklärung dieser Installation', + 'update_js_checking' => 'Es wird gesucht …', + 'update_js_current' => 'Diese Installation ist auf dem neuesten Stand.', + 'update_js_available' => 'Eine neue Fassung ist verfügbar.', + 'update_js_behind' => '{count} Stand/Stände zurück', + 'update_js_target' => 'Zielversion:', + 'update_js_installing' => 'Aktualisierung wird vorbereitet …', + 'update_js_done' => 'Aktualisierung abgeschlossen.', + 'update_js_failed' => 'Die Aktualisierung ist fehlgeschlagen.', + 'update_js_more' => 'Vollständiges Änderungsprotokoll ansehen', + 'update_js_channel_switch' => 'Der gemeldete Stand stammt aus dem Kanal {to} (bisher {from}).', + 'update_js_confirm' => 'Jetzt aktualisieren? Die Seite ist währenddessen kurz nicht erreichbar.', + 'update_js_migrated' => '{count} Migration(en) ausgeführt.', ]; diff --git a/lang/en.php b/lang/en.php index ed8fc9c..d7125f7 100644 --- a/lang/en.php +++ b/lang/en.php @@ -17,7 +17,7 @@ return [ 'nav_security' => 'Security (2FA)', 'nav_integrations' => 'Integration & Maintenance', 'nav_backup' => 'Backup & Restore', - 'nav_update' => 'System Update', + 'nav_update' => 'Update', 'nav_back' => 'Back to Home', 'nav_administration'=> 'Administration', @@ -667,4 +667,48 @@ return [ 'never' => 'Never', 'unknown' => 'Unknown', 'or' => 'or', + + // Self updater + 'update_title' => 'Update', + 'update_subtitle' => 'Check for new versions and install them without server access.', + 'update_installed' => 'Installed version', + 'update_version' => 'Version', + 'update_state' => 'Revision', + 'update_state_unknown' => 'Not determined yet – run a check once.', + 'update_channel' => 'Channel', + 'update_channel_change' => 'Change channel', + 'update_channel_save' => 'Apply channel', + 'update_channel_hint' => 'The development channel carries pre-releases. For production use, pick "stable".', + 'update_search' => 'Check for updates', + 'update_search_btn' => 'Check for updates', + 'update_install_btn' => 'Update now', + 'update_migrations' => 'Database migrations', + 'update_migrations_hint' => '{total} migrations in total, {open} of them pending.', + 'update_migrations_btn' => 'Run migrations', + 'update_migration_file' => 'File', + 'update_migration_state' => 'Status', + 'update_migration_applied' => 'Applied', + 'update_migration_open' => 'Pending', + 'update_history' => 'Changelog', + 'update_history_empty' => 'No changelog shipped with this version.', + 'update_privacy_title' => 'Privacy notice', + 'update_privacy_intro' => 'Checking for updates and downloading a new version transmits data to update.loheide.cloud. Transmitted are:', + 'update_privacy_item_state' => 'the version installed on your side, so the service knows what is new', + 'update_privacy_item_tech' => 'for technical reasons: your IP address, date and time of the request', + 'update_privacy_purpose' => 'Purpose: delivering the update.', + 'update_privacy_not' => 'No content from this application is transmitted: no documents, no database, no input. The connection is encrypted.', + 'update_privacy_retention' => 'Requests to the update endpoints are kept on the server for 400 days and deleted afterwards.', + 'update_privacy_link' => 'Privacy policy of this installation', + 'update_js_checking' => 'Checking …', + 'update_js_current' => 'This installation is up to date.', + 'update_js_available' => 'A new version is available.', + 'update_js_behind' => '{count} revision(s) behind', + 'update_js_target' => 'Target version:', + 'update_js_installing' => 'Preparing the update …', + 'update_js_done' => 'Update completed.', + 'update_js_failed' => 'The update failed.', + 'update_js_more' => 'View the full changelog', + 'update_js_channel_switch' => 'The reported revision comes from channel {to} (previously {from}).', + 'update_js_confirm' => 'Update now? The site will be briefly unavailable.', + 'update_js_migrated' => '{count} migration(s) applied.', ]; diff --git a/m365_callback.php b/m365_callback.php index 584e77f..3ffd401 100644 --- a/m365_callback.php +++ b/m365_callback.php @@ -1,4 +1,7 @@ requireAdmin(); +// Ohne config.php gibt es keine Anmeldung - und damit auch keine Diagnose. +// Sonst laege auf einer frisch entpackten, noch nicht eingerichteten +// Installation eine Seite mit PHP- und Serverdaten offen im Netz. +if (!file_exists(__DIR__ . '/config.php')) { + http_response_code(503); + header('Content-Type: text/plain; charset=utf-8'); + echo "Diese Installation ist noch nicht eingerichtet. Bitte zuerst install.php aufrufen.\n"; + exit; } +require_once __DIR__ . '/config.php'; +require_once __DIR__ . '/includes/Database.php'; +require_once __DIR__ . '/includes/Auth.php'; +require_once __DIR__ . '/includes/Crypto.php'; +$auth = new Auth(); +$auth->requireAdmin(); + echo '' . '' . 'System-Test' diff --git a/tests/UpdaterTest.php b/tests/UpdaterTest.php new file mode 100644 index 0000000..4209dcf --- /dev/null +++ b/tests/UpdaterTest.php @@ -0,0 +1,302 @@ +tmp = sys_get_temp_dir() . '/uvt-updater-' . bin2hex(random_bytes(6)); + mkdir($this->tmp, 0775, true); + Version::useStorageDir($this->tmp . '/storage'); + mkdir($this->tmp . '/storage', 0775, true); + } + + protected function tearDown(): void + { + Version::useStorageDir(null); + $this->removeTree($this->tmp); + } + + // ------------------------------------------------------------- Version + + public function testVersionIsStoredAndReadBack(): void + { + $sha = str_repeat('a1b2c3d4', 5); + + $this->assertNull(Version::current(), 'Frische Installation kennt noch keinen Stand'); + $this->assertTrue(Version::save($sha)); + $this->assertSame($sha, Version::current()); + $this->assertSame(substr($sha, 0, 7), Version::short()); + } + + /** + * Eine halbe Proxy-Antwort darf sich nicht als Version einzementieren - + * sonst meldet die Installation dauerhaft einen Stand, den es nicht gibt. + */ + public function testInvalidRevisionIsRejected(): void + { + foreach (['', 'nope', str_repeat('z', 40), str_repeat('ab', 10)] as $bad) { + $this->assertFalse(Version::save($bad), 'Abgelehnt werden muss: ' . var_export($bad, true)); + } + $this->assertNull(Version::current()); + } + + public function testReleaseConstantMatchesVersionFile(): void + { + $file = trim((string)file_get_contents(dirname(__DIR__) . '/VERSION')); + + $this->assertSame($file, Version::RELEASE, 'VERSION-Datei und Konstante duerfen nicht auseinanderlaufen'); + } + + // --------------------------------------------------------- Wartungsmodus + + public function testMaintenanceCanBeSwitchedOnAndOff(): void + { + $this->assertFalse(Maintenance::isActive()); + Maintenance::activate(); + $this->assertTrue(Maintenance::isActive()); + Maintenance::deactivate(); + $this->assertFalse(Maintenance::isActive()); + } + + /** + * Ohne Selbstheilung legt ein Absturz mitten im Update die Installation + * dauerhaft lahm - und niemand kaeme mehr an die Oberflaeche, um den + * Modus abzuschalten. + */ + public function testMaintenanceHealsItselfAfterExpiry(): void + { + file_put_contents( + $this->tmp . '/storage/.maintenance', + json_encode(['since' => time() - 7200, 'until' => time() - 60]) + ); + + $this->assertFalse(Maintenance::isActive(), 'Abgelaufene Wartung darf nicht mehr greifen'); + $this->assertFileDoesNotExist($this->tmp . '/storage/.maintenance', 'und wird dabei aufgeraeumt'); + } + + // -------------------------------------------------------------- Fortschritt + + public function testProgressIsWrittenAndRead(): void + { + Progress::set(42, 'download', 'Update wird geladen …'); + $state = Progress::get(); + + $this->assertSame(42, $state['pct']); + $this->assertSame('download', $state['step']); + $this->assertSame('Update wird geladen …', $state['text']); + $this->assertTrue(Progress::isRunning()); + } + + /** pct = -1 trennt "fehlgeschlagen" eindeutig von "0 % erledigt". */ + public function testProgressErrorStateIsDistinguishable(): void + { + Progress::error('Der Update-Dienst ist nicht erreichbar.'); + $state = Progress::get(); + + $this->assertSame(-1, $state['pct']); + $this->assertSame('error', $state['step']); + $this->assertFalse(Progress::isRunning()); + } + + /** Ein abgestuerzter Lauf darf den naechsten nicht dauerhaft blockieren. */ + public function testStaleProgressDoesNotCountAsRunning(): void + { + file_put_contents($this->tmp . '/storage/.update-progress', json_encode([ + 'pct' => 50, + 'step' => 'extract', + 'text' => 'haengt seit gestern', + 'ts' => time() - (Progress::STALE_AFTER + 60), + ])); + + $this->assertFalse(Progress::isRunning()); + } + + // ------------------------------------------------------------- ZIP-Slip + + public function testEntryNamesOutsideTheArchiveAreRejected(): void + { + foreach (['../evil.php', 'a/../../evil.php', '/etc/passwd', 'C:\\windows\\evil', "ok\0.php"] as $bad) { + $this->assertFalse(Updater::isSafeEntryName($bad), 'Abgelehnt werden muss: ' . $bad); + } + foreach (['index.php', 'admin/index.php', 'a/b/c.txt'] as $good) { + $this->assertTrue(Updater::isSafeEntryName($good)); + } + } + + public function testZipSlipEntryNeverLandsOutsideTheStagingArea(): void + { + $zipPath = $this->tmp . '/slip.zip'; + $zip = new \ZipArchive(); + $this->assertTrue($zip->open($zipPath, \ZipArchive::CREATE) === true); + $zip->addFromString('harmlos.txt', 'ok'); + $zip->addFromString('../evil.txt', 'boesartig'); + $zip->addFromString('a/../../auch-boese.txt', 'boesartig'); + $zip->close(); + + $staging = $this->tmp . '/staging'; + $updater = new Updater(null, null, 'stable', null, $this->tmp . '/root'); + $written = $updater->extractZip($zipPath, $staging); + + $this->assertSame(1, $written, 'Nur der harmlose Eintrag darf ankommen'); + $this->assertFileExists($staging . '/harmlos.txt'); + $this->assertFileDoesNotExist($this->tmp . '/evil.txt'); + $this->assertFileDoesNotExist($this->tmp . '/auch-boese.txt'); + } + + // ------------------------------------------------------- Geschuetzte Pfade + + public function testProtectedPathsAreRecognised(): void + { + $this->assertTrue(Updater::isProtected('config.php')); + $this->assertTrue(Updater::isProtected('uploads/logo.png')); + $this->assertTrue(Updater::isProtected('updater/storage/.version')); + $this->assertFalse(Updater::isProtected('index.php')); + $this->assertFalse(Updater::isProtected('updater/Updater.php')); + $this->assertFalse(Updater::isProtected('uploads.php'), 'Der Ordnername darf nicht auf Dateien durchschlagen'); + } + + public function testApplyStagingKeepsProtectedFilesAndUpdatesTheRest(): void + { + $root = $this->tmp . '/root'; + mkdir($root . '/uploads', 0775, true); + file_put_contents($root . '/config.php', 'tmp . '/staging-apply'; + mkdir($staging . '/uploads', 0775, true); + file_put_contents($staging . '/config.php', 'applyStaging($staging); + + $this->assertSame('assertSame('altes Logo', file_get_contents($root . '/uploads/logo.png')); + $this->assertSame('neu', file_get_contents($root . '/index.php')); + $this->assertSame('neue Datei', file_get_contents($root . '/neu.php')); + $this->assertSame(2, $applied, 'Nur die ungeschuetzten Dateien zaehlen'); + } + + public function testApplyStagingLeavesNoHalfWrittenFiles(): void + { + $root = $this->tmp . '/root2'; + mkdir($root, 0775, true); + $staging = $this->tmp . '/staging2'; + mkdir($staging, 0775, true); + file_put_contents($staging . '/index.php', 'applyStaging($staging); + + $this->assertFileExists($root . '/index.php'); + $this->assertFileDoesNotExist($root . '/index.php.new', 'Die Zwischendatei muss verschwinden'); + } + + // ------------------------------------------------------------ Migrationen + + public function testMigrationRunnerCountsOnlyPendingFiles(): void + { + $dir = $this->tmp . '/migrations'; + mkdir($dir, 0775, true); + file_put_contents($dir . '/0001_erste.sql', 'CREATE TABLE test_a (id INTEGER PRIMARY KEY);'); + file_put_contents($dir . '/0002_zweite.sql', 'CREATE TABLE test_b (id INTEGER PRIMARY KEY);'); + + $pdo = new \PDO('sqlite::memory:'); + $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + $runner = new MigrationRunner($pdo, $dir, $this->tmp . '/storage'); + + $this->assertCount(2, $runner->runPending(true)); + $this->assertCount(0, $runner->runPending(true), 'Ein zweiter Lauf hat nichts mehr zu tun'); + + $status = $runner->status(); + $this->assertCount(2, $status); + $this->assertTrue($status[0]['applied']); + } + + /** Der Fingerabdruck entscheidet, ob ueberhaupt migriert wird. */ + public function testMigrationFingerprintChangesWithTheFiles(): void + { + $dir = $this->tmp . '/migrations-fp'; + mkdir($dir, 0775, true); + file_put_contents($dir . '/0001_a.sql', 'SELECT 1;'); + $before = \Updater\AutoMigrate::fingerprint($dir); + + file_put_contents($dir . '/0002_b.sql', 'SELECT 1;'); + $after = \Updater\AutoMigrate::fingerprint($dir); + + $this->assertNotSame($before, $after); + $this->assertSame($after, \Updater\AutoMigrate::fingerprint($dir), 'Ohne Aenderung bleibt er gleich'); + } + + // -------------------------------------------------------------- Changelog + + public function testChangelogIsSplitIntoVersions(): void + { + $markdown = "# Änderungsprotokoll\n\n## 3.0.0 – 2026-09-25\n\n- Selbst-Updater\n- Wartungsmodus\n\n## 2.9.0 – 2026-09-24\n\n- Display-Seiten\n"; + $sections = Changelog::sections($markdown); + + $this->assertCount(2, $sections); + $this->assertSame('3.0.0', $sections[0]['version']); + $this->assertStringContainsString('Selbst-Updater', $sections[0]['text']); + $this->assertSame('2.9.0', $sections[1]['version']); + } + + public function testChangelogRendersListsAndKeepsUnsafeLinksOut(): void + { + $html = Changelog::toHtml("- Erster Punkt mit **Nachdruck**\n- [Doku](https://example.com/doku)\n- [Böse](javascript:alert(1))\n"); + + $this->assertStringContainsString(''; + $listOpen = false; + } + continue; + } + + if (preg_match('/^[-*+]\s+(.*)$/', $trimmed, $m)) { + $html .= self::paragraph($paragraph); + $paragraph = []; + if (!$listOpen) { + $html .= ''; + $listOpen = false; + } + $html .= '

' . self::inline($m[1]) . '

'; + continue; + } + + $paragraph[] = $trimmed; + } + + $html .= self::paragraph($paragraph); + if ($listOpen) { + $html .= ''; + } + + return $html; + } + + /** + * @param array $lines + */ + private static function paragraph(array $lines): string + { + return $lines === [] ? '' : '

' . self::inline(implode(' ', $lines)) . '

'; + } + + /** Fetter/kursiver Text, Code und sichere Verweise. */ + private static function inline(string $text): string + { + $escaped = htmlspecialchars($text, ENT_QUOTES, 'UTF-8'); + + $escaped = preg_replace_callback( + '/\[([^\]]+)\]\(([^)\s]+)\)/', + function ($m) { + $label = $m[1]; + $url = html_entity_decode($m[2], ENT_QUOTES, 'UTF-8'); + if (!preg_match('#^https?://#i', $url)) { + return $label; // unsichere Ziele verlieren den Verweis + } + + return '
' . $label . ''; + }, + $escaped + ); + + $escaped = preg_replace('/`([^`]+)`/', '$1', $escaped); + $escaped = preg_replace('/\*\*([^*]+)\*\*/', '$1', $escaped); + $escaped = preg_replace('/(?$1', $escaped); + + return (string)$escaped; + } +} diff --git a/updater/Maintenance.php b/updater/Maintenance.php new file mode 100644 index 0000000..a4f0601 --- /dev/null +++ b/updater/Maintenance.php @@ -0,0 +1,91 @@ + time(), + 'until' => time() + $maxSeconds, + ])); + } + + public static function deactivate(): void + { + $file = self::file(); + if (is_file($file)) { + @unlink($file); + } + } + + /** + * @return array{since:int, until:int}|null + */ + public static function info(): ?array + { + $file = self::file(); + if (!is_file($file)) { + return null; + } + + $data = json_decode((string)@file_get_contents($file), true); + if (!is_array($data) || !isset($data['until'])) { + // Aeltere oder beschaedigte Markierung: ab der Dateizeit rechnen, + // damit auch sie von allein ablaeuft. + $since = (int)@filemtime($file); + + return ['since' => $since, 'until' => $since + self::DEFAULT_MAX_SECONDS]; + } + + return ['since' => (int)($data['since'] ?? 0), 'until' => (int)$data['until']]; + } + + public static function isActive(): bool + { + $info = self::info(); + if ($info === null) { + return false; + } + + if ($info['until'] <= time()) { + self::deactivate(); + + return false; + } + + return true; + } + + /** Verbleibende Sekunden, mindestens 5 - fuer den Retry-After-Kopf. */ + public static function retryAfter(): int + { + $info = self::info(); + if ($info === null) { + return 0; + } + + return max(5, $info['until'] - time()); + } +} diff --git a/updater/Progress.php b/updater/Progress.php new file mode 100644 index 0000000..3bebf32 --- /dev/null +++ b/updater/Progress.php @@ -0,0 +1,90 @@ + 0, 'step' => 'idle', 'text' => '', 'ts' => 0]; + } + + $data = json_decode((string)@file_get_contents($file), true); + if (!is_array($data)) { + return ['pct' => 0, 'step' => 'idle', 'text' => '', 'ts' => 0]; + } + + return [ + 'pct' => (int)($data['pct'] ?? 0), + 'step' => (string)($data['step'] ?? 'idle'), + 'text' => (string)($data['text'] ?? ''), + 'ts' => (int)($data['ts'] ?? 0), + ]; + } + + public static function set(int $pct, string $step, string $text): void + { + $dir = Version::storageDir(); + if (!is_dir($dir)) { + @mkdir($dir, 0775, true); + } + + @file_put_contents(self::file(), json_encode([ + 'pct' => $pct, + 'step' => $step, + 'text' => $text, + 'ts' => time(), + ], JSON_UNESCAPED_UNICODE)); + } + + /** + * Fehlerzustand. pct = -1 statt 0, damit sich "fehlgeschlagen" nicht als + * "0 % erledigt" liest - die Oberflaeche kann beides sonst nicht trennen. + */ + public static function error(string $text): void + { + self::set(-1, 'error', $text); + } + + /** + * Laeuft gerade ein Update? Ein abgestuerzter Lauf wuerde den naechsten + * sonst dauerhaft blockieren, deshalb zaehlt nur ein frisches + * Lebenszeichen. + */ + public static function isRunning(): bool + { + $state = self::get(); + if (in_array($state['step'], ['idle', 'done', 'error'], true)) { + return false; + } + + return (time() - $state['ts']) < self::STALE_AFTER; + } + + public static function clear(): void + { + $file = self::file(); + if (is_file($file)) { + @unlink($file); + } + } +} diff --git a/updater/ProxyClient.php b/updater/ProxyClient.php new file mode 100644 index 0000000..297daa5 --- /dev/null +++ b/updater/ProxyClient.php @@ -0,0 +1,217 @@ +baseUrl = $baseUrl; + } + + public function baseUrl(): string + { + return $this->baseUrl; + } + + /** Neuester Stand des Kanals. */ + public function version(): array + { + return $this->getJson('/version'); + } + + /** + * Vergleicht den installierten Stand mit dem Kanal. + * Ohne SHA antwortet der Proxy wie "aktuell" - die erste Pruefung einer + * frischen Installation liefert also latest_sha zum Merken. + */ + public function check(?string $currentSha): array + { + $path = '/check'; + if ($currentSha !== null && $currentSha !== '') { + $path .= '?current_sha=' . urlencode($currentSha); + } + + return $this->getJson($path); + } + + /** Aenderungsprotokoll des aktuellen Stands als Markdown. */ + public function changelogRaw(): string + { + [$status, $body, $type] = $this->request('/changelog?format=raw', self::TIMEOUT_JSON); + if ($status === 404) { + return ''; + } + $this->guardRetry($status, $body); + if ($status !== 200 || stripos((string)$type, 'json') !== false) { + return ''; + } + + return (string)$body; + } + + /** + * Laedt das ZIP in eine Datei - bewusst als Stream, nicht in den Speicher. + * + * @return array{sha:string, content_sha256:string} + */ + public function downloadZip(string $sha, string $target): array + { + if (!Version::isSha($sha)) { + throw new \RuntimeException('Ungueltiger Ziel-Stand fuer den Download.'); + } + + $fh = @fopen($target, 'w'); + if ($fh === false) { + throw new \RuntimeException( + 'Update-Paket kann nicht gespeichert werden. Schreibrechte fuer updater/storage/ pruefen.' + ); + } + + $headers = []; + $ch = curl_init($this->baseUrl . '/zip?ref=' . urlencode($sha)); + curl_setopt_array($ch, [ + CURLOPT_FILE => $fh, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_MAXREDIRS => self::MAX_REDIRECTS, + CURLOPT_PROTOCOLS => CURLPROTO_HTTPS, + CURLOPT_REDIR_PROTOCOLS=> CURLPROTO_HTTPS, + CURLOPT_SSL_VERIFYPEER => true, + CURLOPT_SSL_VERIFYHOST => 2, + CURLOPT_TIMEOUT => self::TIMEOUT_ZIP, + CURLOPT_CONNECTTIMEOUT => 15, + CURLOPT_USERAGENT => self::USER_AGENT, + CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$headers) { + $parts = explode(':', $line, 2); + if (count($parts) === 2) { + $headers[strtolower(trim($parts[0]))] = trim($parts[1]); + } + + return strlen($line); + }, + ]); + $ok = curl_exec($ch); + $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); + $err = curl_error($ch); + curl_close($ch); + fclose($fh); + + if (!$ok || $status !== 200) { + $body = (string)@file_get_contents($target, false, null, 0, 400); + @unlink($target); + $this->guardRetry($status, $body); + throw new \RuntimeException( + $err !== '' + ? 'Update-Paket konnte nicht geladen werden: ' . $err + : 'Update-Paket konnte nicht geladen werden (HTTP ' . $status . ').' + ); + } + + return [ + 'sha' => $headers['x-commit-sha'] ?? $sha, + 'content_sha256' => $headers['x-content-sha256'] ?? '', + ]; + } + + // ------------------------------------------------------------- intern + + private function getJson(string $path): array + { + [$status, $body] = $this->request($path, self::TIMEOUT_JSON); + $this->guardRetry($status, $body); + + $data = json_decode((string)$body, true); + if (!is_array($data)) { + throw new \RuntimeException( + 'Der Update-Dienst hat keine verwertbare Antwort geliefert (HTTP ' . $status . ').' + ); + } + // Der Proxy kann einen Fehler auch mit HTTP 200 senden. + if (isset($data['error'])) { + throw new \RuntimeException('Update-Dienst meldet: ' . (string)$data['error']); + } + if ($status !== 200) { + throw new \RuntimeException('Update-Dienst nicht erreichbar (HTTP ' . $status . ').'); + } + + return $data; + } + + /** + * 503 mit mirror_pending/not_released ist kein Fehler des Clients: + * der Stand wird gerade gespiegelt oder ist noch nicht freigegeben. + */ + private function guardRetry(int $status, $body): void + { + if ($status !== 503) { + return; + } + + $data = json_decode((string)$body, true); + $code = is_array($data) ? (string)($data['error'] ?? '') : ''; + $retry = is_array($data) ? (int)($data['retry_after'] ?? 60) : 60; + + if ($code === 'not_released') { + throw new RetryLaterException( + 'Beim Update-Dienst liegt noch keine freigegebene Fassung bereit. Bitte spaeter erneut versuchen.', + $retry + ); + } + + throw new RetryLaterException( + 'Der Update-Dienst bereitet den neuen Stand gerade vor. Bitte in Kuerze erneut versuchen.', + $retry + ); + } + + /** + * @return array{0:int, 1:string, 2:string} + */ + private function request(string $path, int $timeout): array + { + $ch = curl_init($this->baseUrl . $path); + curl_setopt_array($ch, [ + CURLOPT_RETURNTRANSFER => true, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_MAXREDIRS => self::MAX_REDIRECTS, + CURLOPT_PROTOCOLS => CURLPROTO_HTTPS, + CURLOPT_REDIR_PROTOCOLS=> CURLPROTO_HTTPS, + CURLOPT_SSL_VERIFYPEER => true, + CURLOPT_SSL_VERIFYHOST => 2, + CURLOPT_TIMEOUT => $timeout, + CURLOPT_CONNECTTIMEOUT => 10, + CURLOPT_USERAGENT => self::USER_AGENT, + ]); + $body = curl_exec($ch); + $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); + $type = (string)curl_getinfo($ch, CURLINFO_CONTENT_TYPE); + $err = curl_error($ch); + curl_close($ch); + + if ($body === false) { + throw new \RuntimeException('Update-Dienst nicht erreichbar: ' . $err); + } + + return [$status, (string)$body, $type]; + } +} diff --git a/updater/README.md b/updater/README.md index c1701ef..4f6f8c7 100644 --- a/updater/README.md +++ b/updater/README.md @@ -1,88 +1,125 @@ -# Updater (OpenVoucherTool) +# Selbst-Updater -Auto-Update-System nach dem OpenNIT-Modell: zieht Quellcode + DB-Migrationen -aus einem zentralen Repository über einen HTTP-Update-Proxy nach. +Aktualisiert eine laufende Installation per Klick im Administrationsbereich – +**ohne Zugang zum Server**. Quellcode und Datenbank-Migrationen kommen über +einen Update-Dienst, der den aktuellen Stand eines Branches als ZIP bereitstellt. ``` -[diese App] ←HTTPS→ [Update-Proxy] ←pull→ [Git-Repo] +[diese Installation] ←HTTPS→ [Update-Dienst] ←pull→ [Git-Repository] ``` -- **Versions-Identität:** 40-stelliger Git-Commit-SHA in `updater/storage/.version` -- **Channels:** `stable` → `https://update.loheide.eu/openvouchertool`, - `development` → `https://update.loheide.eu/openvouchertool-development` -- **User-Agent:** `OpenVoucherTool-Updater/1.0` -- **DB-Treiber:** MySQL/MariaDB (Migrations-Tracking-Tabelle `_updater_migrations`) +Es gibt **keine Tags und keine Releases**: gezählt wird der Stand des Branches, +und die Identität eines Stands ist sein Commit-SHA. „Ein Stand zurück“ heißt +also ein Commit zurück, nicht eine Versionsnummer. -## Aufruf +## Dateien -Admin-Oberfläche: **`/admin/update.php`** (nur für angemeldete Admins). +| Datei | Aufgabe | +|---|---| +| `Version.php` | Release-Version (Konstante) und installierter Commit-SHA (`storage/.version`) | +| `Progress.php` | Fortschrittsdatei `storage/.update-progress`, inklusive Fehlerzustand | +| `Maintenance.php` | Wartungsmarkierung `storage/.maintenance`, läuft von allein aus | +| `ProxyClient.php` | HTTP-Client für den Update-Dienst, nur HTTPS | +| `Updater.php` | Kern: prüfen, laden, entpacken, übernehmen, migrieren | +| `UpdaterFactory.php` | Kanalwahl, persistiert in `storage/updater-settings.json` | +| `AutoMigrate.php` | zieht Migrationen beim ersten Seitenaufruf nach einem Update nach | +| `MigrationRunner.php` | führt die SQL-Dateien aus `migrations/` aus | +| `Changelog.php` | zerlegt die `CHANGELOG.md` und rendert Markdown | +| `AuditLogger.php` | schreibt jeden Lauf in die Tabelle `audit_log` | +| `guard.php` | Wartungs-Wächter für die Einstiegsseiten | +| `UpdateController.php` | die JSON-Endpunkte | +| `templates/maintenance.php` | eigenständige Wartungsseite | -| Endpoint | Methode | Zweck | -|---|---|---| -| `admin/update.php` | GET | Admin-UI | -| `admin/update.php?action=check` | GET | Update-Prüfung (JSON) | -| `admin/update.php?action=progress` | GET | Fortschritt (JSON) | -| `admin/update.php?action=migrations` | GET | Migrations-Status (JSON) | -| `admin/update.php` `action=install` | POST | Update installieren (+`csrf_token`) | -| `admin/update.php` `action=set_channel` | POST | Channel wählen (+`csrf_token`) | +## Ablauf einer Aktualisierung -> Optional: In der Admin-Navigation (`admin/index.php`) einen Link zu -> `update.php` ergänzen, damit die Seite auffindbar ist. Das ist bewusst -> **nicht** automatisch geschehen (Isolations-Prinzip – siehe unten). +| Fortschritt | Schritt | +|---|---| +| 0 % | Wartungsmodus aktivieren | +| 5 % | `GET /version` – Ziel-Stand ermitteln | +| 20 % | `GET /zip?ref=` in eine Datei streamen, gegen `X-Content-Sha256` prüfen | +| 50 % | nach `storage/.update-staging` entpacken, gemeinsamen Deckel-Ordner strippen | +| 65 % | über die Produktion legen, geschützte Pfade auslassen | +| 80 % | ausstehende Migrationen ausführen | +| 90 % | Zwischenspeicher und Bytecode-Cache leeren | +| 100 % | neuen Stand speichern, Audit-Eintrag schreiben, aufräumen | -## Isolation +Der Wartungsmodus wird im `finally` **immer** wieder abgebaut. Scheitert ein +Schritt, steht die Fortschrittsdatei auf `pct = -1`, `step = error` samt +Meldung – das ist eindeutig von „0 % erledigt“ unterscheidbar. -Der Updater liegt vollständig in `updater/` (eigener Namespace `Updater\`) plus -zwei dünne, klar markierte Anknüpfungen: +## Sicherheitseigenschaften -1. **Front-Controller-Hook** in `index.php` (Maintenance-Check, markiert mit - `// Updater maintenance hook`). -2. **Entry-Shim** `admin/update.php` (lädt nur Basis + Bootstrap, delegiert an - den Controller). +- **ZIP-Slip, zweistufig.** Eintragsnamen werden vorab abgelehnt (absolute + Pfade, Laufwerksbuchstaben, `..`-Segmente, Null-Bytes); nach dem Schreiben + wird der aufgelöste Pfad geprüft und alles außerhalb des Arbeitsverzeichnisses + sofort gelöscht. Die zweite Stufe fängt ab, was die erste übersieht. +- **Geschützte Pfade** (`Updater::PROTECTED_PATHS`) werden nie überschrieben: + `config.php`, `.env`, `.git/`, `uploads/`, `vendor/`, `node_modules/`, + `composer.lock`, `package-lock.json`, `updater/storage/`, `data/`. +- **Atomar je Datei.** Erst daneben schreiben, dann umbenennen. Ein Abbruch + mittendrin hinterlässt sonst eine halbe PHP-Datei, die den nächsten Aufruf + mit einem Parse-Fehler abwürgt. +- **Nur überschreiben und ergänzen, nie löschen.** Eine im neuen Stand fehlende + Datei bleibt liegen: etwas unaufgeräumter, aber ein Fehler in der + Pfadberechnung nimmt so keine Nutzdaten mit. +- **Prüfsumme.** Der Dienst nennt die SHA-256 des Pakets im Kopf + `X-Content-Sha256`; stimmt sie nicht, bricht der Lauf ab. +- **Nur HTTPS**, Zertifikatsprüfung an, Weiterleitungen begrenzt. +- **Selbstheilender Wartungsmodus.** Ein abgelaufenes `until` wird beim Prüfen + entfernt – ohne das legt ein Absturz die Installation dauerhaft lahm. +- **Nur Administratoren** dürfen prüfen, aktualisieren und den Kanal wechseln; + alle schreibenden Endpunkte verlangen ein CSRF-Token. -Eigene Settings (`updater/storage/updater-settings.json`), eigener Autoloader -(`updater/bootstrap.php`), eigener AuditLogger (schreibt in die vorhandene -`audit_log`-Tabelle), eigenes Migrations-System (`updater/migrations/` + -Tabelle `_updater_migrations`). Es werden **keine** Projekt-Klassen erweitert – -`\Database` und `\Auth` werden nur per Injection genutzt. +## Kanäle -### Geschützte Pfade (werden bei Updates nie überschrieben) +| Kanal | Adresse | +|---|---| +| `stable` | `https://update.loheide.cloud/unifivouchertool` | +| `development` | `https://update.loheide.cloud/unifivouchertool-development` | -`config.php`, `.htaccess`, `.env*`, `.git/`, `.gitignore`, `public/uploads/`, -`vendor/`, `composer.lock`, `updater/storage/`. +Der aktive Kanal liegt in `storage/updater-settings.json` – nicht in der +Datenbank, damit der Updater ihn auch bei hängender Datenbank lesen kann. -## Rückbau (restlos entfernen) +## Automatische Migration -1. In `index.php` den Block **„Updater maintenance hook"** (die Zeilen 2–8, - beginnend mit `$maintenanceFile = …` bis zum schließenden `}`) entfernen. -2. `rm -r updater/` -3. `rm admin/update.php` -4. *(optional)* In der Datenbank: `DROP TABLE _updater_migrations;` -5. *(optional, falls vorhanden)* Laufzeitdateien sind bereits in `updater/` - und damit mit Schritt 2 weg. Nichts liegt außerhalb. +Ohne Serverzugang ist der erste Seitenaufruf nach einem Update der einzige +verlässliche Zeitpunkt, zu dem neue Migrationen laufen können. `AutoMigrate` +hängt deshalb an `Database::getInstance()`. Zwei Vorkehrungen: -Danach ist keine Spur des Updaters mehr im Bestandscode – der Beweis für die -Isolation. +- ein **Fingerabdruck** über die Migrationsdateien; nur wenn er sich geändert + hat, wird überhaupt migriert – sonst liefe der Migrator bei jedem Aufruf, +- eine **Sperrdatei** gegen Parallellauf, denn nach einem Update treffen oft + mehrere Aufrufe gleichzeitig ein. -## Smoke-Test +Fehler werden protokolliert, nicht geworfen: eine fehlgeschlagene Nachführung +darf nicht jede Seite unbenutzbar machen. -```bash -# 1) Syntax aller Updater-Dateien -php -l updater/UpdateManager.php -php -l updater/MigrationRunner.php -php -l updater/UpdateController.php -php -l updater/UpdaterFactory.php -php -l updater/AuditLogger.php +## Endpunkte -# 2) Admin-Seite aufrufen (eingeloggt als Admin): -# https:///admin/update.php -# -> "Auf Updates prüfen" klicken. Erwartung: Proxy-Antwort oder klare -# Fehlermeldung (wenn Proxy/Channel nicht erreichbar). +Dieses Projekt hat kein Routing-System – die Zuordnung steht in `routes.php`: -# 3) Maintenance-Mode manuell testen: -touch updater/storage/.maintenance # index.php zeigt jetzt 503-Wartungsseite -rm updater/storage/.maintenance # wieder normal +``` +POST /admin/update/check -> admin/update_api.php?action=check +POST /admin/update/install -> admin/update_api.php?action=install +GET /admin/update/progress -> admin/update_api.php?action=progress +POST /admin/update/channel -> admin/update_api.php?action=channel +POST /admin/update/migrations -> admin/update_api.php?action=migrations ``` -> Hinweis: Ein vollständiger Installations-Durchlauf (`action=install`) setzt -> einen erreichbaren Update-Proxy unter den oben genannten URLs voraus. +## Neue Fassung veröffentlichen + +1. `CHANGELOG.md`: neuen Abschnitt `## MAJOR.MINOR.PATCH – Datum` ergänzen +2. `Updater\Version::RELEASE` **und** die Datei `VERSION` anheben + (Patch = Fehlerbehebung, Minor = Funktion) – ein Test wacht darüber, dass + beide übereinstimmen +3. Tests grün (`composer test`), statische Analyse grün (`composer stan`) +4. Commit und Merge nach `main` – der Update-Dienst liefert den Stand aus, + sobald er gespiegelt ist + +Kompilierte Assets gehören mit ins Repository: beim Anwender läuft kein Build. + +## Rückbau + +`updater/` löschen, `admin/update.php` und `admin/update_api.php` entfernen, +die `require`-Zeile des Wächters aus den Einstiegsseiten nehmen und den Aufruf +von `AutoMigrate` in `includes/Database.php` streichen. diff --git a/updater/RetryLaterException.php b/updater/RetryLaterException.php new file mode 100644 index 0000000..715376c --- /dev/null +++ b/updater/RetryLaterException.php @@ -0,0 +1,20 @@ +retryAfter = max(5, $retryAfter); + } +} diff --git a/updater/UpdateController.php b/updater/UpdateController.php index c7543df..da3dba8 100644 --- a/updater/UpdateController.php +++ b/updater/UpdateController.php @@ -2,12 +2,20 @@ namespace Updater; /** - * UpdateController – bedient die Admin-Seite /admin/update sowie deren - * AJAX-Actions (check, install, progress, set_channel, migrations). + * Bedient die Update-Endpunkte. * - * Nutzt die vorhandenen Projekt-Klassen \Database und \Auth per Injection. - * Die eigentliche Logik liegt im UpdateManager; dieser Controller ist nur - * die duenne Auslieferungs-/Routing-Schicht. + * Routing-Anpassung: Dieses Projekt hat keinen Router - die Auslieferung ist + * datei-basiert. Die Endpunkte der Vorlage bilden wir deshalb ueber + * admin/update_api.php mit dem Parameter `action` ab: + * + * POST /admin/update/check -> POST admin/update_api.php?action=check + * POST /admin/update/install -> POST admin/update_api.php?action=install + * GET /admin/update/progress -> GET admin/update_api.php?action=progress + * POST /admin/update/channel -> POST admin/update_api.php?action=channel + * POST /admin/update/migrations -> POST admin/update_api.php?action=migrations + * + * Alle Endpunkte setzen einen angemeldeten Administrator voraus; alle + * schreibenden zusaetzlich ein gueltiges CSRF-Token. */ class UpdateController { @@ -15,131 +23,143 @@ class UpdateController private $db; /** @var \Auth */ private $auth; - /** @var UpdateManager */ - private $manager; public function __construct(\Database $db, \Auth $auth) { $this->db = $db; $this->auth = $auth; - $this->manager = UpdaterFactory::create($db, new AuditLogger($db)); } - public function handle(): void - { - $action = $_GET['action'] ?? $_POST['action'] ?? ''; - switch ($action) { - case 'check': $this->actionCheck(); break; - case 'install': $this->actionInstall(); break; - case 'progress': $this->actionProgress(); break; - case 'set_channel': $this->actionSetChannel(); break; - case 'migrations': $this->actionMigrations(); break; - case 'run_migrations': $this->actionRunMigrations(); break; - default: $this->renderPage(); - } - } - - // ------------------------------------------------------------- AJAX-Actions - - private function actionCheck(): void + public function handle(string $action): void { try { - $this->json($this->manager->checkForUpdates()); - } catch (\Throwable $e) { - $this->json(['error' => $e->getMessage()], 502); - } - } - - private function actionInstall(): void - { - if (!$this->auth->validateCsrfToken($_POST['csrf_token'] ?? '')) { - $this->json(['error' => 'Ungültiges Sicherheits-Token'], 403); - return; - } - // Session-Lock freigeben, damit parallele Progress-Polls nicht blockieren. - if (session_status() === PHP_SESSION_ACTIVE) { - session_write_close(); - } - @set_time_limit(300); - $userId = $_SESSION['user_id'] ?? null; - $result = $this->manager->installUpdate($userId !== null ? (int)$userId : null); - $this->json($result, $result['success'] ? 200 : 500); - } - - private function actionProgress(): void - { - // Kein CSRF noetig (read-only). Session-Lock sofort freigeben. - if (session_status() === PHP_SESSION_ACTIVE) { - session_write_close(); - } - $this->json($this->manager->getProgress()); - } - - private function actionSetChannel(): void - { - if (!$this->auth->validateCsrfToken($_POST['csrf_token'] ?? '')) { - $this->json(['error' => 'Ungültiges Sicherheits-Token'], 403); - return; - } - $channel = $_POST['channel'] ?? 'stable'; - UpdaterFactory::saveChannel($channel); - $this->json(['success' => true, 'channel' => $channel]); - } - - private function actionMigrations(): void - { - try { - $runner = new MigrationRunner( - $this->db->getConnection(), - __DIR__ . '/migrations', - __DIR__ . '/storage' - ); - $this->json(['migrations' => $runner->status()]); - } catch (\Throwable $e) { - $this->json(['error' => $e->getMessage()], 500); - } - } - - private function actionRunMigrations(): void - { - if (!$this->auth->validateCsrfToken($_POST['csrf_token'] ?? '')) { - $this->json(['error' => 'Ungültiges Sicherheits-Token'], 403); - return; - } - try { - $runner = new MigrationRunner( - $this->db->getConnection(), - __DIR__ . '/migrations', - __DIR__ . '/storage' - ); - $applied = $runner->runPending(true); - if ($this->audit) { - $this->audit->log('migrations_run', ['applied' => $applied], $_SESSION['user_id'] ?? null); + switch ($action) { + case 'check': + $this->requirePost(); + $this->json($this->check()); + break; + case 'install': + $this->requirePost(); + $this->json($this->install()); + break; + case 'progress': + $this->json($this->progress()); + break; + case 'channel': + $this->requirePost(); + $this->json($this->channel()); + break; + case 'migrations': + $this->requirePost(); + $this->json($this->migrations()); + break; + default: + http_response_code(404); + $this->json(['ok' => false, 'error' => 'Unbekannter Endpunkt.']); } - $this->json(['success' => true, 'applied' => $applied, 'migrations' => $runner->status()]); + } catch (RetryLaterException $e) { + http_response_code(503); + header('Retry-After: ' . $e->retryAfter); + $this->json(['ok' => false, 'retry' => true, 'retry_after' => $e->retryAfter, 'error' => $e->getMessage()]); } catch (\Throwable $e) { - $this->json(['error' => $e->getMessage()], 500); + http_response_code(500); + $this->json(['ok' => false, 'error' => $e->getMessage()]); } } - // ------------------------------------------------------------------- Render + // ----------------------------------------------------------------- Aktionen - private function renderPage(): void + private function check(): array { - $manager = $this->manager; - $auth = $this->auth; - $currentSha = $manager->getCurrentVersion(); - $channel = $manager->getChannel(); - $csrfToken = $auth->getCsrfToken(); - require __DIR__ . '/templates/update.php'; + $updater = UpdaterFactory::create($this->db, new AuditLogger($this->db)); + $result = $updater->check(); + $result['ok'] = true; + $result['current_release'] = Version::RELEASE; + + return $result; } - private function json($data, int $status = 200): void + private function install(): array { - if (!headers_sent()) { - http_response_code($status); - header('Content-Type: application/json; charset=utf-8'); + if (Progress::isRunning()) { + return ['ok' => false, 'error' => 'Es laeuft bereits eine Aktualisierung.']; } + + // Der Ablauf laeuft serverseitig weiter, auch wenn der Browser die + // Verbindung kappt - die Oberflaeche fragt nur den Fortschritt ab. + @set_time_limit(0); + ignore_user_abort(true); + + $updater = UpdaterFactory::create($this->db, new AuditLogger($this->db)); + $result = $updater->installUpdate($_SESSION['user_id'] ?? null); + $result['ok'] = $result['success']; + + return $result; + } + + private function progress(): array + { + $progress = Progress::get(); + + return [ + 'ok' => true, + 'pct' => $progress['pct'], + 'step' => $progress['step'], + 'text' => $progress['text'], + 'running' => Progress::isRunning(), + 'maintenance' => Maintenance::isActive(), + ]; + } + + private function channel(): array + { + $channel = (string)($_POST['channel'] ?? ''); + if (!isset(Updater::CHANNELS[$channel])) { + http_response_code(400); + + return ['ok' => false, 'error' => 'Unbekannter Kanal.']; + } + + UpdaterFactory::saveChannel($channel); + (new AuditLogger($this->db))->log('update_channel_changed', ['channel' => $channel], $_SESSION['user_id'] ?? null); + + return ['ok' => true, 'channel' => $channel]; + } + + private function migrations(): array + { + $updater = UpdaterFactory::create($this->db, new AuditLogger($this->db)); + $done = $updater->runMigrations(); + (new AuditLogger($this->db))->log('update_migrations_run', ['count' => count($done)], $_SESSION['user_id'] ?? null); + + return [ + 'ok' => true, + 'applied' => $done, + 'count' => count($done), + 'status' => $updater->migrationStatus(), + ]; + } + + // ------------------------------------------------------------------ Helfer + + private function requirePost(): void + { + if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { + http_response_code(405); + $this->json(['ok' => false, 'error' => 'Nur POST erlaubt.']); + exit; + } + if (!$this->auth->validateCsrfToken($_POST['csrf_token'] ?? '')) { + http_response_code(403); + $this->json(['ok' => false, 'error' => 'Sicherheitstoken ungueltig. Seite neu laden.']); + exit; + } + } + + private function json(array $data): void + { + header('Content-Type: application/json; charset=utf-8'); + header('Cache-Control: no-store'); echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } } diff --git a/updater/UpdateManager.php b/updater/UpdateManager.php deleted file mode 100644 index 88a310b..0000000 --- a/updater/UpdateManager.php +++ /dev/null @@ -1,426 +0,0 @@ - [Update-Proxy] <-pull- [Git-Repo] - * Versions-Identitaet: 40-stelliger Git-Commit-SHA in /.version. - * - * Vollstaendig isoliert im updater/-Ordner; nutzt die vorhandene - * \Database-Klasse per Injection (keine Erweiterung von Projekt-Klassen). - */ -class UpdateManager -{ - public const CHANNELS = [ - 'stable' => 'https://update.loheide.eu/openvouchertool', - 'development' => 'https://update.loheide.eu/openvouchertool-development', - ]; - - private const USER_AGENT = 'OpenVoucherTool-Updater/1.0'; - - /** - * Pfade, die beim Staging->Production-Move NIEMALS ueberschrieben werden. - * Relativ zum Projekt-Root. Prefix-Match (Ordner mit Slash). - */ - private const PROTECTED_PATHS = [ - 'config.php', - '.htaccess', - '.env', - '.env.example', - '.git/', - '.gitignore', - 'public/uploads/', - 'vendor/', - 'composer.lock', - // Updater-Laufzeitdaten (Version, Settings, Staging) – nie ueberschreiben. - // Der restliche updater/-Code SOLL aktualisiert werden. - 'updater/storage/', - ]; - - /** @var \Database */ - private $db; - /** @var AuditLogger|null */ - private $audit; - private $channel; - private $proxyUrl; - private $rootDir; - private $storageDir; - - public function __construct(\Database $db, ?AuditLogger $audit = null, string $channel = 'stable') - { - $this->db = $db; - $this->audit = $audit; - $this->channel = isset(self::CHANNELS[$channel]) ? $channel : 'stable'; - $this->proxyUrl = self::CHANNELS[$this->channel]; - $this->rootDir = dirname(__DIR__); // updater/ liegt im Projekt-Root - $this->storageDir = __DIR__ . '/storage'; // updater/storage/ - if (!is_dir($this->storageDir)) { - @mkdir($this->storageDir, 0775, true); - } - } - - public function getChannel(): string - { - return $this->channel; - } - - public function getProxyUrl(): string - { - return $this->proxyUrl; - } - - // ---------------------------------------------------------------- Version - - public function getCurrentVersion(): string - { - $file = $this->storageDir . '/.version'; - return is_file($file) ? trim((string)file_get_contents($file)) : ''; - } - - public function saveCurrentVersion(string $sha): void - { - file_put_contents($this->storageDir . '/.version', trim($sha)); - } - - // ------------------------------------------------------------ Maintenance - - public function maintenanceOn(): void - { - file_put_contents($this->storageDir . '/.maintenance', date('c')); - } - - public function maintenanceOff(): void - { - $file = $this->storageDir . '/.maintenance'; - if (is_file($file)) { - @unlink($file); - } - } - - public function isMaintenance(): bool - { - return is_file($this->storageDir . '/.maintenance'); - } - - // --------------------------------------------------------------- Progress - - public function getProgress(): array - { - $file = $this->storageDir . '/.update-progress'; - if (!is_file($file)) { - return ['percent' => 0, 'message' => '', 'status' => 'idle']; - } - $data = json_decode((string)file_get_contents($file), true); - return is_array($data) ? $data : ['percent' => 0, 'message' => '', 'status' => 'idle']; - } - - private function setProgress(int $percent, string $message, string $status = 'running'): void - { - file_put_contents($this->storageDir . '/.update-progress', json_encode([ - 'percent' => $percent, - 'message' => $message, - 'status' => $status, - 'updated_at' => date('c'), - ])); - } - - // ------------------------------------------------------------ Update-Check - - /** - * Fragt den Proxy nach verfuegbaren Updates. - * @return array Normalisiertes Ergebnis inkl. has_update/latest_sha/changelog. - */ - public function checkForUpdates(): array - { - $current = $this->getCurrentVersion(); - [$status, $body] = $this->httpGet($this->proxyUrl . '/check?current_sha=' . urlencode($current)); - - $data = json_decode((string)$body, true); - // Wichtig: Proxy kann JSON-Fehler auch mit HTTP 200 senden – nicht - // allein auf den Statuscode verlassen. - if (!is_array($data) || isset($data['error'])) { - $msg = is_array($data) && isset($data['error']) ? $data['error'] : "HTTP $status"; - throw new \RuntimeException('Update-Pruefung fehlgeschlagen: ' . $msg); - } - - return [ - 'has_update' => (bool)($data['has_update'] ?? false), - 'current_sha' => $current, - 'latest_sha' => $data['latest_sha'] ?? '', - 'latest_commit' => $data['latest_commit'] ?? null, - 'versions_behind' => (int)($data['versions_behind'] ?? 0), - 'title' => $data['title'] ?? '', - 'changelog' => $data['changelog'] ?? '', - 'channel' => $this->channel, - ]; - } - - // ------------------------------------------------------------ Update-Flow - - /** - * Fuehrt das Update durch. Reihenfolge laut Spezifikation, maintenanceOff() - * garantiert im finally. - * - * @return array Ergebnis-Status - */ - public function installUpdate(?int $userId = null): array - { - $this->setProgress(0, 'Update wird vorbereitet …', 'running'); - $this->maintenanceOn(); - - $stagingDir = $this->storageDir . '/.update-staging'; - $zipPath = $this->storageDir . '/.update.zip'; - - try { - // 1) Neueste Version ermitteln - $this->setProgress(5, 'Ermittle neueste Version …'); - [$status, $body] = $this->httpGet($this->proxyUrl . '/version'); - $verData = json_decode((string)$body, true); - $latestSha = is_array($verData) ? ($verData['sha'] ?? '') : ''; - if ($latestSha === '') { - throw new \RuntimeException('Konnte neueste Version nicht ermitteln (Proxy-Antwort ungueltig).'); - } - - // 2) ZIP herunterladen (Fallback: Einzeldatei-Download) - $this->setProgress(20, 'Lade Update herunter …'); - $usedZip = $this->downloadZip($latestSha, $zipPath); - - // 3) Entpacken / Stagen - $this->setProgress(45, 'Entpacke Update …'); - $this->cleanDir($stagingDir); - if ($usedZip) { - $this->extractZip($zipPath, $stagingDir); - } else { - $this->downloadFilesIndividually($latestSha, $stagingDir); - } - $stagingRoot = $this->resolveStagingRoot($stagingDir); - - // 4) Staging -> Production (geschuetzte Pfade ueberspringen) - $this->setProgress(65, 'Wende Update an …'); - $this->applyStaging($stagingRoot); - - // 5) Migrationen ausfuehren - $this->setProgress(80, 'Fuehre Datenbank-Migrationen aus …'); - $runner = new MigrationRunner( - $this->db->getConnection(), - __DIR__ . '/migrations', - $this->storageDir - ); - $runner->runPending(true); - - // 6) Caches leeren - $this->setProgress(90, 'Leere Caches …'); - if (function_exists('opcache_reset')) { - @opcache_reset(); - } - - // 7) Version speichern - $this->saveCurrentVersion($latestSha); - - $this->setProgress(100, 'Update abgeschlossen.', 'done'); - - if ($this->audit) { - $this->audit->log('update_installed', ['sha' => $latestSha, 'channel' => $this->channel], $userId); - } - - return ['success' => true, 'sha' => $latestSha]; - } catch (\Throwable $e) { - $this->setProgress(100, 'Fehler: ' . $e->getMessage(), 'error'); - if ($this->audit) { - $this->audit->log('update_failed', ['error' => $e->getMessage()], $userId); - } - return ['success' => false, 'error' => $e->getMessage()]; - } finally { - // .maintenance MUSS immer abgebaut werden. - $this->maintenanceOff(); - @unlink($zipPath); - $this->cleanDir($stagingDir); - @rmdir($stagingDir); - } - } - - // ----------------------------------------------------------------- Helper - - private function downloadZip(string $sha, string $target): bool - { - $fh = @fopen($target, 'w'); - if ($fh === false) { - return false; - } - $ch = curl_init($this->proxyUrl . '/zip?ref=' . urlencode($sha)); - curl_setopt_array($ch, [ - CURLOPT_FILE => $fh, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_TIMEOUT => 120, - CURLOPT_USERAGENT => self::USER_AGENT, - ]); - $ok = curl_exec($ch); - $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); - $type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); - curl_close($ch); - fclose($fh); - - // Erfolg nur, wenn 200 UND es nach ZIP aussieht (Proxy kann JSON-Error 200 senden). - if (!$ok || $code !== 200 || stripos((string)$type, 'zip') === false) { - @unlink($target); - return false; - } - if (!class_exists('ZipArchive')) { - @unlink($target); - return false; // Einzeldatei-Fallback nutzen - } - return true; - } - - private function extractZip(string $zipPath, string $dest): void - { - $zip = new \ZipArchive(); - if ($zip->open($zipPath) !== true) { - throw new \RuntimeException('ZIP konnte nicht geoeffnet werden.'); - } - if (!is_dir($dest)) { - @mkdir($dest, 0775, true); - } - if (!$zip->extractTo($dest)) { - $zip->close(); - throw new \RuntimeException('ZIP konnte nicht entpackt werden.'); - } - $zip->close(); - } - - /** - * Fallback ohne ZIP: Dateiliste vom Proxy holen und einzeln laden. - */ - private function downloadFilesIndividually(string $sha, string $dest): void - { - [$status, $body] = $this->httpGet($this->proxyUrl . '/files?path='); - $files = json_decode((string)$body, true); - if (!is_array($files)) { - throw new \RuntimeException('Dateiliste vom Proxy ungueltig.'); - } - if (!is_dir($dest)) { - @mkdir($dest, 0775, true); - } - foreach ($files as $entry) { - if (($entry['type'] ?? '') !== 'file' || empty($entry['path'])) { - continue; - } - $relPath = $entry['path']; - [$st, $content] = $this->httpGet($this->proxyUrl . '/download/' . str_replace('%2F', '/', rawurlencode($relPath))); - if ($st !== 200) { - throw new \RuntimeException("Download fehlgeschlagen: $relPath (HTTP $st)"); - } - $targetPath = $dest . '/' . $relPath; - $dir = dirname($targetPath); - if (!is_dir($dir)) { - @mkdir($dir, 0775, true); - } - file_put_contents($targetPath, $content); - } - } - - /** - * Manche Proxies/Zipballs verpacken alles in EINEN Wurzelordner - * (z.B. "repo-/"). Diesen erkennen und als Staging-Root verwenden. - */ - private function resolveStagingRoot(string $stagingDir): string - { - $entries = array_values(array_filter(scandir($stagingDir), function ($e) { - return $e !== '.' && $e !== '..'; - })); - if (count($entries) === 1 && is_dir($stagingDir . '/' . $entries[0])) { - return $stagingDir . '/' . $entries[0]; - } - return $stagingDir; - } - - /** - * Verschiebt/kopiert den Staging-Baum in die Produktion und ueberspringt - * dabei alle PROTECTED_PATHS. - */ - private function applyStaging(string $stagingRoot): void - { - $iterator = new \RecursiveIteratorIterator( - new \RecursiveDirectoryIterator($stagingRoot, \FilesystemIterator::SKIP_DOTS), - \RecursiveIteratorIterator::SELF_FIRST - ); - - foreach ($iterator as $item) { - $rel = ltrim(str_replace('\\', '/', substr($item->getPathname(), strlen($stagingRoot))), '/'); - if ($rel === '' || $this->isProtected($rel)) { - continue; - } - $target = $this->rootDir . '/' . $rel; - if ($item->isDir()) { - if (!is_dir($target)) { - @mkdir($target, 0775, true); - } - } else { - $dir = dirname($target); - if (!is_dir($dir)) { - @mkdir($dir, 0775, true); - } - if (!@copy($item->getPathname(), $target)) { - throw new \RuntimeException("Konnte Datei nicht schreiben: $rel"); - } - } - } - } - - private function isProtected(string $rel): bool - { - foreach (self::PROTECTED_PATHS as $p) { - if (substr($p, -1) === '/') { - if (strpos($rel . '/', $p) === 0) { - return true; - } - } elseif ($rel === $p) { - return true; - } - } - return false; - } - - private function cleanDir(string $dir): void - { - if (!is_dir($dir)) { - return; - } - $it = new \RecursiveIteratorIterator( - new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS), - \RecursiveIteratorIterator::CHILD_FIRST - ); - foreach ($it as $item) { - if ($item->isDir()) { - @rmdir($item->getPathname()); - } else { - @unlink($item->getPathname()); - } - } - } - - /** - * Einfacher HTTP-GET via curl. Gibt [httpStatus, body] zurueck. - */ - private function httpGet(string $url): array - { - $ch = curl_init($url); - curl_setopt_array($ch, [ - CURLOPT_RETURNTRANSFER => true, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_TIMEOUT => 30, - CURLOPT_CONNECTTIMEOUT => 10, - CURLOPT_USERAGENT => self::USER_AGENT, - ]); - $body = curl_exec($ch); - $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); - $err = curl_error($ch); - curl_close($ch); - if ($body === false) { - throw new \RuntimeException("Verbindung zum Update-Proxy fehlgeschlagen: $err"); - } - return [$status, $body]; - } -} diff --git a/updater/Updater.php b/updater/Updater.php new file mode 100644 index 0000000..4b488f9 --- /dev/null +++ b/updater/Updater.php @@ -0,0 +1,509 @@ + [Update-Proxy] <-pull- [Git-Repository] + * + * Ablauf einer Aktualisierung (installUpdate): Wartungsmodus an, Ziel-Stand + * ermitteln, ZIP streamen, kontrolliert entpacken, ueber die Produktion legen, + * Migrationen nachziehen, Caches leeren, neuen Stand speichern. + * + * Es gibt keine Tags und keine Releases: gezaehlt wird der Stand des Branches, + * seine Identitaet ist der Commit-SHA. + */ +class Updater +{ + public const CHANNELS = [ + 'stable' => 'https://update.loheide.cloud/unifivouchertool', + 'development' => 'https://update.loheide.cloud/unifivouchertool-development', + ]; + + /** + * Pfade, die beim Uebernehmen NIE ueberschrieben werden - relativ zum + * Projektstamm. Ordner enden auf "/", Dateien treffen exakt. + */ + public const PROTECTED_PATHS = [ + 'config.php', // Zugangsdaten und APP_KEY dieser Installation + '.env', + '.env.example', + '.git/', + '.gitignore', + 'uploads/', // hochgeladene Logos und Hintergruende + 'vendor/', + 'node_modules/', + 'composer.lock', + 'package-lock.json', + 'updater/storage/', // installierter Stand, Fortschritt, Staging + 'data/', // lokale Datenbankdateien, falls vorhanden + ]; + + /** @var \Database|null */ + private $db; + /** @var AuditLogger|null */ + private $audit; + /** @var string */ + private $channel; + /** @var ProxyClient */ + private $client; + /** @var string */ + private $rootDir; + /** @var string */ + private $storageDir; + + /** + * $rootDir und $db sind absichtlich ueberschreibbar: die Dateioperationen + * (Entpacken, Uebernehmen) lassen sich so in einem Testverzeichnis pruefen, + * ohne Datenbank und ohne die laufende Installation anzufassen. + */ + public function __construct(?\Database $db = null, ?AuditLogger $audit = null, string $channel = 'stable', ?ProxyClient $client = null, ?string $rootDir = null) + { + $this->db = $db; + $this->audit = $audit; + $this->channel = isset(self::CHANNELS[$channel]) ? $channel : 'stable'; + $this->client = $client ?: new ProxyClient(self::CHANNELS[$this->channel]); + $this->rootDir = $rootDir !== null ? rtrim($rootDir, '/') : dirname(__DIR__); + $this->storageDir = Version::storageDir(); + if (!is_dir($this->storageDir)) { + @mkdir($this->storageDir, 0775, true); + } + } + + public function channel(): string + { + return $this->channel; + } + + public function proxyUrl(): string + { + return $this->client->baseUrl(); + } + + // ---------------------------------------------------------------- Pruefen + + /** + * Fragt den Proxy, ob es etwas Neues gibt. + * + * Angezeigt werden spaeter genau zwei Dinge: dass eine neue Fassung da ist + * und was daran neu ist. Commit-Texte gibt es hier bewusst nicht - die sind + * fuer Entwickler geschrieben. + */ + public function check(): array + { + $current = Version::current(); + $data = $this->client->check($current); + + $result = [ + 'has_update' => (bool)($data['has_update'] ?? false), + 'current_sha' => $current, + 'latest_sha' => (string)($data['latest_sha'] ?? ''), + 'version' => $data['version'] ?? null, + 'released_at' => $data['released_at'] ?? null, + 'versions_behind' => (int)($data['versions_behind'] ?? 0), + 'channel' => $this->channel, + 'changelog' => null, + 'changelog_complete' => true, + 'channel_switch' => null, + ]; + + // Ein fehlendes changelog_preview bedeutet: es gibt nichts zu berichten. + // Dann bleibt es bei "neue Fassung verfuegbar" - ohne Ersatztext. + if (isset($data['changelog_preview']['entries']) && is_array($data['changelog_preview']['entries'])) { + $entries = []; + foreach ($data['changelog_preview']['entries'] as $entry) { + if (!is_array($entry)) { + continue; + } + $entries[] = [ + 'version' => (string)($entry['version'] ?? ''), + 'heading' => (string)($entry['heading'] ?? ''), + 'text' => (string)($entry['text'] ?? ''), + ]; + } + if ($entries !== []) { + $result['changelog'] = $entries; + $result['changelog_complete'] = (bool)($data['changelog_preview']['complete'] ?? true); + } + } + + // Kanalwechsel: der gemeldete Stand stammt aus einem anderen Kanal. + // Bei "back" ist er aelter als der laufende - das ist beim Zurueck- + // schalten auf den Hauptkanal der Normalfall und kein Grund abzubrechen. + if (isset($data['channel_switch']) && is_array($data['channel_switch'])) { + $result['channel_switch'] = [ + 'from_channel' => (string)($data['channel_switch']['from_channel'] ?? ''), + 'to_channel' => (string)($data['channel_switch']['to_channel'] ?? ''), + 'direction' => ($data['channel_switch']['direction'] ?? 'forward') === 'back' ? 'back' : 'forward', + ]; + } + + // Frische Installation: der Proxy antwortet wie "aktuell". Den + // gemeldeten Stand merken wir uns, damit die naechste Pruefung + // vergleichen kann. + if ($current === null && Version::isSha($result['latest_sha'])) { + Version::save($result['latest_sha']); + $result['current_sha'] = $result['latest_sha']; + } + + return $result; + } + + // ------------------------------------------------------------ Installation + + /** + * Fuehrt die Aktualisierung durch. Der Wartungsmodus wird im finally in + * jedem Fall wieder abgebaut. + * + * @return array{success:bool, sha?:string, migrations?:int, error?:string} + */ + public function installUpdate(?int $userId = null): array + { + $zipPath = $this->storageDir . '/.update.zip'; + $staging = $this->storageDir . '/.update-staging'; + $targetSha = ''; + $migrations = 0; + + Progress::set(0, 'maintenance', 'Wartungsmodus wird aktiviert …'); + Maintenance::activate(); + + try { + Progress::set(5, 'version', 'Neuesten Stand ermitteln …'); + $version = $this->client->version(); + $targetSha = (string)($version['sha'] ?? ''); + if (!Version::isSha($targetSha)) { + throw new \RuntimeException('Der Update-Dienst hat keinen gueltigen Stand gemeldet.'); + } + + Progress::set(20, 'download', 'Update wird geladen …'); + $meta = $this->client->downloadZip($targetSha, $zipPath); + $this->assertIsZip($zipPath); + $this->assertChecksum($zipPath, $meta['content_sha256']); + + Progress::set(50, 'extract', 'Update wird entpackt …'); + $this->removeTree($staging); + @mkdir($staging, 0775, true); + $this->extractZip($zipPath, $staging); + $stagingRoot = $this->resolveStagingRoot($staging); + + Progress::set(65, 'apply', 'Dateien werden uebernommen …'); + $this->applyStaging($stagingRoot); + + Progress::set(80, 'migrate', 'Datenbank wird nachgezogen …'); + $migrations = count($this->runMigrations()); + + Progress::set(90, 'cache', 'Zwischenspeicher wird geleert …'); + $this->clearCaches(); + + Version::save($targetSha); + Progress::set(100, 'done', 'Aktualisierung abgeschlossen.'); + + $this->log('update_installed', [ + 'channel' => $this->channel, + 'sha' => $targetSha, + 'migrations' => $migrations, + ], $userId); + + return ['success' => true, 'sha' => $targetSha, 'migrations' => $migrations]; + } catch (\Throwable $e) { + Progress::error($e->getMessage()); + $this->log('update_failed', [ + 'channel' => $this->channel, + 'sha' => $targetSha, + 'error' => $e->getMessage(), + ], $userId); + + return ['success' => false, 'error' => $e->getMessage()]; + } finally { + Maintenance::deactivate(); + @unlink($zipPath); + $this->removeTree($staging); + } + } + + /** Migrationen einzeln ausloesbar (Schaltflaeche in der Oberflaeche). */ + public function runMigrations(): array + { + $runner = new MigrationRunner($this->requireDb()->getConnection(), __DIR__ . '/migrations', $this->storageDir); + + return $runner->runPending(true); + } + + public function migrationStatus(): array + { + $runner = new MigrationRunner($this->requireDb()->getConnection(), __DIR__ . '/migrations', $this->storageDir); + + return $runner->status(); + } + + // ------------------------------------------------------------------ Pruefen + + /** + * Beginnt die Datei mit "PK"? Sonst hat in Wahrheit eine Fehlerseite + * geantwortet, und das Entpacken wuerde mit einer nichtssagenden Meldung + * scheitern. + */ + private function assertIsZip(string $path): void + { + $fh = @fopen($path, 'rb'); + $magic = $fh ? (string)fread($fh, 2) : ''; + if ($fh) { + fclose($fh); + } + if ($magic !== 'PK') { + throw new \RuntimeException( + 'Die Gegenstelle hat kein Update-Paket geliefert (Antwort ist kein ZIP-Archiv).' + ); + } + } + + /** Der Proxy nennt die Pruefsumme des Pakets im Kopf X-Content-Sha256. */ + private function assertChecksum(string $path, string $expected): void + { + $expected = strtolower(trim($expected)); + if ($expected === '' || !preg_match('/^[0-9a-f]{64}$/', $expected)) { + return; // Kopfzeile fehlt: nicht erzwingbar, aber auch kein Fehler + } + + $actual = hash_file('sha256', $path); + if (!is_string($actual) || !hash_equals($expected, $actual)) { + throw new \RuntimeException('Das geladene Update-Paket ist unvollstaendig oder beschaedigt.'); + } + } + + // ---------------------------------------------------------------- Entpacken + + /** + * Entpackt kontrolliert - Eintrag fuer Eintrag, mit zweistufigem + * ZIP-Slip-Schutz: + * a) Namen vorab ablehnen (absolute Pfade, Laufwerksbuchstaben, + * ".."-Segmente, Null-Bytes) + * b) nach dem Schreiben den aufgeloesten Pfad pruefen + * Die zweite Stufe faengt ab, was die erste uebersieht. + */ + public function extractZip(string $zipPath, string $destination): int + { + if (!class_exists('ZipArchive')) { + throw new \RuntimeException('Die PHP-Erweiterung "zip" fehlt - das Update kann nicht entpackt werden.'); + } + + $zip = new \ZipArchive(); + if ($zip->open($zipPath) !== true) { + throw new \RuntimeException('Das Update-Paket konnte nicht geoeffnet werden.'); + } + + if (!is_dir($destination) && !@mkdir($destination, 0775, true) && !is_dir($destination)) { + $zip->close(); + throw new \RuntimeException('Arbeitsverzeichnis konnte nicht angelegt werden: ' . $destination); + } + $realDest = realpath($destination); + if ($realDest === false) { + $zip->close(); + throw new \RuntimeException('Arbeitsverzeichnis konnte nicht aufgeloest werden: ' . $destination); + } + + $written = 0; + for ($i = 0; $i < $zip->numFiles; $i++) { + $name = (string)$zip->getNameIndex($i); + if ($name === '' || !self::isSafeEntryName($name)) { + continue; // Stufe a + } + + $target = $realDest . '/' . $name; + if (substr($name, -1) === '/') { + if (!is_dir($target)) { + @mkdir($target, 0775, true); + } + continue; + } + + $dir = dirname($target); + if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) { + throw new \RuntimeException('Verzeichnis konnte nicht angelegt werden: ' . $dir); + } + + $stream = $zip->getStream($name); + if ($stream === false) { + continue; + } + $out = @fopen($target, 'wb'); + if ($out === false) { + fclose($stream); + throw new \RuntimeException('Datei konnte nicht geschrieben werden: ' . $name); + } + stream_copy_to_stream($stream, $out); + fclose($stream); + fclose($out); + + // Stufe b: liegt die geschriebene Datei wirklich im Arbeitsverzeichnis? + $real = realpath($target); + if ($real === false || strpos($real, $realDest . DIRECTORY_SEPARATOR) !== 0) { + @unlink($target); + continue; + } + $written++; + } + $zip->close(); + + return $written; + } + + /** Stufe a des ZIP-Slip-Schutzes, ohne Dateisystem-Zugriff pruefbar. */ + public static function isSafeEntryName(string $name): bool + { + if ($name === '' || strpos($name, "\0") !== false) { + return false; + } + $normalised = str_replace('\\', '/', $name); + if ($normalised[0] === '/' || preg_match('#^[a-zA-Z]:#', $normalised)) { + return false; + } + foreach (explode('/', $normalised) as $segment) { + if ($segment === '..') { + return false; + } + } + + return true; + } + + /** Das Archiv hat einen gemeinsamen Deckel-Ordner - der faellt weg. */ + private function resolveStagingRoot(string $staging): string + { + $entries = array_values(array_diff((array)scandir($staging), ['.', '..'])); + if (count($entries) === 1 && is_dir($staging . '/' . $entries[0])) { + return $staging . '/' . $entries[0]; + } + + return $staging; + } + + // --------------------------------------------------------------- Uebernehmen + + /** + * Legt den neuen Stand ueber die Produktion. + * + * Zwei bewusste Entscheidungen: + * - je Datei erst daneben schreiben, dann umbenennen. Ein Abbruch + * mittendrin hinterlaesst sonst eine halbe PHP-Datei, die den naechsten + * Aufruf mit einem Parse-Fehler abwuergt. + * - nur ueberschreiben und ergaenzen, nie loeschen. Eine im neuen Stand + * fehlende Datei bleibt liegen: etwas unaufgeraeumter, aber ein Fehler + * in der Pfadberechnung nimmt so keine Nutzdaten mit. + * + * @return int Anzahl uebernommener Dateien + */ + public function applyStaging(string $stagingRoot): int + { + $stagingRoot = rtrim($stagingRoot, '/'); + $iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($stagingRoot, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::SELF_FIRST + ); + + $count = 0; + foreach ($iterator as $item) { + $rel = ltrim(str_replace('\\', '/', substr($item->getPathname(), strlen($stagingRoot))), '/'); + if ($rel === '' || self::isProtected($rel)) { + continue; + } + + $target = $this->rootDir . '/' . $rel; + if ($item->isDir()) { + if (!is_dir($target)) { + @mkdir($target, 0775, true); + } + continue; + } + + $dir = dirname($target); + if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) { + throw new \RuntimeException('Verzeichnis konnte nicht angelegt werden: ' . dirname($rel)); + } + + $tmp = $target . '.new'; + if (!@copy($item->getPathname(), $tmp)) { + throw new \RuntimeException( + 'Datei konnte nicht geschrieben werden: ' . $rel . ' (Schreibrechte des Webservers pruefen)' + ); + } + if (!@rename($tmp, $target)) { + @unlink($tmp); + throw new \RuntimeException('Datei konnte nicht ersetzt werden: ' . $rel); + } + $count++; + } + + return $count; + } + + public static function isProtected(string $rel): bool + { + $rel = ltrim(str_replace('\\', '/', $rel), '/'); + foreach (self::PROTECTED_PATHS as $protected) { + if (substr($protected, -1) === '/') { + if (strpos($rel . '/', $protected) === 0) { + return true; + } + } elseif ($rel === $protected) { + return true; + } + } + + return false; + } + + // -------------------------------------------------------------------- Rest + + /** + * Zwischenspeicher leeren. Ohne das Verwerfen des Bytecode-Caches laeuft + * nach dem Update noch eine Weile der alte Code. + */ + private function clearCaches(): void + { + if (function_exists('opcache_reset')) { + @opcache_reset(); + } + if (function_exists('apcu_clear_cache')) { + @apcu_clear_cache(); + } + // Dieses Projekt haelt keinen View-, Config- oder Route-Cache vor; + // der Migrations-Fingerabdruck wird verworfen, damit der naechste + // Aufruf sauber nachzieht. + $fingerprint = $this->storageDir . '/.migration-fingerprint'; + if (is_file($fingerprint)) { + @unlink($fingerprint); + } + } + + private function removeTree(string $dir): void + { + if (!is_dir($dir)) { + return; + } + $it = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($dir, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::CHILD_FIRST + ); + foreach ($it as $item) { + $item->isDir() ? @rmdir($item->getPathname()) : @unlink($item->getPathname()); + } + @rmdir($dir); + } + + private function requireDb(): \Database + { + if ($this->db === null) { + throw new \RuntimeException('Fuer Migrationen wird eine Datenbankverbindung benoetigt.'); + } + + return $this->db; + } + + private function log(string $action, array $details, ?int $userId): void + { + if ($this->audit) { + $this->audit->log($action, $details, $userId); + } + } +} diff --git a/updater/UpdaterFactory.php b/updater/UpdaterFactory.php index 8247425..842ef42 100644 --- a/updater/UpdaterFactory.php +++ b/updater/UpdaterFactory.php @@ -2,50 +2,73 @@ namespace Updater; /** - * Zentrale Fabrik fuer den UpdateManager. + * Erzeugt den Updater fuer den aktiven oder einen ausdruecklich genannten + * Kanal. Unbekannte Kanaele werden abgelehnt. * - * Der Channel wird ausschliesslich aus einer EIGENEN, isolierten Settings-Datei - * gelesen (updater/storage/updater-settings.json) – NICHT aus der bestehenden - * Settings-/Config-Konvention des Projekts. Beim Rueckbau einfach loeschbar. - * - * Default-Channel-Fallback existiert NUR hier (eine Stelle). + * Der aktive Kanal liegt in einer eigenen Datei unter updater/storage/ und + * nicht in den App-Einstellungen: der Updater muss ihn auch lesen koennen, + * wenn die Datenbank gerade nicht erreichbar ist - und storage/ ist ein + * geschuetzter Pfad, ueberlebt ein Update also unveraendert. */ final class UpdaterFactory { + public const DEFAULT_CHANNEL = 'stable'; + private static function settingsFile(): string { - return __DIR__ . '/storage/updater-settings.json'; + return Version::storageDir() . '/updater-settings.json'; } - public static function create(\Database $db, ?AuditLogger $audit = null): UpdateManager + public static function create(\Database $db, ?AuditLogger $audit = null, ?string $channel = null): Updater { - $settings = self::loadSettings(); - $channel = $settings['channel'] ?? 'stable'; - return new UpdateManager($db, $audit, $channel); + $channel = $channel ?? self::channel(); + if (!isset(Updater::CHANNELS[$channel])) { + throw new \InvalidArgumentException('Unbekannter Update-Kanal: ' . $channel); + } + + return new Updater($db, $audit, $channel); } - public static function loadSettings(): array + public static function channel(): string + { + $settings = self::settings(); + $channel = (string)($settings['channel'] ?? self::DEFAULT_CHANNEL); + + return isset(Updater::CHANNELS[$channel]) ? $channel : self::DEFAULT_CHANNEL; + } + + public static function settings(): array { $file = self::settingsFile(); if (!is_file($file)) { return []; } - $data = json_decode((string)file_get_contents($file), true); + $data = json_decode((string)@file_get_contents($file), true); + return is_array($data) ? $data : []; } public static function saveChannel(string $channel): void { - if (!isset(UpdateManager::CHANNELS[$channel])) { - $channel = 'stable'; + if (!isset(Updater::CHANNELS[$channel])) { + throw new \InvalidArgumentException('Unbekannter Update-Kanal: ' . $channel); } - $settings = self::loadSettings(); - $settings['channel'] = $channel; - $dir = dirname(self::settingsFile()); + $dir = Version::storageDir(); if (!is_dir($dir)) { @mkdir($dir, 0775, true); } - file_put_contents(self::settingsFile(), json_encode($settings, JSON_PRETTY_PRINT)); + $settings = self::settings(); + $settings['channel'] = $channel; + @file_put_contents(self::settingsFile(), json_encode($settings, JSON_PRETTY_PRINT)); + } + + /** @return array Kanal => Anzeigename */ + public static function channelLabels(): array + { + return [ + 'stable' => 'Stabil (empfohlen)', + 'development' => 'Entwicklung (Vorabfassungen)', + ]; } } diff --git a/updater/Version.php b/updater/Version.php new file mode 100644 index 0000000..d01e3bc --- /dev/null +++ b/updater/Version.php @@ -0,0 +1,105 @@ + 'maintenance', + 'message' => 'Es wird gerade ein Update eingespielt.', + 'retry_after' => $retry, + ], JSON_UNESCAPED_UNICODE); + exit; + } + + header('Content-Type: text/html; charset=utf-8'); + $percent = max(0, (int)$progress['pct']); + $status = (string)$progress['text']; + require __DIR__ . "/templates/maintenance.php"; + exit; +} diff --git a/updater/routes.php b/updater/routes.php index a03a369..4032aba 100644 --- a/updater/routes.php +++ b/updater/routes.php @@ -1,29 +1,34 @@ \Updater\UpdateController). + * Dieses Projekt hat KEIN zentrales Routing - die Auslieferung ist + * datei-basiert ueber den Webserver. Die Endpunkte der Vorlage bilden reale + * Dateien ab: * - * Diese Datei existiert, um die Routing-Konvention der Vorlage zu erfuellen und - * dokumentiert die einzige Routing-Einklink-Stelle. Sollte das Projekt spaeter - * einen echten Router erhalten, koennen hier die Routen registriert werden: + * Vorlage hier + * ------------------------------ ------------------------------------------- + * GET /admin/update GET admin/update.php + * POST /admin/update/check POST admin/update_api.php?action=check + * POST /admin/update/install POST admin/update_api.php?action=install + * GET /admin/update/progress GET admin/update_api.php?action=progress + * POST /admin/update/channel POST admin/update_api.php?action=channel + * POST /admin/update/migrations POST admin/update_api.php?action=migrations * - * $router->get('/admin/update', fn() => (new \Updater\UpdateController($db, $auth))->handle()); - * $router->post('/admin/update', fn() => (new \Updater\UpdateController($db, $auth))->handle()); + * Alle Endpunkte setzen einen angemeldeten Administrator voraus + * (\Auth::requireAdmin), alle schreibenden zusaetzlich ein gueltiges + * CSRF-Token. * - * Aktuelle Endpunkte (alle ueber admin/update.php, Parameter `action`): - * GET /admin/update.php -> Admin-UI - * GET /admin/update.php?action=check -> Update-Pruefung (JSON) - * GET /admin/update.php?action=progress -> Fortschritt (JSON) - * GET /admin/update.php?action=migrations-> Migrations-Status (JSON) - * POST /admin/update.php action=install (+csrf_token) - * POST /admin/update.php action=set_channel (+csrf_token, channel) + * Bekommt das Projekt spaeter einen Router, genuegt hier: + * + * $router->post('/admin/update/check', fn() => (new \Updater\UpdateController($db, $auth))->handle('check')); */ return [ - ['method' => 'GET', 'path' => '/admin/update', 'handler' => 'admin/update.php'], - ['method' => 'POST', 'path' => '/admin/update', 'handler' => 'admin/update.php'], + ['method' => 'GET', 'path' => '/admin/update', 'handler' => 'admin/update.php'], + ['method' => 'POST', 'path' => '/admin/update/check', 'handler' => 'admin/update_api.php?action=check'], + ['method' => 'POST', 'path' => '/admin/update/install', 'handler' => 'admin/update_api.php?action=install'], + ['method' => 'GET', 'path' => '/admin/update/progress', 'handler' => 'admin/update_api.php?action=progress'], + ['method' => 'POST', 'path' => '/admin/update/channel', 'handler' => 'admin/update_api.php?action=channel'], + ['method' => 'POST', 'path' => '/admin/update/migrations', 'handler' => 'admin/update_api.php?action=migrations'], ]; diff --git a/updater/templates/maintenance.html b/updater/templates/maintenance.php similarity index 75% rename from updater/templates/maintenance.html rename to updater/templates/maintenance.php index a1c7502..b912207 100644 --- a/updater/templates/maintenance.html +++ b/updater/templates/maintenance.php @@ -1,3 +1,15 @@ + @@ -65,6 +77,13 @@ 0% { transform: translateX(-100%); } 100% { transform: translateX(300%); } } + .bar-known::after { content: none; } + .bar-known span { + display: block; height: 100%; + border-radius: 999px; + background: linear-gradient(90deg, #5b5bd6, #8b5cf6); + transition: width .4s ease; + } .hint { font-size: 12.5px; color: #8a93a3; } @media (prefers-reduced-motion: reduce) { .bar::after { animation: none; width: 45%; } @@ -87,9 +106,14 @@

Kurz mal Wartung

-

Es wird gerade ein Update eingespielt. Die Seite ist in wenigen Augenblicken wieder erreichbar.

-
-

Diese Seite aktualisiert sich automatisch.

+

+ 0): ?> +
+

% erledigt – diese Seite aktualisiert sich automatisch.

+ +
+

Diese Seite aktualisiert sich automatisch.

+

Entwickelt von Loheide.eu

diff --git a/updater/templates/update.php b/updater/templates/update.php deleted file mode 100644 index 8c3c139..0000000 --- a/updater/templates/update.php +++ /dev/null @@ -1,267 +0,0 @@ - - - - - - - System-Update - - - - - -
-
-
- -
-

System-Update

-

Aktualisierung aus dem gewählten Release-Channel

-
-
- Administration -
- -
-
Update
-
Migrationen
-
- -
-
-

Aktuelle Version

-
Installierte Version (SHA)
-
Update-Channel - - - -
-

Channel wird in updater/storage/updater-settings.json gespeichert.

-
- -
-

Updates

- - - -
- -
-
-
-
- -
-
-
-
- -
-
-

Migrations-Status

-

Wird geladen …

- -
-
-
- -
- - - -