diff --git a/.gitignore b/.gitignore index 8a1af41..b4e36b1 100644 --- a/.gitignore +++ b/.gitignore @@ -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/ diff --git a/AGENTS.md b/AGENTS.md index 54a7bce..9dad74c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/README.md b/README.md index 98962e1..9acdd7a 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/docs/credentials.example.txt b/docs/credentials.example.txt index 09109da..92521be 100644 --- a/docs/credentials.example.txt +++ b/docs/credentials.example.txt @@ -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= diff --git a/docs/hub.md b/docs/hub.md new file mode 100644 index 0000000..d552637 --- /dev/null +++ b/docs/hub.md @@ -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 . 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. diff --git a/hub/app/.htaccess b/hub/app/.htaccess new file mode 100644 index 0000000..b29145e --- /dev/null +++ b/hub/app/.htaccess @@ -0,0 +1,2 @@ +Require all denied +Options -Indexes diff --git a/hub/app/api.php b/hub/app/api.php new file mode 100644 index 0000000..f11d549 --- /dev/null +++ b/hub/app/api.php @@ -0,0 +1,255 @@ + $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); +} diff --git a/hub/app/auth.php b/hub/app/auth.php new file mode 100644 index 0000000..17b80f8 --- /dev/null +++ b/hub/app/auth.php @@ -0,0 +1,364 @@ + 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(), + ]); +} diff --git a/hub/app/bootstrap.php b/hub/app/bootstrap.php new file mode 100644 index 0000000..f128693 --- /dev/null +++ b/hub/app/bootstrap.php @@ -0,0 +1,59 @@ +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 'Fehler' + . '' + . '

Interner Fehler

Bitte später erneut versuchen.

'; +}); + +security_headers(); + +if (PHP_SAPI !== 'cli') { + start_session(); +} diff --git a/hub/app/config.example.php b/hub/app/config.example.php new file mode 100644 index 0000000..2c154b7 --- /dev/null +++ b/hub/app/config.example.php @@ -0,0 +1,31 @@ + [ + '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, + ], +]; diff --git a/hub/app/db.php b/hub/app/db.php new file mode 100644 index 0000000..9f0e66f --- /dev/null +++ b/hub/app/db.php @@ -0,0 +1,28 @@ + 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; +} diff --git a/hub/app/invites.php b/hub/app/invites.php new file mode 100644 index 0000000..3e9a0dd --- /dev/null +++ b/hub/app/invites.php @@ -0,0 +1,118 @@ + 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'; +} diff --git a/hub/app/pages.php b/hub/app/pages.php new file mode 100644 index 0000000..a543201 --- /dev/null +++ b/hub/app/pages.php @@ -0,0 +1,729 @@ + 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(); +} diff --git a/hub/app/routines.php b/hub/app/routines.php new file mode 100644 index 0000000..ce6dac7 --- /dev/null +++ b/hub/app/routines.php @@ -0,0 +1,638 @@ +// 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; +} diff --git a/hub/app/tokens.php b/hub/app/tokens.php new file mode 100644 index 0000000..cc82c75 --- /dev/null +++ b/hub/app/tokens.php @@ -0,0 +1,112 @@ +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; +} diff --git a/hub/app/util.php b/hub/app/util.php new file mode 100644 index 0000000..b89643e --- /dev/null +++ b/hub/app/util.php @@ -0,0 +1,320 @@ +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 ''; +} + +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); +} diff --git a/hub/install.php b/hub/install.php new file mode 100644 index 0000000..1bbaa4c --- /dev/null +++ b/hub/install.php @@ -0,0 +1,135 @@ +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"; diff --git a/hub/sql/.htaccess b/hub/sql/.htaccess new file mode 100644 index 0000000..b29145e --- /dev/null +++ b/hub/sql/.htaccess @@ -0,0 +1,2 @@ +Require all denied +Options -Indexes diff --git a/hub/sql/schema.sql b/hub/sql/schema.sql new file mode 100644 index 0000000..cb76069 --- /dev/null +++ b/hub/sql/schema.sql @@ -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; diff --git a/hub/views/.htaccess b/hub/views/.htaccess new file mode 100644 index 0000000..b29145e --- /dev/null +++ b/hub/views/.htaccess @@ -0,0 +1,2 @@ +Require all denied +Options -Indexes diff --git a/hub/views/_admin_nav.php b/hub/views/_admin_nav.php new file mode 100644 index 0000000..2644760 --- /dev/null +++ b/hub/views/_admin_nav.php @@ -0,0 +1,7 @@ + + diff --git a/hub/views/account.php b/hub/views/account.php new file mode 100644 index 0000000..272cd52 --- /dev/null +++ b/hub/views/account.php @@ -0,0 +1,77 @@ + + +
+
+

Konto

+

·

+
+
+ + +
Bitte ein neues Passwort setzen, bevor du den Hub weiter nutzt.
+ + +
+
+

Passwort ändern

+
+ + + + + +
+
+ +
+

API-Tokens

+

Für die Godot-App. Ein Token ersetzt Benutzername und Passwort im Client und lässt sich jederzeit widerrufen.

+
+ + + +
+ + +
+ + + + + + + + + + + + + + + + +
NamePrefixErstelltZuletztStatus
… + +
+ + + +
+ +
+
+ +

Noch kein Token erzeugt.

+ +
+
diff --git a/hub/views/admin_audit.php b/hub/views/admin_audit.php new file mode 100644 index 0000000..bb7d79b --- /dev/null +++ b/hub/views/admin_audit.php @@ -0,0 +1,34 @@ + +
+
+

Verwaltung

+

Die letzten Ereignisse.

+
+
+ + +
+ +

Noch keine Einträge.

+ +
+ + + + + + + + + + + + + + + + +
ZeitAkteurAktionObjektDetailIP
+
+ +
diff --git a/hub/views/admin_invites.php b/hub/views/admin_invites.php new file mode 100644 index 0000000..a360248 --- /dev/null +++ b/hub/views/admin_invites.php @@ -0,0 +1,83 @@ + +
+
+

Verwaltung

+

Einladungen für die geschlossene Beta.

+
+
+ + +
+

Neue Einladung

+

Der Code wird nach dem Anlegen genau einmal angezeigt. Er gilt für ein Konto.

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

Einladungen

+ +

Noch keine Einladungen.

+ +
+ + + + + + + 'open', + 'eingelöst' => 'used', + 'abgelaufen' => 'expired', + 'widerrufen' => 'revoked', + ][$status] ?? 'expired'; + ?> + + + + + + + + + + + +
ErstelltNotizE-MailStatusVon / anGültig bis
+ + + → + + + +
+ + + +
+ +
+
+ +
diff --git a/hub/views/admin_routines.php b/hub/views/admin_routines.php new file mode 100644 index 0000000..4d8f71c --- /dev/null +++ b/hub/views/admin_routines.php @@ -0,0 +1,86 @@ + + + + + + 1) { + $params['page'] = $targetPage; + } + return url('/admin/routines') . ($params ? '?' . http_build_query($params) : ''); +}; +?> +
+
+

Verwaltung

+

Küren insgesamt, auch versteckte.

+
+
+ + +
+ +
+ + +

Keine Küren gefunden.

+ +
+ + + + + + + + + + + + + + + + + +
TitelVonStatusRev.AktualisiertDownloadsAktionen
+
+
+ + + + +
+
+ löschen +
+ + + + + +
+
+
+
+
+ + 1): ?> + + + diff --git a/hub/views/admin_users.php b/hub/views/admin_users.php new file mode 100644 index 0000000..174ac75 --- /dev/null +++ b/hub/views/admin_users.php @@ -0,0 +1,84 @@ + + +
+
+

Verwaltung

+

Beta-Konten verwalten.

+
+
+ + +
+

Benutzer

+
+ + + + + + + + + + + + + + + + + +
BenutzerRolleStatusKürenRegistriertLetzte AnmeldungAktionen
+ + @ + +
+ +
+ + + + + + eigenes Konto + +
+ +
+ + + + +
+ +
+ + + + +
+ +
+ + + + +
+
+ löschen +
+ + + + + +
+
+
+ +
+
+
diff --git a/hub/views/dashboard.php b/hub/views/dashboard.php new file mode 100644 index 0000000..2d01c56 --- /dev/null +++ b/hub/views/dashboard.php @@ -0,0 +1,110 @@ + + + + + + + 1) { + $params['page'] = $targetPage; + } + return url('/') . ($params ? '?' . http_build_query($params) : ''); +}; +?> +
+
+

Küren

+

im Hub.

+
+ Kür hochladen +
+ +
+ + +
+ + +
+

Keine Küren gefunden.

+ +

Suche zurücksetzen oder selbst eine Kür hochladen.

+ +

Der Hub ist noch leer. Erste Kür hochladen.

+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
TitelSkaterMusikRev.GrößeAktualisiertVon
+ + + versteckt + + + + + + + + · + + + + + + + +
+
+ + 1): ?> + + + diff --git a/hub/views/error.php b/hub/views/error.php new file mode 100644 index 0000000..a2f999c --- /dev/null +++ b/hub/views/error.php @@ -0,0 +1,7 @@ + + +
+

Fehler

+

+

Zurück zur Küren-Übersicht.

+
diff --git a/hub/views/layout.php b/hub/views/layout.php new file mode 100644 index 0000000..bfcb0c9 --- /dev/null +++ b/hub/views/layout.php @@ -0,0 +1,65 @@ + + + + + + + <?= e($title) ?> · Rinkplanner-Hub + + + +
+ + R + Rinkplanner Hub + + +
+ +
+ +
+ + +
+ + +
+ +
+ +
+ + +
+ + + +
+ + + + diff --git a/hub/views/login.php b/hub/views/login.php new file mode 100644 index 0000000..161ed1c --- /dev/null +++ b/hub/views/login.php @@ -0,0 +1,31 @@ + + + +
+

Anmelden

+

Der Kür-Hub ist in einer geschlossenen Beta. Zugang gibt es per Einladungscode.

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

Noch keinen Zugang? Ein Beta-Code kommt von der Hub-Administration.

+
diff --git a/hub/views/register.php b/hub/views/register.php new file mode 100644 index 0000000..006e388 --- /dev/null +++ b/hub/views/register.php @@ -0,0 +1,62 @@ + + + + +
+

Beta-Zugang einlösen

+

Ein Einladungscode legt genau ein Konto an. Der Code verliert danach seine Gültigkeit.

+ + +
+
    + +
  • + +
+
+ + +
+ + +
+ + +
+ +
+ + +
+ + +
+ +

Schon ein Konto? Anmelden

+
diff --git a/hub/views/routine.php b/hub/views/routine.php new file mode 100644 index 0000000..012c5a1 --- /dev/null +++ b/hub/views/routine.php @@ -0,0 +1,93 @@ + + + + +
+
+
+

Küren / Kür

+

+

+ + · Revision + · + + · versteckt + +

+
+ +
+ + +
+ Du kannst diese Kür verwalten. + Neue Revision hochladen + +
+ + +
+ +
+ + +
+ + + In der Verwaltung öffnen + +
+ + + +
+

Beschreibung

+

+
+ + + +
+

Musik

+ +

·

+
+ + +
+

Details

+
+
Skater
+
Kategorie
+
Musiktitel
+
Musik
+
Kür-Datei
·
+
Audio-Datei
+
Downloads
+
Eingestellt
+
+
+ +
+

Prüfsummen

+
+ Kür + +
+ +
+ Musik + +
+ +

Beim Download prüfen, ob die SHA-256-Summe zur Kür passt.

+
+
diff --git a/hub/views/upload.php b/hub/views/upload.php new file mode 100644 index 0000000..01e1fe7 --- /dev/null +++ b/hub/views/upload.php @@ -0,0 +1,66 @@ + + + + +
+

+ +

Neue Fassung von „“. Die bisherige Revision bleibt erhalten.

+ +

Lade die Kür-JSON und – falls die Kür Musik nutzt – die zugehörige Audiodatei hoch. Beide gehören als Paket zusammen.

+ + + +
+
    + +
  • + +
+
+ + +
+ +
+ + +
+ + + +
+ + +
+ + + +
+ + Abbrechen +
+
+
diff --git a/hub/web/.htaccess b/hub/web/.htaccess new file mode 100644 index 0000000..921989e --- /dev/null +++ b/hub/web/.htaccess @@ -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 + + + 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] + + + + Header always set X-Content-Type-Options "nosniff" + Header always set X-Frame-Options "DENY" + Header always set Referrer-Policy "same-origin" + + Header set Cache-Control "public, max-age=604800" + + + + + Require all denied + + +# PHP-FPM: Fehler nicht an Besucher ausgeben (die App setzt das zusätzlich). + + php_flag display_errors off + php_flag log_errors on + diff --git a/hub/web/assets/hub.css b/hub/web/assets/hub.css new file mode 100644 index 0000000..8799b36 --- /dev/null +++ b/hub/web/assets/hub.css @@ -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%; + } +} diff --git a/hub/web/index.php b/hub/web/index.php new file mode 100644 index 0000000..e66ae40 --- /dev/null +++ b/hub/web/index.php @@ -0,0 +1,24 @@ +&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""" [ + '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