Merge pull request 'Selbst-Updater neu gebaut, Diagnoseseiten abgesichert' (#18) from feature/self-updater into main
2
.github/workflows/ci.yml
vendored
|
|
@ -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
|
||||
|
|
|
|||
1
.github/workflows/release.yml
vendored
|
|
@ -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 \
|
||||
|
|
|
|||
30
CHANGELOG.md
Normal file
|
|
@ -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
|
||||
67
Readme.md
|
|
@ -10,7 +10,7 @@ Entwickelt von **[Loheide.eu](https://loheide.eu)**
|
|||

|
||||

|
||||

|
||||

|
||||

|
||||
[](https://git.loheide.cloud/friloo/Unifi-Voucher-Tool/actions)
|
||||
[](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:
|
||||
|
||||
<div align="center">
|
||||
<img src="docs/screenshots/maintenance.png" alt="Wartungsmodus" width="60%">
|
||||
</div>
|
||||
|
||||
> 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.
|
|||
|
||||
<div align="center">
|
||||
|
||||
**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)**
|
||||
|
||||
|
|
|
|||
2
VERSION
|
|
@ -1 +1 @@
|
|||
2.9.0
|
||||
3.0.0
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/../updater/guard.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/../updater/guard.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/../updater/guard.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/../updater/guard.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/../updater/guard.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/../updater/guard.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/../updater/guard.php';
|
||||
|
||||
/**
|
||||
* Verwaltung der öffentlichen Display-Seiten ("Kiosk").
|
||||
*
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/../updater/guard.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/../updater/guard.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/../updater/guard.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/../updater/guard.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/../updater/guard.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
|
|
|||
341
admin/update.php
|
|
@ -1,12 +1,17 @@
|
|||
<?php
|
||||
/**
|
||||
* Admin-Entry-Point fuer den Updater (URL: /admin/update.php).
|
||||
* Admin-Seite "Aktualisierung".
|
||||
*
|
||||
* Bewusst sehr duenn gehalten: laedt nur die Projekt-Basis + den isolierten
|
||||
* Updater-Bootstrap und delegiert alles an \Updater\UpdateController.
|
||||
* Zeigt den installierten Stand, den Kanal, gefundene Updates samt der
|
||||
* Abschnitte aus dem Aenderungsprotokoll, den Fortschritt einer laufenden
|
||||
* Aktualisierung, den Stand der Migrationen und die Versionsgeschichte.
|
||||
*
|
||||
* Beim Rueckbau des Updaters kann diese Datei mitgeloescht werden.
|
||||
* Die Endpunkte liegen in admin/update_api.php.
|
||||
*/
|
||||
// Kein Wartungs-Waechter: waehrend eines Updates muss genau diese Seite
|
||||
// erreichbar bleiben, sonst sieht niemand mehr den Fortschritt.
|
||||
require_once __DIR__ . '/../updater/bootstrap.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
|
@ -14,12 +19,334 @@ ini_set('log_errors', 1);
|
|||
require_once __DIR__ . '/../config.php';
|
||||
require_once __DIR__ . '/../includes/Database.php';
|
||||
require_once __DIR__ . '/../includes/Auth.php';
|
||||
require_once __DIR__ . '/../updater/bootstrap.php';
|
||||
require_once __DIR__ . '/../includes/I18n.php';
|
||||
|
||||
$auth = new Auth();
|
||||
$auth->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 = '';
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="<?= I18n::getLanguage() ?>">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title><?= __('update_title') ?> – <?= htmlspecialchars($appTitle) ?></title>
|
||||
<?php require __DIR__ . '/../includes/admin_nav.php'; ?>
|
||||
<div class="page-header">
|
||||
<div>
|
||||
<h1 class="page-title"><?= __('update_title') ?></h1>
|
||||
<p class="page-subtitle"><?= __('update_subtitle') ?></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2><?= __('update_installed') ?></h2>
|
||||
<dl class="about-list">
|
||||
<dt><?= __('update_version') ?></dt>
|
||||
<dd><?= htmlspecialchars($release) ?><?= $installedSha ? ' <code>' . htmlspecialchars(substr($installedSha, 0, 7)) . '</code>' : '' ?></dd>
|
||||
|
||||
<dt><?= __('update_state') ?></dt>
|
||||
<dd>
|
||||
<?php if ($installedSha): ?>
|
||||
<code><?= htmlspecialchars($installedSha) ?></code>
|
||||
<?php else: ?>
|
||||
<span class="muted"><?= __('update_state_unknown') ?></span>
|
||||
<?php endif; ?>
|
||||
</dd>
|
||||
|
||||
<dt><?= __('update_channel') ?></dt>
|
||||
<dd><?= htmlspecialchars($channelLabels[$channel] ?? $channel) ?></dd>
|
||||
</dl>
|
||||
|
||||
<form method="post" id="channelForm" class="update-channel">
|
||||
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf) ?>">
|
||||
<label for="channelSelect"><?= __('update_channel_change') ?></label>
|
||||
<div class="update-channel-row">
|
||||
<select name="channel" id="channelSelect" class="input">
|
||||
<?php foreach ($channelLabels as $key => $label): ?>
|
||||
<option value="<?= htmlspecialchars($key) ?>" <?= $key === $channel ? 'selected' : '' ?>><?= htmlspecialchars($label) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<button type="submit" class="btn btn-secondary"><?= __('update_channel_save') ?></button>
|
||||
</div>
|
||||
<p class="help-text"><?= __('update_channel_hint') ?></p>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2><?= __('update_search') ?></h2>
|
||||
<div class="update-actions">
|
||||
<button type="button" class="btn btn-primary" id="btnCheck">
|
||||
<i class="fas fa-magnifying-glass" aria-hidden="true"></i> <?= __('update_search_btn') ?>
|
||||
</button>
|
||||
<button type="button" class="btn btn-success" id="btnInstall" hidden>
|
||||
<i class="fas fa-download" aria-hidden="true"></i> <?= __('update_install_btn') ?>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="checkResult" class="update-result" hidden></div>
|
||||
|
||||
<div id="progressBox" class="update-progress" hidden>
|
||||
<div class="update-bar"><span id="progressBar" style="width:0%"></span></div>
|
||||
<p class="update-progress-text"><span id="progressPercent">0</span> % – <span id="progressText"></span></p>
|
||||
</div>
|
||||
|
||||
<!-- Datenschutzhinweis: steht dauerhaft dort, wo die Uebertragung
|
||||
ausgeloest wird - nicht in einem Dialog, den man wegklickt. -->
|
||||
<div class="update-privacy">
|
||||
<h3><?= __('update_privacy_title') ?></h3>
|
||||
<p><?= __('update_privacy_intro') ?></p>
|
||||
<ul>
|
||||
<li><?= __('update_privacy_item_state') ?></li>
|
||||
<li><?= __('update_privacy_item_tech') ?></li>
|
||||
</ul>
|
||||
<p><?= __('update_privacy_purpose') ?></p>
|
||||
<p><?= __('update_privacy_not') ?></p>
|
||||
<p class="muted"><?= __('update_privacy_retention') ?></p>
|
||||
<?php if ($privacyUrl !== ''): ?>
|
||||
<p><a href="<?= htmlspecialchars($privacyUrl) ?>" target="_blank" rel="noopener"><?= __('update_privacy_link') ?></a></p>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2><?= __('update_migrations') ?></h2>
|
||||
<?php if ($migrationError !== ''): ?>
|
||||
<div class="alert alert-error"><?= htmlspecialchars($migrationError) ?></div>
|
||||
<?php else: ?>
|
||||
<p class="muted">
|
||||
<?= str_replace(['{total}', '{open}'], [(string)count($migrations), (string)$openMigrations], __('update_migrations_hint')) ?>
|
||||
</p>
|
||||
<div class="table-container">
|
||||
<table class="table table-stack">
|
||||
<thead>
|
||||
<tr>
|
||||
<th><?= __('update_migration_file') ?></th>
|
||||
<th><?= __('update_migration_state') ?></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($migrations as $migration): ?>
|
||||
<tr>
|
||||
<td data-label="<?= __('update_migration_file') ?>"><code><?= htmlspecialchars($migration['filename']) ?></code></td>
|
||||
<td data-label="<?= __('update_migration_state') ?>">
|
||||
<?php if ($migration['applied']): ?>
|
||||
<span class="badge badge-success"><i class="fas fa-check" aria-hidden="true"></i> <?= __('update_migration_applied') ?></span>
|
||||
<?php else: ?>
|
||||
<span class="badge badge-warning"><i class="fas fa-clock" aria-hidden="true"></i> <?= __('update_migration_open') ?></span>
|
||||
<?php endif; ?>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<button type="button" class="btn btn-secondary" id="btnMigrate" style="margin-top:14px;">
|
||||
<i class="fas fa-database" aria-hidden="true"></i> <?= __('update_migrations_btn') ?>
|
||||
</button>
|
||||
<span id="migrationResult" class="muted" style="margin-left:10px;"></span>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2><?= __('update_history') ?></h2>
|
||||
<?php if ($changelog === []): ?>
|
||||
<p class="muted"><?= __('update_history_empty') ?></p>
|
||||
<?php else: ?>
|
||||
<?php foreach ($changelog as $section): ?>
|
||||
<div class="changelog-entry">
|
||||
<h3><?= htmlspecialchars($section['heading']) ?></h3>
|
||||
<div class="changelog-body"><?= \Updater\Changelog::toHtml($section['text']) ?></div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
<script src="../assets/global.js"></script>
|
||||
<script>
|
||||
(function () {
|
||||
const csrf = <?= json_encode($csrf) ?>;
|
||||
const api = 'update_api.php';
|
||||
const text = <?= json_encode([
|
||||
'checking' => __('update_js_checking'),
|
||||
'current' => __('update_js_current'),
|
||||
'available' => __('update_js_available'),
|
||||
'behind' => __('update_js_behind'),
|
||||
'target' => __('update_js_target'),
|
||||
'installing' => __('update_js_installing'),
|
||||
'done' => __('update_js_done'),
|
||||
'failed' => __('update_js_failed'),
|
||||
'more' => __('update_js_more'),
|
||||
'switch' => __('update_js_channel_switch'),
|
||||
'confirm' => __('update_js_confirm'),
|
||||
'migrated' => __('update_js_migrated'),
|
||||
], JSON_UNESCAPED_UNICODE) ?>;
|
||||
|
||||
const btnCheck = document.getElementById('btnCheck');
|
||||
const btnInstall = document.getElementById('btnInstall');
|
||||
const btnMigrate = document.getElementById('btnMigrate');
|
||||
const result = document.getElementById('checkResult');
|
||||
const progress = document.getElementById('progressBox');
|
||||
const bar = document.getElementById('progressBar');
|
||||
const pct = document.getElementById('progressPercent');
|
||||
const status = document.getElementById('progressText');
|
||||
|
||||
function post(action, extra) {
|
||||
const body = new FormData();
|
||||
body.append('csrf_token', csrf);
|
||||
Object.entries(extra || {}).forEach(([k, v]) => body.append(k, v));
|
||||
return fetch(api + '?action=' + action, { method: 'POST', body: body })
|
||||
.then(r => r.json().catch(() => ({ ok: false, error: 'HTTP ' + r.status })));
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = value == null ? '' : String(value);
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
function renderCheck(data) {
|
||||
result.hidden = false;
|
||||
if (!data.ok) {
|
||||
result.className = 'update-result alert alert-error';
|
||||
result.textContent = data.error || text.failed;
|
||||
return;
|
||||
}
|
||||
if (!data.has_update) {
|
||||
result.className = 'update-result alert alert-ok';
|
||||
result.textContent = text.current;
|
||||
btnInstall.hidden = true;
|
||||
return;
|
||||
}
|
||||
|
||||
let html = '<p><strong>' + escapeHtml(text.available) + '</strong></p><ul class="update-facts">';
|
||||
if (data.version) { html += '<li>' + escapeHtml(text.target) + ' ' + escapeHtml(data.version) + '</li>'; }
|
||||
if (data.latest_sha) { html += '<li><code>' + escapeHtml(data.latest_sha.substring(0, 7)) + '</code></li>'; }
|
||||
if (data.versions_behind > 0) {
|
||||
html += '<li>' + escapeHtml(text.behind.replace('{count}', data.versions_behind)) + '</li>';
|
||||
}
|
||||
if (data.channel_switch) {
|
||||
html += '<li>' + escapeHtml(text.switch
|
||||
.replace('{from}', data.channel_switch.from_channel)
|
||||
.replace('{to}', data.channel_switch.to_channel)) + '</li>';
|
||||
}
|
||||
html += '</ul>';
|
||||
|
||||
// Fehlt changelog_preview, bleibt es bei "neue Fassung verfuegbar" -
|
||||
// kein leerer Kasten, kein erfundener Ersatztext.
|
||||
if (Array.isArray(data.changelog) && data.changelog.length) {
|
||||
html += '<div class="update-changelog">';
|
||||
data.changelog.forEach(entry => {
|
||||
html += '<h4>' + escapeHtml(entry.heading || entry.version) + '</h4>';
|
||||
html += '<pre class="update-changelog-text">' + escapeHtml(entry.text) + '</pre>';
|
||||
});
|
||||
if (data.changelog_complete === false) {
|
||||
html += '<p><a href="<?= \Updater\Updater::CHANNELS['stable'] ?>/changelog" target="_blank" rel="noopener">'
|
||||
+ escapeHtml(text.more) + '</a></p>';
|
||||
}
|
||||
html += '</div>';
|
||||
}
|
||||
|
||||
result.className = 'update-result alert alert-info';
|
||||
result.innerHTML = html;
|
||||
btnInstall.hidden = false;
|
||||
}
|
||||
|
||||
let pollTimer = null;
|
||||
function poll() {
|
||||
fetch(api + '?action=progress')
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
progress.hidden = false;
|
||||
const value = Math.max(0, data.pct);
|
||||
bar.style.width = value + '%';
|
||||
pct.textContent = data.pct < 0 ? '–' : value;
|
||||
status.textContent = data.text || '';
|
||||
if (data.step === 'done') {
|
||||
window.clearInterval(pollTimer);
|
||||
window.setTimeout(() => window.location.reload(), 1500);
|
||||
}
|
||||
if (data.step === 'error') {
|
||||
window.clearInterval(pollTimer);
|
||||
btnInstall.disabled = false;
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
btnCheck.addEventListener('click', function () {
|
||||
btnCheck.disabled = true;
|
||||
result.hidden = false;
|
||||
result.className = 'update-result alert alert-info';
|
||||
result.textContent = text.checking;
|
||||
post('check').then(data => { renderCheck(data); btnCheck.disabled = false; });
|
||||
});
|
||||
|
||||
btnInstall.addEventListener('click', function () {
|
||||
if (!window.confirm(text.confirm)) { return; }
|
||||
btnInstall.disabled = true;
|
||||
progress.hidden = false;
|
||||
status.textContent = text.installing;
|
||||
pollTimer = window.setInterval(poll, 2000);
|
||||
poll();
|
||||
post('install').then(data => {
|
||||
if (!data.ok) {
|
||||
window.clearInterval(pollTimer);
|
||||
result.hidden = false;
|
||||
result.className = 'update-result alert alert-error';
|
||||
result.textContent = data.error || text.failed;
|
||||
btnInstall.disabled = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (btnMigrate) {
|
||||
btnMigrate.addEventListener('click', function () {
|
||||
btnMigrate.disabled = true;
|
||||
post('migrations').then(data => {
|
||||
const out = document.getElementById('migrationResult');
|
||||
out.textContent = data.ok ? text.migrated.replace('{count}', data.count) : (data.error || text.failed);
|
||||
btnMigrate.disabled = false;
|
||||
if (data.ok && data.count > 0) { window.setTimeout(() => window.location.reload(), 1200); }
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
document.getElementById('channelForm').addEventListener('submit', function (event) {
|
||||
event.preventDefault();
|
||||
post('channel', { channel: document.getElementById('channelSelect').value })
|
||||
.then(data => { if (data.ok) { window.location.reload(); } });
|
||||
});
|
||||
|
||||
// Laeuft beim Aufruf schon ein Update, direkt den Fortschritt zeigen.
|
||||
fetch(api + '?action=progress').then(r => r.json()).then(data => {
|
||||
if (data.running) { progress.hidden = false; pollTimer = window.setInterval(poll, 2000); poll(); }
|
||||
}).catch(() => {});
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
21
admin/update_api.php
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
<?php
|
||||
/**
|
||||
* Endpunkte des Selbst-Updaters (JSON).
|
||||
*
|
||||
* Bewusst duenn: Anmeldung pruefen, an \Updater\UpdateController uebergeben.
|
||||
* Die Zuordnung zu den Routen der Vorlage steht dort im Klassenkommentar.
|
||||
*/
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
||||
require_once __DIR__ . '/../config.php';
|
||||
require_once __DIR__ . '/../includes/Database.php';
|
||||
require_once __DIR__ . '/../includes/Auth.php';
|
||||
require_once __DIR__ . '/../updater/bootstrap.php';
|
||||
|
||||
$auth = new Auth();
|
||||
$auth->requireAdmin();
|
||||
|
||||
$controller = new \Updater\UpdateController(Database::getInstance(), $auth);
|
||||
$controller->handle((string)($_GET['action'] ?? $_POST['action'] ?? ''));
|
||||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/../updater/guard.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/../updater/guard.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/../updater/guard.php';
|
||||
|
||||
/**
|
||||
* OpenAPI 3.0 Spezifikation der REST-API (zum Import in Postman/Swagger).
|
||||
* GET /api/openapi.php
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/../updater/guard.php';
|
||||
|
||||
/**
|
||||
* GET /api/sites.php – Liste aktiver Sites (für API-Clients).
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/../updater/guard.php';
|
||||
|
||||
/**
|
||||
* REST-Endpunkt für Voucher.
|
||||
*
|
||||
|
|
|
|||
|
|
@ -1474,6 +1474,63 @@ input.search-bar, .site-selector .search-bar { min-width: 240px; width: auto; fl
|
|||
.about-list dd { margin-bottom: 10px; }
|
||||
}
|
||||
|
||||
/* Selbst-Updater */
|
||||
.update-channel { margin-top: 20px; }
|
||||
.update-channel-row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
|
||||
.update-channel-row .input { max-width: 320px; }
|
||||
.update-actions { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 16px; }
|
||||
/* Der Ergebniskasten nutzt die Alert-Optik, stapelt seinen Inhalt aber
|
||||
untereinander - sonst laufen Eckdaten und Aenderungsprotokoll nebeneinander. */
|
||||
.update-result { margin-bottom: 16px; }
|
||||
.update-result.alert { display: block; }
|
||||
.update-facts { margin: 8px 0 0; padding-left: 18px; }
|
||||
.update-facts li { margin: 2px 0; }
|
||||
.update-changelog { margin-top: 14px; }
|
||||
.update-changelog h4 { margin: 12px 0 4px; font-size: 13.5px; font-weight: 650; }
|
||||
.update-changelog-text {
|
||||
margin: 0;
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--r-sm);
|
||||
background: var(--bg-subtle);
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
.update-progress { margin: 6px 0 18px; }
|
||||
.update-bar {
|
||||
height: 8px;
|
||||
border-radius: var(--r-pill);
|
||||
background: var(--bg-hover);
|
||||
overflow: hidden;
|
||||
}
|
||||
.update-bar span {
|
||||
display: block;
|
||||
height: 100%;
|
||||
width: 0;
|
||||
border-radius: var(--r-pill);
|
||||
background: linear-gradient(90deg, var(--grad-from, var(--accent)), var(--grad-to, var(--accent)));
|
||||
transition: width .4s ease;
|
||||
}
|
||||
.update-progress-text { margin: 8px 0 0; font-size: 13px; color: var(--text-secondary); }
|
||||
.update-privacy {
|
||||
margin-top: 22px;
|
||||
padding: 16px 18px;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--r-md);
|
||||
background: var(--bg-subtle);
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
.update-privacy h3 { margin: 0 0 8px; font-size: 13.5px; font-weight: 650; color: var(--text-primary); }
|
||||
.update-privacy p { margin: 0 0 8px; }
|
||||
.update-privacy ul { margin: 0 0 8px; padding-left: 18px; }
|
||||
.update-privacy li { margin: 2px 0; }
|
||||
.changelog-entry + .changelog-entry { margin-top: 22px; padding-top: 18px; border-top: 1px solid var(--border-color); }
|
||||
.changelog-entry h3 { margin: 0 0 8px; font-size: 15px; font-weight: 650; }
|
||||
.changelog-body ul { margin: 0; padding-left: 20px; }
|
||||
.changelog-body li { margin: 3px 0; color: var(--text-secondary); font-size: 13.5px; }
|
||||
.changelog-body p { margin: 6px 0; color: var(--text-secondary); font-size: 13.5px; }
|
||||
|
||||
/* Einstellungen: Tabs */
|
||||
.tab-container {
|
||||
background: var(--bg-card);
|
||||
|
|
|
|||
|
|
@ -27,6 +27,6 @@
|
|||
},
|
||||
"scripts": {
|
||||
"test": "phpunit",
|
||||
"stan": "phpstan analyse"
|
||||
"stan": "phpstan analyse --memory-limit=512M"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -110,8 +110,8 @@ try {
|
|||
if (!$lastCheck || strtotime($lastCheck) < strtotime('-23 hours')) {
|
||||
try {
|
||||
require_once $bootstrap;
|
||||
$mgr = \Updater\UpdaterFactory::create($db, null);
|
||||
$res = $mgr->checkForUpdates();
|
||||
$updater = \Updater\UpdaterFactory::create($db, null);
|
||||
$res = $updater->check();
|
||||
if (!empty($res['has_update'])) {
|
||||
Notifier::updateAvailable($res['latest_sha'] ?? '');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,72 +0,0 @@
|
|||
<?php
|
||||
// Minimaler Test für Cron-Sync Debugging
|
||||
header('Content-Type: application/json');
|
||||
|
||||
echo json_encode(['step' => 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!']);
|
||||
|
Before Width: | Height: | Size: 397 KiB After Width: | Height: | Size: 395 KiB |
|
Before Width: | Height: | Size: 390 KiB After Width: | Height: | Size: 382 KiB |
|
Before Width: | Height: | Size: 321 KiB After Width: | Height: | Size: 314 KiB |
|
Before Width: | Height: | Size: 316 KiB After Width: | Height: | Size: 318 KiB |
|
Before Width: | Height: | Size: 319 KiB After Width: | Height: | Size: 313 KiB |
|
Before Width: | Height: | Size: 217 KiB After Width: | Height: | Size: 212 KiB |
|
Before Width: | Height: | Size: 216 KiB After Width: | Height: | Size: 212 KiB |
|
Before Width: | Height: | Size: 242 KiB After Width: | Height: | Size: 242 KiB |
|
Before Width: | Height: | Size: 290 KiB After Width: | Height: | Size: 282 KiB |
|
Before Width: | Height: | Size: 447 KiB After Width: | Height: | Size: 445 KiB |
|
Before Width: | Height: | Size: 472 KiB After Width: | Height: | Size: 470 KiB |
|
Before Width: | Height: | Size: 1 MiB After Width: | Height: | Size: 1 MiB |
|
Before Width: | Height: | Size: 250 KiB After Width: | Height: | Size: 241 KiB |
|
Before Width: | Height: | Size: 123 KiB After Width: | Height: | Size: 118 KiB |
|
Before Width: | Height: | Size: 190 KiB After Width: | Height: | Size: 184 KiB |
|
Before Width: | Height: | Size: 192 KiB After Width: | Height: | Size: 186 KiB |
|
Before Width: | Height: | Size: 192 KiB After Width: | Height: | Size: 186 KiB |
|
Before Width: | Height: | Size: 284 KiB After Width: | Height: | Size: 284 KiB |
|
Before Width: | Height: | Size: 235 KiB After Width: | Height: | Size: 374 KiB |
|
Before Width: | Height: | Size: 235 KiB After Width: | Height: | Size: 371 KiB |
|
Before Width: | Height: | Size: 304 KiB After Width: | Height: | Size: 304 KiB |
|
Before Width: | Height: | Size: 751 KiB After Width: | Height: | Size: 748 KiB |
|
Before Width: | Height: | Size: 420 KiB After Width: | Height: | Size: 413 KiB |
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/updater/guard.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
|
|
|||
|
|
@ -36,6 +36,16 @@ class Database {
|
|||
}
|
||||
self::renderUnavailable();
|
||||
}
|
||||
|
||||
// Nach einem Update muessen neue Migrationen nachgezogen werden.
|
||||
// Ohne Serverzugang ist der erste Seitenaufruf danach der einzige
|
||||
// verlaessliche Zeitpunkt dafuer. Der Aufruf ist billig: er
|
||||
// vergleicht nur einen Fingerabdruck und tut sonst nichts.
|
||||
$autoMigrate = dirname(__DIR__) . '/updater/AutoMigrate.php';
|
||||
if (is_file($autoMigrate)) {
|
||||
require_once dirname(__DIR__) . '/updater/bootstrap.php';
|
||||
\Updater\AutoMigrate::run(self::$instance);
|
||||
}
|
||||
}
|
||||
return self::$instance;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,6 @@
|
|||
<?php
|
||||
// Updater maintenance hook — see updater/README.md
|
||||
$maintenanceFile = __DIR__ . '/updater/storage/.maintenance';
|
||||
if (file_exists($maintenanceFile)) {
|
||||
http_response_code(503);
|
||||
require __DIR__ . '/updater/templates/maintenance.html';
|
||||
exit;
|
||||
}
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/updater/guard.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/updater/guard.php';
|
||||
|
||||
/**
|
||||
* Öffentliche Display-Seite ("Kiosk").
|
||||
*
|
||||
|
|
|
|||
46
lang/de.php
|
|
@ -17,7 +17,7 @@ return [
|
|||
'nav_security' => '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.',
|
||||
];
|
||||
|
|
|
|||
46
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.',
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/updater/guard.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/updater/guard.php';
|
||||
|
||||
/**
|
||||
* Generischer OpenID-Connect-Callback (Authorization-Code-Flow).
|
||||
* Konfiguration unter Administration → Integration & Wartung.
|
||||
|
|
|
|||
|
|
@ -2,10 +2,17 @@ parameters:
|
|||
level: 5
|
||||
# __() stammt aus der I18n-Klasse und wird global definiert
|
||||
scanFiles:
|
||||
- includes/Database.php
|
||||
- includes/Auth.php
|
||||
- includes/I18n.php
|
||||
- includes/UniFiController.php
|
||||
- includes/Crypto.php
|
||||
# Der Updater wird vollstaendig geprueft; Vorlagen und SQL-Dateien nicht.
|
||||
excludePaths:
|
||||
- updater/templates/
|
||||
- updater/migrations/
|
||||
paths:
|
||||
- updater/
|
||||
- includes/Totp.php
|
||||
- includes/Crypto.php
|
||||
- includes/ApiKey.php
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
<?php
|
||||
// Waehrend eines Updates antwortet der Waechter mit einer Wartungsseite.
|
||||
require_once __DIR__ . '/updater/guard.php';
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set('display_errors', 0);
|
||||
ini_set('log_errors', 1);
|
||||
|
|
|
|||
22
test.php
|
|
@ -6,15 +6,23 @@ ini_set('log_errors', 1);
|
|||
// Diagnose-Seite nur fuer angemeldete Admins zugaenglich (verhindert Info-Leak)
|
||||
require_once __DIR__ . '/includes/Ui.php';
|
||||
|
||||
if (file_exists(__DIR__ . '/config.php')) {
|
||||
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();
|
||||
// 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 '<!DOCTYPE html><html lang="de"><head><meta charset="UTF-8">'
|
||||
. '<meta name="viewport" content="width=device-width, initial-scale=1.0">'
|
||||
. '<title>System-Test</title>'
|
||||
|
|
|
|||
302
tests/UpdaterTest.php
Normal file
|
|
@ -0,0 +1,302 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Updater\Changelog;
|
||||
use Updater\Maintenance;
|
||||
use Updater\MigrationRunner;
|
||||
use Updater\Progress;
|
||||
use Updater\Updater;
|
||||
use Updater\Version;
|
||||
|
||||
require_once __DIR__ . '/../updater/bootstrap.php';
|
||||
|
||||
/**
|
||||
* Der Updater schreibt in die laufende Installation - die Tests fassen
|
||||
* deshalb ausschliesslich temporaere Verzeichnisse an. Version::useStorageDir()
|
||||
* lenkt Version, Fortschritt und Wartungsmarkierung dorthin um.
|
||||
*/
|
||||
class UpdaterTest extends TestCase
|
||||
{
|
||||
/** @var string */
|
||||
private $tmp;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
$this->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', '<?php // Zugangsdaten dieser Installation');
|
||||
file_put_contents($root . '/uploads/logo.png', 'altes Logo');
|
||||
file_put_contents($root . '/index.php', 'alt');
|
||||
|
||||
$staging = $this->tmp . '/staging-apply';
|
||||
mkdir($staging . '/uploads', 0775, true);
|
||||
file_put_contents($staging . '/config.php', '<?php // Beispielkonfiguration aus dem Paket');
|
||||
file_put_contents($staging . '/uploads/logo.png', 'Logo aus dem Paket');
|
||||
file_put_contents($staging . '/index.php', 'neu');
|
||||
file_put_contents($staging . '/neu.php', 'neue Datei');
|
||||
|
||||
$updater = new Updater(null, null, 'stable', null, $root);
|
||||
$applied = $updater->applyStaging($staging);
|
||||
|
||||
$this->assertSame('<?php // Zugangsdaten dieser Installation', file_get_contents($root . '/config.php'));
|
||||
$this->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', '<?php echo "neu";');
|
||||
|
||||
(new Updater(null, null, 'stable', null, $root))->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('<ul><li>Erster Punkt mit <strong>Nachdruck</strong></li>', $html);
|
||||
$this->assertStringContainsString('<a href="https://example.com/doku"', $html);
|
||||
$this->assertStringNotContainsString('javascript:', $html);
|
||||
$this->assertStringNotContainsString('<script', $html);
|
||||
}
|
||||
|
||||
public function testChangelogEscapesHtmlFromTheSource(): void
|
||||
{
|
||||
$html = Changelog::toHtml('- <img src=x onerror=alert(1)>');
|
||||
|
||||
$this->assertStringNotContainsString('<img', $html);
|
||||
$this->assertStringContainsString('<img', $html);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Helfer
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -104,6 +104,29 @@ $headline = trim((string)($kiosk['headline'] ?? ''))''')
|
|||
'<div class="modal" id="kioskModal">',
|
||||
'<div class="modal<?= ($_GET[\'demo\'] ?? \'\') === \'form\' ? \' active\' : \'\' ?>" id="kioskModal">')
|
||||
|
||||
# Updater: Ergebnis einer Pruefung ohne echten Update-Dienst zeigen
|
||||
# (?demo=available). Die Oberflaeche selbst laedt das sonst per fetch.
|
||||
patch(os.path.join(target, 'admin', 'update.php'),
|
||||
'<div id="checkResult" class="update-result" hidden></div>',
|
||||
"""<?php if (($_GET['demo'] ?? '') === 'available'): ?>
|
||||
<div id="checkResult" class="update-result alert alert-info">
|
||||
<p><strong>Eine neue Fassung ist verfügbar.</strong></p>
|
||||
<ul class="update-facts">
|
||||
<li>Zielversion: 3.1.0</li>
|
||||
<li><code>a1b2c3d</code></li>
|
||||
<li>2 Stände zurück</li>
|
||||
</ul>
|
||||
<div class="update-changelog">
|
||||
<h4>3.1.0 – 2026-10-02</h4>
|
||||
<pre class="update-changelog-text">- Voucher-Import erkennt jetzt auch Semikolon-getrennte Dateien
|
||||
- Display-Seiten: QR-Code optional größer darstellbar
|
||||
- Fehler behoben: Zeitzone im Reporting-Export</pre>
|
||||
</div>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<div id="checkResult" class="update-result" hidden></div>
|
||||
<?php endif; ?>""")
|
||||
|
||||
# Theme per Query-Parameter erzwingen (fuer Dark-Mode-Screenshots)
|
||||
ui = os.path.join(target, 'includes', 'Ui.php')
|
||||
patch(ui, 'var s=localStorage.getItem("theme");',
|
||||
|
|
|
|||
|
|
@ -48,7 +48,26 @@ class Database {
|
|||
}
|
||||
|
||||
public static function getInstance() { return self::$instance ??= new self(); }
|
||||
public function getConnection() { return null; }
|
||||
/**
|
||||
* Fuer die Demo genuegt eine SQLite-Datei: der Updater fragt darueber den
|
||||
* Stand der Migrationen ab. Angewendet sind alle bis auf die letzte,
|
||||
* damit die Uebersicht beide Zustaende zeigt.
|
||||
*/
|
||||
public function getConnection() {
|
||||
static $pdo = null;
|
||||
if ($pdo === null) {
|
||||
$pdo = new PDO('sqlite:' . sys_get_temp_dir() . '/uvt-demo-migrations.sqlite');
|
||||
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
$pdo->exec('CREATE TABLE IF NOT EXISTS "_updater_migrations" (filename TEXT PRIMARY KEY, applied_at TEXT)');
|
||||
$files = glob(dirname(__DIR__) . '/updater/migrations/*.sql') ?: [];
|
||||
sort($files);
|
||||
foreach (array_slice($files, 0, max(0, count($files) - 1)) as $file) {
|
||||
$stmt = $pdo->prepare('INSERT OR IGNORE INTO "_updater_migrations" (filename) VALUES (?)');
|
||||
$stmt->execute([basename($file)]);
|
||||
}
|
||||
}
|
||||
return $pdo;
|
||||
}
|
||||
public function getSetting($key, $default = null) { return $this->settings[$key] ?? $default; }
|
||||
public function setSetting($key, $value) { $this->settings[$key] = $value; }
|
||||
public function execute($sql, $params = []) { return 1; }
|
||||
|
|
|
|||
|
|
@ -33,15 +33,18 @@ SHOTS = [
|
|||
('api-keys.png', 'admin/api_keys.php?demo=new', 1200, 830),
|
||||
('integrations.png', 'admin/integrations.php', 1200, 900),
|
||||
('two-factor.png', 'admin/security.php', 1200, 900),
|
||||
('updater.png', 'admin/update.php', 1200, 780),
|
||||
('updater-available.png', 'admin/update.php?demo=available', 1200, 780),
|
||||
('updater.png', 'admin/update.php', 1200, 1420),
|
||||
('updater-available.png', 'admin/update.php?demo=available', 1200, 1500),
|
||||
('kiosk-display.png', 'kiosk.php?k=0f1e2d3c4b5a69788796a5b4c3d2e1f0', 1200, 900),
|
||||
('kiosk-code.png', 'kiosk.php?k=a1b2c3d4e5f60718293a4b5c6d7e8f90&demo=code', 1200, 900),
|
||||
('kiosk-branded.png', 'kiosk.php?k=a1b2c3d4e5f60718293a4b5c6d7e8f90', 1200, 900),
|
||||
('kiosks-admin.png', 'admin/kiosks.php', 1200, 780),
|
||||
('kiosks-form.png', 'admin/kiosks.php?demo=form', 1200, 1150),
|
||||
('mobile-vouchers.png', 'admin/users.php', 430, 860),
|
||||
('maintenance.png', 'updater/templates/maintenance.html', 1200, 700),
|
||||
# Die Wartungsseite zeigt ohne laufendes Update den unbestimmten Balken.
|
||||
# Das mitgelieferte Bild wurde bei 65 % aufgenommen (Markierung in
|
||||
# updater/storage/ gesetzt) - wer es neu erzeugt, bekommt die Ruhefassung.
|
||||
('maintenance.png', 'updater/templates/maintenance.php', 1200, 700),
|
||||
]
|
||||
|
||||
CANDIDATES = [
|
||||
|
|
|
|||
|
|
@ -2,15 +2,12 @@
|
|||
namespace Updater;
|
||||
|
||||
/**
|
||||
* Minimaler AuditLogger fuer den Updater.
|
||||
* Schreibt Updater-Ereignisse in die vorhandene Tabelle `audit_log`.
|
||||
*
|
||||
* Das Projekt besitzt KEINE eigene AuditLogger-Klasse, aber eine vorhandene
|
||||
* Tabelle `audit_log`. Dieser Logger schreibt dort hinein, ohne eine
|
||||
* Projekt-Klasse zu erweitern. Faellt das Schreiben fehl (z.B. Tabelle fehlt),
|
||||
* wird der Fehler still ignoriert – Logging darf ein Update nie blockieren.
|
||||
*
|
||||
* Wird dem UpdateManager optional injiziert; ist er null, wird Logging
|
||||
* komplett uebersprungen.
|
||||
* Jeder Lauf hinterlaesst einen Eintrag - Erfolg wie Fehler, mit Kanal,
|
||||
* Ziel-Stand, Anzahl der Migrationen und ausloesendem Benutzer. Schlaegt das
|
||||
* Schreiben fehl, wird der Fehler verschluckt: Protokollierung darf ein
|
||||
* Update nie verhindern.
|
||||
*/
|
||||
class AuditLogger
|
||||
{
|
||||
|
|
@ -22,7 +19,10 @@ class AuditLogger
|
|||
$this->db = $db;
|
||||
}
|
||||
|
||||
public function log($action, $details = null, $userId = null)
|
||||
/**
|
||||
* @param string|array $details
|
||||
*/
|
||||
public function log(string $action, $details = null, ?int $userId = null): void
|
||||
{
|
||||
try {
|
||||
$this->db->query(
|
||||
|
|
@ -36,7 +36,7 @@ class AuditLogger
|
|||
]
|
||||
);
|
||||
} catch (\Throwable $e) {
|
||||
// Logging darf nie ein Update verhindern.
|
||||
// bewusst still
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
76
updater/AutoMigrate.php
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
<?php
|
||||
namespace Updater;
|
||||
|
||||
/**
|
||||
* Zieht Migrationen beim ersten Seitenaufruf nach einem Update nach.
|
||||
*
|
||||
* Ohne SSH-Zugang auf dem Zielserver ist das der einzige verlaessliche
|
||||
* Zeitpunkt, zu dem neue Migrationen laufen koennen.
|
||||
*
|
||||
* Zwei Vorkehrungen, ohne die das reihenweise schiefgeht:
|
||||
* - ein Fingerabdruck ueber die Liste der Migrationsdateien. Nur wenn der
|
||||
* sich geaendert hat, wird ueberhaupt migriert - sonst liefe der Migrator
|
||||
* bei JEDEM Aufruf.
|
||||
* - eine Sperrdatei gegen Parallellauf, denn nach einem Update treffen
|
||||
* oft mehrere Aufrufe gleichzeitig ein.
|
||||
*
|
||||
* Fehler werden protokolliert, nicht geworfen: eine fehlgeschlagene
|
||||
* Nachfuehrung darf nicht jede Seite unbenutzbar machen.
|
||||
*/
|
||||
final class AutoMigrate
|
||||
{
|
||||
public static function run(\Database $db): void
|
||||
{
|
||||
if (PHP_SAPI === 'cli' || defined('PHPUNIT_RUNNING')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$storage = Version::storageDir();
|
||||
$migrationsDir = __DIR__ . '/migrations';
|
||||
if (!is_dir($migrationsDir) || !is_dir($storage)) {
|
||||
return; // nicht installiert
|
||||
}
|
||||
|
||||
$fingerprint = self::fingerprint($migrationsDir);
|
||||
$stampFile = $storage . '/.migration-fingerprint';
|
||||
$known = is_file($stampFile) ? trim((string)@file_get_contents($stampFile)) : '';
|
||||
if ($known === $fingerprint) {
|
||||
return;
|
||||
}
|
||||
|
||||
$lockFile = $storage . '/.migration-lock';
|
||||
$lock = @fopen($lockFile, 'c');
|
||||
if ($lock === false) {
|
||||
return;
|
||||
}
|
||||
if (!flock($lock, LOCK_EX | LOCK_NB)) {
|
||||
fclose($lock);
|
||||
|
||||
return; // ein anderer Aufruf ist schon dabei
|
||||
}
|
||||
|
||||
try {
|
||||
$runner = new MigrationRunner($db->getConnection(), $migrationsDir, $storage);
|
||||
$runner->runPending(true);
|
||||
@file_put_contents($stampFile, $fingerprint);
|
||||
} catch (\Throwable $e) {
|
||||
error_log('Automatische Migration fehlgeschlagen: ' . $e->getMessage());
|
||||
} finally {
|
||||
flock($lock, LOCK_UN);
|
||||
fclose($lock);
|
||||
}
|
||||
}
|
||||
|
||||
/** Hash ueber Namen und Groessen aller Migrationsdateien. */
|
||||
public static function fingerprint(string $migrationsDir): string
|
||||
{
|
||||
$files = glob($migrationsDir . '/*.sql') ?: [];
|
||||
sort($files);
|
||||
$parts = [];
|
||||
foreach ($files as $file) {
|
||||
$parts[] = basename($file) . ':' . (int)@filesize($file);
|
||||
}
|
||||
|
||||
return hash('sha256', implode('|', $parts));
|
||||
}
|
||||
}
|
||||
167
updater/Changelog.php
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
<?php
|
||||
namespace Updater;
|
||||
|
||||
/**
|
||||
* Liest die mitgelieferte CHANGELOG.md und macht daraus Abschnitte.
|
||||
*
|
||||
* Aufbau: je Version eine Ueberschrift "## 1.2.3 - Datum", darunter
|
||||
* Stichpunkte. Neueste Version oben.
|
||||
*
|
||||
* Der Markdown-Renderer ist bewusst klein gehalten - das Projekt bringt
|
||||
* keine Markdown-Bibliothek mit, und hier wird nur das gebraucht, was in
|
||||
* einem Aenderungsprotokoll vorkommt. Alles andere wird als Text ausgegeben,
|
||||
* niemals als HTML.
|
||||
*/
|
||||
final class Changelog
|
||||
{
|
||||
public static function file(): string
|
||||
{
|
||||
return dirname(__DIR__) . '/CHANGELOG.md';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{version:string, heading:string, text:string}>
|
||||
*/
|
||||
public static function sections(?string $markdown = null): array
|
||||
{
|
||||
if ($markdown === null) {
|
||||
$file = self::file();
|
||||
$markdown = is_file($file) ? (string)file_get_contents($file) : '';
|
||||
}
|
||||
if (trim($markdown) === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
$sections = [];
|
||||
$current = null;
|
||||
foreach (preg_split('/\R/', $markdown) as $line) {
|
||||
if (preg_match('/^##\s+(.+?)\s*$/', $line, $m)) {
|
||||
if ($current !== null) {
|
||||
$sections[] = self::finish($current);
|
||||
}
|
||||
$heading = trim($m[1]);
|
||||
preg_match('/(\d+\.\d+\.\d+)/', $heading, $v);
|
||||
$current = [
|
||||
'version' => $v[1] ?? '',
|
||||
'heading' => $heading,
|
||||
'lines' => [],
|
||||
];
|
||||
continue;
|
||||
}
|
||||
if ($current !== null) {
|
||||
$current['lines'][] = $line;
|
||||
}
|
||||
}
|
||||
if ($current !== null) {
|
||||
$sections[] = self::finish($current);
|
||||
}
|
||||
|
||||
return $sections;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{version:string, heading:string, lines:array<int,string>} $section
|
||||
* @return array{version:string, heading:string, text:string}
|
||||
*/
|
||||
private static function finish(array $section): array
|
||||
{
|
||||
return [
|
||||
'version' => $section['version'],
|
||||
'heading' => $section['heading'],
|
||||
'text' => trim(implode("\n", $section['lines'])),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Markdown -> HTML fuer Aenderungsprotokolle: Listen, Absaetze, fetter und
|
||||
* kursiver Text, Code und Verweise. Verweise nur mit http(s), alles andere
|
||||
* wird zu reinem Text - ein "javascript:"-Link aus einer fremden Quelle
|
||||
* hat in der Oberflaeche nichts verloren.
|
||||
*/
|
||||
public static function toHtml(string $markdown): string
|
||||
{
|
||||
$html = '';
|
||||
$listOpen = false;
|
||||
$paragraph = [];
|
||||
|
||||
foreach (preg_split('/\R/', $markdown) as $line) {
|
||||
$trimmed = trim($line);
|
||||
|
||||
if ($trimmed === '') {
|
||||
$html .= self::paragraph($paragraph);
|
||||
$paragraph = [];
|
||||
if ($listOpen) {
|
||||
$html .= '</ul>';
|
||||
$listOpen = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^[-*+]\s+(.*)$/', $trimmed, $m)) {
|
||||
$html .= self::paragraph($paragraph);
|
||||
$paragraph = [];
|
||||
if (!$listOpen) {
|
||||
$html .= '<ul>';
|
||||
$listOpen = true;
|
||||
}
|
||||
$html .= '<li>' . self::inline($m[1]) . '</li>';
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/^#{3,6}\s+(.*)$/', $trimmed, $m)) {
|
||||
$html .= self::paragraph($paragraph);
|
||||
$paragraph = [];
|
||||
if ($listOpen) {
|
||||
$html .= '</ul>';
|
||||
$listOpen = false;
|
||||
}
|
||||
$html .= '<h4>' . self::inline($m[1]) . '</h4>';
|
||||
continue;
|
||||
}
|
||||
|
||||
$paragraph[] = $trimmed;
|
||||
}
|
||||
|
||||
$html .= self::paragraph($paragraph);
|
||||
if ($listOpen) {
|
||||
$html .= '</ul>';
|
||||
}
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $lines
|
||||
*/
|
||||
private static function paragraph(array $lines): string
|
||||
{
|
||||
return $lines === [] ? '' : '<p>' . self::inline(implode(' ', $lines)) . '</p>';
|
||||
}
|
||||
|
||||
/** 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 '<a href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8')
|
||||
. '" target="_blank" rel="noopener noreferrer">' . $label . '</a>';
|
||||
},
|
||||
$escaped
|
||||
);
|
||||
|
||||
$escaped = preg_replace('/`([^`]+)`/', '<code>$1</code>', $escaped);
|
||||
$escaped = preg_replace('/\*\*([^*]+)\*\*/', '<strong>$1</strong>', $escaped);
|
||||
$escaped = preg_replace('/(?<![\w*])\*([^*]+)\*(?![\w*])/', '<em>$1</em>', $escaped);
|
||||
|
||||
return (string)$escaped;
|
||||
}
|
||||
}
|
||||
91
updater/Maintenance.php
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
<?php
|
||||
namespace Updater;
|
||||
|
||||
/**
|
||||
* Wartungsmodus waehrend eines Updates.
|
||||
*
|
||||
* Die Pruefung ist selbstheilend: laeuft das hinterlegte Ende ab, raeumt der
|
||||
* naechste Aufruf die Markierung weg. Ohne das legt ein Absturz mitten im
|
||||
* Update die Installation dauerhaft lahm - und niemand kaeme mehr an die
|
||||
* Oberflaeche, um den Modus abzuschalten.
|
||||
*/
|
||||
final class Maintenance
|
||||
{
|
||||
public const DEFAULT_MAX_SECONDS = 600;
|
||||
|
||||
private static function file(): string
|
||||
{
|
||||
return Version::storageDir() . '/.maintenance';
|
||||
}
|
||||
|
||||
public static function activate(int $maxSeconds = self::DEFAULT_MAX_SECONDS): void
|
||||
{
|
||||
$maxSeconds = max(30, $maxSeconds);
|
||||
$dir = Version::storageDir();
|
||||
if (!is_dir($dir)) {
|
||||
@mkdir($dir, 0775, true);
|
||||
}
|
||||
|
||||
@file_put_contents(self::file(), json_encode([
|
||||
'since' => 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());
|
||||
}
|
||||
}
|
||||
90
updater/Progress.php
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
<?php
|
||||
namespace Updater;
|
||||
|
||||
/**
|
||||
* Fortschritt eines laufenden Updates.
|
||||
*
|
||||
* Der Ablauf laeuft serverseitig weiter, auch wenn der Browser die Verbindung
|
||||
* abbricht. Die Oberflaeche fragt deshalb nur diese Datei ab, statt auf die
|
||||
* Antwort des Installations-Aufrufs zu warten.
|
||||
*/
|
||||
final class Progress
|
||||
{
|
||||
/** Ohne Lebenszeichen in dieser Zeit gilt ein Lauf als abgestuerzt. */
|
||||
public const STALE_AFTER = 600;
|
||||
|
||||
private static function file(): string
|
||||
{
|
||||
return Version::storageDir() . '/.update-progress';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{pct:int, step:string, text:string, ts:int}
|
||||
*/
|
||||
public static function get(): array
|
||||
{
|
||||
$file = self::file();
|
||||
if (!is_file($file)) {
|
||||
return ['pct' => 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
217
updater/ProxyClient.php
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
<?php
|
||||
namespace Updater;
|
||||
|
||||
/**
|
||||
* HTTP-Client fuer den Update-Proxy.
|
||||
*
|
||||
* Der Proxy stellt den Stand eines Branches bereit; es gibt keine Tags und
|
||||
* keine Releases. Die Identitaet eines Stands ist sein Commit-SHA.
|
||||
*
|
||||
* Es werden ausschliesslich HTTPS-Adressen akzeptiert, Weiterleitungen sind
|
||||
* begrenzt, und die Zertifikatspruefung bleibt eingeschaltet.
|
||||
*/
|
||||
class ProxyClient
|
||||
{
|
||||
private const USER_AGENT = 'UnifiVoucherTool-Updater/1.0';
|
||||
private const TIMEOUT_JSON = 30;
|
||||
private const TIMEOUT_ZIP = 180;
|
||||
private const MAX_REDIRECTS = 3;
|
||||
|
||||
/** @var string */
|
||||
private $baseUrl;
|
||||
|
||||
public function __construct(string $baseUrl)
|
||||
{
|
||||
$baseUrl = rtrim($baseUrl, '/');
|
||||
if (stripos($baseUrl, 'https://') !== 0) {
|
||||
throw new \InvalidArgumentException('Update-Adresse muss mit https:// beginnen.');
|
||||
}
|
||||
$this->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];
|
||||
}
|
||||
}
|
||||
|
|
@ -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=<sha>` 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://<host>/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.
|
||||
|
|
|
|||
20
updater/RetryLaterException.php
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
<?php
|
||||
namespace Updater;
|
||||
|
||||
/**
|
||||
* Der Proxy ist erreichbar, kann aber gerade nicht ausliefern
|
||||
* (mirror_pending: Stand wird gespiegelt, not_released: noch nichts
|
||||
* freigegeben). Das ist kein Fehler des Clients - die Oberflaeche bittet
|
||||
* deshalb um Geduld statt eine Stoerung zu melden.
|
||||
*/
|
||||
class RetryLaterException extends \RuntimeException
|
||||
{
|
||||
/** @var int Sekunden, die der Proxy als Wartezeit nennt. */
|
||||
public $retryAfter;
|
||||
|
||||
public function __construct(string $message, int $retryAfter = 60)
|
||||
{
|
||||
parent::__construct($message);
|
||||
$this->retryAfter = max(5, $retryAfter);
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,426 +0,0 @@
|
|||
<?php
|
||||
namespace Updater;
|
||||
|
||||
/**
|
||||
* UpdateManager – zieht Quellcode + DB-Migrationen aus einem zentralen
|
||||
* Repository ueber einen HTTP-Update-Proxy nach.
|
||||
*
|
||||
* Architektur: [diese App] <-HTTPS-> [Update-Proxy] <-pull- [Git-Repo]
|
||||
* Versions-Identitaet: 40-stelliger Git-Commit-SHA in <storage>/.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-<sha>/"). 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];
|
||||
}
|
||||
}
|
||||
509
updater/Updater.php
Normal file
|
|
@ -0,0 +1,509 @@
|
|||
<?php
|
||||
namespace Updater;
|
||||
|
||||
/**
|
||||
* Der eigentliche Selbst-Updater.
|
||||
*
|
||||
* [diese Installation] <-HTTPS-> [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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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<string, string> Kanal => Anzeigename */
|
||||
public static function channelLabels(): array
|
||||
{
|
||||
return [
|
||||
'stable' => 'Stabil (empfohlen)',
|
||||
'development' => 'Entwicklung (Vorabfassungen)',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
105
updater/Version.php
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
<?php
|
||||
namespace Updater;
|
||||
|
||||
/**
|
||||
* Versions-Auskunft.
|
||||
*
|
||||
* Zwei Angaben beschreiben einen Stand:
|
||||
* - die Release-Version (SemVer) steht als Konstante im Code und wandert
|
||||
* damit automatisch mit jedem Update mit,
|
||||
* - der Git-Commit-SHA ist die technische Identitaet und steht in einer
|
||||
* DATEI unter updater/storage/.version.
|
||||
*
|
||||
* Die Datei ist Absicht: der Updater muss den installierten Stand auch dann
|
||||
* lesen koennen, wenn die Datenbank gerade nicht erreichbar ist. Ausserdem
|
||||
* liegt storage/ auf der Liste der geschuetzten Pfade - ein Update
|
||||
* ueberschreibt die Datei also nie mit dem Stand aus dem Archiv.
|
||||
*/
|
||||
final class Version
|
||||
{
|
||||
/**
|
||||
* Release-Version dieses Codes (SemVer).
|
||||
* Bei jeder Aenderung anheben, siehe CHANGELOG.md.
|
||||
*/
|
||||
public const RELEASE = '3.0.0';
|
||||
|
||||
/** @var string|null Nur fuer Tests: abweichender Ablageort. */
|
||||
private static $storageOverride = null;
|
||||
|
||||
public static function storageDir(): string
|
||||
{
|
||||
return self::$storageOverride ?? __DIR__ . '/storage';
|
||||
}
|
||||
|
||||
/**
|
||||
* Lenkt Version, Fortschritt und Wartungsmarkierung in ein anderes
|
||||
* Verzeichnis um. Ausschliesslich fuer Tests gedacht - im Betrieb bleibt
|
||||
* es bei updater/storage/.
|
||||
*/
|
||||
public static function useStorageDir(?string $dir): void
|
||||
{
|
||||
self::$storageOverride = $dir === null ? null : rtrim($dir, '/');
|
||||
}
|
||||
|
||||
private static function file(): string
|
||||
{
|
||||
return self::storageDir() . '/.version';
|
||||
}
|
||||
|
||||
/** Installierter Commit-SHA oder null bei einer frischen Installation. */
|
||||
public static function current(): ?string
|
||||
{
|
||||
$file = self::file();
|
||||
if (!is_file($file)) {
|
||||
return null;
|
||||
}
|
||||
$sha = trim((string)@file_get_contents($file));
|
||||
|
||||
return self::isSha($sha) ? $sha : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schreibt den Stand zurueck. Ungueltige Werte werden abgelehnt, damit
|
||||
* eine halbe Proxy-Antwort nicht als Version einzementiert wird.
|
||||
*/
|
||||
public static function save(string $sha): bool
|
||||
{
|
||||
$sha = strtolower(trim($sha));
|
||||
if (!self::isSha($sha)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$dir = self::storageDir();
|
||||
if (!is_dir($dir) && !@mkdir($dir, 0775, true) && !is_dir($dir)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return @file_put_contents(self::file(), $sha . "\n") !== false;
|
||||
}
|
||||
|
||||
public static function isSha(string $value): bool
|
||||
{
|
||||
return (bool)preg_match('/^[0-9a-f]{40}$/', strtolower(trim($value)));
|
||||
}
|
||||
|
||||
/** Kurzform fuer die Anzeige. */
|
||||
public static function short(?string $sha = null): string
|
||||
{
|
||||
$sha = $sha ?? self::current();
|
||||
|
||||
return $sha === null ? '' : substr($sha, 0, 7);
|
||||
}
|
||||
|
||||
public static function release(): string
|
||||
{
|
||||
return self::RELEASE;
|
||||
}
|
||||
|
||||
/** "3.0.0 (a1b2c3d)" bzw. nur "3.0.0", solange kein SHA bekannt ist. */
|
||||
public static function full(): string
|
||||
{
|
||||
$short = self::short();
|
||||
|
||||
return $short === '' ? self::RELEASE : self::RELEASE . ' (' . $short . ')';
|
||||
}
|
||||
}
|
||||
45
updater/guard.php
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
<?php
|
||||
/**
|
||||
* Wartungs-Waechter.
|
||||
*
|
||||
* Dieses Projekt hat kein Framework und damit keine Middleware-Schicht; die
|
||||
* Auslieferung ist datei-basiert. Der Waechter wird deshalb als erste Zeile
|
||||
* der Einstiegsseiten eingebunden und uebernimmt dort dieselbe Aufgabe.
|
||||
*
|
||||
* Waehrend eines Updates antwortet er mit 503 und einer verstaendlichen
|
||||
* Wartungsseite. Ausgenommen bleiben die Update-Endpunkte selbst, die
|
||||
* Anmeldeseite und der Health-Check - sonst koennte niemand mehr sehen, wie
|
||||
* weit das laufende Update ist.
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/bootstrap.php';
|
||||
|
||||
if (PHP_SAPI !== 'cli' && \Updater\Maintenance::isActive()) {
|
||||
$retry = \Updater\Maintenance::retryAfter();
|
||||
$progress = \Updater\Progress::get();
|
||||
|
||||
http_response_code(503);
|
||||
header('Retry-After: ' . $retry);
|
||||
header('Cache-Control: no-store');
|
||||
|
||||
// Schnittstellen bekommen JSON - eine HTML-Wartungsseite kann ein
|
||||
// aufrufendes Programm nicht auswerten.
|
||||
$isApi = strpos((string)($_SERVER['SCRIPT_NAME'] ?? ''), '/api/') !== false
|
||||
|| strpos((string)($_SERVER['HTTP_ACCEPT'] ?? ''), 'application/json') !== false;
|
||||
|
||||
if ($isApi) {
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode([
|
||||
'error' => '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;
|
||||
}
|
||||
|
|
@ -1,29 +1,34 @@
|
|||
<?php
|
||||
/**
|
||||
* Routen-Registrierung fuer den Updater.
|
||||
* Zuordnung der Update-Endpunkte.
|
||||
*
|
||||
* Dieses Projekt besitzt KEIN zentrales Routing-System (Slim/FastRoute/o.ae.) –
|
||||
* die Auslieferung erfolgt datei-basiert ueber den Webserver. Die Updater-Route
|
||||
* `/admin/update` wird daher durch die reale Datei `admin/update.php`
|
||||
* bereitgestellt (duenner Shim -> \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'],
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,3 +1,15 @@
|
|||
<?php
|
||||
/**
|
||||
* Wartungsseite waehrend eines Updates.
|
||||
*
|
||||
* Bewusst vollstaendig eigenstaendig: waehrend des Updates koennen assets/
|
||||
* und externe Ressourcen kurzzeitig nicht verfuegbar sein.
|
||||
*
|
||||
* $percent und $status kommen aus updater/guard.php.
|
||||
*/
|
||||
$percent = isset($percent) ? (int)$percent : 0;
|
||||
$status = isset($status) ? (string)$status : '';
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
|
|
@ -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 @@
|
|||
</svg>
|
||||
</div>
|
||||
<h1>Kurz mal Wartung</h1>
|
||||
<p>Es wird gerade ein Update eingespielt. Die Seite ist in wenigen Augenblicken wieder erreichbar.</p>
|
||||
<div class="bar"></div>
|
||||
<p class="hint">Diese Seite aktualisiert sich automatisch.</p>
|
||||
<p><?= htmlspecialchars($status !== '' ? $status : 'Es wird gerade ein Update eingespielt. Die Seite ist in wenigen Augenblicken wieder erreichbar.', ENT_QUOTES, 'UTF-8') ?></p>
|
||||
<?php if ($percent > 0): ?>
|
||||
<div class="bar bar-known"><span style="width: <?= min(100, max(0, (int)$percent)) ?>%;"></span></div>
|
||||
<p class="hint"><?= min(100, max(0, (int)$percent)) ?> % erledigt – diese Seite aktualisiert sich automatisch.</p>
|
||||
<?php else: ?>
|
||||
<div class="bar"></div>
|
||||
<p class="hint">Diese Seite aktualisiert sich automatisch.</p>
|
||||
<?php endif; ?>
|
||||
<p class="hint" style="margin-top:10px;">Entwickelt von <a href="https://loheide.eu" style="color:inherit;">Loheide.eu</a></p>
|
||||
</div>
|
||||
</body>
|
||||
|
|
@ -1,267 +0,0 @@
|
|||
<?php
|
||||
/**
|
||||
* Admin-UI fuer den Updater. Nutzt das gemeinsame Design-System
|
||||
* (assets/global.css); nur Updater-spezifische Regeln stehen inline.
|
||||
*
|
||||
* Verfuegbare Variablen: $manager, $auth, $currentSha, $channel, $csrfToken
|
||||
*
|
||||
* @var \Updater\UpdateManager $manager
|
||||
* @var \Auth $auth
|
||||
* @var string $currentSha
|
||||
* @var string $channel
|
||||
* @var string $csrfToken
|
||||
*/
|
||||
$shortSha = $currentSha !== '' ? substr($currentSha, 0, 7) : 'unbekannt';
|
||||
$channels = \Updater\UpdateManager::CHANNELS;
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>System-Update</title>
|
||||
<?php require_once dirname(__DIR__, 2) . '/includes/Ui.php'; ?>
|
||||
<?= Ui::head(class_exists('Database') ? Database::getInstance() : null, '../') ?>
|
||||
<style>
|
||||
/* Updater-spezifisch – der Rest kommt aus dem gemeinsamen Design-System. */
|
||||
.wrap { max-width: 780px; margin: 0 auto; padding: 36px 0 60px; }
|
||||
.update-head { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 24px; }
|
||||
.update-head .title { display: flex; align-items: center; gap: 13px; }
|
||||
.kv-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 11px 0; border-bottom: 1px solid var(--border-color); }
|
||||
.kv-row:last-of-type { border-bottom: none; }
|
||||
.kv-row .k { color: var(--text-secondary); font-size: 13.5px; }
|
||||
.kv-row .v { color: var(--text-primary); font-size: 13.5px; font-weight: 600; font-family: var(--font-mono); }
|
||||
.kv-row .v select { font-family: var(--font-sans); font-weight: 500; width: auto; min-width: 150px; }
|
||||
.progress-wrap { display: none; margin-top: 18px; }
|
||||
.progress-bar { height: 8px; border-radius: var(--r-pill); background: var(--bg-hover); overflow: hidden; }
|
||||
.progress-fill { height: 100%; width: 0; border-radius: var(--r-pill); background: var(--accent); transition: width .3s; }
|
||||
.progress-msg { margin-top: 8px; font-size: 12.5px; color: var(--text-muted); }
|
||||
.alert { display: none; margin: 16px 0 0; }
|
||||
.alert.show { display: flex; }
|
||||
.changelog {
|
||||
display: none;
|
||||
margin-top: 16px; padding: 14px;
|
||||
max-height: 260px; overflow: auto;
|
||||
background: var(--bg-subtle); border: 1px solid var(--border-color); border-radius: var(--r-md);
|
||||
font-size: 13px; color: var(--text-secondary); white-space: pre-wrap;
|
||||
}
|
||||
.mig-item { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 9px 0; border-bottom: 1px solid var(--border-color); font-size: 13.5px; }
|
||||
.mig-item:last-child { border-bottom: none; }
|
||||
.mig-item span:first-child { font-family: var(--font-mono); font-size: 12.5px; }
|
||||
.badge-on { background: var(--success-soft); color: var(--success); border: 1px solid var(--success-border); }
|
||||
.badge-off { background: var(--warning-soft); color: var(--warning); border: 1px solid var(--warning-border); }
|
||||
.tabs { display: inline-flex; gap: 3px; padding: 3px; margin-bottom: 18px; background: var(--bg-hover); border: 1px solid var(--border-color); border-radius: var(--r-md); }
|
||||
.tab { padding: 7px 16px; border-radius: var(--r-sm); font-size: 13px; font-weight: 550; color: var(--text-secondary); cursor: pointer; }
|
||||
.tab.active { background: var(--bg-card); color: var(--text-primary); box-shadow: var(--shadow-xs); font-weight: 600; }
|
||||
.pane { display: none; }
|
||||
.pane.active { display: block; }
|
||||
</style>
|
||||
</head>
|
||||
<body class="app-body">
|
||||
<div class="wrap">
|
||||
<div class="update-head">
|
||||
<div class="title">
|
||||
<span class="focus-icon"><i class="fas fa-rotate" aria-hidden="true"></i></span>
|
||||
<div>
|
||||
<h1 style="font-size:20px;">System-Update</h1>
|
||||
<p class="sub">Aktualisierung aus dem gewählten Release-Channel</p>
|
||||
</div>
|
||||
</div>
|
||||
<a href="/admin/" class="btn btn-secondary"><i class="fas fa-arrow-left" aria-hidden="true"></i> Administration</a>
|
||||
</div>
|
||||
|
||||
<div class="tabs">
|
||||
<div class="tab active" data-pane="update">Update</div>
|
||||
<div class="tab" data-pane="migrations">Migrationen</div>
|
||||
</div>
|
||||
|
||||
<div class="pane active" id="pane-update">
|
||||
<div class="card">
|
||||
<h2>Aktuelle Version</h2>
|
||||
<div class="kv-row"><span class="k">Installierte Version (SHA)</span><span class="v" id="curSha"><?= htmlspecialchars($shortSha) ?></span></div>
|
||||
<div class="kv-row"><span class="k">Update-Channel</span>
|
||||
<span class="v">
|
||||
<select id="channel">
|
||||
<?php foreach ($channels as $key => $url): ?>
|
||||
<option value="<?= htmlspecialchars($key) ?>" <?= $channel === $key ? 'selected' : '' ?>><?= htmlspecialchars(ucfirst($key)) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</span>
|
||||
</div>
|
||||
<p class="muted">Channel wird in <code>updater/storage/updater-settings.json</code> gespeichert.</p>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2>Updates</h2>
|
||||
<button class="btn btn-primary" id="btnCheck"><i class="fas fa-magnifying-glass" aria-hidden="true"></i> Auf Updates prüfen</button>
|
||||
<button class="btn btn-success" id="btnInstall" style="display:none;margin-left:8px;"><i class="fas fa-download" aria-hidden="true"></i> Update installieren</button>
|
||||
|
||||
<div class="changelog" id="changelog"></div>
|
||||
|
||||
<div class="progress-wrap" id="progressWrap">
|
||||
<div class="progress-bar"><div class="progress-fill" id="progressFill"></div></div>
|
||||
<div class="progress-msg" id="progressMsg"></div>
|
||||
</div>
|
||||
|
||||
<div class="alert alert-error" id="alertError"></div>
|
||||
<div class="alert alert-ok" id="alertOk"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="pane" id="pane-migrations">
|
||||
<div class="card">
|
||||
<h2>Migrations-Status</h2>
|
||||
<div id="migList"><p class="muted">Wird geladen …</p></div>
|
||||
<button class="btn btn-primary" id="btnRunMig" style="margin-top:16px; display:none;">Ausstehende Migrationen ausführen</button>
|
||||
<div class="alert alert-ok" id="migAlert"></div>
|
||||
</div>
|
||||
</div>
|
||||
<?= Ui::credit() ?>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const CSRF = <?= json_encode($csrfToken) ?>;
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
function showAlert(type, msg) {
|
||||
const el = type === 'error' ? $('alertError') : $('alertOk');
|
||||
el.textContent = msg; el.classList.add('show');
|
||||
const other = type === 'error' ? $('alertOk') : $('alertError');
|
||||
other.classList.remove('show');
|
||||
}
|
||||
function clearAlerts() { $('alertError').classList.remove('show'); $('alertOk').classList.remove('show'); }
|
||||
|
||||
// Tabs
|
||||
document.querySelectorAll('.tab').forEach(t => t.addEventListener('click', () => {
|
||||
document.querySelectorAll('.tab').forEach(x => x.classList.remove('active'));
|
||||
document.querySelectorAll('.pane').forEach(x => x.classList.remove('active'));
|
||||
t.classList.add('active');
|
||||
$('pane-' + t.dataset.pane).classList.add('active');
|
||||
if (t.dataset.pane === 'migrations') loadMigrations();
|
||||
}));
|
||||
|
||||
// Channel speichern
|
||||
$('channel').addEventListener('change', async (e) => {
|
||||
const body = new URLSearchParams({ action: 'set_channel', channel: e.target.value, csrf_token: CSRF });
|
||||
const r = await fetch('update.php', { method: 'POST', body });
|
||||
if (r.ok) showAlert('ok', 'Channel auf "' + e.target.value + '" gesetzt.');
|
||||
else showAlert('error', 'Channel konnte nicht gespeichert werden.');
|
||||
});
|
||||
|
||||
// Auf Updates pruefen
|
||||
$('btnCheck').addEventListener('click', async () => {
|
||||
clearAlerts();
|
||||
$('btnCheck').disabled = true; $('btnCheck').innerHTML = '<i class="fas fa-circle-notch fa-spin" aria-hidden="true"></i> Prüfe …';
|
||||
try {
|
||||
const r = await fetch('update.php?action=check');
|
||||
const d = await r.json();
|
||||
if (d.error) { showAlert('error', d.error); return; }
|
||||
if (d.has_update) {
|
||||
showAlert('ok', 'Update verfügbar: ' + (d.latest_sha ? d.latest_sha.substring(0,7) : '') +
|
||||
(d.versions_behind ? ' (' + d.versions_behind + ' Commits zurück)' : ''));
|
||||
$('btnInstall').style.display = 'inline-block';
|
||||
if (d.changelog || d.title) {
|
||||
const cl = $('changelog');
|
||||
cl.textContent = (d.title ? d.title + '\n\n' : '') + (d.changelog || '');
|
||||
cl.style.display = 'block';
|
||||
}
|
||||
} else {
|
||||
showAlert('ok', 'System ist aktuell.');
|
||||
$('btnInstall').style.display = 'none';
|
||||
$('changelog').style.display = 'none';
|
||||
}
|
||||
} catch (e) {
|
||||
showAlert('error', 'Prüfung fehlgeschlagen: ' + e.message);
|
||||
} finally {
|
||||
$('btnCheck').disabled = false; $('btnCheck').innerHTML = '<i class="fas fa-magnifying-glass" aria-hidden="true"></i> Auf Updates prüfen';
|
||||
}
|
||||
});
|
||||
|
||||
// Update installieren
|
||||
$('btnInstall').addEventListener('click', async () => {
|
||||
if (!confirm('Update jetzt installieren? Die Seite ist während des Updates kurz im Wartungsmodus.')) return;
|
||||
clearAlerts();
|
||||
$('btnInstall').disabled = true; $('btnCheck').disabled = true;
|
||||
$('progressWrap').style.display = 'block';
|
||||
|
||||
let polling = setInterval(pollProgress, 1500);
|
||||
try {
|
||||
const body = new URLSearchParams({ action: 'install', csrf_token: CSRF });
|
||||
const r = await fetch('update.php', { method: 'POST', body });
|
||||
const d = await r.json();
|
||||
clearInterval(polling); pollProgress();
|
||||
if (d.success) {
|
||||
setProgress(100, 'Update abgeschlossen.');
|
||||
showAlert('ok', 'Update erfolgreich installiert (' + (d.sha ? d.sha.substring(0,7) : '') + '). Seite wird neu geladen …');
|
||||
setTimeout(() => location.reload(), 2500);
|
||||
} else {
|
||||
showAlert('error', 'Update fehlgeschlagen: ' + (d.error || 'Unbekannter Fehler'));
|
||||
$('btnInstall').disabled = false; $('btnCheck').disabled = false;
|
||||
}
|
||||
} catch (e) {
|
||||
clearInterval(polling);
|
||||
showAlert('error', 'Update-Request fehlgeschlagen: ' + e.message);
|
||||
$('btnInstall').disabled = false; $('btnCheck').disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
function setProgress(pct, msg) {
|
||||
$('progressFill').style.width = pct + '%';
|
||||
$('progressMsg').textContent = msg || '';
|
||||
}
|
||||
async function pollProgress() {
|
||||
try {
|
||||
const r = await fetch('update.php?action=progress');
|
||||
const d = await r.json();
|
||||
setProgress(d.percent || 0, d.message || '');
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
async function loadMigrations() {
|
||||
const el = $('migList');
|
||||
el.innerHTML = '<p class="muted">Wird geladen …</p>';
|
||||
try {
|
||||
const r = await fetch('update.php?action=migrations');
|
||||
const d = await r.json();
|
||||
if (d.error) { el.innerHTML = '<p class="muted">' + d.error + '</p>'; return; }
|
||||
if (!d.migrations || !d.migrations.length) {
|
||||
el.innerHTML = '<p class="muted">Keine Updater-Migrationen vorhanden.</p>';
|
||||
return;
|
||||
}
|
||||
el.innerHTML = d.migrations.map(m =>
|
||||
'<div class="mig-item"><span>' + m.filename + '</span>' +
|
||||
'<span class="badge ' + (m.applied ? 'badge-on">angewandt' : 'badge-off">offen') + '</span></div>'
|
||||
).join('');
|
||||
const pending = d.migrations.some(m => !m.applied);
|
||||
$('btnRunMig').style.display = pending ? 'inline-block' : 'none';
|
||||
} catch (e) {
|
||||
el.innerHTML = '<p class="muted">Fehler: ' + e.message + '</p>';
|
||||
}
|
||||
}
|
||||
|
||||
$('btnRunMig').addEventListener('click', async () => {
|
||||
$('btnRunMig').disabled = true; $('btnRunMig').textContent = 'Führe aus …';
|
||||
$('migAlert').classList.remove('show');
|
||||
try {
|
||||
const body = new URLSearchParams({ action: 'run_migrations', csrf_token: CSRF });
|
||||
const r = await fetch('update.php', { method: 'POST', body });
|
||||
const d = await r.json();
|
||||
if (d.error) {
|
||||
$('migAlert').textContent = 'Fehler: ' + d.error;
|
||||
$('migAlert').className = 'alert alert-error show';
|
||||
} else {
|
||||
const n = (d.applied || []).length;
|
||||
$('migAlert').textContent = n > 0 ? (n + ' Migration(en) ausgeführt.') : 'Keine ausstehenden Migrationen.';
|
||||
$('migAlert').className = 'alert alert-ok show';
|
||||
loadMigrations();
|
||||
}
|
||||
} catch (e) {
|
||||
$('migAlert').textContent = 'Fehler: ' + e.message;
|
||||
$('migAlert').className = 'alert alert-error show';
|
||||
} finally {
|
||||
$('btnRunMig').disabled = false; $('btnRunMig').textContent = 'Ausstehende Migrationen ausführen';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||