feat: Kür-Hub mit Einladungen, Uploads und API

- PHP-App unter hub/ für rinkplanner-hub.programmschmiede.de
- MariaDB-Schema, Argon2id, Sessions, CSRF und Ratenbegrenzung
- Einladungscodes, Admin-Bereich und Kür-Pakete mit Audiodatei
- JSON-API v1 mit Bearer-Tokens für die Godot-App
- Deployment und Erstinstallation über tools/deploy_hub.sh
- Doku und Credentials-Vorlage ergänzt
This commit is contained in:
torsten 2026-11-11 13:14:26 +01:00
parent e79b477ee0
commit 055a2919c3
38 changed files with 5111 additions and 0 deletions

4
.gitignore vendored
View file

@ -38,3 +38,7 @@ docs/.credentials*
# OAuth-App-Zugaenge (werden per tools/sync_apps_config.sh erzeugt)
rinkplanner/sync_apps.cfg
# Kür-Hub: lokal erzeugte Serverkonfiguration und Uploads
hub/app/config.local.php
hub/storage/

View file

@ -1,5 +1,18 @@
# Hinweise für Agenten
## Kür-Hub
- Website: `https://rinkplanner-hub.programmschmiede.de`, Code unter `hub/`,
Doku `docs/hub.md`.
- Deployment nur über `./tools/deploy_hub.sh` (`--sync`, `--install`,
`--check`, `--all`). Keine zweite Kopie auf dem Webserver anlegen.
- Zugänge stehen in `docs/credentials.txt` (`DB_*`, `HUB_ADMIN_*`, `FTP_*`).
`app/config.local.php` wird beim Deployment erzeugt und nie eingecheckt.
- Schema `hub/sql/schema.sql`; der Installer legt es an und erzeugt den ersten
Benutzer als Admin. `storage/.installed` verhindert einen zweiten Lauf.
- Uploads liegen in `storage/uploads/` (gesperrt); nur `web/` ist öffentlich.
- API v1 mit Bearer-Tokens für die App; Web-UI nutzt Session + CSRF.
## Website und Downloads
- Die Rinkplanner-Seite liegt nur noch unter

View file

@ -13,3 +13,4 @@ Planner for Figure Skating free skate
- **Builds:** [`docs/builds.md`](docs/builds.md)
- **Kür-Sync (Dropbox):** [`docs/sync.md`](docs/sync.md)
- **Cloud-Sync einrichten:** [`docs/cloud-setup.md`](docs/cloud-setup.md)
- **Kür-Hub:** [`docs/hub.md`](docs/hub.md)

View file

@ -35,3 +35,18 @@ GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
DROPBOX_APP_KEY=
DROPBOX_APP_SECRET=
# ---------------------------------------------------------------------------
# Kür-Hub (rinkplanner-hub.programmschmiede.de)
# ---------------------------------------------------------------------------
# MariaDB-Datenbank des Hubs. Der DB-Benutzer braucht alle Rechte auf DB_NAME
# (CREATE, ALTER, INDEX, SELECT, INSERT, UPDATE, DELETE).
DB_NAME=
DB_USER=
DB_PASSWORD=
# Erster Benutzer der Installation; wird von tools/deploy_hub.sh --install
# einmalig als Administrator angelegt. Das Passwort wird nie gespeichert,
# sondern nur per HTTPS an den Installer übergeben.
HUB_ADMIN_USER=
HUB_ADMIN_PASSWORD=

293
docs/hub.md Normal file
View file

@ -0,0 +1,293 @@
# Kür-Hub
Der Kür-Hub ist die geschlossene Beta-Ablage für Küren und ihre Musik. Nutzer
laden ein Paket aus Rinkplanner-JSON und Audiodatei hoch, andere Beta-Nutzer
sehen die Kür in einer Liste und laden sie wieder herunter. Die Godot-App
bekommt dafür eine kleine JSON-API mit persönlichen Tokens.
Lebt unter <https://rinkplanner-hub.programmschmiede.de>. Der Code liegt im
Repo unter `hub/`, die Binärdaten und die Serverkonfiguration bleiben auf dem
Host.
## Entscheidungen
| Thema | Entscheidung |
| :--- | :--- |
| Zugang | Einladungscodes; genau ein Konto pro Code |
| Erster Nutzer | `HUB_ADMIN_USER` aus `docs/credentials.txt`, Rolle `admin` |
| Inhalte | Kür-Paket: JSON + optionale Audiodatei (MP3/OGG/WAV/M4A/AAC) |
| Sichtbarkeit | Alles nur nach Anmeldung; versteckte Küren sieht der Eigentümer und der Admin |
| App-Anbindung | Web-UI plus JSON-API v1 mit Bearer-Tokens |
| Stack | PHP 8.5 ohne Framework, MariaDB 10.11, Apache/FTP-Deployment |
## Umgebung
Geprüft am 2026-11-11:
- PHP 8.5.12 (FPM), `pdo_mysql`, `mbstring`, `fileinfo`, `openssl`, `zip`, `intl`.
- MariaDB 10.11, DB `d048f0d5`, Zugriff nur vom Host (`localhost`).
- `upload_max_filesize`/`post_max_size` 256 MB, `max_allowed_packet` 64 MB.
- Kein SSH, kein Composer auf dem Host. Deployment per FTPS.
## Verzeichnisse
Repo:
```
hub/
├── app/ # PHP: Bootstrap, DB, Auth, Routinen, Seiten, API
├── views/ # Server-gerenderte Templates
├── sql/ # schema.sql
├── web/ # DocumentRoot: index.php, .htaccess, assets/hub.css
├── install.php # Einmal-Installer (löscht sich selbst)
└── app/config.example.php
tools/deploy_hub.sh
```
Server (`rinkplanner-hub.programmschmiede.de/`):
```
index.php, .htaccess, assets/
app/ # Konfiguration mit DB-Zugang, per .htaccess gesperrt
views/, sql/ # per .htaccess gesperrt
storage/
├── uploads/YYYY/MM/ # Zufallsnamen, nie direkt ausgeliefert
├── logs/php.log
├── .htaccess # Require all denied
└── .installed
```
## Datenmodell
Schema: `hub/sql/schema.sql`, Migrationstabelle `schema_migrations`.
| Tabelle | Zweck |
| :--- | :--- |
| `users` | Konten, Rolle (`admin`/`user`), Status, Passwort-Hash, `auth_epoch` |
| `invites` | Einmal-Codes (nur SHA-256 gespeichert), optional an E-Mail gebunden |
| `routines` | Kür-Metadaten, Eigentümer, Status, aktuelle Revision, Downloadzähler |
| `routine_revisions` | Jede hochgeladene Fassung mit Dateipfaden, Größe und SHA-256 |
| `downloads` | Download-Protokoll je Kür/Revision/Nutzer |
| `api_tokens` | Persönliche App-Tokens (nur SHA-256, Präfix für die Anzeige) |
| `remember_tokens` | „Angemeldet bleiben“ (Selector + Validator-Hash, Rotation) |
| `login_attempts` | Fehlversuche für die Ratenbegrenzung |
| `audit_log` | Admin- und Inhaltsereignisse |
Wichtige Beziehungen:
- `routines.owner_id → users.id` (`ON DELETE CASCADE`).
- `routine_revisions.routine_id → routines.id` (`ON DELETE CASCADE`);
`routines.current_revision_id → routine_revisions.id` (`ON DELETE SET NULL`).
- Alte Revisionen bleiben erhalten; heruntergeladen wird immer die aktuelle.
- Zeitstempel sind UTC, die Oberfläche zeigt `Europe/Berlin`.
## Authentifizierung
### Einladungen und Registrierung
1. Admin erzeugt unter `/admin/invites` einen Code im Format
`RHUB-XXXX-XXXX-XXXX-XXXX`. Der Klartext wird genau einmal angezeigt.
2. In der DB liegt nur `SHA-256(code)`; zusätzlich Notiz, optionale
E-Mail-Bindung und Ablaufdatum.
3. Registrierung unter `/register?code=…`: Benutzername, Anzeigename,
optional E-Mail, Passwort, Beta-Regeln.
4. In einer Transaktion wird der Nutzer angelegt und der Code atomar als
eingelöst markiert. Schlägt die Markierung fehl, wird der Nutzer
zurückgerollt. Ein eingelöster Code bleibt auch nach Löschen des Nutzers
verbraucht (`used_at`).
Benutzername: 3–32 Zeichen, `a-z 0-9 . _ -`, Anfang/Ende alphanumerisch,
reservierte Namen gesperrt. Passwort: mindestens 10 Zeichen.
### Passwörter
- `password_hash()` mit **Argon2id**, falls verfügbar, sonst PHP-Standard.
- `password_needs_rehash()` wird bei der Anmeldung geprüft.
- Kein Klartextpasswort in der DB, in Logs oder in der Konfiguration.
- Der Installer erhält das Admin-Passwort per HTTPS, hasht es und speichert es
nie im Klartext.
### Sessions
- Native PHP-Session, Cookie `RHUB_SESSION`:
`HttpOnly`, `Secure` (unter HTTPS), `SameSite=Lax`, `use_strict_mode`.
- Nach Login und Remember-Restore wird die Session-ID erneuert.
- Idle-Timeout 14 Tage, absolute Lebensdauer 30 Tage.
- `users.auth_epoch` wird bei Passwortwechsel, Admin-Reset, Sperre und
Löschung erhöht. Jede Session speichert die Epoche; alte Sessions sind
damit sofort ungültig, auch ohne Session-Tabelle.
- Passwortwechsel, Reset und Sperre löschen zusätzlich alle
„Angemeldet bleiben“- und API-Tokens des Kontos.
### „Angemeldet bleiben“
- Cookie `RHUB_REMEMBER` = `selector:validator` (30 Tage).
- DB speichert den SHA-256 des Validators; bei Nutzung wird das Token
rotiert (altes gelöscht, neues gesetzt).
- Wird bei Passwortwechsel, Reset und Sperre gelöscht.
### Ratenbegrenzung und CSRF
- Fehlversuche: maximal 5 pro Benutzername und 10 pro IP in 15 Minuten;
danach `429` mit `Retry-After`.
- Alle Web-POSTs brauchen ein CSRF-Token aus der Session
(`hash_equals`, Feld `_csrf`). Die API nutzt stattdessen Bearer-Tokens.
- Login-Fehler sind bewusst generisch; bei unbekanntem Nutzer wird trotzdem
ein Dummy-Hash geprüft.
### Rollen
`admin` darf Einladungen, Nutzer und alle Küren verwalten. `user` darf Küren
hochladen, eigene Küren verstecken/ändern und alles Sichtbare herunterladen.
Der eigene Account lässt sich weder sperren noch löschen, damit immer ein
Admin bleibt.
## Dateien und Validierung
Upload (`/upload`, `/routines/{id}/revise`, `POST /api/v1/routines`):
- Kürdatei: `.json`, max. 8 MiB, gültiges JSON, `format` =
`rinkplanner.routine`, `format_version` 1, `sections` als Liste (max. 500).
- Audiodatei: max. 50 MiB, Magic-Bytes-Prüfung (MP3/OGG/WAV/M4A/AAC), der
Dateiname muss exakt dem Feld `music_file` der Kür entsprechen.
- Eine Kür mit `music_file` braucht die Audiodatei; eine Kür ohne
`music_file` darf keine Audiodatei mitbringen.
- Rechte-Checkbox ist Pflicht (Web und API).
- Ablage unter `storage/uploads/YYYY/MM/` mit Zufallsnamen; Originalnamen
stehen nur in der DB. `storage/` ist per `.htaccess` und Rewrite gesperrt.
- Download nur über PHP mit Anmeldung, `Content-Disposition: attachment`,
SHA-256-Prüfsumme in der Detailansicht. Audio unterstützt HTTP-Range.
- Upload-Limit: 20 Revisionen pro Nutzer und Stunde.
- Doppelte Pakete desselben Nutzers (gleiche Kür- und Audio-SHA) werden
erkannt und nicht doppelt angelegt.
Alte Revisionen bleiben auf der Platte, bis der Admin die Kür endgültig
löscht. Die Kür-Detailseite zeigt immer die aktuelle Revision; Prüfsummen
stehen darunter.
## API v1
Basis: `https://rinkplanner-hub.programmschmiede.de/api/v1`
### Token erzeugen
```bash
curl -sS -X POST \
-H 'Content-Type: application/json' \
-d '{"username":"…","password":"…","name":"Büro-PC"}' \
https://rinkplanner-hub.programmschmiede.de/api/v1/tokens
```
Antwort `201` mit `token` (`rhub_…`), `prefix`, `name`, `user`. Das Token wird
nur einmal ausgegeben; in der DB liegt nur der SHA-256. Alternativ lässt sich
ein Token im Web unter `/account` erzeugen.
### Endpunkte
| Methode | Pfad | Zweck |
| :--- | :--- | :--- |
| `GET` | `/me` | eigenes Konto |
| `GET` | `/routines?q=&page=&per_page=&mine=1` | Liste (max. 50 pro Seite) |
| `GET` | `/routines/{id}` | Metadaten + Download-URLs + Prüfsummen |
| `POST` | `/routines` | neues Paket (multipart: `routine`, `audio`, `rights=1`) |
| `POST` | `/routines/{id}/revisions` | neue Revision (Eigentümer/Admin) |
| `DELETE` | `/routines/{id}` | Kür verstecken (Eigentümer/Admin) |
| `GET` | `/routines/{id}/download` | Kür-JSON |
| `GET` | `/routines/{id}/audio` | Audiodatei (Range-fähig) |
Alle außer `/tokens` brauchen `Authorization: Bearer rhub_…`.
Fehlerformat:
```json
{"error": {"code": "validation_failed", "message": "…"}, "errors": ["…"]}
```
Statuscodes: `401` Token fehlt/ungültig, `403` keine Berechtigung oder
Passwortwechsel nötig, `404`, `409` Duplikat, `422` Validierung,
`429` Limit.
## Deployment
`tools/deploy_hub.sh` liest die Zugänge aus `docs/credentials.txt`
(`FTP_*`, `DB_*`, `HUB_ADMIN_*`) und arbeitet über FTPS:
```bash
./tools/deploy_hub.sh --sync # Code + config.local.php hochladen
./tools/deploy_hub.sh --install # Schema + ersten Admin anlegen (einmalig)
./tools/deploy_hub.sh --all # sync + install + check
./tools/deploy_hub.sh --check # Health, Login, Sperren, Installer prüfen
```
Ablauf der Erstinstallation:
1. `--sync` lädt `app/`, `views/`, `sql/`, `web/` und die generierte
`app/config.local.php` (Modus 600) hoch.
2. `--install` lädt `install.php`, ruft es per HTTPS mit Installations-Token
und Admin-Zugang auf.
3. Der Installer legt das Schema an, erzeugt den Admin, schreibt
`storage/.installed` und löscht sich selbst.
4. `--check` prüft `/health`, `/login`, dass `app/config.local.php` und
`storage/` gesperrt sind und der Installer weg ist.
Ein erneutes `--sync` ändert nur Code und Konfiguration; es installiert nicht
neu. `--install` bricht ab, wenn bereits Benutzer existieren.
## Administration
- **Einladungen:** `/admin/invites` – Code erzeugen (Notiz, optionale
E-Mail-Bindung, Gültigkeit), offene Codes widerrufen.
- **Benutzer:** `/admin/users` – sperren/entsperren, Passwort zurücksetzen
(temporäres Passwort wird einmal angezeigt, Wechsel beim nächsten Login
erzwungen), Konto mit allen Küren löschen.
- **Küren:** `/admin/routines` – suchen, verstecken/veröffentlichen,
endgültig löschen (löscht auch alle Revisionsdateien).
- **Audit:** `/admin/audit` – letzte Ereignisse (Login, Upload, Revision,
Status, Einladungen, Token, Sperren).
- **API-Tokens:** Nutzer verwalten ihre Tokens selbst unter `/account`.
Gespeicherte Kennwörter: nur Hashes. Für einen Notfallzugang kann der Admin
sein Passwort über die Web-Oberfläche ändern; ohne funktionierenden Login
hilft nur ein DB-Eingriff oder ein neuer Installationslauf.
## Betrieb und Sicherheit
- `.htaccess`: HTTPS erzwingen (auch hinter Proxy), `app/`, `storage/`,
`sql/`, versteckte Dateien sperren, unbekannte Pfade an `index.php`.
- PHP sendet CSP (`script-src 'none'`, kein Inline-JS), `nosniff`,
`X-Frame-Options: DENY`, `Referrer-Policy: same-origin`, HSTS.
- Kein JavaScript, keine externen CDNs, dadurch kleine Angriffsfläche.
- Uploads werden nie als ausführbarer Code abgelegt; nur `.json` und
Audio-Endungen, Zufallsnamen, Rechte 0640.
- Fehler gehen nach `storage/logs/php.log`, nie in die Antwort.
- Backups: DB und `storage/uploads/` sichern. Auf dem Host gibt es kein SSH;
DB-Backup über das Hoster-Werkzeug (phpMyAdmin/DB-Verwaltung) oder einen
zusätzlichen PHP-Backup-Endpunkt (noch nicht gebaut).
- Das Beta-Paket enthält fremde Küren und Musik. Die Rechte-Checkbox ist eine
Zusicherung des Uploaders, keine Lizenzprüfung. Bei Beschwerden Kür
verstecken/löschen und Audit-Log prüfen.
## Getestet am 2026-11-11
Auf der echten Subdomain durchgespielt:
- Installation, Admin-Login, Session, Dashboard.
- Einladung erzeugen, Registrierung, Login als Beta-Nutzer.
- Upload einer Kür mit MP3, Detailseite, Download von JSON und MP3
(SHA-256 identisch), Downloadzähler.
- Duplikat-Erkennung (`409`), neue Revision (`201`), Verstecken und
Wiederveröffentlichen.
- API-Token, `/me`, Liste, Detail, Download, fehlendes Token (`401`).
- Admin-Löschung von Nutzer samt Kür; Upload-Dateien wurden entfernt.
- Sperren von `app/config.local.php`, `storage/`; Installer nach der
Installation nicht mehr erreichbar.
## Offene Punkte
- Godot-Client an die API anbinden (Token im Client speichern, Upload/Download
als Paket).
- Optional: E-Mail-Versand für Einladungen und Passwort-Reset.
- Optional: Quota pro Nutzer, Aufräumen alter Revisionen, Suche nach
Kategorien/Saison.
- Optional: Vorschau/Validierung der Kür im Hub (Sections zählen, Musiklänge).
- Lizenz-/Rechteprüfung der Musik bleibt Aufgabe der Administration.

2
hub/app/.htaccess Normal file
View file

@ -0,0 +1,2 @@
Require all denied
Options -Indexes

255
hub/app/api.php Normal file
View file

@ -0,0 +1,255 @@
<?php
declare(strict_types=1);
/** JSON-API v1 für die Godot-App. Authentifizierung: Bearer-Token. */
function api_base_url(): string
{
$base = rtrim((string) config('app.public_url', ''), '/');
if ($base !== '') {
return $base;
}
$scheme = is_https() ? 'https' : 'http';
return $scheme . '://' . (string) ($_SERVER['HTTP_HOST'] ?? 'localhost');
}
function api_truthy(mixed $value): bool
{
return $value === true || $value === 1 || $value === '1' || $value === 'true';
}
function api_routine_payload(array $routine): array
{
$base = api_base_url();
$id = (int) $routine['id'];
$audio = null;
if (!empty($routine['audio_path'])) {
$audio = [
'name' => $routine['audio_original_name'],
'bytes' => (int) $routine['audio_bytes'],
'sha256' => $routine['audio_sha256'],
'mime' => $routine['audio_mime'],
'url' => $base . url('/api/v1/routines/' . $id . '/audio'),
];
}
return [
'id' => $id,
'title' => $routine['title'],
'skater_name' => $routine['skater_name'],
'category' => $routine['category'],
'description' => $routine['description'],
'music_title' => $routine['music_title'],
'music_artist' => $routine['music_artist'],
'status' => $routine['status'],
'revision' => $routine['revision'] !== null ? (int) $routine['revision'] : null,
'download_count' => (int) $routine['download_count'],
'created_at' => $routine['created_at'],
'updated_at' => $routine['updated_at'],
'owner' => [
'username' => $routine['owner_username'],
'display_name' => $routine['owner_display_name'],
],
'files' => [
'routine' => [
'name' => $routine['routine_original_name'],
'bytes' => (int) $routine['routine_bytes'],
'sha256' => $routine['routine_sha256'],
'url' => $base . url('/api/v1/routines/' . $id . '/download'),
],
'audio' => $audio,
],
'url' => $base . url('/routines/' . $id),
];
}
function api_routine_summary(array $row): array
{
return [
'id' => (int) $row['id'],
'title' => $row['title'],
'skater_name' => $row['skater_name'],
'category' => $row['category'],
'music_title' => $row['music_title'],
'music_artist' => $row['music_artist'],
'status' => $row['status'],
'revision' => $row['revision'] !== null ? (int) $row['revision'] : null,
'routine_bytes' => isset($row['routine_bytes']) ? (int) $row['routine_bytes'] : null,
'audio_bytes' => isset($row['audio_bytes']) ? (int) $row['audio_bytes'] : null,
'download_count' => (int) $row['download_count'],
'updated_at' => $row['updated_at'],
'owner' => [
'username' => $row['owner_username'],
'display_name' => $row['owner_display_name'],
],
];
}
function api_handle(string $method, string $path): void
{
$path = '/' . trim($path, '/');
if ($path === '/api/v1/tokens') {
if ($method !== 'POST') {
abort_api(405, 'method_not_allowed', 'Nur POST ist erlaubt.');
}
api_create_token();
return;
}
$user = api_require_user();
if ($path === '/api/v1/me') {
if ($method !== 'GET') {
abort_api(405, 'method_not_allowed', 'Nur GET ist erlaubt.');
}
json_response([
'id' => (int) $user['id'],
'username' => $user['username'],
'display_name' => $user['display_name'],
'role' => $user['role'],
'created_at' => $user['created_at'],
]);
}
if ($path === '/api/v1/routines') {
if ($method === 'GET') {
$query = mb_substr(query_string('q'), 0, 100, 'UTF-8');
$page = max(1, query_int('page', 1));
$perPage = max(1, min(50, query_int('per_page', 20)));
$mine = query_string('mine') === '1';
$result = routines_query($query, $page, $perPage, $mine ? (int) $user['id'] : null, $mine);
json_response([
'items' => array_map('api_routine_summary', $result['items']),
'total' => $result['total'],
'page' => $result['page'],
'pages' => $result['pages'],
]);
}
if ($method === 'POST') {
api_upload($user, null);
}
abort_api(405, 'method_not_allowed', 'Nur GET oder POST ist erlaubt.');
}
if (preg_match('#^/api/v1/routines/(\d+)$#', $path, $matches) === 1) {
api_routine((int) $matches[1], $method, $user);
return;
}
if (preg_match('#^/api/v1/routines/(\d+)/(download|audio)$#', $path, $matches) === 1) {
if ($method !== 'GET') {
abort_api(405, 'method_not_allowed', 'Nur GET ist erlaubt.');
}
$routine = api_fetch_visible((int) $matches[1], $user);
routine_send_file($routine, (string) $matches[2], $user, true);
}
if (preg_match('#^/api/v1/routines/(\d+)/revisions$#', $path, $matches) === 1) {
if ($method !== 'POST') {
abort_api(405, 'method_not_allowed', 'Nur POST ist erlaubt.');
}
api_upload($user, (int) $matches[1]);
return;
}
abort_api(404, 'not_found', 'Unbekannter API-Pfad.');
}
function api_create_token(): void
{
$input = json_input();
$login = trim((string) ($input['username'] ?? $input['login'] ?? ''));
$password = (string) ($input['password'] ?? '');
$name = trim((string) ($input['name'] ?? 'App'));
if ($login === '' || $password === '') {
abort_api(422, 'invalid_credentials', 'Benutzername und Passwort sind erforderlich.');
}
$result = auth_attempt($login, $password);
if (!$result['ok']) {
if (($result['retry'] ?? 0) > 0) {
header('Retry-After: ' . (int) $result['retry']);
abort_api(429, 'rate_limited', (string) $result['error']);
}
abort_api(401, 'invalid_credentials', (string) $result['error']);
}
$user = $result['user'];
if ((int) ($user['must_change_password'] ?? 0) === 1) {
abort_api(403, 'password_change_required', 'Bitte zuerst im Web das Passwort ändern.');
}
$created = token_create((int) $user['id'], $name);
json_response([
'token' => $created['token'],
'prefix' => $created['prefix'],
'name' => $name !== '' ? $name : 'App',
'user' => [
'id' => (int) $user['id'],
'username' => $user['username'],
'display_name' => $user['display_name'],
],
], 201);
}
function api_fetch_visible(int $id, array $user): array
{
$routine = routine_fetch($id);
if ($routine === null) {
abort_api(404, 'not_found', 'Kür nicht gefunden.');
}
if (!routine_can_view($routine, $user)) {
abort_api(403, 'forbidden', 'Diese Kür ist nicht freigegeben.');
}
return $routine;
}
function api_routine(int $id, string $method, array $user): void
{
$routine = api_fetch_visible($id, $user);
if ($method === 'GET') {
json_response(api_routine_payload($routine));
}
if ($method === 'DELETE') {
if (!routine_can_edit($routine, $user)) {
abort_api(403, 'forbidden', 'Nur der Eigentümer oder ein Admin darf die Kür ändern.');
}
routine_set_status($id, 'hidden');
json_response(['id' => $id, 'status' => 'hidden']);
}
abort_api(405, 'method_not_allowed', 'Nur GET oder DELETE ist erlaubt.');
}
function api_upload(array $user, ?int $routineId): void
{
if (!api_truthy($_POST['rights'] ?? null)) {
abort_api(422, 'rights_required', 'Bitte bestätigen, dass Kür und Musik geteilt werden dürfen.');
}
if (!routine_upload_quota_ok((int) $user['id'])) {
abort_api(429, 'upload_limit', 'Stündliches Upload-Limit erreicht.');
}
$package = routine_validate_package($_POST);
if (!$package['ok']) {
json_response([
'error' => ['code' => 'validation_failed', 'message' => 'Die Dateien sind nicht gültig.'],
'errors' => $package['errors'],
], 422);
}
if ($routineId === null) {
$duplicate = routine_duplicate_exists((int) $user['id'], $package);
if ($duplicate !== null) {
abort_api(409, 'duplicate', 'Diese Kür ist bereits im Hub (ID ' . $duplicate . ').');
}
$routineId = routine_create((int) $user['id'], $package);
} else {
$routine = routine_fetch($routineId);
if ($routine === null) {
abort_api(404, 'not_found', 'Kür nicht gefunden.');
}
if (!routine_can_edit($routine, $user)) {
abort_api(403, 'forbidden', 'Nur der Eigentümer oder ein Admin darf die Kür ändern.');
}
routine_add_revision($routineId, (int) $user['id'], $package);
}
$created = routine_fetch($routineId);
if ($created === null) {
abort_api(500, 'server_error', 'Kür konnte nicht geladen werden.');
}
json_response(api_routine_payload($created), 201);
}

364
hub/app/auth.php Normal file
View file

@ -0,0 +1,364 @@
<?php
declare(strict_types=1);
/**
* Anmeldung, Sessions, Remember-Me und Ratenbegrenzung.
*
* Passwörter: Argon2id, falls verfügbar, sonst der PHP-Standard (bcrypt).
* Sessions: native PHP-Session, Cookie HttpOnly/Secure/SameSite=Lax.
* Zusätzlich auth_epoch in users: Passwortwechsel und Sperren machen alle
* bestehenden Sessions sofort ungültig.
*/
const HUB_DUMMY_HASH = '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2uheWG/igi.';
const HUB_REMEMBER_COOKIE = 'RHUB_REMEMBER';
function hash_password(string $password): string
{
if (defined('PASSWORD_ARGON2ID')) {
return password_hash($password, PASSWORD_ARGON2ID, [
'memory_cost' => 32768,
'time_cost' => 3,
'threads' => 2,
]);
}
return password_hash($password, PASSWORD_DEFAULT);
}
function password_needs_upgrade(string $hash): bool
{
if (defined('PASSWORD_ARGON2ID')) {
return password_needs_rehash($hash, PASSWORD_ARGON2ID, [
'memory_cost' => 32768,
'time_cost' => 3,
'threads' => 2,
]);
}
return password_needs_rehash($hash, PASSWORD_DEFAULT);
}
function auth_user(): ?array
{
static $loaded = false;
static $user = null;
if ($loaded) {
return $user;
}
$loaded = true;
$uid = $_SESSION['uid'] ?? null;
if (!is_int($uid) && !ctype_digit((string) $uid)) {
auth_restore_from_remember();
$uid = $_SESSION['uid'] ?? null;
if (!is_int($uid) && !ctype_digit((string) $uid)) {
return $user;
}
}
$uid = (int) $uid;
$stmt = db()->prepare('SELECT * FROM users WHERE id = ? LIMIT 1');
$stmt->execute([$uid]);
$row = $stmt->fetch();
if (!$row || $row['status'] !== 'active') {
auth_clear_session();
return $user;
}
if ((int) ($_SESSION['epoch'] ?? 0) !== (int) $row['auth_epoch']) {
auth_clear_session();
return $user;
}
$now = time();
$idleLimit = (int) config('app.session_idle_seconds', 1209600);
$absoluteLimit = (int) config('app.session_absolute_seconds', 2592000);
$created = (int) ($_SESSION['created'] ?? 0);
$lastSeen = (int) ($_SESSION['last_seen'] ?? 0);
if ($created === 0 || $lastSeen === 0
|| $now - $lastSeen > $idleLimit
|| $now - $created > $absoluteLimit
) {
auth_clear_session();
return $user;
}
if ($now - $lastSeen > 300) {
$_SESSION['last_seen'] = $now;
}
$row['id'] = (int) $row['id'];
$row['auth_epoch'] = (int) $row['auth_epoch'];
$row['must_change_password'] = (int) $row['must_change_password'];
$user = $row;
return $user;
}
function auth_user_by_id(int $id): ?array
{
$stmt = db()->prepare('SELECT * FROM users WHERE id = ? LIMIT 1');
$stmt->execute([$id]);
$row = $stmt->fetch();
if (!$row) {
return null;
}
$row['id'] = (int) $row['id'];
$row['auth_epoch'] = (int) $row['auth_epoch'];
$row['must_change_password'] = (int) $row['must_change_password'];
return $row;
}
function auth_login(array $user, bool $remember = false): void
{
session_regenerate_id(true);
$_SESSION['uid'] = (int) $user['id'];
$_SESSION['epoch'] = (int) $user['auth_epoch'];
$_SESSION['created'] = time();
$_SESSION['last_seen'] = time();
$_SESSION['csrf'] = bin2hex(random_bytes(32));
$stmt = db()->prepare('UPDATE users SET last_login_at = ? WHERE id = ?');
$stmt->execute([utc_now(), (int) $user['id']]);
if ($remember) {
auth_issue_remember((int) $user['id']);
}
audit('user.login', 'user', (int) $user['id'], 'Anmeldung', (int) $user['id']);
}
function auth_clear_session(): void
{
$_SESSION = [];
if (session_status() === PHP_SESSION_ACTIVE) {
session_regenerate_id(true);
}
}
function auth_logout(): void
{
$user = auth_user();
if ($user) {
audit('user.logout', 'user', (int) $user['id'], '', (int) $user['id']);
}
auth_forget_remember();
auth_clear_session();
session_destroy();
}
function auth_require_login(): array
{
$user = auth_user();
if ($user === null) {
$target = (string) ($_SERVER['REQUEST_URI'] ?? '/');
redirect('/login?next=' . rawurlencode($target));
}
return $user;
}
function auth_require_admin(): array
{
$user = auth_require_login();
if ($user['role'] !== 'admin') {
abort_page(403, 'Dieser Bereich ist nur für Administratoren.');
}
return $user;
}
function auth_is_admin(?array $user): bool
{
return $user !== null && ($user['role'] ?? '') === 'admin';
}
function auth_attempt(string $login, string $password): array
{
$login = trim($login);
$ip = client_ip();
$window = (int) config('app.login_window_seconds', 900);
$maxUser = (int) config('app.login_max_per_user', 5);
$maxIp = (int) config('app.login_max_per_ip', 10);
$since = gmdate('Y-m-d H:i:s', time() - $window);
$stmt = db()->prepare(
'SELECT SUM(username = ?) AS by_user, SUM(ip = ?) AS by_ip, MIN(created_at) AS first_seen
FROM login_attempts
WHERE success = 0 AND created_at >= ? AND (username = ? OR ip = ?)'
);
$stmt->execute([$login, $ip, $since, $login, $ip]);
$window_row = $stmt->fetch() ?: [];
$byUser = (int) ($window_row['by_user'] ?? 0);
$byIp = (int) ($window_row['by_ip'] ?? 0);
if ($byUser >= $maxUser || $byIp >= $maxIp) {
$first = strtotime((string) ($window_row['first_seen'] ?? 'now') . ' UTC');
$retry = max(60, (int) $first + $window - time());
return [
'ok' => false,
'error' => 'Zu viele Fehlversuche. Bitte in ' . max(1, (int) ceil($retry / 60)) . ' Minuten erneut versuchen.',
'retry' => $retry,
];
}
$stmt = db()->prepare('SELECT * FROM users WHERE username = ? OR email = ? LIMIT 1');
$stmt->execute([$login, $login]);
$user = $stmt->fetch() ?: null;
$hash = $user['password_hash'] ?? HUB_DUMMY_HASH;
$valid = password_verify($password, $hash);
$stmt = db()->prepare(
'INSERT INTO login_attempts (username, ip, success, created_at) VALUES (?, ?, ?, ?)'
);
$stmt->execute([mb_substr($login, 0, 190, 'UTF-8'), $ip, $valid ? 1 : 0, utc_now()]);
if (random_int(1, 100) === 1) {
db()->prepare('DELETE FROM login_attempts WHERE created_at < ? LIMIT 1000')
->execute([gmdate('Y-m-d H:i:s', time() - 30 * 86400)]);
}
if (!$user || !$valid) {
return ['ok' => false, 'error' => 'Benutzername oder Passwort ist falsch.', 'retry' => 0];
}
if ($user['status'] !== 'active') {
return ['ok' => false, 'error' => 'Dieses Konto ist deaktiviert.', 'retry' => 0];
}
if (password_needs_upgrade((string) $user['password_hash'])) {
db()->prepare('UPDATE users SET password_hash = ? WHERE id = ?')
->execute([hash_password($password), (int) $user['id']]);
}
return ['ok' => true, 'user' => $user, 'error' => '', 'retry' => 0];
}
function auth_next_url(string $fallback = '/'): string
{
$next = (string) ($_POST['next'] ?? $_GET['next'] ?? '');
if ($next === '' || $next[0] !== '/' || str_starts_with($next, '//')
|| str_starts_with($next, '/api/')
) {
return $fallback;
}
return $next;
}
function auth_issue_remember(int $userId): void
{
$selector = bin2hex(random_bytes(12));
$validator = bin2hex(random_bytes(32));
$seconds = (int) config('app.remember_seconds', 2592000);
$stmt = db()->prepare(
'INSERT INTO remember_tokens (user_id, selector, validator_hash, created_at, expires_at, user_agent, ip)
VALUES (?, ?, ?, ?, ?, ?, ?)'
);
$stmt->execute([
$userId,
$selector,
hash('sha256', $validator),
utc_now(),
utc_after($seconds),
user_agent(),
client_ip(),
]);
setcookie(HUB_REMEMBER_COOKIE, $selector . ':' . $validator, [
'expires' => time() + $seconds,
'path' => '/',
'secure' => is_https(),
'httponly' => true,
'samesite' => 'Lax',
]);
}
function auth_restore_from_remember(): void
{
$cookie = (string) ($_COOKIE[HUB_REMEMBER_COOKIE] ?? '');
if ($cookie === '' || substr_count($cookie, ':') !== 1) {
return;
}
[$selector, $validator] = explode(':', $cookie, 2);
if (strlen($selector) !== 24 || strlen($validator) !== 64) {
return;
}
$stmt = db()->prepare(
'SELECT rt.*, u.* FROM remember_tokens rt
JOIN users u ON u.id = rt.user_id
WHERE rt.selector = ? AND rt.expires_at > ? LIMIT 1'
);
$stmt->execute([$selector, utc_now()]);
$row = $stmt->fetch();
if (!$row || !hash_equals((string) $row['validator_hash'], hash('sha256', $validator))) {
return;
}
if ($row['status'] !== 'active') {
return;
}
db()->prepare('DELETE FROM remember_tokens WHERE id = ?')->execute([(int) $row['id']]);
$_SESSION['uid'] = (int) $row['user_id'];
$_SESSION['epoch'] = (int) $row['auth_epoch'];
$_SESSION['created'] = time();
$_SESSION['last_seen'] = time();
$_SESSION['csrf'] = bin2hex(random_bytes(32));
session_regenerate_id(true);
auth_issue_remember((int) $row['user_id']);
db()->prepare('UPDATE users SET last_login_at = ? WHERE id = ?')
->execute([utc_now(), (int) $row['user_id']]);
audit('user.login_remember', 'user', (int) $row['user_id'], '', (int) $row['user_id']);
}
function auth_forget_remember(): void
{
$cookie = (string) ($_COOKIE[HUB_REMEMBER_COOKIE] ?? '');
if (str_contains($cookie, ':')) {
[$selector] = explode(':', $cookie, 2);
if (strlen($selector) === 24) {
db()->prepare('DELETE FROM remember_tokens WHERE selector = ?')->execute([$selector]);
}
}
if (isset($_COOKIE[HUB_REMEMBER_COOKIE])) {
setcookie(HUB_REMEMBER_COOKIE, '', [
'expires' => time() - 3600,
'path' => '/',
'secure' => is_https(),
'httponly' => true,
'samesite' => 'Lax',
]);
}
}
function auth_revoke_sessions(int $userId): void
{
db()->prepare('UPDATE users SET auth_epoch = auth_epoch + 1 WHERE id = ?')->execute([$userId]);
db()->prepare('DELETE FROM remember_tokens WHERE user_id = ?')->execute([$userId]);
db()->prepare('DELETE FROM api_tokens WHERE user_id = ?')->execute([$userId]);
if ((int) ($_SESSION['uid'] ?? 0) === $userId) {
$stmt = db()->prepare('SELECT auth_epoch FROM users WHERE id = ?');
$stmt->execute([$userId]);
$epoch = $stmt->fetchColumn();
if ($epoch !== false) {
$_SESSION['epoch'] = (int) $epoch;
session_regenerate_id(true);
}
}
}
function audit(
string $action,
?string $subjectType = null,
?int $subjectId = null,
string $detail = '',
?int $actorId = null
): void {
if ($actorId === null) {
$current = auth_user();
$actorId = $current ? (int) $current['id'] : null;
}
$stmt = db()->prepare(
'INSERT INTO audit_log (actor_id, action, subject_type, subject_id, detail, ip, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)'
);
$stmt->execute([
$actorId,
mb_substr($action, 0, 64, 'UTF-8'),
$subjectType,
$subjectId,
mb_substr($detail, 0, 255, 'UTF-8'),
client_ip(),
utc_now(),
]);
}

59
hub/app/bootstrap.php Normal file
View file

@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
/**
* Rinkplanner-Hub – Bootstrap.
*
* Lädt Konfiguration, Datenbank, Session und Helfer. Die Konfiguration mit
* Zugangsdaten liegt in app/config.local.php und wird beim Deployment erzeugt.
*/
define('HUB_ROOT', dirname(__DIR__));
define('HUB_APP', __DIR__);
$configFile = HUB_APP . '/config.local.php';
if (!is_file($configFile)) {
http_response_code(500);
header('Content-Type: text/plain; charset=utf-8');
echo "Der Hub ist noch nicht konfiguriert (app/config.local.php fehlt).\n";
exit;
}
$GLOBALS['hub_config'] = require $configFile;
date_default_timezone_set('UTC');
ini_set('display_errors', '0');
ini_set('log_errors', '1');
require HUB_APP . '/util.php';
require HUB_APP . '/db.php';
require HUB_APP . '/auth.php';
require HUB_APP . '/invites.php';
require HUB_APP . '/tokens.php';
require HUB_APP . '/routines.php';
require HUB_APP . '/pages.php';
require HUB_APP . '/api.php';
$storage = (string) config('app.storage_path', HUB_ROOT . '/storage');
if (is_dir($storage) && is_writable($storage)) {
ini_set('error_log', $storage . '/logs/php.log');
}
set_exception_handler(static function (Throwable $error): void {
error_log('Hub: ' . $error::class . ': ' . $error->getMessage() . ' in ' . $error->getFile() . ':' . $error->getLine());
if (function_exists('wants_json') && wants_json()) {
json_response(['error' => ['code' => 'server_error', 'message' => 'Interner Fehler.']], 500);
return;
}
http_response_code(500);
header('Content-Type: text/html; charset=utf-8');
echo '<!doctype html><meta charset="utf-8"><title>Fehler</title>'
. '<body style="font-family:system-ui;background:#050d19;color:#eefaff;padding:2rem">'
. '<h1>Interner Fehler</h1><p>Bitte später erneut versuchen.</p></body>';
});
security_headers();
if (PHP_SAPI !== 'cli') {
start_session();
}

View file

@ -0,0 +1,31 @@
<?php
/**
* Beispielkonfiguration. Wird nicht ausgeliefert; beim Deployment erzeugt
* tools/deploy_hub.sh daraus app/config.local.php.
*/
return [
'db' => [
'host' => 'localhost',
'port' => 3306,
'name' => 'DB_NAME',
'user' => 'DB_USER',
'password' => 'DB_PASSWORD',
'charset' => 'utf8mb4',
],
'app' => [
// Leer, wenn der Hub direkt im DocumentRoot der Subdomain liegt.
'base_path' => '',
'public_url' => 'https://rinkplanner-hub.programmschmiede.de',
'storage_path' => dirname(__DIR__) . '/storage',
'install_token' => 'wird-beim-deployment-erzeugt',
'max_routine_bytes' => 8 * 1024 * 1024,
'max_audio_bytes' => 50 * 1024 * 1024,
'session_idle_seconds' => 14 * 86400,
'session_absolute_seconds' => 30 * 86400,
'remember_seconds' => 30 * 86400,
'login_window_seconds' => 900,
'login_max_per_user' => 5,
'login_max_per_ip' => 10,
'uploads_per_hour' => 20,
],
];

28
hub/app/db.php Normal file
View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
function db(): PDO
{
static $pdo = null;
if ($pdo instanceof PDO) {
return $pdo;
}
$db = (array) config('db', []);
$dsn = sprintf(
'mysql:host=%s;port=%d;dbname=%s;charset=%s',
(string) ($db['host'] ?? 'localhost'),
(int) ($db['port'] ?? 3306),
(string) ($db['name'] ?? ''),
(string) ($db['charset'] ?? 'utf8mb4')
);
$pdo = new PDO($dsn, (string) ($db['user'] ?? ''), (string) ($db['password'] ?? ''), [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_STRINGIFY_FETCHES => false,
]);
$pdo->exec("SET time_zone = '+00:00'");
return $pdo;
}

118
hub/app/invites.php Normal file
View file

@ -0,0 +1,118 @@
<?php
declare(strict_types=1);
const HUB_INVITE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
function invite_normalize(string $code): string
{
$code = strtoupper(trim($code));
return preg_replace('/[^A-Z0-9]/', '', $code) ?? '';
}
function invite_hash(string $code): string
{
return hash('sha256', invite_normalize($code));
}
function invite_generate(): string
{
$groups = [];
for ($group = 0; $group < 4; $group++) {
$part = '';
for ($i = 0; $i < 4; $i++) {
$part .= HUB_INVITE_ALPHABET[random_int(0, strlen(HUB_INVITE_ALPHABET) - 1)];
}
$groups[] = $part;
}
return 'RHUB-' . implode('-', $groups);
}
function invite_create(string $note, string $email, int $expiresDays, int $createdBy): string
{
$code = invite_generate();
$expiresAt = null;
if ($expiresDays > 0) {
$expiresAt = utc_after(min($expiresDays, 365) * 86400);
}
$stmt = db()->prepare(
'INSERT INTO invites (code_hash, note, email, created_by, created_at, expires_at)
VALUES (?, ?, ?, ?, ?, ?)'
);
$stmt->execute([
invite_hash($code),
$note !== '' ? mb_substr($note, 0, 190, 'UTF-8') : null,
$email !== '' ? mb_substr($email, 0, 190, 'UTF-8') : null,
$createdBy,
utc_now(),
$expiresAt,
]);
audit('invite.create', 'invite', (int) db()->lastInsertId(), $note, $createdBy);
return $code;
}
function invite_find_valid(string $code): ?array
{
$normalized = invite_normalize($code);
if ($normalized === '') {
return null;
}
$stmt = db()->prepare(
'SELECT * FROM invites WHERE code_hash = ? AND used_by IS NULL AND used_at IS NULL
AND revoked_at IS NULL LIMIT 1'
);
$stmt->execute([invite_hash($normalized)]);
$row = $stmt->fetch();
if (!$row) {
return null;
}
if ($row['expires_at'] !== null && $row['expires_at'] <= utc_now()) {
return null;
}
return $row;
}
function invite_consume(int $inviteId, int $userId): bool
{
$stmt = db()->prepare(
'UPDATE invites SET used_by = ?, used_at = ?
WHERE id = ? AND used_by IS NULL AND used_at IS NULL AND revoked_at IS NULL
AND (expires_at IS NULL OR expires_at > ?)'
);
$stmt->execute([$userId, utc_now(), $inviteId, utc_now()]);
return $stmt->rowCount() === 1;
}
function invite_revoke(int $inviteId): bool
{
$stmt = db()->prepare(
'UPDATE invites SET revoked_at = ? WHERE id = ? AND used_by IS NULL AND revoked_at IS NULL'
);
$stmt->execute([utc_now(), $inviteId]);
return $stmt->rowCount() === 1;
}
function invites_list(): array
{
return db()->query(
"SELECT i.*, c.username AS creator_name, u.username AS used_name
FROM invites i
LEFT JOIN users c ON c.id = i.created_by
LEFT JOIN users u ON u.id = i.used_by
ORDER BY i.created_at DESC, i.id DESC
LIMIT 200"
)->fetchAll();
}
function invite_status(array $invite): string
{
if ($invite['revoked_at'] !== null) {
return 'widerrufen';
}
if ($invite['used_at'] !== null) {
return 'eingelöst';
}
if ($invite['expires_at'] !== null && $invite['expires_at'] <= utc_now()) {
return 'abgelaufen';
}
return 'offen';
}

729
hub/app/pages.php Normal file
View file

@ -0,0 +1,729 @@
<?php
declare(strict_types=1);
/** Web-Oberfläche: Routen, Formulare und Admin-Seiten. */
const HUB_RESERVED_USERNAMES = [
'admin', 'administrator', 'root', 'system', 'support', 'moderator',
'rinkplanner', 'hub', 'team', 'test', 'guest', 'gast',
];
function page_handle(string $method, string $path): void
{
$path = '/' . trim($path, '/');
if (!in_array($method, ['GET', 'POST'], true)) {
abort_page(405, 'Diese Methode ist nicht erlaubt.');
}
if ($path === '/health') {
health_check();
return;
}
$user = auth_user();
if ($user !== null && $user['must_change_password'] === 1
&& !in_array($path, ['/account', '/account/password', '/logout'], true)
) {
flash('info', 'Bitte zuerst das Passwort ändern.');
redirect('/account');
}
if ($path === '/login') {
page_login($method);
return;
}
if ($path === '/register') {
page_register($method);
return;
}
if ($path === '/logout') {
if ($method !== 'POST' || !csrf_valid()) {
redirect('/');
}
auth_logout();
flash('success', 'Abgemeldet.');
redirect('/login');
}
if ($path === '/') {
page_dashboard($method);
return;
}
if ($path === '/upload') {
page_upload($method);
return;
}
if ($path === '/account') {
page_account($method);
return;
}
if ($path === '/account/password') {
page_account_password($method);
return;
}
if ($path === '/account/tokens') {
page_account_token_create($method);
return;
}
if ($path === '/account/tokens/revoke') {
page_account_token_revoke($method);
return;
}
if ($path === '/admin/invites') {
page_admin_invites($method);
return;
}
if ($path === '/admin/invites/revoke') {
page_admin_invite_revoke($method);
return;
}
if ($path === '/admin/users') {
page_admin_users($method);
return;
}
if ($path === '/admin/users/action') {
page_admin_user_action($method);
return;
}
if ($path === '/admin/routines') {
page_admin_routines($method);
return;
}
if ($path === '/admin/routines/action') {
page_admin_routine_action($method);
return;
}
if ($path === '/admin/audit') {
require_admin_page();
render_page('admin_audit', ['entries' => audit_list(200)], 'Audit-Log');
return;
}
if (preg_match('#^/routines/(\d+)$#', $path, $matches) === 1) {
page_routine_detail((int) $matches[1], $method);
return;
}
if (preg_match('#^/routines/(\d+)/(download|audio)$#', $path, $matches) === 1) {
page_routine_file((int) $matches[1], (string) $matches[2]);
return;
}
if (preg_match('#^/routines/(\d+)/revise$#', $path, $matches) === 1) {
page_routine_revise((int) $matches[1], $method);
return;
}
if (preg_match('#^/routines/(\d+)/(hide|publish)$#', $path, $matches) === 1) {
page_routine_status((int) $matches[1], (string) $matches[2], $method);
return;
}
abort_page(404, 'Diese Seite gibt es nicht.');
}
function health_check(): void
{
try {
db()->query('SELECT 1');
header('Content-Type: text/plain; charset=utf-8');
echo "ok\n";
} catch (Throwable) {
http_response_code(503);
header('Content-Type: text/plain; charset=utf-8');
echo "db error\n";
}
}
function require_admin_page(): array
{
return auth_require_admin();
}
function page_login(string $method): void
{
if (auth_user() !== null) {
redirect('/');
}
$error = '';
$login = '';
$next = auth_next_url('/');
if ($method === 'POST') {
csrf_require();
$login = post_string('login');
$password = (string) ($_POST['password'] ?? '');
$result = auth_attempt($login, $password);
if ($result['ok']) {
auth_login($result['user'], isset($_POST['remember']));
redirect(auth_next_url($next));
}
$error = (string) $result['error'];
if (($result['retry'] ?? 0) > 0) {
http_response_code(429);
header('Retry-After: ' . (int) $result['retry']);
}
}
render_page('login', [
'error' => $error,
'login' => $login,
'next' => $next,
], 'Anmelden');
}
function username_error(string $username): ?string
{
if (mb_strlen($username, 'UTF-8') < 3 || mb_strlen($username, 'UTF-8') > 32) {
return 'Der Benutzername muss 3 bis 32 Zeichen lang sein.';
}
if (preg_match('/^[a-z0-9](?:[a-z0-9._-]{1,30}[a-z0-9])$/u', $username) !== 1) {
return 'Nur Kleinbuchstaben, Ziffern, Punkt, Bindestrich und Unterstrich; Anfang und Ende alphanumerisch.';
}
if (in_array($username, HUB_RESERVED_USERNAMES, true)) {
return 'Dieser Benutzername ist reserviert.';
}
return null;
}
function page_register(string $method): void
{
if (auth_user() !== null) {
redirect('/');
}
$invite = null;
$code = '';
$errors = [];
$input = [
'username' => '',
'display_name' => '',
'email' => '',
];
if ($method === 'GET') {
$code = query_string('code');
$invite = invite_find_valid($code);
if ($invite !== null && !empty($invite['email'])) {
$input['email'] = (string) $invite['email'];
}
} else {
csrf_require();
$code = post_string('code');
$invite = invite_find_valid($code);
$input['username'] = mb_strtolower(post_string('username'));
$input['display_name'] = post_string('display_name');
$input['email'] = post_string('email');
if ($invite === null) {
$errors[] = 'Dieser Einladungscode ist ungültig, abgelaufen oder bereits eingelöst.';
} elseif (!empty($invite['email']) && $input['email'] === '') {
$input['email'] = (string) $invite['email'];
}
$usernameError = username_error($input['username']);
if ($usernameError !== null) {
$errors[] = $usernameError;
}
if ($input['display_name'] === '') {
$input['display_name'] = $input['username'];
}
if (mb_strlen($input['display_name'], 'UTF-8') > 64) {
$errors[] = 'Der Anzeigename darf höchstens 64 Zeichen lang sein.';
}
if ($input['email'] !== '' && filter_var($input['email'], FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Die E-Mail-Adresse ist nicht gültig.';
}
if ($invite !== null && !empty($invite['email'])
&& strcasecmp((string) $invite['email'], $input['email']) !== 0
) {
$errors[] = 'Diese Einladung ist an eine andere E-Mail-Adresse gebunden.';
}
$password = (string) ($_POST['password'] ?? '');
$repeat = (string) ($_POST['password_repeat'] ?? '');
$policy = password_policy_error($password, $input['username']);
if ($policy !== null) {
$errors[] = $policy;
}
if ($password !== $repeat) {
$errors[] = 'Die Passwortwiederholung passt nicht.';
}
if (($_POST['rights'] ?? '') !== '1') {
$errors[] = 'Bitte die Beta-Regeln akzeptieren.';
}
if (!$errors && $invite !== null) {
$pdo = db();
try {
$pdo->beginTransaction();
$stmt = $pdo->prepare(
'INSERT INTO users
(username, display_name, email, password_hash, role, status,
must_change_password, auth_epoch, created_at, password_changed_at)
VALUES (?, ?, ?, ?, ?, ?, 0, 1, ?, ?)'
);
$now = utc_now();
$stmt->execute([
$input['username'],
$input['display_name'],
$input['email'] !== '' ? $input['email'] : null,
hash_password($password),
'user',
'active',
$now,
$now,
]);
$newId = (int) $pdo->lastInsertId();
if (!invite_consume((int) $invite['id'], $newId)) {
$pdo->rollBack();
$errors[] = 'Der Einladungscode wurde gerade eingelöst. Bitte einen neuen Code anfordern.';
} else {
audit('invite.use', 'invite', (int) $invite['id'], $input['username'], $newId);
audit('user.register', 'user', $newId, $input['username'], $newId);
$pdo->commit();
}
} catch (PDOException $exception) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
if (str_contains($exception->getMessage(), 'uq_users_username')) {
$errors[] = 'Dieser Benutzername ist schon vergeben.';
} elseif (str_contains($exception->getMessage(), 'uq_users_email')) {
$errors[] = 'Diese E-Mail-Adresse ist schon registriert.';
} else {
throw $exception;
}
}
if (!$errors) {
$user = auth_user_by_id($newId);
if ($user !== null) {
auth_login($user);
flash('success', 'Willkommen im Kür-Hub!');
redirect('/');
}
}
}
}
render_page('register', [
'invite' => $invite,
'code' => $code,
'errors' => $errors,
'input' => $input,
], 'Registrieren');
}
function page_dashboard(string $method): void
{
$user = auth_require_login();
$query = query_string('q');
$page = max(1, query_int('page', 1));
$mine = query_string('mine') === '1';
$result = routines_query($query, $page, 20, $mine ? (int) $user['id'] : null, $mine);
render_page('dashboard', [
'items' => $result['items'],
'total' => $result['total'],
'page' => $result['page'],
'pages' => $result['pages'],
'query' => $query,
'mine' => $mine,
], 'Küren');
}
function page_routine_detail(int $id, string $method): void
{
$user = auth_require_login();
$routine = routine_fetch($id);
if ($routine === null) {
abort_page(404, 'Diese Kür gibt es nicht.');
}
if (!routine_can_view($routine, $user)) {
abort_page(403, 'Diese Kür ist nicht freigegeben.');
}
render_page('routine', [
'routine' => $routine,
'can_edit' => routine_can_edit($routine, $user),
'is_admin' => auth_is_admin($user),
], $routine['title']);
}
function page_routine_file(int $id, string $kind): void
{
$user = auth_require_login();
$routine = routine_fetch($id);
if ($routine === null) {
abort_page(404, 'Diese Kür gibt es nicht.');
}
if (!routine_can_view($routine, $user)) {
abort_page(403, 'Diese Kür ist nicht freigegeben.');
}
routine_send_file($routine, $kind);
}
function page_upload(string $method): void
{
$user = auth_require_login();
$errors = [];
$input = [
'description' => '',
'music_title' => '',
'music_artist' => '',
];
if ($method === 'POST') {
csrf_require();
if (!routine_upload_quota_ok((int) $user['id'])) {
$errors[] = 'Stündliches Upload-Limit erreicht. Bitte später erneut versuchen.';
}
if (($_POST['rights'] ?? '') !== '1') {
$errors[] = 'Bitte bestätigen, dass du Kür und Musik teilen darfst.';
}
if (!$errors) {
$package = routine_validate_package($_POST);
if (!$package['ok']) {
$errors = $package['errors'];
} else {
$duplicate = routine_duplicate_exists((int) $user['id'], $package);
if ($duplicate !== null) {
flash('info', 'Diese Kür ist bereits im Hub.');
redirect('/routines/' . $duplicate);
}
try {
$routineId = routine_create((int) $user['id'], $package);
flash('success', 'Kür veröffentlicht.');
redirect('/routines/' . $routineId);
} catch (Throwable $error) {
hub_log('Upload fehlgeschlagen: ' . $error->getMessage());
$errors[] = 'Die Kür konnte nicht gespeichert werden.';
}
}
}
$input['description'] = post_string('description');
$input['music_title'] = post_string('music_title');
$input['music_artist'] = post_string('music_artist');
}
render_page('upload', [
'errors' => $errors,
'input' => $input,
'routine' => null,
], 'Kür hochladen');
}
function page_routine_revise(int $id, string $method): void
{
$user = auth_require_login();
$routine = routine_fetch($id);
if ($routine === null) {
abort_page(404, 'Diese Kür gibt es nicht.');
}
if (!routine_can_edit($routine, $user)) {
abort_page(403, 'Nur der Eigentümer oder ein Admin kann diese Kür ändern.');
}
$errors = [];
$input = [
'description' => (string) ($routine['description'] ?? ''),
'music_title' => (string) ($routine['music_title'] ?? ''),
'music_artist' => (string) ($routine['music_artist'] ?? ''),
];
if ($method === 'POST') {
csrf_require();
if (!routine_upload_quota_ok((int) $user['id'])) {
$errors[] = 'Stündliches Upload-Limit erreicht. Bitte später erneut versuchen.';
}
if (($_POST['rights'] ?? '') !== '1') {
$errors[] = 'Bitte bestätigen, dass du Kür und Musik teilen darfst.';
}
if (!$errors) {
$package = routine_validate_package($_POST);
if (!$package['ok']) {
$errors = $package['errors'];
} else {
try {
$revision = routine_add_revision($id, (int) $user['id'], $package);
flash('success', 'Neue Revision ' . $revision . ' gespeichert.');
redirect('/routines/' . $id);
} catch (Throwable $error) {
hub_log('Revision fehlgeschlagen: ' . $error->getMessage());
$errors[] = 'Die Revision konnte nicht gespeichert werden.';
}
}
}
$input['description'] = post_string('description');
$input['music_title'] = post_string('music_title');
$input['music_artist'] = post_string('music_artist');
}
render_page('upload', [
'errors' => $errors,
'input' => $input,
'routine' => $routine,
], 'Neue Revision');
}
function page_routine_status(int $id, string $action, string $method): void
{
$user = auth_require_login();
if ($method !== 'POST') {
redirect('/routines/' . $id);
}
csrf_require();
$routine = routine_fetch($id);
if ($routine === null) {
abort_page(404, 'Diese Kür gibt es nicht.');
}
if (!routine_can_edit($routine, $user)) {
abort_page(403, 'Nur der Eigentümer oder ein Admin kann diese Kür ändern.');
}
$status = $action === 'publish' ? 'published' : 'hidden';
routine_set_status($id, $status);
flash('success', $status === 'published' ? 'Kür ist wieder sichtbar.' : 'Kür wurde aus dem Hub genommen.');
redirect('/routines/' . $id);
}
function page_account(string $method): void
{
$user = auth_require_login();
render_page('account', [
'tokens' => tokens_list((int) $user['id']),
], 'Konto');
}
function page_account_password(string $method): void
{
$user = auth_require_login();
if ($method !== 'POST') {
redirect('/account');
}
csrf_require();
$current = (string) ($_POST['current_password'] ?? '');
$password = (string) ($_POST['password'] ?? '');
$repeat = (string) ($_POST['password_repeat'] ?? '');
$errors = [];
if (!password_verify($current, (string) $user['password_hash'])) {
$errors[] = 'Das aktuelle Passwort ist falsch.';
}
$policy = password_policy_error($password, (string) $user['username']);
if ($policy !== null) {
$errors[] = $policy;
}
if ($password !== $repeat) {
$errors[] = 'Die Passwortwiederholung passt nicht.';
}
if ($errors) {
foreach ($errors as $error) {
flash('error', $error);
}
redirect('/account');
}
db()->prepare(
'UPDATE users SET password_hash = ?, password_changed_at = ?, must_change_password = 0 WHERE id = ?'
)->execute([hash_password($password), utc_now(), (int) $user['id']]);
auth_revoke_sessions((int) $user['id']);
audit('user.password_change', 'user', (int) $user['id']);
flash('success', 'Passwort geändert. Andere Sitzungen wurden abgemeldet.');
redirect('/account');
}
function page_account_token_create(string $method): void
{
$user = auth_require_login();
if ($method !== 'POST') {
redirect('/account');
}
csrf_require();
$name = post_string('name');
if ($name === '') {
$name = 'App';
}
$created = token_create((int) $user['id'], $name);
flash_secret('Neuer API-Token – jetzt kopieren, er wird nicht erneut angezeigt', $created['token']);
redirect('/account');
}
function page_account_token_revoke(string $method): void
{
$user = auth_require_login();
if ($method !== 'POST') {
redirect('/account');
}
csrf_require();
$tokenId = (int) post_string('token_id');
if (token_revoke($tokenId, (int) $user['id'])) {
audit('token.revoke', 'token', $tokenId);
flash('success', 'Token widerrufen.');
} else {
flash('error', 'Token nicht gefunden.');
}
redirect('/account');
}
function page_admin_invites(string $method): void
{
$admin = require_admin_page();
if ($method === 'POST') {
csrf_require();
$note = post_string('note');
$email = post_string('email');
$days = (int) post_string('expires_days', '30');
$errors = [];
if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Die E-Mail-Adresse ist nicht gültig.';
}
if ($errors) {
foreach ($errors as $error) {
flash('error', $error);
}
} else {
$code = invite_create($note, $email, $days, (int) $admin['id']);
$publicUrl = rtrim((string) config('app.public_url', ''), '/');
$link = $publicUrl . '/register?code=' . rawurlencode($code);
flash_secret('Einladungscode', $code . ' – Link: ' . $link);
flash('success', 'Einladung erstellt.');
}
redirect('/admin/invites');
}
render_page('admin_invites', [
'invites' => invites_list(),
], 'Einladungen');
}
function page_admin_invite_revoke(string $method): void
{
require_admin_page();
if ($method !== 'POST') {
redirect('/admin/invites');
}
csrf_require();
$inviteId = (int) post_string('invite_id');
if (invite_revoke($inviteId)) {
audit('invite.revoke', 'invite', $inviteId);
flash('success', 'Einladung widerrufen.');
} else {
flash('error', 'Einladung konnte nicht widerrufen werden.');
}
redirect('/admin/invites');
}
function page_admin_users(string $method): void
{
require_admin_page();
$users = db()->query(
'SELECT u.*, (SELECT COUNT(*) FROM routines r WHERE r.owner_id = u.id) AS routine_count
FROM users u ORDER BY u.created_at DESC, u.id DESC'
)->fetchAll();
render_page('admin_users', ['users' => $users], 'Benutzer');
}
function page_admin_user_action(string $method): void
{
$admin = require_admin_page();
if ($method !== 'POST') {
redirect('/admin/users');
}
csrf_require();
$targetId = (int) post_string('user_id');
$action = post_string('action');
$target = auth_user_by_id($targetId);
if ($target === null) {
flash('error', 'Benutzer nicht gefunden.');
redirect('/admin/users');
}
if ($targetId === (int) $admin['id']) {
flash('error', 'Das eigene Konto lässt sich hier nicht ändern.');
redirect('/admin/users');
}
if ($action === 'disable') {
db()->prepare("UPDATE users SET status = 'disabled' WHERE id = ?")->execute([$targetId]);
auth_revoke_sessions($targetId);
audit('user.disable', 'user', $targetId, (string) $target['username']);
flash('success', 'Benutzer deaktiviert.');
} elseif ($action === 'enable') {
db()->prepare("UPDATE users SET status = 'active' WHERE id = ?")->execute([$targetId]);
audit('user.enable', 'user', $targetId, (string) $target['username']);
flash('success', 'Benutzer aktiviert.');
} elseif ($action === 'reset') {
$alphabet = HUB_INVITE_ALPHABET;
$temp = '';
for ($i = 0; $i < 12; $i++) {
$temp .= $alphabet[random_int(0, strlen($alphabet) - 1)];
}
db()->prepare(
'UPDATE users SET password_hash = ?, must_change_password = 1, password_changed_at = ? WHERE id = ?'
)->execute([hash_password($temp), utc_now(), $targetId]);
auth_revoke_sessions($targetId);
audit('user.password_reset', 'user', $targetId, (string) $target['username']);
flash_secret('Temporäres Passwort für ' . $target['username'], $temp);
flash('info', 'Der Benutzer muss das Passwort bei der nächsten Anmeldung ändern.');
} elseif ($action === 'delete') {
if (($_POST['confirm'] ?? '') !== '1') {
flash('error', 'Löschen muss bestätigt werden.');
redirect('/admin/users');
}
$stmt = db()->prepare('SELECT id FROM routines WHERE owner_id = ?');
$stmt->execute([$targetId]);
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $routineId) {
routine_delete((int) $routineId);
}
db()->prepare('UPDATE invites SET revoked_at = ? WHERE used_by = ? AND revoked_at IS NULL')
->execute([utc_now(), $targetId]);
audit('user.delete', 'user', $targetId, (string) $target['username']);
db()->prepare('DELETE FROM users WHERE id = ?')->execute([$targetId]);
flash('success', 'Benutzer und zugehörige Küren gelöscht.');
} else {
flash('error', 'Unbekannte Aktion.');
}
redirect('/admin/users');
}
function page_admin_routines(string $method): void
{
require_admin_page();
$query = query_string('q');
$page = max(1, query_int('page', 1));
$result = routines_query($query, $page, 50, null, true);
render_page('admin_routines', [
'items' => $result['items'],
'total' => $result['total'],
'page' => $result['page'],
'pages' => $result['pages'],
'query' => $query,
], 'Alle Küren');
}
function page_admin_routine_action(string $method): void
{
require_admin_page();
if ($method !== 'POST') {
redirect('/admin/routines');
}
csrf_require();
$routineId = (int) post_string('routine_id');
$action = post_string('action');
$routine = routine_fetch($routineId);
if ($routine === null) {
flash('error', 'Kür nicht gefunden.');
redirect('/admin/routines');
}
if ($action === 'hide' || $action === 'publish') {
routine_set_status($routineId, $action === 'publish' ? 'published' : 'hidden');
flash('success', 'Status geändert.');
} elseif ($action === 'delete') {
if (($_POST['confirm'] ?? '') !== '1') {
flash('error', 'Löschen muss bestätigt werden.');
redirect('/admin/routines');
}
routine_delete($routineId);
flash('success', 'Kür endgültig gelöscht.');
} else {
flash('error', 'Unbekannte Aktion.');
}
redirect('/admin/routines');
}
function audit_list(int $limit = 200): array
{
$limit = max(1, min($limit, 500));
return db()->query(
"SELECT a.*, u.username AS actor_name
FROM audit_log a LEFT JOIN users u ON u.id = a.actor_id
ORDER BY a.created_at DESC, a.id DESC LIMIT $limit"
)->fetchAll();
}

638
hub/app/routines.php Normal file
View file

@ -0,0 +1,638 @@
<?php
declare(strict_types=1);
/**
* Küren: Validierung, Ablage, Metadaten und Auslieferung.
*
* Eine Kür ist ein Paket aus JSON-Datei und optionaler Audiodatei. Beide
* werden unter storage/uploads/<jahr>/<monat>/ mit Zufallsnamen abgelegt;
* der ursprüngliche Dateiname steht nur in der Datenbank.
*/
const HUB_AUDIO_EXTENSIONS = ['mp3', 'ogg', 'wav', 'm4a', 'aac'];
function storage_path(string $relative = ''): string
{
$root = rtrim((string) config('app.storage_path', HUB_ROOT . '/storage'), '/');
if ($relative === '') {
return $root;
}
return $root . '/' . ltrim($relative, '/');
}
function storage_uploads_dir(): string
{
$relative = 'uploads/' . gmdate('Y/m');
$absolute = storage_path($relative);
if (!is_dir($absolute) && !mkdir($absolute, 0770, true) && !is_dir($absolute)) {
throw new RuntimeException('Upload-Verzeichnis nicht anlegbar.');
}
return $absolute;
}
function routine_music_name_valid(string $name): bool
{
if ($name === '' || mb_strlen($name, 'UTF-8') > 160) {
return false;
}
if (str_contains($name, '/') || str_contains($name, '\\') || str_contains($name, ':')
|| str_contains($name, '..') || str_starts_with($name, '.')
) {
return false;
}
$extension = strtolower((string) pathinfo($name, PATHINFO_EXTENSION));
return in_array($extension, HUB_AUDIO_EXTENSIONS, true);
}
function upload_error_message(int $code): string
{
return match ($code) {
UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE => 'Die Datei ist zu groß.',
UPLOAD_ERR_PARTIAL => 'Der Upload wurde unterbrochen.',
UPLOAD_ERR_NO_FILE => 'Es wurde keine Datei ausgewählt.',
UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_CANT_WRITE, UPLOAD_ERR_EXTENSION => 'Die Datei konnte nicht gespeichert werden.',
default => 'Unbekannter Upload-Fehler.',
};
}
function audio_sniff(string $tmpPath): ?string
{
$handle = @fopen($tmpPath, 'rb');
if ($handle === false) {
return null;
}
$head = (string) fread($handle, 12);
fclose($handle);
if ($head === '') {
return null;
}
if (str_starts_with($head, 'ID3')) {
return 'mp3';
}
if (strlen($head) >= 2 && ord($head[0]) === 0xFF && (ord($head[1]) & 0xE0) === 0xE0) {
$second = ord($head[1]);
if (($second & 0xF6) === 0xF0) {
return 'aac';
}
return 'mp3';
}
if (str_starts_with($head, 'OggS')) {
return 'ogg';
}
if (str_starts_with($head, 'RIFF') && substr($head, 8, 4) === 'WAVE') {
return 'wav';
}
if (strlen($head) >= 8 && substr($head, 4, 4) === 'ftyp') {
return 'm4a';
}
return null;
}
function audio_mime_for(string $extension): string
{
return match ($extension) {
'mp3' => 'audio/mpeg',
'ogg' => 'audio/ogg',
'wav' => 'audio/wav',
'm4a' => 'audio/mp4',
'aac' => 'audio/aac',
default => 'application/octet-stream',
};
}
/**
* Prüft Kür- und Audiodatei. Gibt bei Erfolg das Paket mit temporären Pfaden
* zurück; gespeichert wird erst danach.
*/
function routine_validate_package(array $post): array
{
$errors = [];
$maxRoutine = (int) config('app.max_routine_bytes', 8 * 1024 * 1024);
$maxAudio = (int) config('app.max_audio_bytes', 50 * 1024 * 1024);
$routineFile = $_FILES['routine'] ?? null;
if (!is_array($routineFile) || ($routineFile['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
$errors[] = 'Bitte eine Kür-Datei (.json) auswählen.';
return ['ok' => false, 'errors' => $errors];
}
$routineTmp = (string) $routineFile['tmp_name'];
$routineBytes = (int) $routineFile['size'];
if (!is_uploaded_file($routineTmp)) {
return ['ok' => false, 'errors' => ['Ungültiger Upload.']];
}
if ($routineBytes <= 0 || $routineBytes > $maxRoutine) {
$errors[] = 'Die Kür-Datei ist zu groß (max. ' . human_bytes($maxRoutine) . ').';
}
$routineName = clean_filename((string) ($routineFile['name'] ?? 'kuer.json'));
if (!str_ends_with(strtolower($routineName), '.json')) {
$errors[] = 'Kürdateien müssen im JSON-Format vorliegen (.json).';
}
if ($errors) {
return ['ok' => false, 'errors' => $errors];
}
$contents = file_get_contents($routineTmp);
if (!is_string($contents)) {
return ['ok' => false, 'errors' => ['Die Kür-Datei konnte nicht gelesen werden.']];
}
try {
$json = json_decode($contents, true, 64, JSON_THROW_ON_ERROR);
} catch (JsonException) {
return ['ok' => false, 'errors' => ['Die Kür-Datei ist kein gültiges JSON.']];
}
if (!is_array($json)) {
return ['ok' => false, 'errors' => ['Die Kür-Datei enthält kein JSON-Objekt.']];
}
if (($json['format'] ?? '') !== 'rinkplanner.routine') {
return ['ok' => false, 'errors' => ['Das ist keine Rinkplanner-Kür (format fehlt oder ist falsch).']];
}
$formatVersion = (int) ($json['format_version'] ?? 0);
if ($formatVersion !== 1) {
return ['ok' => false, 'errors' => ['Diese Kür-Formatversion wird nicht unterstützt.']];
}
if (!is_array($json['sections'] ?? null)) {
return ['ok' => false, 'errors' => ['Die Kür enthält keine Abschnittsliste.']];
}
if (count($json['sections']) > 500) {
return ['ok' => false, 'errors' => ['Die Kür hat zu viele Abschnitte (max. 500).']];
}
$title = trim((string) ($json['title'] ?? ''));
if ($title === '') {
$title = (string) pathinfo($routineName, PATHINFO_FILENAME);
}
if ($title === '') {
return ['ok' => false, 'errors' => ['Die Kür braucht einen Titel.']];
}
$title = truncate_text($title, 190);
$skater = truncate_text(trim((string) ($json['skater_name'] ?? '')), 190);
$category = truncate_text(trim((string) ($json['adult_category'] ?? '')), 40);
$musicFile = trim((string) ($json['music_file'] ?? ''));
if ($musicFile !== '' && !routine_music_name_valid($musicFile)) {
return ['ok' => false, 'errors' => ['Die Kür verweist auf einen ungültigen Musikdateinamen.']];
}
$fileRoutineId = trim((string) ($json['routine_id'] ?? ''));
$audio = null;
$audioFile = $_FILES['audio'] ?? null;
$hasAudioUpload = is_array($audioFile) && ($audioFile['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE;
if ($musicFile !== '' && !$hasAudioUpload) {
$errors[] = 'Die Kür verweist auf „' . $musicFile . '“. Bitte die passende Audiodatei mit hochladen.';
}
if ($musicFile === '' && $hasAudioUpload) {
$errors[] = 'Die Kür verweist auf keine Musikdatei; die Audiodatei passt nicht dazu.';
}
if ($hasAudioUpload) {
if (($audioFile['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
$errors[] = upload_error_message((int) $audioFile['error']);
} else {
$audioTmp = (string) $audioFile['tmp_name'];
$audioBytes = (int) $audioFile['size'];
$audioName = clean_filename((string) ($audioFile['name'] ?? ''));
if (!is_uploaded_file($audioTmp)) {
$errors[] = 'Ungültiger Audio-Upload.';
} elseif ($audioBytes <= 0 || $audioBytes > $maxAudio) {
$errors[] = 'Die Audiodatei ist zu groß (max. ' . human_bytes($maxAudio) . ').';
} elseif ($audioName !== $musicFile) {
$errors[] = 'Die Audiodatei heißt „' . $audioName . '“, die Kür verweist aber auf „' . $musicFile . '“.';
} else {
$sniffed = audio_sniff($audioTmp);
if ($sniffed === null) {
$errors[] = 'Die Audiodatei ist kein unterstütztes Format (MP3, OGG, WAV, M4A, AAC).';
} else {
$audio = [
'tmp' => $audioTmp,
'name' => $audioName,
'bytes' => $audioBytes,
'sha256' => (string) hash_file('sha256', $audioTmp),
'mime' => audio_mime_for($sniffed),
'extension' => $sniffed,
];
}
}
}
}
if ($errors) {
return ['ok' => false, 'errors' => $errors];
}
return [
'ok' => true,
'errors' => [],
'meta' => [
'title' => $title,
'skater_name' => $skater !== '' ? $skater : null,
'category' => $category !== '' ? $category : null,
'music_title' => mb_substr(trim((string) ($post['music_title'] ?? '')), 0, 190, 'UTF-8') ?: null,
'music_artist' => mb_substr(trim((string) ($post['music_artist'] ?? '')), 0, 190, 'UTF-8') ?: null,
'description' => mb_substr(trim((string) ($post['description'] ?? '')), 0, 2000, 'UTF-8') ?: null,
],
'routine' => [
'tmp' => $routineTmp,
'name' => $routineName,
'bytes' => $routineBytes,
'sha256' => (string) hash_file('sha256', $routineTmp),
'file_routine_id' => $fileRoutineId !== '' ? mb_substr($fileRoutineId, 0, 36, 'UTF-8') : null,
],
'audio' => $audio,
];
}
/** Verschiebt die geprüften Dateien und liefert relative Pfade. */
function routine_store_files(array $package): array
{
$dir = storage_uploads_dir();
$relativeDir = 'uploads/' . gmdate('Y/m');
$routineName = bin2hex(random_bytes(16)) . '.json';
$routinePath = $dir . '/' . $routineName;
if (!move_uploaded_file((string) $package['routine']['tmp'], $routinePath)) {
throw new RuntimeException('Kür-Datei konnte nicht gespeichert werden.');
}
@chmod($routinePath, 0640);
$audioPath = null;
$audioRelative = null;
if (is_array($package['audio'] ?? null)) {
$audioName = bin2hex(random_bytes(16)) . '.' . $package['audio']['extension'];
$audioPath = $dir . '/' . $audioName;
if (!move_uploaded_file((string) $package['audio']['tmp'], $audioPath)) {
@unlink($routinePath);
throw new RuntimeException('Audiodatei konnte nicht gespeichert werden.');
}
@chmod($audioPath, 0640);
$audioRelative = $relativeDir . '/' . $audioName;
}
return [
'routine' => $relativeDir . '/' . $routineName,
'audio' => $audioRelative,
];
}
function routine_duplicate_exists(int $ownerId, array $package): ?int
{
$stmt = db()->prepare(
'SELECT r.id FROM routines r
JOIN routine_revisions v ON v.id = r.current_revision_id
WHERE r.owner_id = ? AND v.routine_sha256 = ? AND v.audio_sha256 <=> ?
LIMIT 1'
);
$stmt->execute([$ownerId, $package['routine']['sha256'], $package['audio']['sha256'] ?? null]);
$id = $stmt->fetchColumn();
return $id !== false ? (int) $id : null;
}
function routine_create(int $userId, array $package): int
{
$files = routine_store_files($package);
$meta = $package['meta'];
$pdo = db();
try {
$pdo->beginTransaction();
$stmt = $pdo->prepare(
'INSERT INTO routines
(owner_id, title, skater_name, category, music_title, music_artist, description,
status, current_revision_id, download_count, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, 0, ?, ?)'
);
$now = utc_now();
$stmt->execute([
$userId,
$meta['title'],
$meta['skater_name'],
$meta['category'],
$meta['music_title'],
$meta['music_artist'],
$meta['description'],
'published',
$now,
$now,
]);
$routineId = (int) $pdo->lastInsertId();
$revisionId = routine_insert_revision($routineId, 1, $userId, $package, $files);
$pdo->prepare('UPDATE routines SET current_revision_id = ? WHERE id = ?')
->execute([$revisionId, $routineId]);
$pdo->commit();
} catch (Throwable $error) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
@unlink(storage_path($files['routine']));
if ($files['audio'] !== null) {
@unlink(storage_path($files['audio']));
}
throw $error;
}
audit('routine.create', 'routine', $routineId, $meta['title'], $userId);
return $routineId;
}
function routine_add_revision(int $routineId, int $userId, array $package): int
{
$routine = routine_fetch($routineId);
if ($routine === null) {
throw new RuntimeException('Kür nicht gefunden.');
}
$files = routine_store_files($package);
$meta = $package['meta'];
$pdo = db();
try {
$pdo->beginTransaction();
$stmt = $pdo->prepare('SELECT COALESCE(MAX(revision), 0) + 1 FROM routine_revisions WHERE routine_id = ?');
$stmt->execute([$routineId]);
$next = (int) $stmt->fetchColumn();
$revisionId = routine_insert_revision($routineId, $next, $userId, $package, $files);
$pdo->prepare(
'UPDATE routines SET current_revision_id = ?, title = ?, skater_name = ?, category = ?,
music_title = ?, music_artist = ?, description = ?, updated_at = ? WHERE id = ?'
)->execute([
$revisionId,
$meta['title'],
$meta['skater_name'],
$meta['category'],
$meta['music_title'],
$meta['music_artist'],
$meta['description'],
utc_now(),
$routineId,
]);
$pdo->commit();
} catch (Throwable $error) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
@unlink(storage_path($files['routine']));
if ($files['audio'] !== null) {
@unlink(storage_path($files['audio']));
}
throw $error;
}
audit('routine.revision', 'routine', $routineId, 'Revision ' . $next, $userId);
return $next;
}
function routine_insert_revision(
int $routineId,
int $revision,
int $userId,
array $package,
array $files
): int {
$routine = $package['routine'];
$audio = $package['audio'];
$stmt = db()->prepare(
'INSERT INTO routine_revisions
(routine_id, revision, uploaded_by, routine_original_name, routine_path, routine_bytes, routine_sha256,
file_routine_id, audio_original_name, audio_path, audio_bytes, audio_sha256, audio_mime, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
);
$stmt->execute([
$routineId,
$revision,
$userId,
$routine['name'],
$files['routine'],
$routine['bytes'],
$routine['sha256'],
$routine['file_routine_id'],
$audio['name'] ?? null,
$files['audio'],
$audio['bytes'] ?? null,
$audio['sha256'] ?? null,
$audio['mime'] ?? null,
utc_now(),
]);
return (int) db()->lastInsertId();
}
function routine_fetch(int $id): ?array
{
$stmt = db()->prepare(
'SELECT r.*, u.username AS owner_username, u.display_name AS owner_display_name,
v.id AS revision_id, v.revision, v.uploaded_by,
v.routine_original_name, v.routine_path, v.routine_bytes, v.routine_sha256, v.file_routine_id,
v.audio_original_name, v.audio_path, v.audio_bytes, v.audio_sha256, v.audio_mime,
v.created_at AS revision_created_at
FROM routines r
JOIN users u ON u.id = r.owner_id
LEFT JOIN routine_revisions v ON v.id = r.current_revision_id
WHERE r.id = ? LIMIT 1'
);
$stmt->execute([$id]);
$row = $stmt->fetch();
if (!$row) {
return null;
}
foreach (['id', 'owner_id', 'download_count', 'revision_id', 'revision', 'uploaded_by',
'routine_bytes', 'audio_bytes'] as $key) {
if (array_key_exists($key, $row) && $row[$key] !== null) {
$row[$key] = (int) $row[$key];
}
}
return $row;
}
function routines_query(
string $query,
int $page,
int $perPage = 20,
?int $ownerId = null,
bool $includeHidden = false
): array {
$where = [];
$params = [];
if ($ownerId !== null) {
$where[] = 'r.owner_id = ?';
$params[] = $ownerId;
}
if (!$includeHidden) {
$where[] = "r.status = 'published'";
}
if ($query !== '') {
$like = '%' . addcslashes($query, '\\%_') . '%';
$where[] = '(r.title LIKE ? OR r.skater_name LIKE ? OR r.music_title LIKE ? OR r.music_artist LIKE ?'
. ' OR u.username LIKE ? OR u.display_name LIKE ?)';
array_push($params, $like, $like, $like, $like, $like, $like);
}
$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';
$stmt = db()->prepare(
"SELECT COUNT(*) FROM routines r JOIN users u ON u.id = r.owner_id $whereSql"
);
$stmt->execute($params);
$total = (int) $stmt->fetchColumn();
$page = max(1, $page);
$pages = max(1, (int) ceil($total / $perPage));
$page = min($page, $pages);
$offset = ($page - 1) * $perPage;
$sql = "SELECT r.id, r.title, r.skater_name, r.category, r.music_title, r.music_artist,
r.status, r.download_count, r.updated_at,
u.username AS owner_username, u.display_name AS owner_display_name,
v.revision, v.routine_bytes, v.audio_bytes, v.audio_original_name
FROM routines r
JOIN users u ON u.id = r.owner_id
LEFT JOIN routine_revisions v ON v.id = r.current_revision_id
$whereSql
ORDER BY r.updated_at DESC, r.id DESC
LIMIT $perPage OFFSET $offset";
$stmt = db()->prepare($sql);
$stmt->execute($params);
$items = $stmt->fetchAll();
return ['items' => $items, 'total' => $total, 'page' => $page, 'pages' => $pages];
}
function routine_can_view(array $routine, ?array $user): bool
{
if ($routine['status'] === 'published') {
return true;
}
return $user !== null
&& ((int) $user['id'] === (int) $routine['owner_id'] || $user['role'] === 'admin');
}
function routine_can_edit(array $routine, ?array $user): bool
{
return $user !== null
&& ((int) $user['id'] === (int) $routine['owner_id'] || $user['role'] === 'admin');
}
function routine_set_status(int $routineId, string $status): void
{
if (!in_array($status, ['published', 'hidden'], true)) {
throw new InvalidArgumentException('Ungültiger Status.');
}
$stmt = db()->prepare('UPDATE routines SET status = ?, updated_at = ? WHERE id = ?');
$stmt->execute([$status, utc_now(), $routineId]);
audit('routine.status', 'routine', $routineId, $status);
}
function routine_delete(int $routineId): void
{
$stmt = db()->prepare('SELECT routine_path, audio_path FROM routine_revisions WHERE routine_id = ?');
$stmt->execute([$routineId]);
$paths = $stmt->fetchAll();
db()->prepare('DELETE FROM routines WHERE id = ?')->execute([$routineId]);
foreach ($paths as $row) {
if (!empty($row['routine_path'])) {
@unlink(storage_path((string) $row['routine_path']));
}
if (!empty($row['audio_path'])) {
@unlink(storage_path((string) $row['audio_path']));
}
}
audit('routine.delete', 'routine', $routineId, '');
}
function routine_upload_quota_ok(int $userId): bool
{
$limit = (int) config('app.uploads_per_hour', 20);
$stmt = db()->prepare(
'SELECT COUNT(*) FROM routine_revisions WHERE uploaded_by = ? AND created_at >= ?'
);
$stmt->execute([$userId, gmdate('Y-m-d H:i:s', time() - 3600)]);
return (int) $stmt->fetchColumn() < $limit;
}
function routine_send_file(array $routine, string $kind, ?array $user = null, bool $api = false): never
{
$kind = $kind === 'audio' ? 'audio' : 'routine';
$revision = routine_fetch((int) $routine['id']);
if ($revision === null || $revision['revision_id'] === null) {
if ($api) {
abort_api(404, 'no_file', 'Diese Kür hat noch keine Datei.');
}
abort_page(404, 'Diese Kür hat noch keine Datei.');
}
if ($kind === 'audio') {
$path = (string) ($revision['audio_path'] ?? '');
$name = (string) ($revision['audio_original_name'] ?? 'musik');
$mime = (string) ($revision['audio_mime'] ?? 'application/octet-stream');
} else {
$path = (string) ($revision['routine_path'] ?? '');
$name = (string) ($revision['routine_original_name'] ?? 'kuer.json');
$mime = 'application/json';
}
$absolute = storage_path($path);
if ($path === '' || !is_file($absolute)) {
if ($api) {
abort_api(404, 'file_missing', 'Die Datei fehlt im Speicher.');
}
abort_page(404, 'Die Datei fehlt im Speicher.');
}
$handle = fopen($absolute, 'rb');
if ($handle === false) {
if ($api) {
abort_api(500, 'file_unreadable', 'Die Datei konnte nicht geöffnet werden.');
}
abort_page(500, 'Die Datei konnte nicht geöffnet werden.');
}
$user ??= auth_user();
db()->prepare(
'INSERT INTO downloads (routine_id, revision_id, user_id, kind, ip, created_at)
VALUES (?, ?, ?, ?, ?, ?)'
)->execute([
(int) $revision['id'],
(int) $revision['revision_id'],
$user ? (int) $user['id'] : null,
$kind,
client_ip(),
utc_now(),
]);
if ($kind === 'routine') {
db()->prepare('UPDATE routines SET download_count = download_count + 1 WHERE id = ?')
->execute([(int) $revision['id']]);
}
session_write_close();
set_time_limit(0);
while (ob_get_level() > 0) {
ob_end_clean();
}
$size = (int) filesize($absolute);
header('Content-Type: ' . $mime);
header('Content-Disposition: ' . content_disposition($name));
header('X-Content-Type-Options: nosniff');
header('Cache-Control: private, no-store');
header('Accept-Ranges: bytes');
$start = 0;
$end = $size - 1;
$range = (string) ($_SERVER['HTTP_RANGE'] ?? '');
if ($range !== '' && $kind === 'audio'
&& preg_match('/^bytes=(\d*)-(\d*)$/', $range, $matches) === 1
) {
if ($matches[1] === '' && $matches[2] !== '') {
$start = max(0, $size - (int) $matches[2]);
} else {
$start = (int) $matches[1];
if ($matches[2] !== '') {
$end = min($end, (int) $matches[2]);
}
}
if ($start > $end || $start >= $size) {
header('Content-Range: bytes */' . $size);
http_response_code(416);
exit;
}
http_response_code(206);
header(sprintf('Content-Range: bytes %d-%d/%d', $start, $end, $size));
}
header('Content-Length: ' . ($end - $start + 1));
fseek($handle, $start);
$remaining = $end - $start + 1;
while ($remaining > 0 && !feof($handle)) {
$chunk = fread($handle, min(65536, $remaining));
if ($chunk === false || $chunk === '') {
break;
}
echo $chunk;
$remaining -= strlen($chunk);
}
fclose($handle);
exit;
}

112
hub/app/tokens.php Normal file
View file

@ -0,0 +1,112 @@
<?php
declare(strict_types=1);
/**
* Persönliche API-Tokens für die Godot-App.
*
* Das Klartext-Token wird nur einmal ausgegeben; in der Datenbank liegt
* ausschließlich der SHA-256-Hash. Format: rhub_ + 64 Hex-Zeichen.
*/
function token_create(int $userId, string $name): array
{
$token = 'rhub_' . bin2hex(random_bytes(32));
$prefix = substr($token, 0, 12);
$stmt = db()->prepare(
'INSERT INTO api_tokens (user_id, name, prefix, token_hash, created_at)
VALUES (?, ?, ?, ?, ?)'
);
$stmt->execute([
$userId,
mb_substr($name !== '' ? $name : 'App', 0, 64, 'UTF-8'),
$prefix,
hash('sha256', $token),
utc_now(),
]);
$tokenId = (int) db()->lastInsertId();
audit('token.create', 'token', $tokenId, $name, $userId);
return ['token' => $token, 'prefix' => $prefix, 'id' => $tokenId];
}
function tokens_list(int $userId): array
{
$stmt = db()->prepare(
'SELECT id, name, prefix, created_at, last_used_at, expires_at, revoked_at
FROM api_tokens WHERE user_id = ? ORDER BY created_at DESC'
);
$stmt->execute([$userId]);
return $stmt->fetchAll();
}
function token_revoke(int $tokenId, int $userId): bool
{
$stmt = db()->prepare(
'UPDATE api_tokens SET revoked_at = ? WHERE id = ? AND user_id = ? AND revoked_at IS NULL'
);
$stmt->execute([utc_now(), $tokenId, $userId]);
return $stmt->rowCount() === 1;
}
function bearer_token(): string
{
$header = (string) ($_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '');
if ($header === '' && function_exists('apache_request_headers')) {
$headers = apache_request_headers();
foreach ($headers as $name => $value) {
if (strtolower((string) $name) === 'authorization') {
$header = (string) $value;
break;
}
}
}
if (preg_match('/^Bearer\s+(\S+)$/i', trim($header), $matches) === 1) {
return $matches[1];
}
return '';
}
function token_user(string $token): ?array
{
if (!str_starts_with($token, 'rhub_') || strlen($token) !== 69) {
return null;
}
$stmt = db()->prepare(
'SELECT t.id AS token_id, t.prefix AS token_prefix, t.last_used_at AS token_last_used, u.*
FROM api_tokens t
JOIN users u ON u.id = t.user_id
WHERE t.token_hash = ? AND t.revoked_at IS NULL
AND (t.expires_at IS NULL OR t.expires_at > ?)
AND u.status = ? LIMIT 1'
);
$stmt->execute([hash('sha256', $token), utc_now(), 'active']);
$row = $stmt->fetch();
if (!$row) {
return null;
}
$lastUsed = $row['token_last_used'];
if ($lastUsed === null || strtotime($lastUsed . ' UTC') < time() - 60) {
db()->prepare('UPDATE api_tokens SET last_used_at = ? WHERE id = ?')
->execute([utc_now(), (int) $row['token_id']]);
}
$row['id'] = (int) $row['id'];
$row['auth_epoch'] = (int) $row['auth_epoch'];
$row['must_change_password'] = (int) $row['must_change_password'];
$row['token_id'] = (int) $row['token_id'];
return $row;
}
function api_require_user(): array
{
$token = bearer_token();
if ($token === '') {
abort_api(401, 'unauthorized', 'Bearer-Token fehlt.');
}
$user = token_user($token);
if ($user === null) {
abort_api(401, 'invalid_token', 'Token ist ungültig, abgelaufen oder widerrufen.');
}
if ($user['must_change_password'] === 1) {
abort_api(403, 'password_change_required', 'Bitte zuerst im Web das Passwort ändern.');
}
return $user;
}

320
hub/app/util.php Normal file
View file

@ -0,0 +1,320 @@
<?php
declare(strict_types=1);
/**
* Kleine Helfer: Konfiguration, Session, CSRF, Ausgabe, Zeit und Dateien.
*/
function config(string $key, mixed $default = null): mixed
{
$value = $GLOBALS['hub_config'] ?? [];
foreach (explode('.', $key) as $part) {
if (!is_array($value) || !array_key_exists($part, $value)) {
return $default;
}
$value = $value[$part];
}
return $value;
}
function is_https(): bool
{
if (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off') {
return true;
}
return strtolower((string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https';
}
function security_headers(): void
{
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-Robots-Tag: noindex, nofollow, noarchive');
header('Referrer-Policy: same-origin');
header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
header(
"Content-Security-Policy: default-src 'self'; img-src 'self' data:; "
. "style-src 'self'; script-src 'none'; media-src 'self'; "
. "form-action 'self'; frame-ancestors 'none'; base-uri 'none'"
);
header('Cache-Control: no-store');
if (is_https()) {
header('Strict-Transport-Security: max-age=15552000');
}
}
function start_session(): void
{
if (session_status() === PHP_SESSION_ACTIVE) {
return;
}
$absolute = (int) config('app.session_absolute_seconds', 2592000);
ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_samesite', 'Lax');
ini_set('session.cookie_secure', is_https() ? '1' : '0');
ini_set('session.cookie_path', '/');
ini_set('session.gc_maxlifetime', (string) $absolute);
session_name('RHUB_SESSION');
session_start();
}
function utc_now(): string
{
return gmdate('Y-m-d H:i:s');
}
function utc_after(int $seconds): string
{
return gmdate('Y-m-d H:i:s', time() + $seconds);
}
function e(mixed $value): string
{
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function url(string $path = '/'): string
{
$base = rtrim((string) config('app.base_path', ''), '/');
if ($path === '' || $path[0] !== '/') {
$path = '/' . $path;
}
return $base . $path;
}
function redirect(string $path, int $status = 303): never
{
header('Location: ' . url($path), true, $status);
exit;
}
function client_ip(): string
{
$ip = (string) ($_SERVER['REMOTE_ADDR'] ?? '');
return $ip !== '' ? substr($ip, 0, 45) : '0.0.0.0';
}
function user_agent(): string
{
return substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255);
}
function request_method(): string
{
return strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));
}
function is_post(): bool
{
return request_method() === 'POST';
}
function post_string(string $key, string $default = ''): string
{
$value = $_POST[$key] ?? $default;
return is_string($value) ? trim($value) : $default;
}
function query_string(string $key, string $default = ''): string
{
$value = $_GET[$key] ?? $default;
return is_string($value) ? trim($value) : $default;
}
function query_int(string $key, int $default = 0): int
{
$value = $_GET[$key] ?? null;
return is_numeric($value) ? (int) $value : $default;
}
function e_attr(mixed $value): string
{
return e($value);
}
function fmt_dt(?string $utc): string
{
if ($utc === null || $utc === '') {
return '–';
}
try {
$date = new DateTimeImmutable($utc, new DateTimeZone('UTC'));
return $date->setTimezone(new DateTimeZone('Europe/Berlin'))->format('d.m.Y H:i');
} catch (Throwable) {
return '–';
}
}
function human_bytes(int|float|null $bytes): string
{
$bytes = (float) ($bytes ?? 0);
if ($bytes < 1024) {
return number_format($bytes, 0, ',', '.') . ' B';
}
$units = ['KB', 'MB', 'GB'];
$index = -1;
do {
$bytes /= 1024;
$index++;
} while ($bytes >= 1024 && $index < count($units) - 1);
return number_format($bytes, 1, ',', '.') . ' ' . $units[$index];
}
function truncate_text(string $value, int $length): string
{
if (mb_strlen($value, 'UTF-8') <= $length) {
return $value;
}
return mb_substr($value, 0, max(0, $length - 1), 'UTF-8') . '…';
}
function clean_filename(string $name): string
{
$name = basename(str_replace('\\', '/', $name));
$name = preg_replace('/[\x00-\x1F\x7F]/u', '', $name) ?? '';
$name = trim($name);
if ($name === '' || $name === '.' || $name === '..') {
return 'datei';
}
return mb_substr($name, 0, 190, 'UTF-8');
}
/** Dateiname für Content-Disposition: ASCII-Fallback plus UTF-8-Variante. */
function content_disposition(string $filename): string
{
$filename = clean_filename($filename);
$ascii = preg_replace('/[^\x20-\x7E]/', '_', $filename) ?? 'datei';
$ascii = str_replace(['"', '\\', ';'], '_', $ascii);
return 'attachment; filename="' . $ascii . '"; filename*=UTF-8\'\'' . rawurlencode($filename);
}
function flash(string $type, string $message): void
{
$_SESSION['flash'][] = ['type' => $type, 'message' => $message];
}
function flash_secret(string $label, string $value): void
{
$_SESSION['flash'][] = ['type' => 'secret', 'label' => $label, 'value' => $value];
}
function flash_pull(): array
{
$items = $_SESSION['flash'] ?? [];
unset($_SESSION['flash']);
return is_array($items) ? $items : [];
}
function csrf_token(): string
{
if (empty($_SESSION['csrf'])) {
$_SESSION['csrf'] = bin2hex(random_bytes(32));
}
return (string) $_SESSION['csrf'];
}
function csrf_field(): string
{
return '<input type="hidden" name="_csrf" value="' . e(csrf_token()) . '">';
}
function csrf_valid(): bool
{
$sent = $_POST['_csrf'] ?? '';
return is_string($sent) && $sent !== '' && hash_equals(csrf_token(), $sent);
}
function csrf_require(): void
{
if (!csrf_valid()) {
abort_page(419, 'Die Sitzung ist abgelaufen. Bitte die Seite neu laden.');
}
}
function wants_json(): bool
{
$path = (string) parse_url((string) ($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH);
return str_starts_with($path, '/api/')
|| str_contains(strtolower((string) ($_SERVER['HTTP_ACCEPT'] ?? '')), 'application/json');
}
function json_response(mixed $data, int $status = 200): never
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
function json_input(): array
{
$raw = file_get_contents('php://input');
if (is_string($raw) && $raw !== '') {
$decoded = json_decode($raw, true);
if (is_array($decoded)) {
return $decoded;
}
}
return $_POST;
}
function render(string $view, array $data = []): string
{
$file = HUB_ROOT . '/views/' . $view . '.php';
if (!is_file($file)) {
throw new RuntimeException('View fehlt: ' . $view);
}
extract($data, EXTR_SKIP);
ob_start();
require $file;
return (string) ob_get_clean();
}
function render_page(string $view, array $data = [], string $title = 'Kür-Hub'): void
{
$content = render($view, $data);
echo render('layout', [
'title' => $title,
'content' => $content,
'user' => auth_user(),
]);
}
function abort_page(int $status, string $message): never
{
http_response_code($status);
$content = render('error', ['status' => $status, 'message' => $message]);
echo render('layout', [
'title' => 'Fehler ' . $status,
'content' => $content,
'user' => auth_user(),
]);
exit;
}
function abort_api(int $status, string $code, string $message): never
{
json_response(['error' => ['code' => $code, 'message' => $message]], $status);
}
function password_policy_error(string $password, string $username = ''): ?string
{
$length = mb_strlen($password, 'UTF-8');
if ($length < 10) {
return 'Das Passwort muss mindestens 10 Zeichen lang sein.';
}
if ($length > 200) {
return 'Das Passwort darf höchstens 200 Zeichen lang sein.';
}
if ($username !== '' && mb_strtolower($password) === mb_strtolower($username)) {
return 'Das Passwort darf nicht dem Benutzernamen entsprechen.';
}
return null;
}
function hub_log(string $message): void
{
error_log('Hub: ' . $message);
}

135
hub/install.php Normal file
View file

@ -0,0 +1,135 @@
<?php
declare(strict_types=1);
/**
* Einmal-Installer für den Rinkplanner-Hub.
*
* Wird beim Deployment mit hochgeladen, per HTTPS mit dem Installations-Token
* aufgerufen und löscht sich nach Erfolg selbst. Vorher legt er das Schema an
* und erzeugt den ersten Benutzer als Administrator.
*
* Aufruf nur per POST:
* token, admin_user, admin_password, admin_display, admin_email (optional)
*/
require __DIR__ . '/app/bootstrap.php';
function install_fail(int $status, string $message): never
{
http_response_code($status);
header('Content-Type: text/plain; charset=utf-8');
echo $message . "\n";
exit;
}
if (request_method() !== 'POST') {
install_fail(405, 'Nur POST.');
}
$expected = (string) config('app.install_token', '');
$given = (string) ($_POST['token'] ?? '');
if ($expected === '' || $given === '' || !hash_equals($expected, $given)) {
install_fail(403, 'Installations-Token ungültig.');
}
if (is_file(storage_path('.installed'))) {
install_fail(409, 'Bereits installiert. Zum Neuaufsetzen storage/.installed entfernen.');
}
$adminUser = strtolower(trim((string) ($_POST['admin_user'] ?? '')));
$adminPassword = (string) ($_POST['admin_password'] ?? '');
$adminDisplay = trim((string) ($_POST['admin_display'] ?? ''));
$adminEmail = trim((string) ($_POST['admin_email'] ?? ''));
if (preg_match('/^[a-z0-9](?:[a-z0-9._-]{1,30}[a-z0-9])$/', $adminUser) !== 1) {
install_fail(422, 'Admin-Benutzername ungültig (3–32 Zeichen, Kleinbuchstaben/Ziffern/._-).');
}
if (mb_strlen($adminPassword, 'UTF-8') < 10) {
install_fail(422, 'Admin-Passwort muss mindestens 10 Zeichen haben.');
}
if ($adminDisplay === '') {
$adminDisplay = $adminUser;
}
if ($adminEmail !== '' && filter_var($adminEmail, FILTER_VALIDATE_EMAIL) === false) {
install_fail(422, 'Admin-E-Mail ungültig.');
}
$pdo = db();
$hasUsers = false;
try {
$hasUsers = (int) $pdo->query('SELECT COUNT(*) FROM users')->fetchColumn() > 0;
} catch (PDOException) {
$hasUsers = false;
}
if ($hasUsers) {
install_fail(409, 'Es gibt bereits Benutzer. Installation abgebrochen.');
}
$schemaFile = __DIR__ . '/sql/schema.sql';
if (!is_file($schemaFile)) {
install_fail(500, 'schema.sql fehlt.');
}
try {
$sql = (string) file_get_contents($schemaFile);
$sql = preg_replace('/^\s*--.*$/m', '', $sql) ?? $sql;
$statements = preg_split('/;\s*(?:\r?\n|$)/', $sql) ?: [];
foreach ($statements as $statement) {
$statement = trim($statement);
if ($statement === '') {
continue;
}
try {
$pdo->exec($statement);
} catch (PDOException $error) {
// Ein erneuter Lauf darf an einer bereits vorhandenen
// Fremdschlüssel-Bedingung nicht scheitern.
$code = (int) ($error->errorInfo[1] ?? 0);
if (str_contains($statement, 'ADD CONSTRAINT')
&& in_array($code, [121, 1005, 1061, 1826], true)
) {
continue;
}
throw $error;
}
}
$stmt = $pdo->prepare(
'INSERT INTO users
(username, display_name, email, password_hash, role, status,
must_change_password, auth_epoch, created_at, password_changed_at)
VALUES (?, ?, ?, ?, ?, ?, 0, 1, ?, ?)'
);
$now = utc_now();
$stmt->execute([
$adminUser,
mb_substr($adminDisplay, 0, 64, 'UTF-8'),
$adminEmail !== '' ? $adminEmail : null,
hash_password($adminPassword),
'admin',
'active',
$now,
$now,
]);
$adminId = (int) $pdo->lastInsertId();
audit('install.admin', 'user', $adminId, $adminUser, $adminId);
foreach (['', 'logs', 'uploads'] as $sub) {
$dir = storage_path($sub);
if (!is_dir($dir)) {
@mkdir($dir, 0770, true);
}
}
$guard = storage_path('.htaccess');
if (!is_file($guard)) {
@file_put_contents($guard, "Require all denied\n");
}
@file_put_contents(storage_path('.installed'), utc_now() . "\n");
} catch (Throwable $error) {
install_fail(500, 'Installation fehlgeschlagen: ' . $error->getMessage());
}
@unlink(__FILE__);
header('Content-Type: text/plain; charset=utf-8');
echo "installiert\n";
echo "admin=" . $adminUser . "\n";

2
hub/sql/.htaccess Normal file
View file

@ -0,0 +1,2 @@
Require all denied
Options -Indexes

172
hub/sql/schema.sql Normal file
View file

@ -0,0 +1,172 @@
-- Rinkplanner-Hub – Datenbankschema (MariaDB 10.11, utf8mb4)
--
-- Wird vom Installer (install.php) angewendet. Alle Zeitstempel sind UTC.
-- Änderungen am Schema brauchen eine neue Migrationsnummer in schema_migrations.
CREATE TABLE IF NOT EXISTS schema_migrations (
version INT UNSIGNED NOT NULL,
applied_at DATETIME NOT NULL,
PRIMARY KEY (version)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS users (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(32) NOT NULL,
display_name VARCHAR(64) NOT NULL,
email VARCHAR(190) NULL,
password_hash VARCHAR(255) NOT NULL,
role ENUM('admin', 'user') NOT NULL DEFAULT 'user',
status ENUM('active', 'disabled') NOT NULL DEFAULT 'active',
must_change_password TINYINT(1) NOT NULL DEFAULT 0,
auth_epoch INT UNSIGNED NOT NULL DEFAULT 1,
created_at DATETIME NOT NULL,
last_login_at DATETIME NULL,
password_changed_at DATETIME NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_users_username (username),
UNIQUE KEY uq_users_email (email),
KEY idx_users_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS invites (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
code_hash CHAR(64) NOT NULL,
note VARCHAR(190) NULL,
email VARCHAR(190) NULL,
created_by BIGINT UNSIGNED NULL,
created_at DATETIME NOT NULL,
expires_at DATETIME NULL,
used_by BIGINT UNSIGNED NULL,
used_at DATETIME NULL,
revoked_at DATETIME NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_invites_code (code_hash),
KEY idx_invites_created (created_at),
CONSTRAINT fk_invites_creator FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL,
CONSTRAINT fk_invites_used_by FOREIGN KEY (used_by) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS routines (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
owner_id BIGINT UNSIGNED NOT NULL,
title VARCHAR(190) NOT NULL,
skater_name VARCHAR(190) NULL,
category VARCHAR(40) NULL,
music_title VARCHAR(190) NULL,
music_artist VARCHAR(190) NULL,
description TEXT NULL,
status ENUM('published', 'hidden') NOT NULL DEFAULT 'published',
current_revision_id BIGINT UNSIGNED NULL,
download_count INT UNSIGNED NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
PRIMARY KEY (id),
KEY idx_routines_list (status, updated_at),
KEY idx_routines_owner (owner_id, updated_at),
CONSTRAINT fk_routines_owner FOREIGN KEY (owner_id) REFERENCES users (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS routine_revisions (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
routine_id BIGINT UNSIGNED NOT NULL,
revision INT UNSIGNED NOT NULL,
uploaded_by BIGINT UNSIGNED NOT NULL,
routine_original_name VARCHAR(190) NOT NULL,
routine_path VARCHAR(255) NOT NULL,
routine_bytes INT UNSIGNED NOT NULL,
routine_sha256 CHAR(64) NOT NULL,
file_routine_id CHAR(36) NULL,
audio_original_name VARCHAR(190) NULL,
audio_path VARCHAR(255) NULL,
audio_bytes INT UNSIGNED NULL,
audio_sha256 CHAR(64) NULL,
audio_mime VARCHAR(100) NULL,
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_revision_number (routine_id, revision),
KEY idx_revisions_uploader (uploaded_by),
CONSTRAINT fk_revisions_routine FOREIGN KEY (routine_id) REFERENCES routines (id) ON DELETE CASCADE,
CONSTRAINT fk_revisions_uploader FOREIGN KEY (uploaded_by) REFERENCES users (id) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
ALTER TABLE routines
ADD CONSTRAINT fk_routines_current_revision
FOREIGN KEY (current_revision_id) REFERENCES routine_revisions (id) ON DELETE SET NULL;
CREATE TABLE IF NOT EXISTS downloads (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
routine_id BIGINT UNSIGNED NOT NULL,
revision_id BIGINT UNSIGNED NULL,
user_id BIGINT UNSIGNED NULL,
kind ENUM('routine', 'audio') NOT NULL DEFAULT 'routine',
ip VARCHAR(45) NULL,
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
KEY idx_downloads_routine (routine_id, created_at),
KEY idx_downloads_user (user_id, created_at),
CONSTRAINT fk_downloads_routine FOREIGN KEY (routine_id) REFERENCES routines (id) ON DELETE CASCADE,
CONSTRAINT fk_downloads_revision FOREIGN KEY (revision_id) REFERENCES routine_revisions (id) ON DELETE SET NULL,
CONSTRAINT fk_downloads_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS api_tokens (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id BIGINT UNSIGNED NOT NULL,
name VARCHAR(64) NOT NULL,
prefix CHAR(12) NOT NULL,
token_hash CHAR(64) NOT NULL,
created_at DATETIME NOT NULL,
last_used_at DATETIME NULL,
expires_at DATETIME NULL,
revoked_at DATETIME NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_tokens_hash (token_hash),
KEY idx_tokens_user (user_id, created_at),
CONSTRAINT fk_tokens_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS remember_tokens (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id BIGINT UNSIGNED NOT NULL,
selector CHAR(24) NOT NULL,
validator_hash CHAR(64) NOT NULL,
created_at DATETIME NOT NULL,
last_used_at DATETIME NULL,
expires_at DATETIME NOT NULL,
user_agent VARCHAR(255) NULL,
ip VARCHAR(45) NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_remember_selector (selector),
KEY idx_remember_user (user_id, expires_at),
CONSTRAINT fk_remember_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS login_attempts (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(190) NOT NULL,
ip VARCHAR(45) NOT NULL,
success TINYINT(1) NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
KEY idx_attempts_ip (ip, created_at),
KEY idx_attempts_username (username, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS audit_log (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
actor_id BIGINT UNSIGNED NULL,
action VARCHAR(64) NOT NULL,
subject_type VARCHAR(32) NULL,
subject_id BIGINT UNSIGNED NULL,
detail VARCHAR(255) NULL,
ip VARCHAR(45) NULL,
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
KEY idx_audit_created (created_at),
KEY idx_audit_actor (actor_id, created_at),
CONSTRAINT fk_audit_actor FOREIGN KEY (actor_id) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO schema_migrations (version, applied_at)
VALUES (1, UTC_TIMESTAMP())
ON DUPLICATE KEY UPDATE version = version;

2
hub/views/.htaccess Normal file
View file

@ -0,0 +1,2 @@
Require all denied
Options -Indexes

7
hub/views/_admin_nav.php Normal file
View file

@ -0,0 +1,7 @@
<?php /** @var string $active */ ?>
<nav class="admin-tabs">
<a class="<?= $active === 'invites' ? 'active' : '' ?>" href="<?= e(url('/admin/invites')) ?>">Einladungen</a>
<a class="<?= $active === 'users' ? 'active' : '' ?>" href="<?= e(url('/admin/users')) ?>">Benutzer</a>
<a class="<?= $active === 'routines' ? 'active' : '' ?>" href="<?= e(url('/admin/routines')) ?>">Küren</a>
<a class="<?= $active === 'audit' ? 'active' : '' ?>" href="<?= e(url('/admin/audit')) ?>">Audit-Log</a>
</nav>

77
hub/views/account.php Normal file
View file

@ -0,0 +1,77 @@
<?php /** @var array $tokens */ ?>
<?php $user = auth_user(); ?>
<section class="page-head">
<div>
<h1>Konto</h1>
<p class="muted"><?= e($user['username']) ?> · <?= e($user['role'] === 'admin' ? 'Administrator' : 'Beta-Nutzer') ?></p>
</div>
</section>
<?php if ($user['must_change_password'] === 1): ?>
<div class="flash flash-info">Bitte ein neues Passwort setzen, bevor du den Hub weiter nutzt.</div>
<?php endif; ?>
<div class="columns">
<section class="panel">
<h2>Passwort ändern</h2>
<form method="post" action="<?= e(url('/account/password')) ?>" class="stack">
<?= csrf_field() ?>
<label>
Aktuelles Passwort
<input type="password" name="current_password" autocomplete="current-password" required>
</label>
<label>
Neues Passwort
<input type="password" name="password" autocomplete="new-password" required>
<span class="hint">Mindestens 10 Zeichen.</span>
</label>
<label>
Neues Passwort wiederholen
<input type="password" name="password_repeat" autocomplete="new-password" required>
</label>
<button class="primary" type="submit">Passwort speichern</button>
</form>
</section>
<section class="panel">
<h2>API-Tokens</h2>
<p class="muted">Für die Godot-App. Ein Token ersetzt Benutzername und Passwort im Client und lässt sich jederzeit widerrufen.</p>
<form method="post" action="<?= e(url('/account/tokens')) ?>" class="inline-form">
<?= csrf_field() ?>
<input type="text" name="name" maxlength="64" placeholder="Name, z. B. Büro-PC" required>
<button type="submit">Token erzeugen</button>
</form>
<?php if ($tokens): ?>
<div class="table-wrap">
<table class="list compact">
<thead>
<tr><th>Name</th><th>Prefix</th><th>Erstellt</th><th>Zuletzt</th><th>Status</th><th></th></tr>
</thead>
<tbody>
<?php foreach ($tokens as $token): ?>
<tr>
<td><?= e($token['name']) ?></td>
<td><code><?= e($token['prefix']) ?>…</code></td>
<td><?= e(fmt_dt($token['created_at'])) ?></td>
<td><?= e(fmt_dt($token['last_used_at'])) ?></td>
<td><?= $token['revoked_at'] !== null ? 'widerrufen' : 'aktiv' ?></td>
<td>
<?php if ($token['revoked_at'] === null): ?>
<form class="inline" method="post" action="<?= e(url('/account/tokens/revoke')) ?>">
<?= csrf_field() ?>
<input type="hidden" name="token_id" value="<?= (int) $token['id'] ?>">
<button class="link-button danger" type="submit">widerrufen</button>
</form>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php else: ?>
<p class="muted small">Noch kein Token erzeugt.</p>
<?php endif; ?>
</section>
</div>

34
hub/views/admin_audit.php Normal file
View file

@ -0,0 +1,34 @@
<?php /** @var array $entries */ ?>
<div class="page-head">
<div>
<h1>Verwaltung</h1>
<p class="muted">Die letzten <?= count($entries) ?> Ereignisse.</p>
</div>
</div>
<?php $active = 'audit'; require HUB_ROOT . '/views/_admin_nav.php'; ?>
<section class="panel">
<?php if (!$entries): ?>
<p class="muted">Noch keine Einträge.</p>
<?php else: ?>
<div class="table-wrap">
<table class="list compact">
<thead>
<tr><th>Zeit</th><th>Akteur</th><th>Aktion</th><th>Objekt</th><th>Detail</th><th>IP</th></tr>
</thead>
<tbody>
<?php foreach ($entries as $entry): ?>
<tr>
<td><?= e(fmt_dt($entry['created_at'])) ?></td>
<td><?= e($entry['actor_name'] ?: '–') ?></td>
<td><code><?= e($entry['action']) ?></code></td>
<td><?= e(trim(($entry['subject_type'] ?? '') . ' ' . ($entry['subject_id'] ?? ''))) ?: '–' ?></td>
<td><?= e($entry['detail'] ?: '–') ?></td>
<td><?= e($entry['ip'] ?: '–') ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</section>

View file

@ -0,0 +1,83 @@
<?php /** @var array $invites */ ?>
<div class="page-head">
<div>
<h1>Verwaltung</h1>
<p class="muted">Einladungen für die geschlossene Beta.</p>
</div>
</div>
<?php $active = 'invites'; require HUB_ROOT . '/views/_admin_nav.php'; ?>
<section class="panel">
<h2>Neue Einladung</h2>
<p class="muted">Der Code wird nach dem Anlegen genau einmal angezeigt. Er gilt für ein Konto.</p>
<form method="post" action="<?= e(url('/admin/invites')) ?>" class="stack">
<?= csrf_field() ?>
<div class="grid-3">
<label>
Notiz (intern)
<input type="text" name="note" maxlength="190" placeholder="z. B. Verein Nord">
</label>
<label>
E-Mail binden (optional)
<input type="email" name="email" maxlength="190">
<span class="hint">Nur diese Adresse kann den Code nutzen.</span>
</label>
<label>
Gültig (Tage)
<input type="number" name="expires_days" min="0" max="365" value="30">
<span class="hint">0 = unbegrenzt.</span>
</label>
</div>
<button class="primary" type="submit">Einladung erzeugen</button>
</form>
</section>
<section class="panel">
<h2>Einladungen</h2>
<?php if (!$invites): ?>
<p class="muted">Noch keine Einladungen.</p>
<?php else: ?>
<div class="table-wrap">
<table class="list compact">
<thead>
<tr><th>Erstellt</th><th>Notiz</th><th>E-Mail</th><th>Status</th><th>Von / an</th><th>Gültig bis</th><th></th></tr>
</thead>
<tbody>
<?php foreach ($invites as $invite): ?>
<?php
$status = invite_status($invite);
$statusClass = [
'offen' => 'open',
'eingelöst' => 'used',
'abgelaufen' => 'expired',
'widerrufen' => 'revoked',
][$status] ?? 'expired';
?>
<tr>
<td><?= e(fmt_dt($invite['created_at'])) ?></td>
<td><?= e($invite['note'] ?: '–') ?></td>
<td><?= e($invite['email'] ?: '–') ?></td>
<td><span class="status status-<?= e($statusClass) ?>"><?= e($status) ?></span></td>
<td>
<?= e($invite['creator_name'] ?: '–') ?>
<?php if (!empty($invite['used_name'])): ?>
<span class="muted">→ <?= e($invite['used_name']) ?></span>
<?php endif; ?>
</td>
<td><?= e(fmt_dt($invite['expires_at'])) ?></td>
<td>
<?php if ($status === 'offen'): ?>
<form class="inline" method="post" action="<?= e(url('/admin/invites/revoke')) ?>">
<?= csrf_field() ?>
<input type="hidden" name="invite_id" value="<?= (int) $invite['id'] ?>">
<button class="link-button danger" type="submit">widerrufen</button>
</form>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</section>

View file

@ -0,0 +1,86 @@
<?php /** @var array $items */ ?>
<?php /** @var int $total */ ?>
<?php /** @var int $page */ ?>
<?php /** @var int $pages */ ?>
<?php /** @var string $query */ ?>
<?php
$linkFor = static function (int $targetPage) use ($query): string {
$params = [];
if ($query !== '') {
$params['q'] = $query;
}
if ($targetPage > 1) {
$params['page'] = $targetPage;
}
return url('/admin/routines') . ($params ? '?' . http_build_query($params) : '');
};
?>
<div class="page-head">
<div>
<h1>Verwaltung</h1>
<p class="muted"><?= (int) $total ?> Küren insgesamt, auch versteckte.</p>
</div>
</div>
<?php $active = 'routines'; require HUB_ROOT . '/views/_admin_nav.php'; ?>
<div class="toolbar">
<form method="get" action="<?= e(url('/admin/routines')) ?>" class="search">
<input type="search" name="q" value="<?= e_attr($query) ?>" placeholder="Titel, Skater, Benutzer …">
<button type="submit">Suchen</button>
</form>
</div>
<?php if (!$items): ?>
<div class="empty"><p>Keine Küren gefunden.</p></div>
<?php else: ?>
<div class="table-wrap">
<table class="list compact">
<thead>
<tr><th>Titel</th><th>Von</th><th>Status</th><th>Rev.</th><th>Aktualisiert</th><th>Downloads</th><th>Aktionen</th></tr>
</thead>
<tbody>
<?php foreach ($items as $item): ?>
<tr>
<td><a href="<?= e(url('/routines/' . (int) $item['id'])) ?>"><?= e($item['title']) ?></a></td>
<td><?= e($item['owner_username']) ?></td>
<td><span class="status status-<?= $item['status'] === 'published' ? 'open' : 'expired' ?>"><?= e($item['status']) ?></span></td>
<td><?= $item['revision'] !== null ? (int) $item['revision'] : '–' ?></td>
<td><?= e(fmt_dt($item['updated_at'])) ?></td>
<td><?= (int) $item['download_count'] ?></td>
<td>
<div class="row-actions">
<form class="inline" method="post" action="<?= e(url('/admin/routines/action')) ?>">
<?= csrf_field() ?>
<input type="hidden" name="routine_id" value="<?= (int) $item['id'] ?>">
<input type="hidden" name="action" value="<?= $item['status'] === 'published' ? 'hide' : 'publish' ?>">
<button class="link-button" type="submit"><?= $item['status'] === 'published' ? 'verstecken' : 'veröffentlichen' ?></button>
</form>
<details class="danger-zone">
<summary>löschen</summary>
<form method="post" action="<?= e(url('/admin/routines/action')) ?>" class="stack-tight">
<?= csrf_field() ?>
<input type="hidden" name="routine_id" value="<?= (int) $item['id'] ?>">
<input type="hidden" name="action" value="delete">
<label class="check small">
<input type="checkbox" name="confirm" value="1" required>
endgültig löschen
</label>
<button class="link-button danger" type="submit">Löschen bestätigen</button>
</form>
</details>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php if ($pages > 1): ?>
<nav class="pagination">
<?php if ($page > 1): ?><a href="<?= e($linkFor($page - 1)) ?>">← Zurück</a><?php endif; ?>
<span>Seite <?= (int) $page ?> von <?= (int) $pages ?></span>
<?php if ($page < $pages): ?><a href="<?= e($linkFor($page + 1)) ?>">Weiter →</a><?php endif; ?>
</nav>
<?php endif; ?>
<?php endif; ?>

84
hub/views/admin_users.php Normal file
View file

@ -0,0 +1,84 @@
<?php /** @var array $users */ ?>
<?php $me = auth_user(); ?>
<div class="page-head">
<div>
<h1>Verwaltung</h1>
<p class="muted">Beta-Konten verwalten.</p>
</div>
</div>
<?php $active = 'users'; require HUB_ROOT . '/views/_admin_nav.php'; ?>
<section class="panel">
<h2>Benutzer</h2>
<div class="table-wrap">
<table class="list compact">
<thead>
<tr><th>Benutzer</th><th>Rolle</th><th>Status</th><th>Küren</th><th>Registriert</th><th>Letzte Anmeldung</th><th>Aktionen</th></tr>
</thead>
<tbody>
<?php foreach ($users as $user): ?>
<tr>
<td>
<strong><?= e($user['display_name']) ?></strong>
<span class="muted">@<?= e($user['username']) ?></span>
<?php if (!empty($user['email'])): ?>
<div class="muted small"><?= e($user['email']) ?></div>
<?php endif; ?>
</td>
<td><?= $user['role'] === 'admin' ? 'Admin' : 'Nutzer' ?></td>
<td>
<span class="status status-<?= $user['status'] === 'active' ? 'open' : 'expired' ?>">
<?= $user['status'] === 'active' ? 'aktiv' : 'gesperrt' ?>
</span>
</td>
<td><?= (int) $user['routine_count'] ?></td>
<td><?= e(fmt_dt($user['created_at'])) ?></td>
<td><?= e(fmt_dt($user['last_login_at'])) ?></td>
<td>
<?php if ((int) $user['id'] === (int) $me['id']): ?>
<span class="muted small">eigenes Konto</span>
<?php else: ?>
<div class="row-actions">
<?php if ($user['status'] === 'active'): ?>
<form class="inline" method="post" action="<?= e(url('/admin/users/action')) ?>">
<?= csrf_field() ?>
<input type="hidden" name="user_id" value="<?= (int) $user['id'] ?>">
<input type="hidden" name="action" value="disable">
<button class="link-button danger" type="submit">sperren</button>
</form>
<?php else: ?>
<form class="inline" method="post" action="<?= e(url('/admin/users/action')) ?>">
<?= csrf_field() ?>
<input type="hidden" name="user_id" value="<?= (int) $user['id'] ?>">
<input type="hidden" name="action" value="enable">
<button class="link-button" type="submit">entsperren</button>
</form>
<?php endif; ?>
<form class="inline" method="post" action="<?= e(url('/admin/users/action')) ?>">
<?= csrf_field() ?>
<input type="hidden" name="user_id" value="<?= (int) $user['id'] ?>">
<input type="hidden" name="action" value="reset">
<button class="link-button" type="submit">Passwort zurücksetzen</button>
</form>
<details class="danger-zone">
<summary>löschen</summary>
<form method="post" action="<?= e(url('/admin/users/action')) ?>" class="stack-tight">
<?= csrf_field() ?>
<input type="hidden" name="user_id" value="<?= (int) $user['id'] ?>">
<input type="hidden" name="action" value="delete">
<label class="check small">
<input type="checkbox" name="confirm" value="1" required>
mit allen Küren löschen
</label>
<button class="link-button danger" type="submit">Löschen bestätigen</button>
</form>
</details>
</div>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</section>

110
hub/views/dashboard.php Normal file
View file

@ -0,0 +1,110 @@
<?php /** @var array $items */ ?>
<?php /** @var int $total */ ?>
<?php /** @var int $page */ ?>
<?php /** @var int $pages */ ?>
<?php /** @var string $query */ ?>
<?php /** @var bool $mine */ ?>
<?php
$linkFor = static function (int $targetPage) use ($query, $mine): string {
$params = [];
if ($query !== '') {
$params['q'] = $query;
}
if ($mine) {
$params['mine'] = '1';
}
if ($targetPage > 1) {
$params['page'] = $targetPage;
}
return url('/') . ($params ? '?' . http_build_query($params) : '');
};
?>
<div class="page-head">
<div>
<h1>Küren</h1>
<p class="muted"><?= (int) $total ?> <?= $total === 1 ? 'Kür' : 'Küren' ?> im Hub<?= $mine ? ' (nur deine)' : '' ?>.</p>
</div>
<a class="button primary" href="<?= e(url('/upload')) ?>">Kür hochladen</a>
</div>
<div class="toolbar">
<form method="get" action="<?= e(url('/')) ?>" class="search">
<input type="search" name="q" value="<?= e_attr($query) ?>" placeholder="Titel, Skater, Musik, Benutzer …">
<?php if ($mine): ?><input type="hidden" name="mine" value="1"><?php endif; ?>
<button type="submit">Suchen</button>
</form>
<div class="tabs">
<a class="<?= $mine ? '' : 'active' ?>" href="<?= e(url('/')) ?>">Alle</a>
<a class="<?= $mine ? 'active' : '' ?>" href="<?= e(url('/?mine=1')) ?>">Meine Küren</a>
</div>
</div>
<?php if (!$items): ?>
<div class="empty">
<p>Keine Küren gefunden.</p>
<?php if ($query !== ''): ?>
<p class="muted">Suche zurücksetzen oder <a href="<?= e(url('/upload')) ?>">selbst eine Kür hochladen</a>.</p>
<?php else: ?>
<p class="muted">Der Hub ist noch leer. <a href="<?= e(url('/upload')) ?>">Erste Kür hochladen</a>.</p>
<?php endif; ?>
</div>
<?php else: ?>
<div class="table-wrap">
<table class="list">
<thead>
<tr>
<th>Titel</th>
<th>Skater</th>
<th>Musik</th>
<th>Rev.</th>
<th>Größe</th>
<th>Aktualisiert</th>
<th>Von</th>
</tr>
</thead>
<tbody>
<?php foreach ($items as $item): ?>
<tr>
<td>
<a class="title-link" href="<?= e(url('/routines/' . (int) $item['id'])) ?>"><?= e($item['title']) ?></a>
<?php if ($item['status'] !== 'published'): ?>
<span class="badge">versteckt</span>
<?php endif; ?>
<?php if (!empty($item['category'])): ?>
<span class="badge badge-soft"><?= e($item['category']) ?></span>
<?php endif; ?>
</td>
<td><?= e($item['skater_name'] ?? '–') ?></td>
<td>
<?= e($item['music_title'] ?: ($item['audio_original_name'] ?? '–')) ?>
<?php if (!empty($item['music_artist'])): ?>
<span class="muted">· <?= e($item['music_artist']) ?></span>
<?php endif; ?>
</td>
<td><?= $item['revision'] !== null ? (int) $item['revision'] : '–' ?></td>
<td>
<?= e(human_bytes((int) ($item['routine_bytes'] ?? 0))) ?>
<?php if (!empty($item['audio_bytes'])): ?>
<span class="muted">+ <?= e(human_bytes((int) $item['audio_bytes'])) ?></span>
<?php endif; ?>
</td>
<td><?= e(fmt_dt($item['updated_at'])) ?></td>
<td><?= e($item['owner_display_name'] ?: $item['owner_username']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php if ($pages > 1): ?>
<nav class="pagination">
<?php if ($page > 1): ?>
<a href="<?= e($linkFor($page - 1)) ?>">← Zurück</a>
<?php endif; ?>
<span>Seite <?= (int) $page ?> von <?= (int) $pages ?></span>
<?php if ($page < $pages): ?>
<a href="<?= e($linkFor($page + 1)) ?>">Weiter →</a>
<?php endif; ?>
</nav>
<?php endif; ?>
<?php endif; ?>

7
hub/views/error.php Normal file
View file

@ -0,0 +1,7 @@
<?php /** @var int $status */ ?>
<?php /** @var string $message */ ?>
<section class="auth-card">
<p class="eyebrow">Fehler <?= (int) $status ?></p>
<h1><?= e($message) ?></h1>
<p class="muted">Zurück zur <a href="<?= e(url('/')) ?>">Küren-Übersicht</a>.</p>
</section>

65
hub/views/layout.php Normal file
View file

@ -0,0 +1,65 @@
<?php
/** @var string $title */
/** @var string $content */
/** @var array|null $user */
$flashes = flash_pull();
?>
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= e($title) ?> · Rinkplanner-Hub</title>
<link rel="stylesheet" href="<?= e(url('/assets/hub.css')) ?>">
</head>
<body>
<header class="topbar">
<a class="brand" href="<?= e(url('/')) ?>">
<span class="brand-mark">R</span>
<span>Rinkplanner <strong>Hub</strong></span>
</a>
<nav class="nav">
<?php if ($user !== null): ?>
<a href="<?= e(url('/')) ?>">Küren</a>
<a href="<?= e(url('/upload')) ?>">Hochladen</a>
<a href="<?= e(url('/account')) ?>"><?= e($user['display_name']) ?></a>
<?php if (($user['role'] ?? '') === 'admin'): ?>
<a class="nav-admin" href="<?= e(url('/admin/invites')) ?>">Verwaltung</a>
<?php endif; ?>
<form class="inline" method="post" action="<?= e(url('/logout')) ?>">
<?= csrf_field() ?>
<button class="link-button" type="submit">Abmelden</button>
</form>
<?php else: ?>
<a href="<?= e(url('/login')) ?>">Anmelden</a>
<?php endif; ?>
</nav>
</header>
<main class="page">
<?php if ($flashes): ?>
<div class="flashes">
<?php foreach ($flashes as $flash): ?>
<?php if (($flash['type'] ?? '') === 'secret'): ?>
<div class="flash flash-secret">
<strong><?= e($flash['label'] ?? 'Geheimnis') ?></strong>
<code><?= e($flash['value'] ?? '') ?></code>
</div>
<?php else: ?>
<div class="flash flash-<?= e($flash['type'] ?? 'info') ?>">
<?= e($flash['message'] ?? '') ?>
</div>
<?php endif; ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?= $content ?>
</main>
<footer class="footer">
<span>Geschlossene Beta · Rinkplanner-Hub</span>
<a href="https://rinkplanner.programmschmiede.de/">Zur Rinkplanner-Seite</a>
</footer>
</body>
</html>

31
hub/views/login.php Normal file
View file

@ -0,0 +1,31 @@
<?php /** @var string $error */ ?>
<?php /** @var string $login */ ?>
<?php /** @var string $next */ ?>
<section class="auth-card">
<h1>Anmelden</h1>
<p class="muted">Der Kür-Hub ist in einer geschlossenen Beta. Zugang gibt es per Einladungscode.</p>
<?php if ($error !== ''): ?>
<div class="flash flash-error"><?= e($error) ?></div>
<?php endif; ?>
<form method="post" action="<?= e(url('/login')) ?>" class="stack">
<?= csrf_field() ?>
<input type="hidden" name="next" value="<?= e_attr($next) ?>">
<label>
Benutzername oder E-Mail
<input type="text" name="login" value="<?= e_attr($login) ?>" autocomplete="username" required autofocus>
</label>
<label>
Passwort
<input type="password" name="password" autocomplete="current-password" required>
</label>
<label class="check">
<input type="checkbox" name="remember" value="1">
Angemeldet bleiben (30 Tage)
</label>
<button class="primary" type="submit">Anmelden</button>
</form>
<p class="muted small">Noch keinen Zugang? Ein Beta-Code kommt von der Hub-Administration.</p>
</section>

62
hub/views/register.php Normal file
View file

@ -0,0 +1,62 @@
<?php /** @var array|null $invite */ ?>
<?php /** @var string $code */ ?>
<?php /** @var array $errors */ ?>
<?php /** @var array $input */ ?>
<section class="auth-card wide">
<h1>Beta-Zugang einlösen</h1>
<p class="muted">Ein Einladungscode legt genau ein Konto an. Der Code verliert danach seine Gültigkeit.</p>
<?php if ($errors): ?>
<div class="flash flash-error">
<ul class="plain">
<?php foreach ($errors as $error): ?>
<li><?= e($error) ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="post" action="<?= e(url('/register')) ?>" class="stack">
<?= csrf_field() ?>
<label>
Einladungscode
<input type="text" name="code" value="<?= e_attr($code) ?>" placeholder="RHUB-XXXX-XXXX-XXXX-XXXX" required>
</label>
<div class="grid-2">
<label>
Benutzername
<input type="text" name="username" value="<?= e_attr($input['username']) ?>" autocomplete="username" required>
<span class="hint">3–32 Zeichen, nur Kleinbuchstaben, Ziffern, Punkt, Bindestrich, Unterstrich.</span>
</label>
<label>
Anzeigename
<input type="text" name="display_name" value="<?= e_attr($input['display_name']) ?>" maxlength="64">
</label>
</div>
<label>
E-Mail (optional)
<input type="email" name="email" value="<?= e_attr($input['email']) ?>" autocomplete="email"<?= $invite !== null && !empty($invite['email']) ? ' readonly' : '' ?>>
<?php if ($invite !== null && !empty($invite['email'])): ?>
<span class="hint">Diese Einladung ist an <?= e($invite['email']) ?> gebunden.</span>
<?php endif; ?>
</label>
<div class="grid-2">
<label>
Passwort
<input type="password" name="password" autocomplete="new-password" required>
<span class="hint">Mindestens 10 Zeichen.</span>
</label>
<label>
Passwort wiederholen
<input type="password" name="password_repeat" autocomplete="new-password" required>
</label>
</div>
<label class="check">
<input type="checkbox" name="rights" value="1" required>
Ich akzeptiere die Beta-Regeln und teile keine Inhalte, an denen ich keine Rechte habe.
</label>
<button class="primary" type="submit">Konto anlegen</button>
</form>
<p class="muted small">Schon ein Konto? <a href="<?= e(url('/login')) ?>">Anmelden</a></p>
</section>

93
hub/views/routine.php Normal file
View file

@ -0,0 +1,93 @@
<?php /** @var array $routine */ ?>
<?php /** @var bool $can_edit */ ?>
<?php /** @var bool $is_admin */ ?>
<?php $audioName = $routine['audio_original_name'] ?? ''; ?>
<article class="detail">
<div class="page-head">
<div>
<p class="eyebrow"><a href="<?= e(url('/')) ?>">Küren</a> / Kür</p>
<h1><?= e($routine['title']) ?></h1>
<p class="muted">
<?= e($routine['owner_display_name'] ?: $routine['owner_username']) ?>
· Revision <?= (int) ($routine['revision'] ?? 0) ?>
· <?= e(fmt_dt($routine['updated_at'])) ?>
<?php if ($routine['status'] !== 'published'): ?>
· <span class="badge">versteckt</span>
<?php endif; ?>
</p>
</div>
<div class="actions">
<?php if (!empty($routine['routine_path'])): ?>
<a class="button primary" href="<?= e(url('/routines/' . (int) $routine['id'] . '/download')) ?>">Kür herunterladen</a>
<?php endif; ?>
<?php if ($audioName !== ''): ?>
<a class="button" href="<?= e(url('/routines/' . (int) $routine['id'] . '/audio')) ?>">Musik herunterladen</a>
<?php endif; ?>
</div>
</div>
<?php if ($can_edit): ?>
<div class="owner-bar">
<span class="muted">Du kannst diese Kür verwalten.</span>
<a class="button small" href="<?= e(url('/routines/' . (int) $routine['id'] . '/revise')) ?>">Neue Revision hochladen</a>
<?php if ($routine['status'] === 'published'): ?>
<form class="inline" method="post" action="<?= e(url('/routines/' . (int) $routine['id'] . '/hide')) ?>">
<?= csrf_field() ?>
<button class="button small danger-ghost" type="submit">Aus dem Hub nehmen</button>
</form>
<?php else: ?>
<form class="inline" method="post" action="<?= e(url('/routines/' . (int) $routine['id'] . '/publish')) ?>">
<?= csrf_field() ?>
<button class="button small" type="submit">Wieder veröffentlichen</button>
</form>
<?php endif; ?>
<?php if ($is_admin): ?>
<a class="button small danger-ghost" href="<?= e(url('/admin/routines?q=' . rawurlencode($routine['title']))) ?>">In der Verwaltung öffnen</a>
<?php endif; ?>
</div>
<?php endif; ?>
<?php if (!empty($routine['description'])): ?>
<section class="panel">
<h2>Beschreibung</h2>
<p class="preline"><?= e($routine['description']) ?></p>
</section>
<?php endif; ?>
<?php if ($audioName !== ''): ?>
<section class="panel">
<h2>Musik</h2>
<audio controls preload="none" src="<?= e(url('/routines/' . (int) $routine['id'] . '/audio')) ?>"></audio>
<p class="muted small"><?= e($audioName) ?> · <?= e(human_bytes((int) ($routine['audio_bytes'] ?? 0))) ?></p>
</section>
<?php endif; ?>
<section class="panel">
<h2>Details</h2>
<dl class="facts">
<div><dt>Skater</dt><dd><?= e($routine['skater_name'] ?: '–') ?></dd></div>
<div><dt>Kategorie</dt><dd><?= e($routine['category'] ?: '–') ?></dd></div>
<div><dt>Musiktitel</dt><dd><?= e($routine['music_title'] ?: '–') ?></dd></div>
<div><dt>Musik</dt><dd><?= e($routine['music_artist'] ?: '–') ?></dd></div>
<div><dt>Kür-Datei</dt><dd><?= e($routine['routine_original_name'] ?? '–') ?> · <?= e(human_bytes((int) ($routine['routine_bytes'] ?? 0))) ?></dd></div>
<div><dt>Audio-Datei</dt><dd><?= e($audioName !== '' ? $audioName . ' · ' . human_bytes((int) ($routine['audio_bytes'] ?? 0)) : '–') ?></dd></div>
<div><dt>Downloads</dt><dd><?= (int) $routine['download_count'] ?></dd></div>
<div><dt>Eingestellt</dt><dd><?= e(fmt_dt($routine['created_at'])) ?></dd></div>
</dl>
</section>
<section class="panel">
<h2>Prüfsummen</h2>
<div class="hash">
<span>Kür</span>
<code><?= e($routine['routine_sha256'] ?? '–') ?></code>
</div>
<?php if ($audioName !== ''): ?>
<div class="hash">
<span>Musik</span>
<code><?= e($routine['audio_sha256'] ?? '–') ?></code>
</div>
<?php endif; ?>
<p class="muted small">Beim Download prüfen, ob die SHA-256-Summe zur Kür passt.</p>
</section>
</article>

66
hub/views/upload.php Normal file
View file

@ -0,0 +1,66 @@
<?php /** @var array $errors */ ?>
<?php /** @var array $input */ ?>
<?php /** @var array|null $routine */ ?>
<?php $isRevision = $routine !== null; ?>
<section class="auth-card wide">
<h1><?= $isRevision ? 'Neue Revision' : 'Kür hochladen' ?></h1>
<?php if ($isRevision): ?>
<p class="muted">Neue Fassung von „<?= e($routine['title']) ?>“. Die bisherige Revision bleibt erhalten.</p>
<?php else: ?>
<p class="muted">Lade die Kür-JSON und – falls die Kür Musik nutzt – die zugehörige Audiodatei hoch. Beide gehören als Paket zusammen.</p>
<?php endif; ?>
<?php if ($errors): ?>
<div class="flash flash-error">
<ul class="plain">
<?php foreach ($errors as $error): ?>
<li><?= e($error) ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="post" enctype="multipart/form-data"
action="<?= e(url($isRevision ? '/routines/' . (int) $routine['id'] . '/revise' : '/upload')) ?>"
class="stack">
<?= csrf_field() ?>
<div class="grid-2">
<label>
Kür-Datei (.json)
<input type="file" name="routine" accept=".json,application/json" required>
<span class="hint">Aus Rinkplanner gespeicherte Kür, max. <?= e(human_bytes((int) config('app.max_routine_bytes', 8 * 1024 * 1024))) ?>.</span>
</label>
<label>
Musikdatei (MP3/OGG/WAV/M4A/AAC)
<input type="file" name="audio" accept=".mp3,.ogg,.wav,.m4a,.aac,audio/*">
<span class="hint">Dateiname muss exakt dem Feld „music_file“ der Kür entsprechen.</span>
</label>
</div>
<label>
Beschreibung (optional)
<textarea name="description" rows="4" maxlength="2000"><?= e($input['description']) ?></textarea>
</label>
<div class="grid-2">
<label>
Musiktitel (optional)
<input type="text" name="music_title" maxlength="190" value="<?= e_attr($input['music_title']) ?>">
</label>
<label>
Interpret (optional)
<input type="text" name="music_artist" maxlength="190" value="<?= e_attr($input['music_artist']) ?>">
</label>
</div>
<label class="check">
<input type="checkbox" name="rights" value="1" required>
Ich habe die Rechte an Kür und Musik und darf sie im geschlossenen Beta-Hub teilen.
</label>
<div class="actions">
<button class="primary" type="submit"><?= $isRevision ? 'Revision veröffentlichen' : 'Kür veröffentlichen' ?></button>
<a class="button" href="<?= e(url($isRevision ? '/routines/' . (int) $routine['id'] : '/')) ?>">Abbrechen</a>
</div>
</form>
</section>

46
hub/web/.htaccess Normal file
View file

@ -0,0 +1,46 @@
# Rinkplanner-Hub – Apache-Konfiguration für die Subdomain.
# Die eigentliche Anwendung liegt in app/, die Uploads in storage/.
# Beides ist über HTTP gesperrt; ausgeliefert wird nur web/ (hier: das
# DocumentRoot der Subdomain).
Options -Indexes
DirectoryIndex index.php index.html
AddDefaultCharset UTF-8
<IfModule mod_rewrite.c>
RewriteEngine On
# Immer HTTPS. Der Hoster kann TLS terminieren, daher auch der Proxy-Header.
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# Interne Verzeichnisse und versteckte Dateien nie ausliefern.
RewriteRule ^(app|storage|sql)(/|$) - [F,L]
RewriteCond %{REQUEST_URI} !^/\.well-known/
RewriteRule (^|/)\. - [F,L]
# Nicht vorhandene Pfade an den Front Controller.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
</IfModule>
<IfModule mod_headers.c>
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "DENY"
Header always set Referrer-Policy "same-origin"
<FilesMatch "\.(css|svg|png|jpg|jpeg|webp|ico)$">
Header set Cache-Control "public, max-age=604800"
</FilesMatch>
</IfModule>
<FilesMatch "^(\.env|\.git.*|composer\..*)$">
Require all denied
</FilesMatch>
# PHP-FPM: Fehler nicht an Besucher ausgeben (die App setzt das zusätzlich).
<IfModule mod_php.c>
php_flag display_errors off
php_flag log_errors on
</IfModule>

707
hub/web/assets/hub.css Normal file
View file

@ -0,0 +1,707 @@
:root {
--ink: #050d19;
--navy: #071a30;
--card: rgba(11, 32, 54, 0.78);
--ice: #c9f0ff;
--frost: #eefaff;
--sky: #7dd3fc;
--blue: #38bdf8;
--deep-blue: #185a86;
--gold: #f3d7a3;
--text: #f4fbff;
--muted: rgba(224, 244, 255, 0.66);
--line: rgba(190, 230, 255, 0.17);
--danger: #ff9aa8;
--success: #8ee6b0;
--radius: 16px;
--shadow: 0 24px 60px rgba(0, 0, 0, 0.32);
color-scheme: dark;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
}
body {
background:
radial-gradient(1100px 600px at 15% -10%, rgba(56, 189, 248, 0.16), transparent 60%),
radial-gradient(900px 500px at 110% 10%, rgba(24, 90, 134, 0.22), transparent 55%),
var(--ink);
color: var(--text);
font-family: "Segoe UI", system-ui, -apple-system, "Helvetica Neue", Arial, sans-serif;
line-height: 1.55;
}
a {
color: var(--sky);
text-decoration: none;
}
a:hover,
a:focus {
color: var(--ice);
text-decoration: underline;
}
h1,
h2,
h3 {
line-height: 1.2;
margin: 0 0 0.5rem;
}
h1 {
font-size: clamp(1.7rem, 3vw, 2.4rem);
}
h2 {
font-size: 1.15rem;
color: var(--ice);
}
p {
margin: 0 0 0.75rem;
}
code {
background: rgba(5, 13, 25, 0.55);
border: 1px solid var(--line);
border-radius: 8px;
padding: 0.12rem 0.4rem;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.9em;
word-break: break-all;
}
.topbar {
align-items: center;
backdrop-filter: blur(14px);
background: rgba(5, 13, 25, 0.72);
border-bottom: 1px solid var(--line);
display: flex;
gap: 1rem;
justify-content: space-between;
padding: 0.9rem clamp(1rem, 4vw, 3rem);
position: sticky;
top: 0;
z-index: 10;
}
.brand {
align-items: center;
color: var(--frost);
display: flex;
font-size: 1.05rem;
gap: 0.65rem;
letter-spacing: 0.02em;
}
.brand:hover {
text-decoration: none;
}
.brand strong {
color: var(--sky);
font-weight: 600;
}
.brand-mark {
align-items: center;
background: linear-gradient(135deg, var(--blue), var(--deep-blue));
border-radius: 10px;
color: var(--ink);
display: inline-flex;
font-weight: 800;
height: 2rem;
justify-content: center;
width: 2rem;
}
.nav {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.nav a {
color: var(--muted);
font-size: 0.95rem;
}
.nav a:hover {
color: var(--ice);
}
.nav-admin {
color: var(--gold) !important;
}
.page {
margin: 0 auto;
max-width: 1180px;
padding: clamp(1.5rem, 4vw, 3rem) clamp(1rem, 4vw, 3rem) 4rem;
}
.footer {
border-top: 1px solid var(--line);
color: var(--muted);
display: flex;
flex-wrap: wrap;
font-size: 0.85rem;
gap: 1rem;
justify-content: space-between;
margin: 0 auto;
max-width: 1180px;
padding: 1.5rem clamp(1rem, 4vw, 3rem) 2.5rem;
}
.inline {
display: inline-flex;
margin: 0;
}
.link-button {
background: none;
border: 0;
color: var(--muted);
cursor: pointer;
font: inherit;
padding: 0;
text-decoration: underline;
}
.link-button:hover {
color: var(--ice);
}
.link-button.danger {
color: var(--danger);
}
.page-head {
align-items: flex-start;
display: flex;
flex-wrap: wrap;
gap: 1rem;
justify-content: space-between;
margin-bottom: 1.5rem;
}
.eyebrow {
color: var(--muted);
font-size: 0.8rem;
letter-spacing: 0.08em;
margin-bottom: 0.3rem;
text-transform: uppercase;
}
.muted {
color: var(--muted);
}
.small {
font-size: 0.85rem;
}
.small code {
font-size: 0.8em;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
}
.button,
button {
align-items: center;
background: rgba(125, 211, 252, 0.1);
border: 1px solid var(--line);
border-radius: 999px;
color: var(--text);
cursor: pointer;
display: inline-flex;
font: inherit;
gap: 0.4rem;
justify-content: center;
padding: 0.55rem 1rem;
text-decoration: none;
transition: background 0.15s ease, border-color 0.15s ease, transform 0.15s ease;
}
.button:hover,
button:hover {
background: rgba(125, 211, 252, 0.18);
border-color: rgba(125, 211, 252, 0.4);
text-decoration: none;
transform: translateY(-1px);
}
.button.primary,
button.primary {
background: linear-gradient(135deg, var(--sky), var(--blue));
border-color: transparent;
color: #04121f;
font-weight: 700;
}
.button.small,
button.small {
font-size: 0.85rem;
padding: 0.35rem 0.75rem;
}
.button.danger-ghost,
button.danger-ghost {
background: rgba(255, 122, 144, 0.08);
border-color: rgba(255, 154, 168, 0.3);
color: var(--danger);
}
.auth-card {
background: var(--card);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow);
margin: clamp(1rem, 5vw, 3rem) auto;
max-width: 460px;
padding: clamp(1.4rem, 4vw, 2.4rem);
}
.auth-card.wide {
max-width: 820px;
}
.stack {
display: flex;
flex-direction: column;
gap: 1rem;
margin-top: 1.2rem;
}
.stack-tight {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
label {
display: flex;
flex-direction: column;
font-size: 0.92rem;
gap: 0.35rem;
}
label.check {
align-items: flex-start;
flex-direction: row;
gap: 0.55rem;
}
label.check input {
margin-top: 0.3rem;
width: auto;
}
input,
textarea,
select {
background: rgba(5, 13, 25, 0.63);
border: 1px solid var(--line);
border-radius: 10px;
color: var(--text);
font: inherit;
padding: 0.6rem 0.7rem;
width: 100%;
}
input[type="checkbox"] {
accent-color: var(--blue);
width: auto;
}
input:focus,
textarea:focus,
select:focus {
border-color: var(--sky);
box-shadow: 0 0 0 3px rgba(125, 211, 252, 0.18);
outline: none;
}
textarea {
resize: vertical;
}
.hint {
color: var(--muted);
font-size: 0.8rem;
}
.grid-2,
.grid-3 {
display: grid;
gap: 1rem;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.grid-3 {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.flashes {
display: flex;
flex-direction: column;
gap: 0.6rem;
margin-bottom: 1.2rem;
}
.flash {
border: 1px solid var(--line);
border-radius: 12px;
padding: 0.75rem 1rem;
}
.flash-success {
background: rgba(142, 230, 176, 0.1);
border-color: rgba(142, 230, 176, 0.35);
}
.flash-error {
background: rgba(255, 154, 168, 0.1);
border-color: rgba(255, 154, 168, 0.4);
}
.flash-info {
background: rgba(125, 211, 252, 0.1);
border-color: rgba(125, 211, 252, 0.35);
}
.flash-secret {
background: rgba(243, 215, 163, 0.1);
border-color: rgba(243, 215, 163, 0.45);
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.flash-secret strong {
color: var(--gold);
}
.flash-secret code {
font-size: 0.95rem;
}
.plain {
margin: 0;
padding-left: 1.1rem;
}
.toolbar {
align-items: center;
display: flex;
flex-wrap: wrap;
gap: 1rem;
justify-content: space-between;
margin-bottom: 1.2rem;
}
.search {
display: flex;
flex: 1 1 320px;
gap: 0.5rem;
max-width: 520px;
}
.tabs {
border: 1px solid var(--line);
border-radius: 999px;
display: flex;
overflow: hidden;
}
.tabs a {
color: var(--muted);
padding: 0.45rem 1rem;
}
.tabs a.active {
background: rgba(125, 211, 252, 0.16);
color: var(--ice);
}
.tabs a:hover {
text-decoration: none;
}
.table-wrap {
border: 1px solid var(--line);
border-radius: var(--radius);
overflow-x: auto;
}
table.list {
border-collapse: collapse;
font-size: 0.93rem;
min-width: 720px;
width: 100%;
}
table.list th,
table.list td {
border-bottom: 1px solid var(--line);
padding: 0.7rem 0.85rem;
text-align: left;
vertical-align: top;
}
table.list th {
background: rgba(7, 26, 48, 0.7);
color: var(--muted);
font-size: 0.78rem;
font-weight: 600;
letter-spacing: 0.05em;
text-transform: uppercase;
}
table.list tbody tr:hover {
background: rgba(125, 211, 252, 0.05);
}
table.list tbody tr:last-child td {
border-bottom: 0;
}
table.compact th,
table.compact td {
padding: 0.55rem 0.7rem;
}
.title-link {
color: var(--frost);
font-weight: 600;
}
.badge {
background: rgba(255, 154, 168, 0.14);
border: 1px solid rgba(255, 154, 168, 0.35);
border-radius: 999px;
color: var(--danger);
display: inline-block;
font-size: 0.72rem;
margin-left: 0.35rem;
padding: 0.05rem 0.5rem;
vertical-align: middle;
}
.badge-soft {
background: rgba(125, 211, 252, 0.12);
border-color: rgba(125, 211, 252, 0.3);
color: var(--sky);
}
.status {
border: 1px solid var(--line);
border-radius: 999px;
display: inline-block;
font-size: 0.75rem;
padding: 0.05rem 0.55rem;
}
.status-open,
.status-active {
background: rgba(142, 230, 176, 0.1);
border-color: rgba(142, 230, 176, 0.35);
color: var(--success);
}
.status-used {
background: rgba(125, 211, 252, 0.1);
border-color: rgba(125, 211, 252, 0.35);
color: var(--sky);
}
.status-expired,
.status-revoked {
background: rgba(255, 154, 168, 0.1);
border-color: rgba(255, 154, 168, 0.3);
color: var(--danger);
}
.empty {
background: rgba(7, 26, 48, 0.45);
border: 1px dashed var(--line);
border-radius: var(--radius);
padding: 2rem;
text-align: center;
}
.pagination {
align-items: center;
color: var(--muted);
display: flex;
gap: 1rem;
justify-content: center;
margin-top: 1.2rem;
}
.detail .panel,
.panel {
background: var(--card);
border: 1px solid var(--line);
border-radius: var(--radius);
margin-bottom: 1.2rem;
padding: 1.2rem 1.3rem;
}
.owner-bar {
align-items: center;
background: rgba(125, 211, 252, 0.07);
border: 1px solid rgba(125, 211, 252, 0.22);
border-radius: 12px;
display: flex;
flex-wrap: wrap;
gap: 0.7rem;
margin-bottom: 1.2rem;
padding: 0.7rem 0.9rem;
}
.owner-bar .muted {
margin-right: auto;
}
.preline {
white-space: pre-line;
}
.facts {
display: grid;
gap: 0.9rem 1.2rem;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
margin: 0;
}
.facts div {
min-width: 0;
}
.facts dt {
color: var(--muted);
font-size: 0.78rem;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.facts dd {
margin: 0.1rem 0 0;
overflow-wrap: anywhere;
}
.hash {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
margin-bottom: 0.5rem;
}
.hash span {
color: var(--muted);
min-width: 3rem;
}
audio {
width: 100%;
}
.columns {
display: grid;
gap: 1.2rem;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.inline-form {
display: flex;
gap: 0.5rem;
margin-bottom: 1rem;
}
.inline-form input {
flex: 1;
}
.admin-tabs {
border-bottom: 1px solid var(--line);
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
margin-bottom: 1.2rem;
}
.admin-tabs a {
border-bottom: 2px solid transparent;
color: var(--muted);
padding: 0.55rem 0.9rem;
}
.admin-tabs a.active {
border-bottom-color: var(--sky);
color: var(--ice);
}
.admin-tabs a:hover {
color: var(--ice);
text-decoration: none;
}
.row-actions {
align-items: flex-start;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.danger-zone summary {
color: var(--danger);
cursor: pointer;
font-size: 0.85rem;
}
.danger-zone[open] {
background: rgba(255, 154, 168, 0.06);
border: 1px solid rgba(255, 154, 168, 0.25);
border-radius: 10px;
padding: 0.5rem;
}
.footer a {
color: var(--muted);
}
@media (max-width: 760px) {
.grid-2,
.grid-3,
.columns {
grid-template-columns: 1fr;
}
.topbar {
align-items: flex-start;
flex-direction: column;
}
.page-head {
flex-direction: column;
}
.actions {
width: 100%;
}
}

24
hub/web/index.php Normal file
View file

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
/**
* Rinkplanner-Hub – Front Controller.
* Apache leitet alle nicht vorhandenen Dateien über .htaccess hierher.
*/
require __DIR__ . '/app/bootstrap.php';
$uriPath = (string) parse_url((string) ($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH);
$basePath = rtrim((string) config('app.base_path', ''), '/');
if ($basePath !== '' && str_starts_with($uriPath, $basePath)) {
$uriPath = substr($uriPath, strlen($basePath));
}
$path = '/' . trim($uriPath, '/');
$method = request_method();
if (str_starts_with($path, '/api/')) {
api_handle($method, $path);
exit;
}
page_handle($method, $path);

2
hub/web/robots.txt Normal file
View file

@ -0,0 +1,2 @@
User-agent: *
Disallow: /

234
tools/deploy_hub.sh Executable file
View file

@ -0,0 +1,234 @@
#!/usr/bin/env bash
# Deployt den Rinkplanner-Hub auf rinkplanner-hub.programmschmiede.de.
#
# Aufruf:
# ./tools/deploy_hub.sh --check # Standard: Health, Sperren und Login-Seite prüfen
# ./tools/deploy_hub.sh --sync # Code + Konfiguration hochladen
# ./tools/deploy_hub.sh --install # Schema + Admin anlegen (einmalig)
# ./tools/deploy_hub.sh --all # sync + install + check
#
# Zugangsdaten kommen aus docs/credentials.txt (gitignored).
# Der Installer löscht sich nach Erfolg selbst; das Admin-Passwort wird nur
# per HTTPS übergeben und nie auf dem Server gespeichert.
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
CREDENTIALS="$REPO_ROOT/docs/credentials.txt"
HUB_DIR="$REPO_ROOT/hub"
REMOTE_DIR="rinkplanner-hub.programmschmiede.de"
PUBLIC_URL="https://rinkplanner-hub.programmschmiede.de"
MODE="check"
FORCE=0
while [[ $# -gt 0 ]]; do
case "$1" in
--check) MODE="check" ;;
--sync) MODE="sync" ;;
--install) MODE="install" ;;
--all) MODE="all" ;;
-h|--help)
sed -n '2,16p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
exit 0
;;
*) echo "Unbekannte Option: $1" >&2; exit 2 ;;
esac
shift
done
[[ -f "$CREDENTIALS" ]] || { echo "Fehlt: $CREDENTIALS" >&2; exit 1; }
cred() {
grep -m1 "^$1=" "$CREDENTIALS" | cut -d= -f2- | tr -d '\r'
}
FTP_URL="$(cred FTP_URL)"
FTP_USER="$(cred FTP_USER)"
FTP_PASSWORD="$(cred FTP_PASSWORD)"
DB_NAME="$(cred DB_NAME)"
DB_USER="$(cred DB_USER)"
DB_PASSWORD="$(cred DB_PASSWORD)"
HUB_ADMIN_USER="$(cred HUB_ADMIN_USER)"
HUB_ADMIN_PASSWORD="$(cred HUB_ADMIN_PASSWORD)"
HOST="${FTP_URL#ftp://}"
HOST="${HOST#ftps://}"
HOST="${HOST%%/*}"
HOST="${HOST%%:*}"
[[ -n "$HOST" && -n "$FTP_USER" ]] || { echo "FTP-Zugang unvollständig." >&2; exit 1; }
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/rinkplanner-hub.XXXXXX")"
trap 'rm -rf "$TMP_DIR"' EXIT
CURL=(curl --ssl-reqd --insecure --silent --show-error --connect-timeout 20 --max-time 900 --user "$FTP_USER:$FTP_PASSWORD")
ftp_url() {
printf 'ftp://%s/%s/%s' "$HOST" "$REMOTE_DIR" "$1"
}
ftp_put() {
local local_path="$1" remote_path="$2"
"${CURL[@]}" --ftp-create-dirs -T "$local_path" "$(ftp_url "$remote_path")"
}
ftp_get() {
local remote_path="$1" local_path="$2"
"${CURL[@]}" -o "$local_path" "$(ftp_url "$remote_path")"
}
ftp_chmod() {
local mode="$1" remote_path="$2"
"${CURL[@]}" "ftp://$HOST/" -Q "SITE CHMOD $mode $REMOTE_DIR/$remote_path" >/dev/null || true
}
http_code() {
curl -sS -o /dev/null -w '%{http_code}' --max-time 30 "$1" || true
}
make_config() {
local token="$1"
HUB_INSTALL_TOKEN="$token" HUB_PUBLIC_URL="$PUBLIC_URL" \
DB_NAME="$DB_NAME" DB_USER="$DB_USER" DB_PASSWORD="$DB_PASSWORD" \
python3 - "$CREDENTIALS" "$TMP_DIR/config.local.php" <<'PY'
import os
import sys
def php(value):
return "'" + str(value).replace('\\', '\\\\').replace("'", "\\'") + "'"
path, target = sys.argv[1], sys.argv[2]
values = {}
with open(path, encoding='utf-8') as handle:
for line in handle:
line = line.rstrip('\n').rstrip('\r')
if '=' in line and not line.lstrip().startswith('#'):
key, value = line.split('=', 1)
values[key] = value
config = f"""<?php
declare(strict_types=1);
return [
'db' => [
'host' => 'localhost',
'port' => 3306,
'name' => {php(values.get('DB_NAME', ''))},
'user' => {php(values.get('DB_USER', ''))},
'password' => {php(values.get('DB_PASSWORD', ''))},
'charset' => 'utf8mb4',
],
'app' => [
'base_path' => '',
'public_url' => {php(os.environ['HUB_PUBLIC_URL'])},
'storage_path' => dirname(__DIR__) . '/storage',
'install_token' => {php(os.environ['HUB_INSTALL_TOKEN'])},
'max_routine_bytes' => 8 * 1024 * 1024,
'max_audio_bytes' => 50 * 1024 * 1024,
'session_idle_seconds' => 14 * 86400,
'session_absolute_seconds' => 30 * 86400,
'remember_seconds' => 30 * 86400,
'login_window_seconds' => 900,
'login_max_per_user' => 5,
'login_max_per_ip' => 10,
'uploads_per_hour' => 20,
],
];
"""
with open(target, 'w', encoding='utf-8') as handle:
handle.write(config)
os.chmod(target, 0o600)
PY
}
upload_tree() {
local source_root="$1" remote_prefix="$2"
while IFS= read -r file; do
local relative="${file#"$source_root"/}"
case "$relative" in
*.example.php|config.local.php|.DS_Store|*.swp) continue ;;
esac
ftp_put "$file" "$remote_prefix$relative"
echo " $remote_prefix$relative"
done < <(find "$source_root" -type f | sort)
}
do_sync() {
local token
token="$(openssl rand -hex 24)"
make_config "$token"
echo "Lade App-Code hoch …"
upload_tree "$HUB_DIR/app" "app/"
upload_tree "$HUB_DIR/views" "views/"
upload_tree "$HUB_DIR/sql" "sql/"
upload_tree "$HUB_DIR/web" ""
echo "Lade Konfiguration hoch …"
ftp_put "$TMP_DIR/config.local.php" "app/config.local.php"
ftp_chmod 600 "app/config.local.php"
echo "Sync fertig. Install-Token liegt nur auf dem Server."
}
install_if_needed() {
local config_file="$TMP_DIR/remote-config.php"
if ! ftp_get "app/config.local.php" "$config_file" 2>/dev/null; then
echo "Konfiguration fehlt auf dem Server; zuerst --sync ausführen." >&2
exit 1
fi
local token
token="$(python3 - "$config_file" <<'PY'
import re, sys
text = open(sys.argv[1], encoding='utf-8').read()
match = re.search(r"'install_token'\s*=>\s*'([^']+)'", text)
print(match.group(1) if match else '')
PY
)"
[[ -n "$token" ]] || { echo "Install-Token nicht gefunden." >&2; exit 1; }
ftp_put "$HUB_DIR/install.php" "install.php"
echo "Rufe Installer auf …"
local response status
response="$(curl -sS --max-time 300 -w '\n%{http_code}' \
--data-urlencode "token=$token" \
--data-urlencode "admin_user=$HUB_ADMIN_USER" \
--data-urlencode "admin_password=$HUB_ADMIN_PASSWORD" \
--data-urlencode "admin_display=$HUB_ADMIN_USER" \
"$PUBLIC_URL/install.php" 2>&1)" || true
status="${response##*$'\n'}"
local body="${response%$'\n'*}"
echo "$body"
"${CURL[@]}" "ftp://$HOST/" -Q "-DELE $REMOTE_DIR/install.php" >/dev/null 2>&1 || true
if [[ "$status" != "200" ]]; then
echo "Installation fehlgeschlagen (HTTP $status)." >&2
exit 1
fi
echo "Installation abgeschlossen."
}
do_check() {
local ok=0
local health
health="$(curl -sS --max-time 30 "$PUBLIC_URL/health" || true)"
if [[ "$health" == *"ok"* ]]; then
echo "Health: OK"
else
echo "Health: FEHLER ($health)" >&2
ok=1
fi
local login_code config_code storage_code install_code
login_code="$(http_code "$PUBLIC_URL/login")"
config_code="$(http_code "$PUBLIC_URL/app/config.local.php")"
storage_code="$(http_code "$PUBLIC_URL/storage/")"
install_code="$(http_code "$PUBLIC_URL/install.php")"
[[ "$login_code" == "200" ]] && echo "Login-Seite: OK" || { echo "Login-Seite: HTTP $login_code" >&2; ok=1; }
[[ "$config_code" == "403" || "$config_code" == "404" ]] && echo "Konfiguration gesperrt: OK" || { echo "Konfiguration erreichbar: HTTP $config_code" >&2; ok=1; }
[[ "$storage_code" == "403" || "$storage_code" == "404" ]] && echo "Storage gesperrt: OK" || { echo "Storage erreichbar: HTTP $storage_code" >&2; ok=1; }
[[ "$install_code" == "404" ]] && echo "Installer entfernt: OK" || echo "Hinweis: Installer liefert HTTP $install_code" >&2
if [[ "$ok" -ne 0 ]]; then
exit 1
fi
}
case "$MODE" in
sync) do_sync ;;
install) install_if_needed ;;
check) do_check ;;
all) do_sync; install_if_needed; do_check ;;
esac