feat: Kür-Hub mit Einladungen, Uploads und API
- PHP-App unter hub/ für rinkplanner-hub.programmschmiede.de - MariaDB-Schema, Argon2id, Sessions, CSRF und Ratenbegrenzung - Einladungscodes, Admin-Bereich und Kür-Pakete mit Audiodatei - JSON-API v1 mit Bearer-Tokens für die Godot-App - Deployment und Erstinstallation über tools/deploy_hub.sh - Doku und Credentials-Vorlage ergänzt
This commit is contained in:
parent
e79b477ee0
commit
055a2919c3
38 changed files with 5111 additions and 0 deletions
2
hub/app/.htaccess
Normal file
2
hub/app/.htaccess
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
Require all denied
|
||||
Options -Indexes
|
||||
255
hub/app/api.php
Normal file
255
hub/app/api.php
Normal file
|
|
@ -0,0 +1,255 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/** JSON-API v1 für die Godot-App. Authentifizierung: Bearer-Token. */
|
||||
|
||||
function api_base_url(): string
|
||||
{
|
||||
$base = rtrim((string) config('app.public_url', ''), '/');
|
||||
if ($base !== '') {
|
||||
return $base;
|
||||
}
|
||||
$scheme = is_https() ? 'https' : 'http';
|
||||
return $scheme . '://' . (string) ($_SERVER['HTTP_HOST'] ?? 'localhost');
|
||||
}
|
||||
|
||||
function api_truthy(mixed $value): bool
|
||||
{
|
||||
return $value === true || $value === 1 || $value === '1' || $value === 'true';
|
||||
}
|
||||
|
||||
function api_routine_payload(array $routine): array
|
||||
{
|
||||
$base = api_base_url();
|
||||
$id = (int) $routine['id'];
|
||||
$audio = null;
|
||||
if (!empty($routine['audio_path'])) {
|
||||
$audio = [
|
||||
'name' => $routine['audio_original_name'],
|
||||
'bytes' => (int) $routine['audio_bytes'],
|
||||
'sha256' => $routine['audio_sha256'],
|
||||
'mime' => $routine['audio_mime'],
|
||||
'url' => $base . url('/api/v1/routines/' . $id . '/audio'),
|
||||
];
|
||||
}
|
||||
return [
|
||||
'id' => $id,
|
||||
'title' => $routine['title'],
|
||||
'skater_name' => $routine['skater_name'],
|
||||
'category' => $routine['category'],
|
||||
'description' => $routine['description'],
|
||||
'music_title' => $routine['music_title'],
|
||||
'music_artist' => $routine['music_artist'],
|
||||
'status' => $routine['status'],
|
||||
'revision' => $routine['revision'] !== null ? (int) $routine['revision'] : null,
|
||||
'download_count' => (int) $routine['download_count'],
|
||||
'created_at' => $routine['created_at'],
|
||||
'updated_at' => $routine['updated_at'],
|
||||
'owner' => [
|
||||
'username' => $routine['owner_username'],
|
||||
'display_name' => $routine['owner_display_name'],
|
||||
],
|
||||
'files' => [
|
||||
'routine' => [
|
||||
'name' => $routine['routine_original_name'],
|
||||
'bytes' => (int) $routine['routine_bytes'],
|
||||
'sha256' => $routine['routine_sha256'],
|
||||
'url' => $base . url('/api/v1/routines/' . $id . '/download'),
|
||||
],
|
||||
'audio' => $audio,
|
||||
],
|
||||
'url' => $base . url('/routines/' . $id),
|
||||
];
|
||||
}
|
||||
|
||||
function api_routine_summary(array $row): array
|
||||
{
|
||||
return [
|
||||
'id' => (int) $row['id'],
|
||||
'title' => $row['title'],
|
||||
'skater_name' => $row['skater_name'],
|
||||
'category' => $row['category'],
|
||||
'music_title' => $row['music_title'],
|
||||
'music_artist' => $row['music_artist'],
|
||||
'status' => $row['status'],
|
||||
'revision' => $row['revision'] !== null ? (int) $row['revision'] : null,
|
||||
'routine_bytes' => isset($row['routine_bytes']) ? (int) $row['routine_bytes'] : null,
|
||||
'audio_bytes' => isset($row['audio_bytes']) ? (int) $row['audio_bytes'] : null,
|
||||
'download_count' => (int) $row['download_count'],
|
||||
'updated_at' => $row['updated_at'],
|
||||
'owner' => [
|
||||
'username' => $row['owner_username'],
|
||||
'display_name' => $row['owner_display_name'],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
function api_handle(string $method, string $path): void
|
||||
{
|
||||
$path = '/' . trim($path, '/');
|
||||
|
||||
if ($path === '/api/v1/tokens') {
|
||||
if ($method !== 'POST') {
|
||||
abort_api(405, 'method_not_allowed', 'Nur POST ist erlaubt.');
|
||||
}
|
||||
api_create_token();
|
||||
return;
|
||||
}
|
||||
|
||||
$user = api_require_user();
|
||||
|
||||
if ($path === '/api/v1/me') {
|
||||
if ($method !== 'GET') {
|
||||
abort_api(405, 'method_not_allowed', 'Nur GET ist erlaubt.');
|
||||
}
|
||||
json_response([
|
||||
'id' => (int) $user['id'],
|
||||
'username' => $user['username'],
|
||||
'display_name' => $user['display_name'],
|
||||
'role' => $user['role'],
|
||||
'created_at' => $user['created_at'],
|
||||
]);
|
||||
}
|
||||
|
||||
if ($path === '/api/v1/routines') {
|
||||
if ($method === 'GET') {
|
||||
$query = mb_substr(query_string('q'), 0, 100, 'UTF-8');
|
||||
$page = max(1, query_int('page', 1));
|
||||
$perPage = max(1, min(50, query_int('per_page', 20)));
|
||||
$mine = query_string('mine') === '1';
|
||||
$result = routines_query($query, $page, $perPage, $mine ? (int) $user['id'] : null, $mine);
|
||||
json_response([
|
||||
'items' => array_map('api_routine_summary', $result['items']),
|
||||
'total' => $result['total'],
|
||||
'page' => $result['page'],
|
||||
'pages' => $result['pages'],
|
||||
]);
|
||||
}
|
||||
if ($method === 'POST') {
|
||||
api_upload($user, null);
|
||||
}
|
||||
abort_api(405, 'method_not_allowed', 'Nur GET oder POST ist erlaubt.');
|
||||
}
|
||||
|
||||
if (preg_match('#^/api/v1/routines/(\d+)$#', $path, $matches) === 1) {
|
||||
api_routine((int) $matches[1], $method, $user);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/api/v1/routines/(\d+)/(download|audio)$#', $path, $matches) === 1) {
|
||||
if ($method !== 'GET') {
|
||||
abort_api(405, 'method_not_allowed', 'Nur GET ist erlaubt.');
|
||||
}
|
||||
$routine = api_fetch_visible((int) $matches[1], $user);
|
||||
routine_send_file($routine, (string) $matches[2], $user, true);
|
||||
}
|
||||
if (preg_match('#^/api/v1/routines/(\d+)/revisions$#', $path, $matches) === 1) {
|
||||
if ($method !== 'POST') {
|
||||
abort_api(405, 'method_not_allowed', 'Nur POST ist erlaubt.');
|
||||
}
|
||||
api_upload($user, (int) $matches[1]);
|
||||
return;
|
||||
}
|
||||
|
||||
abort_api(404, 'not_found', 'Unbekannter API-Pfad.');
|
||||
}
|
||||
|
||||
function api_create_token(): void
|
||||
{
|
||||
$input = json_input();
|
||||
$login = trim((string) ($input['username'] ?? $input['login'] ?? ''));
|
||||
$password = (string) ($input['password'] ?? '');
|
||||
$name = trim((string) ($input['name'] ?? 'App'));
|
||||
if ($login === '' || $password === '') {
|
||||
abort_api(422, 'invalid_credentials', 'Benutzername und Passwort sind erforderlich.');
|
||||
}
|
||||
$result = auth_attempt($login, $password);
|
||||
if (!$result['ok']) {
|
||||
if (($result['retry'] ?? 0) > 0) {
|
||||
header('Retry-After: ' . (int) $result['retry']);
|
||||
abort_api(429, 'rate_limited', (string) $result['error']);
|
||||
}
|
||||
abort_api(401, 'invalid_credentials', (string) $result['error']);
|
||||
}
|
||||
$user = $result['user'];
|
||||
if ((int) ($user['must_change_password'] ?? 0) === 1) {
|
||||
abort_api(403, 'password_change_required', 'Bitte zuerst im Web das Passwort ändern.');
|
||||
}
|
||||
$created = token_create((int) $user['id'], $name);
|
||||
json_response([
|
||||
'token' => $created['token'],
|
||||
'prefix' => $created['prefix'],
|
||||
'name' => $name !== '' ? $name : 'App',
|
||||
'user' => [
|
||||
'id' => (int) $user['id'],
|
||||
'username' => $user['username'],
|
||||
'display_name' => $user['display_name'],
|
||||
],
|
||||
], 201);
|
||||
}
|
||||
|
||||
function api_fetch_visible(int $id, array $user): array
|
||||
{
|
||||
$routine = routine_fetch($id);
|
||||
if ($routine === null) {
|
||||
abort_api(404, 'not_found', 'Kür nicht gefunden.');
|
||||
}
|
||||
if (!routine_can_view($routine, $user)) {
|
||||
abort_api(403, 'forbidden', 'Diese Kür ist nicht freigegeben.');
|
||||
}
|
||||
return $routine;
|
||||
}
|
||||
|
||||
function api_routine(int $id, string $method, array $user): void
|
||||
{
|
||||
$routine = api_fetch_visible($id, $user);
|
||||
if ($method === 'GET') {
|
||||
json_response(api_routine_payload($routine));
|
||||
}
|
||||
if ($method === 'DELETE') {
|
||||
if (!routine_can_edit($routine, $user)) {
|
||||
abort_api(403, 'forbidden', 'Nur der Eigentümer oder ein Admin darf die Kür ändern.');
|
||||
}
|
||||
routine_set_status($id, 'hidden');
|
||||
json_response(['id' => $id, 'status' => 'hidden']);
|
||||
}
|
||||
abort_api(405, 'method_not_allowed', 'Nur GET oder DELETE ist erlaubt.');
|
||||
}
|
||||
|
||||
function api_upload(array $user, ?int $routineId): void
|
||||
{
|
||||
if (!api_truthy($_POST['rights'] ?? null)) {
|
||||
abort_api(422, 'rights_required', 'Bitte bestätigen, dass Kür und Musik geteilt werden dürfen.');
|
||||
}
|
||||
if (!routine_upload_quota_ok((int) $user['id'])) {
|
||||
abort_api(429, 'upload_limit', 'Stündliches Upload-Limit erreicht.');
|
||||
}
|
||||
$package = routine_validate_package($_POST);
|
||||
if (!$package['ok']) {
|
||||
json_response([
|
||||
'error' => ['code' => 'validation_failed', 'message' => 'Die Dateien sind nicht gültig.'],
|
||||
'errors' => $package['errors'],
|
||||
], 422);
|
||||
}
|
||||
|
||||
if ($routineId === null) {
|
||||
$duplicate = routine_duplicate_exists((int) $user['id'], $package);
|
||||
if ($duplicate !== null) {
|
||||
abort_api(409, 'duplicate', 'Diese Kür ist bereits im Hub (ID ' . $duplicate . ').');
|
||||
}
|
||||
$routineId = routine_create((int) $user['id'], $package);
|
||||
} else {
|
||||
$routine = routine_fetch($routineId);
|
||||
if ($routine === null) {
|
||||
abort_api(404, 'not_found', 'Kür nicht gefunden.');
|
||||
}
|
||||
if (!routine_can_edit($routine, $user)) {
|
||||
abort_api(403, 'forbidden', 'Nur der Eigentümer oder ein Admin darf die Kür ändern.');
|
||||
}
|
||||
routine_add_revision($routineId, (int) $user['id'], $package);
|
||||
}
|
||||
$created = routine_fetch($routineId);
|
||||
if ($created === null) {
|
||||
abort_api(500, 'server_error', 'Kür konnte nicht geladen werden.');
|
||||
}
|
||||
json_response(api_routine_payload($created), 201);
|
||||
}
|
||||
364
hub/app/auth.php
Normal file
364
hub/app/auth.php
Normal file
|
|
@ -0,0 +1,364 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Anmeldung, Sessions, Remember-Me und Ratenbegrenzung.
|
||||
*
|
||||
* Passwörter: Argon2id, falls verfügbar, sonst der PHP-Standard (bcrypt).
|
||||
* Sessions: native PHP-Session, Cookie HttpOnly/Secure/SameSite=Lax.
|
||||
* Zusätzlich auth_epoch in users: Passwortwechsel und Sperren machen alle
|
||||
* bestehenden Sessions sofort ungültig.
|
||||
*/
|
||||
|
||||
const HUB_DUMMY_HASH = '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2uheWG/igi.';
|
||||
const HUB_REMEMBER_COOKIE = 'RHUB_REMEMBER';
|
||||
|
||||
function hash_password(string $password): string
|
||||
{
|
||||
if (defined('PASSWORD_ARGON2ID')) {
|
||||
return password_hash($password, PASSWORD_ARGON2ID, [
|
||||
'memory_cost' => 32768,
|
||||
'time_cost' => 3,
|
||||
'threads' => 2,
|
||||
]);
|
||||
}
|
||||
return password_hash($password, PASSWORD_DEFAULT);
|
||||
}
|
||||
|
||||
function password_needs_upgrade(string $hash): bool
|
||||
{
|
||||
if (defined('PASSWORD_ARGON2ID')) {
|
||||
return password_needs_rehash($hash, PASSWORD_ARGON2ID, [
|
||||
'memory_cost' => 32768,
|
||||
'time_cost' => 3,
|
||||
'threads' => 2,
|
||||
]);
|
||||
}
|
||||
return password_needs_rehash($hash, PASSWORD_DEFAULT);
|
||||
}
|
||||
|
||||
function auth_user(): ?array
|
||||
{
|
||||
static $loaded = false;
|
||||
static $user = null;
|
||||
if ($loaded) {
|
||||
return $user;
|
||||
}
|
||||
$loaded = true;
|
||||
|
||||
$uid = $_SESSION['uid'] ?? null;
|
||||
if (!is_int($uid) && !ctype_digit((string) $uid)) {
|
||||
auth_restore_from_remember();
|
||||
$uid = $_SESSION['uid'] ?? null;
|
||||
if (!is_int($uid) && !ctype_digit((string) $uid)) {
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
$uid = (int) $uid;
|
||||
|
||||
$stmt = db()->prepare('SELECT * FROM users WHERE id = ? LIMIT 1');
|
||||
$stmt->execute([$uid]);
|
||||
$row = $stmt->fetch();
|
||||
if (!$row || $row['status'] !== 'active') {
|
||||
auth_clear_session();
|
||||
return $user;
|
||||
}
|
||||
if ((int) ($_SESSION['epoch'] ?? 0) !== (int) $row['auth_epoch']) {
|
||||
auth_clear_session();
|
||||
return $user;
|
||||
}
|
||||
|
||||
$now = time();
|
||||
$idleLimit = (int) config('app.session_idle_seconds', 1209600);
|
||||
$absoluteLimit = (int) config('app.session_absolute_seconds', 2592000);
|
||||
$created = (int) ($_SESSION['created'] ?? 0);
|
||||
$lastSeen = (int) ($_SESSION['last_seen'] ?? 0);
|
||||
if ($created === 0 || $lastSeen === 0
|
||||
|| $now - $lastSeen > $idleLimit
|
||||
|| $now - $created > $absoluteLimit
|
||||
) {
|
||||
auth_clear_session();
|
||||
return $user;
|
||||
}
|
||||
|
||||
if ($now - $lastSeen > 300) {
|
||||
$_SESSION['last_seen'] = $now;
|
||||
}
|
||||
|
||||
$row['id'] = (int) $row['id'];
|
||||
$row['auth_epoch'] = (int) $row['auth_epoch'];
|
||||
$row['must_change_password'] = (int) $row['must_change_password'];
|
||||
$user = $row;
|
||||
return $user;
|
||||
}
|
||||
|
||||
function auth_user_by_id(int $id): ?array
|
||||
{
|
||||
$stmt = db()->prepare('SELECT * FROM users WHERE id = ? LIMIT 1');
|
||||
$stmt->execute([$id]);
|
||||
$row = $stmt->fetch();
|
||||
if (!$row) {
|
||||
return null;
|
||||
}
|
||||
$row['id'] = (int) $row['id'];
|
||||
$row['auth_epoch'] = (int) $row['auth_epoch'];
|
||||
$row['must_change_password'] = (int) $row['must_change_password'];
|
||||
return $row;
|
||||
}
|
||||
|
||||
function auth_login(array $user, bool $remember = false): void
|
||||
{
|
||||
session_regenerate_id(true);
|
||||
$_SESSION['uid'] = (int) $user['id'];
|
||||
$_SESSION['epoch'] = (int) $user['auth_epoch'];
|
||||
$_SESSION['created'] = time();
|
||||
$_SESSION['last_seen'] = time();
|
||||
$_SESSION['csrf'] = bin2hex(random_bytes(32));
|
||||
|
||||
$stmt = db()->prepare('UPDATE users SET last_login_at = ? WHERE id = ?');
|
||||
$stmt->execute([utc_now(), (int) $user['id']]);
|
||||
|
||||
if ($remember) {
|
||||
auth_issue_remember((int) $user['id']);
|
||||
}
|
||||
audit('user.login', 'user', (int) $user['id'], 'Anmeldung', (int) $user['id']);
|
||||
}
|
||||
|
||||
function auth_clear_session(): void
|
||||
{
|
||||
$_SESSION = [];
|
||||
if (session_status() === PHP_SESSION_ACTIVE) {
|
||||
session_regenerate_id(true);
|
||||
}
|
||||
}
|
||||
|
||||
function auth_logout(): void
|
||||
{
|
||||
$user = auth_user();
|
||||
if ($user) {
|
||||
audit('user.logout', 'user', (int) $user['id'], '', (int) $user['id']);
|
||||
}
|
||||
auth_forget_remember();
|
||||
auth_clear_session();
|
||||
session_destroy();
|
||||
}
|
||||
|
||||
function auth_require_login(): array
|
||||
{
|
||||
$user = auth_user();
|
||||
if ($user === null) {
|
||||
$target = (string) ($_SERVER['REQUEST_URI'] ?? '/');
|
||||
redirect('/login?next=' . rawurlencode($target));
|
||||
}
|
||||
return $user;
|
||||
}
|
||||
|
||||
function auth_require_admin(): array
|
||||
{
|
||||
$user = auth_require_login();
|
||||
if ($user['role'] !== 'admin') {
|
||||
abort_page(403, 'Dieser Bereich ist nur für Administratoren.');
|
||||
}
|
||||
return $user;
|
||||
}
|
||||
|
||||
function auth_is_admin(?array $user): bool
|
||||
{
|
||||
return $user !== null && ($user['role'] ?? '') === 'admin';
|
||||
}
|
||||
|
||||
function auth_attempt(string $login, string $password): array
|
||||
{
|
||||
$login = trim($login);
|
||||
$ip = client_ip();
|
||||
$window = (int) config('app.login_window_seconds', 900);
|
||||
$maxUser = (int) config('app.login_max_per_user', 5);
|
||||
$maxIp = (int) config('app.login_max_per_ip', 10);
|
||||
$since = gmdate('Y-m-d H:i:s', time() - $window);
|
||||
|
||||
$stmt = db()->prepare(
|
||||
'SELECT SUM(username = ?) AS by_user, SUM(ip = ?) AS by_ip, MIN(created_at) AS first_seen
|
||||
FROM login_attempts
|
||||
WHERE success = 0 AND created_at >= ? AND (username = ? OR ip = ?)'
|
||||
);
|
||||
$stmt->execute([$login, $ip, $since, $login, $ip]);
|
||||
$window_row = $stmt->fetch() ?: [];
|
||||
$byUser = (int) ($window_row['by_user'] ?? 0);
|
||||
$byIp = (int) ($window_row['by_ip'] ?? 0);
|
||||
if ($byUser >= $maxUser || $byIp >= $maxIp) {
|
||||
$first = strtotime((string) ($window_row['first_seen'] ?? 'now') . ' UTC');
|
||||
$retry = max(60, (int) $first + $window - time());
|
||||
return [
|
||||
'ok' => false,
|
||||
'error' => 'Zu viele Fehlversuche. Bitte in ' . max(1, (int) ceil($retry / 60)) . ' Minuten erneut versuchen.',
|
||||
'retry' => $retry,
|
||||
];
|
||||
}
|
||||
|
||||
$stmt = db()->prepare('SELECT * FROM users WHERE username = ? OR email = ? LIMIT 1');
|
||||
$stmt->execute([$login, $login]);
|
||||
$user = $stmt->fetch() ?: null;
|
||||
|
||||
$hash = $user['password_hash'] ?? HUB_DUMMY_HASH;
|
||||
$valid = password_verify($password, $hash);
|
||||
|
||||
$stmt = db()->prepare(
|
||||
'INSERT INTO login_attempts (username, ip, success, created_at) VALUES (?, ?, ?, ?)'
|
||||
);
|
||||
$stmt->execute([mb_substr($login, 0, 190, 'UTF-8'), $ip, $valid ? 1 : 0, utc_now()]);
|
||||
|
||||
if (random_int(1, 100) === 1) {
|
||||
db()->prepare('DELETE FROM login_attempts WHERE created_at < ? LIMIT 1000')
|
||||
->execute([gmdate('Y-m-d H:i:s', time() - 30 * 86400)]);
|
||||
}
|
||||
|
||||
if (!$user || !$valid) {
|
||||
return ['ok' => false, 'error' => 'Benutzername oder Passwort ist falsch.', 'retry' => 0];
|
||||
}
|
||||
if ($user['status'] !== 'active') {
|
||||
return ['ok' => false, 'error' => 'Dieses Konto ist deaktiviert.', 'retry' => 0];
|
||||
}
|
||||
if (password_needs_upgrade((string) $user['password_hash'])) {
|
||||
db()->prepare('UPDATE users SET password_hash = ? WHERE id = ?')
|
||||
->execute([hash_password($password), (int) $user['id']]);
|
||||
}
|
||||
return ['ok' => true, 'user' => $user, 'error' => '', 'retry' => 0];
|
||||
}
|
||||
|
||||
function auth_next_url(string $fallback = '/'): string
|
||||
{
|
||||
$next = (string) ($_POST['next'] ?? $_GET['next'] ?? '');
|
||||
if ($next === '' || $next[0] !== '/' || str_starts_with($next, '//')
|
||||
|| str_starts_with($next, '/api/')
|
||||
) {
|
||||
return $fallback;
|
||||
}
|
||||
return $next;
|
||||
}
|
||||
|
||||
function auth_issue_remember(int $userId): void
|
||||
{
|
||||
$selector = bin2hex(random_bytes(12));
|
||||
$validator = bin2hex(random_bytes(32));
|
||||
$seconds = (int) config('app.remember_seconds', 2592000);
|
||||
$stmt = db()->prepare(
|
||||
'INSERT INTO remember_tokens (user_id, selector, validator_hash, created_at, expires_at, user_agent, ip)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)'
|
||||
);
|
||||
$stmt->execute([
|
||||
$userId,
|
||||
$selector,
|
||||
hash('sha256', $validator),
|
||||
utc_now(),
|
||||
utc_after($seconds),
|
||||
user_agent(),
|
||||
client_ip(),
|
||||
]);
|
||||
setcookie(HUB_REMEMBER_COOKIE, $selector . ':' . $validator, [
|
||||
'expires' => time() + $seconds,
|
||||
'path' => '/',
|
||||
'secure' => is_https(),
|
||||
'httponly' => true,
|
||||
'samesite' => 'Lax',
|
||||
]);
|
||||
}
|
||||
|
||||
function auth_restore_from_remember(): void
|
||||
{
|
||||
$cookie = (string) ($_COOKIE[HUB_REMEMBER_COOKIE] ?? '');
|
||||
if ($cookie === '' || substr_count($cookie, ':') !== 1) {
|
||||
return;
|
||||
}
|
||||
[$selector, $validator] = explode(':', $cookie, 2);
|
||||
if (strlen($selector) !== 24 || strlen($validator) !== 64) {
|
||||
return;
|
||||
}
|
||||
|
||||
$stmt = db()->prepare(
|
||||
'SELECT rt.*, u.* FROM remember_tokens rt
|
||||
JOIN users u ON u.id = rt.user_id
|
||||
WHERE rt.selector = ? AND rt.expires_at > ? LIMIT 1'
|
||||
);
|
||||
$stmt->execute([$selector, utc_now()]);
|
||||
$row = $stmt->fetch();
|
||||
if (!$row || !hash_equals((string) $row['validator_hash'], hash('sha256', $validator))) {
|
||||
return;
|
||||
}
|
||||
if ($row['status'] !== 'active') {
|
||||
return;
|
||||
}
|
||||
|
||||
db()->prepare('DELETE FROM remember_tokens WHERE id = ?')->execute([(int) $row['id']]);
|
||||
$_SESSION['uid'] = (int) $row['user_id'];
|
||||
$_SESSION['epoch'] = (int) $row['auth_epoch'];
|
||||
$_SESSION['created'] = time();
|
||||
$_SESSION['last_seen'] = time();
|
||||
$_SESSION['csrf'] = bin2hex(random_bytes(32));
|
||||
session_regenerate_id(true);
|
||||
auth_issue_remember((int) $row['user_id']);
|
||||
db()->prepare('UPDATE users SET last_login_at = ? WHERE id = ?')
|
||||
->execute([utc_now(), (int) $row['user_id']]);
|
||||
audit('user.login_remember', 'user', (int) $row['user_id'], '', (int) $row['user_id']);
|
||||
}
|
||||
|
||||
function auth_forget_remember(): void
|
||||
{
|
||||
$cookie = (string) ($_COOKIE[HUB_REMEMBER_COOKIE] ?? '');
|
||||
if (str_contains($cookie, ':')) {
|
||||
[$selector] = explode(':', $cookie, 2);
|
||||
if (strlen($selector) === 24) {
|
||||
db()->prepare('DELETE FROM remember_tokens WHERE selector = ?')->execute([$selector]);
|
||||
}
|
||||
}
|
||||
if (isset($_COOKIE[HUB_REMEMBER_COOKIE])) {
|
||||
setcookie(HUB_REMEMBER_COOKIE, '', [
|
||||
'expires' => time() - 3600,
|
||||
'path' => '/',
|
||||
'secure' => is_https(),
|
||||
'httponly' => true,
|
||||
'samesite' => 'Lax',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
function auth_revoke_sessions(int $userId): void
|
||||
{
|
||||
db()->prepare('UPDATE users SET auth_epoch = auth_epoch + 1 WHERE id = ?')->execute([$userId]);
|
||||
db()->prepare('DELETE FROM remember_tokens WHERE user_id = ?')->execute([$userId]);
|
||||
db()->prepare('DELETE FROM api_tokens WHERE user_id = ?')->execute([$userId]);
|
||||
if ((int) ($_SESSION['uid'] ?? 0) === $userId) {
|
||||
$stmt = db()->prepare('SELECT auth_epoch FROM users WHERE id = ?');
|
||||
$stmt->execute([$userId]);
|
||||
$epoch = $stmt->fetchColumn();
|
||||
if ($epoch !== false) {
|
||||
$_SESSION['epoch'] = (int) $epoch;
|
||||
session_regenerate_id(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function audit(
|
||||
string $action,
|
||||
?string $subjectType = null,
|
||||
?int $subjectId = null,
|
||||
string $detail = '',
|
||||
?int $actorId = null
|
||||
): void {
|
||||
if ($actorId === null) {
|
||||
$current = auth_user();
|
||||
$actorId = $current ? (int) $current['id'] : null;
|
||||
}
|
||||
$stmt = db()->prepare(
|
||||
'INSERT INTO audit_log (actor_id, action, subject_type, subject_id, detail, ip, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)'
|
||||
);
|
||||
$stmt->execute([
|
||||
$actorId,
|
||||
mb_substr($action, 0, 64, 'UTF-8'),
|
||||
$subjectType,
|
||||
$subjectId,
|
||||
mb_substr($detail, 0, 255, 'UTF-8'),
|
||||
client_ip(),
|
||||
utc_now(),
|
||||
]);
|
||||
}
|
||||
59
hub/app/bootstrap.php
Normal file
59
hub/app/bootstrap.php
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Rinkplanner-Hub – Bootstrap.
|
||||
*
|
||||
* Lädt Konfiguration, Datenbank, Session und Helfer. Die Konfiguration mit
|
||||
* Zugangsdaten liegt in app/config.local.php und wird beim Deployment erzeugt.
|
||||
*/
|
||||
|
||||
define('HUB_ROOT', dirname(__DIR__));
|
||||
define('HUB_APP', __DIR__);
|
||||
|
||||
$configFile = HUB_APP . '/config.local.php';
|
||||
if (!is_file($configFile)) {
|
||||
http_response_code(500);
|
||||
header('Content-Type: text/plain; charset=utf-8');
|
||||
echo "Der Hub ist noch nicht konfiguriert (app/config.local.php fehlt).\n";
|
||||
exit;
|
||||
}
|
||||
|
||||
$GLOBALS['hub_config'] = require $configFile;
|
||||
|
||||
date_default_timezone_set('UTC');
|
||||
ini_set('display_errors', '0');
|
||||
ini_set('log_errors', '1');
|
||||
|
||||
require HUB_APP . '/util.php';
|
||||
require HUB_APP . '/db.php';
|
||||
require HUB_APP . '/auth.php';
|
||||
require HUB_APP . '/invites.php';
|
||||
require HUB_APP . '/tokens.php';
|
||||
require HUB_APP . '/routines.php';
|
||||
require HUB_APP . '/pages.php';
|
||||
require HUB_APP . '/api.php';
|
||||
|
||||
$storage = (string) config('app.storage_path', HUB_ROOT . '/storage');
|
||||
if (is_dir($storage) && is_writable($storage)) {
|
||||
ini_set('error_log', $storage . '/logs/php.log');
|
||||
}
|
||||
|
||||
set_exception_handler(static function (Throwable $error): void {
|
||||
error_log('Hub: ' . $error::class . ': ' . $error->getMessage() . ' in ' . $error->getFile() . ':' . $error->getLine());
|
||||
if (function_exists('wants_json') && wants_json()) {
|
||||
json_response(['error' => ['code' => 'server_error', 'message' => 'Interner Fehler.']], 500);
|
||||
return;
|
||||
}
|
||||
http_response_code(500);
|
||||
header('Content-Type: text/html; charset=utf-8');
|
||||
echo '<!doctype html><meta charset="utf-8"><title>Fehler</title>'
|
||||
. '<body style="font-family:system-ui;background:#050d19;color:#eefaff;padding:2rem">'
|
||||
. '<h1>Interner Fehler</h1><p>Bitte später erneut versuchen.</p></body>';
|
||||
});
|
||||
|
||||
security_headers();
|
||||
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
start_session();
|
||||
}
|
||||
31
hub/app/config.example.php
Normal file
31
hub/app/config.example.php
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
<?php
|
||||
/**
|
||||
* Beispielkonfiguration. Wird nicht ausgeliefert; beim Deployment erzeugt
|
||||
* tools/deploy_hub.sh daraus app/config.local.php.
|
||||
*/
|
||||
return [
|
||||
'db' => [
|
||||
'host' => 'localhost',
|
||||
'port' => 3306,
|
||||
'name' => 'DB_NAME',
|
||||
'user' => 'DB_USER',
|
||||
'password' => 'DB_PASSWORD',
|
||||
'charset' => 'utf8mb4',
|
||||
],
|
||||
'app' => [
|
||||
// Leer, wenn der Hub direkt im DocumentRoot der Subdomain liegt.
|
||||
'base_path' => '',
|
||||
'public_url' => 'https://rinkplanner-hub.programmschmiede.de',
|
||||
'storage_path' => dirname(__DIR__) . '/storage',
|
||||
'install_token' => 'wird-beim-deployment-erzeugt',
|
||||
'max_routine_bytes' => 8 * 1024 * 1024,
|
||||
'max_audio_bytes' => 50 * 1024 * 1024,
|
||||
'session_idle_seconds' => 14 * 86400,
|
||||
'session_absolute_seconds' => 30 * 86400,
|
||||
'remember_seconds' => 30 * 86400,
|
||||
'login_window_seconds' => 900,
|
||||
'login_max_per_user' => 5,
|
||||
'login_max_per_ip' => 10,
|
||||
'uploads_per_hour' => 20,
|
||||
],
|
||||
];
|
||||
28
hub/app/db.php
Normal file
28
hub/app/db.php
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
function db(): PDO
|
||||
{
|
||||
static $pdo = null;
|
||||
if ($pdo instanceof PDO) {
|
||||
return $pdo;
|
||||
}
|
||||
|
||||
$db = (array) config('db', []);
|
||||
$dsn = sprintf(
|
||||
'mysql:host=%s;port=%d;dbname=%s;charset=%s',
|
||||
(string) ($db['host'] ?? 'localhost'),
|
||||
(int) ($db['port'] ?? 3306),
|
||||
(string) ($db['name'] ?? ''),
|
||||
(string) ($db['charset'] ?? 'utf8mb4')
|
||||
);
|
||||
|
||||
$pdo = new PDO($dsn, (string) ($db['user'] ?? ''), (string) ($db['password'] ?? ''), [
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
||||
PDO::ATTR_EMULATE_PREPARES => false,
|
||||
PDO::ATTR_STRINGIFY_FETCHES => false,
|
||||
]);
|
||||
$pdo->exec("SET time_zone = '+00:00'");
|
||||
return $pdo;
|
||||
}
|
||||
118
hub/app/invites.php
Normal file
118
hub/app/invites.php
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
const HUB_INVITE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||
|
||||
function invite_normalize(string $code): string
|
||||
{
|
||||
$code = strtoupper(trim($code));
|
||||
return preg_replace('/[^A-Z0-9]/', '', $code) ?? '';
|
||||
}
|
||||
|
||||
function invite_hash(string $code): string
|
||||
{
|
||||
return hash('sha256', invite_normalize($code));
|
||||
}
|
||||
|
||||
function invite_generate(): string
|
||||
{
|
||||
$groups = [];
|
||||
for ($group = 0; $group < 4; $group++) {
|
||||
$part = '';
|
||||
for ($i = 0; $i < 4; $i++) {
|
||||
$part .= HUB_INVITE_ALPHABET[random_int(0, strlen(HUB_INVITE_ALPHABET) - 1)];
|
||||
}
|
||||
$groups[] = $part;
|
||||
}
|
||||
return 'RHUB-' . implode('-', $groups);
|
||||
}
|
||||
|
||||
function invite_create(string $note, string $email, int $expiresDays, int $createdBy): string
|
||||
{
|
||||
$code = invite_generate();
|
||||
$expiresAt = null;
|
||||
if ($expiresDays > 0) {
|
||||
$expiresAt = utc_after(min($expiresDays, 365) * 86400);
|
||||
}
|
||||
$stmt = db()->prepare(
|
||||
'INSERT INTO invites (code_hash, note, email, created_by, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)'
|
||||
);
|
||||
$stmt->execute([
|
||||
invite_hash($code),
|
||||
$note !== '' ? mb_substr($note, 0, 190, 'UTF-8') : null,
|
||||
$email !== '' ? mb_substr($email, 0, 190, 'UTF-8') : null,
|
||||
$createdBy,
|
||||
utc_now(),
|
||||
$expiresAt,
|
||||
]);
|
||||
audit('invite.create', 'invite', (int) db()->lastInsertId(), $note, $createdBy);
|
||||
return $code;
|
||||
}
|
||||
|
||||
function invite_find_valid(string $code): ?array
|
||||
{
|
||||
$normalized = invite_normalize($code);
|
||||
if ($normalized === '') {
|
||||
return null;
|
||||
}
|
||||
$stmt = db()->prepare(
|
||||
'SELECT * FROM invites WHERE code_hash = ? AND used_by IS NULL AND used_at IS NULL
|
||||
AND revoked_at IS NULL LIMIT 1'
|
||||
);
|
||||
$stmt->execute([invite_hash($normalized)]);
|
||||
$row = $stmt->fetch();
|
||||
if (!$row) {
|
||||
return null;
|
||||
}
|
||||
if ($row['expires_at'] !== null && $row['expires_at'] <= utc_now()) {
|
||||
return null;
|
||||
}
|
||||
return $row;
|
||||
}
|
||||
|
||||
function invite_consume(int $inviteId, int $userId): bool
|
||||
{
|
||||
$stmt = db()->prepare(
|
||||
'UPDATE invites SET used_by = ?, used_at = ?
|
||||
WHERE id = ? AND used_by IS NULL AND used_at IS NULL AND revoked_at IS NULL
|
||||
AND (expires_at IS NULL OR expires_at > ?)'
|
||||
);
|
||||
$stmt->execute([$userId, utc_now(), $inviteId, utc_now()]);
|
||||
return $stmt->rowCount() === 1;
|
||||
}
|
||||
|
||||
function invite_revoke(int $inviteId): bool
|
||||
{
|
||||
$stmt = db()->prepare(
|
||||
'UPDATE invites SET revoked_at = ? WHERE id = ? AND used_by IS NULL AND revoked_at IS NULL'
|
||||
);
|
||||
$stmt->execute([utc_now(), $inviteId]);
|
||||
return $stmt->rowCount() === 1;
|
||||
}
|
||||
|
||||
function invites_list(): array
|
||||
{
|
||||
return db()->query(
|
||||
"SELECT i.*, c.username AS creator_name, u.username AS used_name
|
||||
FROM invites i
|
||||
LEFT JOIN users c ON c.id = i.created_by
|
||||
LEFT JOIN users u ON u.id = i.used_by
|
||||
ORDER BY i.created_at DESC, i.id DESC
|
||||
LIMIT 200"
|
||||
)->fetchAll();
|
||||
}
|
||||
|
||||
function invite_status(array $invite): string
|
||||
{
|
||||
if ($invite['revoked_at'] !== null) {
|
||||
return 'widerrufen';
|
||||
}
|
||||
if ($invite['used_at'] !== null) {
|
||||
return 'eingelöst';
|
||||
}
|
||||
if ($invite['expires_at'] !== null && $invite['expires_at'] <= utc_now()) {
|
||||
return 'abgelaufen';
|
||||
}
|
||||
return 'offen';
|
||||
}
|
||||
729
hub/app/pages.php
Normal file
729
hub/app/pages.php
Normal file
|
|
@ -0,0 +1,729 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/** Web-Oberfläche: Routen, Formulare und Admin-Seiten. */
|
||||
|
||||
const HUB_RESERVED_USERNAMES = [
|
||||
'admin', 'administrator', 'root', 'system', 'support', 'moderator',
|
||||
'rinkplanner', 'hub', 'team', 'test', 'guest', 'gast',
|
||||
];
|
||||
|
||||
function page_handle(string $method, string $path): void
|
||||
{
|
||||
$path = '/' . trim($path, '/');
|
||||
if (!in_array($method, ['GET', 'POST'], true)) {
|
||||
abort_page(405, 'Diese Methode ist nicht erlaubt.');
|
||||
}
|
||||
|
||||
if ($path === '/health') {
|
||||
health_check();
|
||||
return;
|
||||
}
|
||||
|
||||
$user = auth_user();
|
||||
if ($user !== null && $user['must_change_password'] === 1
|
||||
&& !in_array($path, ['/account', '/account/password', '/logout'], true)
|
||||
) {
|
||||
flash('info', 'Bitte zuerst das Passwort ändern.');
|
||||
redirect('/account');
|
||||
}
|
||||
|
||||
if ($path === '/login') {
|
||||
page_login($method);
|
||||
return;
|
||||
}
|
||||
if ($path === '/register') {
|
||||
page_register($method);
|
||||
return;
|
||||
}
|
||||
if ($path === '/logout') {
|
||||
if ($method !== 'POST' || !csrf_valid()) {
|
||||
redirect('/');
|
||||
}
|
||||
auth_logout();
|
||||
flash('success', 'Abgemeldet.');
|
||||
redirect('/login');
|
||||
}
|
||||
if ($path === '/') {
|
||||
page_dashboard($method);
|
||||
return;
|
||||
}
|
||||
if ($path === '/upload') {
|
||||
page_upload($method);
|
||||
return;
|
||||
}
|
||||
if ($path === '/account') {
|
||||
page_account($method);
|
||||
return;
|
||||
}
|
||||
if ($path === '/account/password') {
|
||||
page_account_password($method);
|
||||
return;
|
||||
}
|
||||
if ($path === '/account/tokens') {
|
||||
page_account_token_create($method);
|
||||
return;
|
||||
}
|
||||
if ($path === '/account/tokens/revoke') {
|
||||
page_account_token_revoke($method);
|
||||
return;
|
||||
}
|
||||
if ($path === '/admin/invites') {
|
||||
page_admin_invites($method);
|
||||
return;
|
||||
}
|
||||
if ($path === '/admin/invites/revoke') {
|
||||
page_admin_invite_revoke($method);
|
||||
return;
|
||||
}
|
||||
if ($path === '/admin/users') {
|
||||
page_admin_users($method);
|
||||
return;
|
||||
}
|
||||
if ($path === '/admin/users/action') {
|
||||
page_admin_user_action($method);
|
||||
return;
|
||||
}
|
||||
if ($path === '/admin/routines') {
|
||||
page_admin_routines($method);
|
||||
return;
|
||||
}
|
||||
if ($path === '/admin/routines/action') {
|
||||
page_admin_routine_action($method);
|
||||
return;
|
||||
}
|
||||
if ($path === '/admin/audit') {
|
||||
require_admin_page();
|
||||
render_page('admin_audit', ['entries' => audit_list(200)], 'Audit-Log');
|
||||
return;
|
||||
}
|
||||
|
||||
if (preg_match('#^/routines/(\d+)$#', $path, $matches) === 1) {
|
||||
page_routine_detail((int) $matches[1], $method);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/routines/(\d+)/(download|audio)$#', $path, $matches) === 1) {
|
||||
page_routine_file((int) $matches[1], (string) $matches[2]);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/routines/(\d+)/revise$#', $path, $matches) === 1) {
|
||||
page_routine_revise((int) $matches[1], $method);
|
||||
return;
|
||||
}
|
||||
if (preg_match('#^/routines/(\d+)/(hide|publish)$#', $path, $matches) === 1) {
|
||||
page_routine_status((int) $matches[1], (string) $matches[2], $method);
|
||||
return;
|
||||
}
|
||||
|
||||
abort_page(404, 'Diese Seite gibt es nicht.');
|
||||
}
|
||||
|
||||
function health_check(): void
|
||||
{
|
||||
try {
|
||||
db()->query('SELECT 1');
|
||||
header('Content-Type: text/plain; charset=utf-8');
|
||||
echo "ok\n";
|
||||
} catch (Throwable) {
|
||||
http_response_code(503);
|
||||
header('Content-Type: text/plain; charset=utf-8');
|
||||
echo "db error\n";
|
||||
}
|
||||
}
|
||||
|
||||
function require_admin_page(): array
|
||||
{
|
||||
return auth_require_admin();
|
||||
}
|
||||
|
||||
function page_login(string $method): void
|
||||
{
|
||||
if (auth_user() !== null) {
|
||||
redirect('/');
|
||||
}
|
||||
$error = '';
|
||||
$login = '';
|
||||
$next = auth_next_url('/');
|
||||
if ($method === 'POST') {
|
||||
csrf_require();
|
||||
$login = post_string('login');
|
||||
$password = (string) ($_POST['password'] ?? '');
|
||||
$result = auth_attempt($login, $password);
|
||||
if ($result['ok']) {
|
||||
auth_login($result['user'], isset($_POST['remember']));
|
||||
redirect(auth_next_url($next));
|
||||
}
|
||||
$error = (string) $result['error'];
|
||||
if (($result['retry'] ?? 0) > 0) {
|
||||
http_response_code(429);
|
||||
header('Retry-After: ' . (int) $result['retry']);
|
||||
}
|
||||
}
|
||||
render_page('login', [
|
||||
'error' => $error,
|
||||
'login' => $login,
|
||||
'next' => $next,
|
||||
], 'Anmelden');
|
||||
}
|
||||
|
||||
function username_error(string $username): ?string
|
||||
{
|
||||
if (mb_strlen($username, 'UTF-8') < 3 || mb_strlen($username, 'UTF-8') > 32) {
|
||||
return 'Der Benutzername muss 3 bis 32 Zeichen lang sein.';
|
||||
}
|
||||
if (preg_match('/^[a-z0-9](?:[a-z0-9._-]{1,30}[a-z0-9])$/u', $username) !== 1) {
|
||||
return 'Nur Kleinbuchstaben, Ziffern, Punkt, Bindestrich und Unterstrich; Anfang und Ende alphanumerisch.';
|
||||
}
|
||||
if (in_array($username, HUB_RESERVED_USERNAMES, true)) {
|
||||
return 'Dieser Benutzername ist reserviert.';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function page_register(string $method): void
|
||||
{
|
||||
if (auth_user() !== null) {
|
||||
redirect('/');
|
||||
}
|
||||
$invite = null;
|
||||
$code = '';
|
||||
$errors = [];
|
||||
$input = [
|
||||
'username' => '',
|
||||
'display_name' => '',
|
||||
'email' => '',
|
||||
];
|
||||
|
||||
if ($method === 'GET') {
|
||||
$code = query_string('code');
|
||||
$invite = invite_find_valid($code);
|
||||
if ($invite !== null && !empty($invite['email'])) {
|
||||
$input['email'] = (string) $invite['email'];
|
||||
}
|
||||
} else {
|
||||
csrf_require();
|
||||
$code = post_string('code');
|
||||
$invite = invite_find_valid($code);
|
||||
$input['username'] = mb_strtolower(post_string('username'));
|
||||
$input['display_name'] = post_string('display_name');
|
||||
$input['email'] = post_string('email');
|
||||
|
||||
if ($invite === null) {
|
||||
$errors[] = 'Dieser Einladungscode ist ungültig, abgelaufen oder bereits eingelöst.';
|
||||
} elseif (!empty($invite['email']) && $input['email'] === '') {
|
||||
$input['email'] = (string) $invite['email'];
|
||||
}
|
||||
$usernameError = username_error($input['username']);
|
||||
if ($usernameError !== null) {
|
||||
$errors[] = $usernameError;
|
||||
}
|
||||
if ($input['display_name'] === '') {
|
||||
$input['display_name'] = $input['username'];
|
||||
}
|
||||
if (mb_strlen($input['display_name'], 'UTF-8') > 64) {
|
||||
$errors[] = 'Der Anzeigename darf höchstens 64 Zeichen lang sein.';
|
||||
}
|
||||
if ($input['email'] !== '' && filter_var($input['email'], FILTER_VALIDATE_EMAIL) === false) {
|
||||
$errors[] = 'Die E-Mail-Adresse ist nicht gültig.';
|
||||
}
|
||||
if ($invite !== null && !empty($invite['email'])
|
||||
&& strcasecmp((string) $invite['email'], $input['email']) !== 0
|
||||
) {
|
||||
$errors[] = 'Diese Einladung ist an eine andere E-Mail-Adresse gebunden.';
|
||||
}
|
||||
$password = (string) ($_POST['password'] ?? '');
|
||||
$repeat = (string) ($_POST['password_repeat'] ?? '');
|
||||
$policy = password_policy_error($password, $input['username']);
|
||||
if ($policy !== null) {
|
||||
$errors[] = $policy;
|
||||
}
|
||||
if ($password !== $repeat) {
|
||||
$errors[] = 'Die Passwortwiederholung passt nicht.';
|
||||
}
|
||||
if (($_POST['rights'] ?? '') !== '1') {
|
||||
$errors[] = 'Bitte die Beta-Regeln akzeptieren.';
|
||||
}
|
||||
|
||||
if (!$errors && $invite !== null) {
|
||||
$pdo = db();
|
||||
try {
|
||||
$pdo->beginTransaction();
|
||||
$stmt = $pdo->prepare(
|
||||
'INSERT INTO users
|
||||
(username, display_name, email, password_hash, role, status,
|
||||
must_change_password, auth_epoch, created_at, password_changed_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 0, 1, ?, ?)'
|
||||
);
|
||||
$now = utc_now();
|
||||
$stmt->execute([
|
||||
$input['username'],
|
||||
$input['display_name'],
|
||||
$input['email'] !== '' ? $input['email'] : null,
|
||||
hash_password($password),
|
||||
'user',
|
||||
'active',
|
||||
$now,
|
||||
$now,
|
||||
]);
|
||||
$newId = (int) $pdo->lastInsertId();
|
||||
if (!invite_consume((int) $invite['id'], $newId)) {
|
||||
$pdo->rollBack();
|
||||
$errors[] = 'Der Einladungscode wurde gerade eingelöst. Bitte einen neuen Code anfordern.';
|
||||
} else {
|
||||
audit('invite.use', 'invite', (int) $invite['id'], $input['username'], $newId);
|
||||
audit('user.register', 'user', $newId, $input['username'], $newId);
|
||||
$pdo->commit();
|
||||
}
|
||||
} catch (PDOException $exception) {
|
||||
if ($pdo->inTransaction()) {
|
||||
$pdo->rollBack();
|
||||
}
|
||||
if (str_contains($exception->getMessage(), 'uq_users_username')) {
|
||||
$errors[] = 'Dieser Benutzername ist schon vergeben.';
|
||||
} elseif (str_contains($exception->getMessage(), 'uq_users_email')) {
|
||||
$errors[] = 'Diese E-Mail-Adresse ist schon registriert.';
|
||||
} else {
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$errors) {
|
||||
$user = auth_user_by_id($newId);
|
||||
if ($user !== null) {
|
||||
auth_login($user);
|
||||
flash('success', 'Willkommen im Kür-Hub!');
|
||||
redirect('/');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
render_page('register', [
|
||||
'invite' => $invite,
|
||||
'code' => $code,
|
||||
'errors' => $errors,
|
||||
'input' => $input,
|
||||
], 'Registrieren');
|
||||
}
|
||||
|
||||
function page_dashboard(string $method): void
|
||||
{
|
||||
$user = auth_require_login();
|
||||
$query = query_string('q');
|
||||
$page = max(1, query_int('page', 1));
|
||||
$mine = query_string('mine') === '1';
|
||||
$result = routines_query($query, $page, 20, $mine ? (int) $user['id'] : null, $mine);
|
||||
render_page('dashboard', [
|
||||
'items' => $result['items'],
|
||||
'total' => $result['total'],
|
||||
'page' => $result['page'],
|
||||
'pages' => $result['pages'],
|
||||
'query' => $query,
|
||||
'mine' => $mine,
|
||||
], 'Küren');
|
||||
}
|
||||
|
||||
function page_routine_detail(int $id, string $method): void
|
||||
{
|
||||
$user = auth_require_login();
|
||||
$routine = routine_fetch($id);
|
||||
if ($routine === null) {
|
||||
abort_page(404, 'Diese Kür gibt es nicht.');
|
||||
}
|
||||
if (!routine_can_view($routine, $user)) {
|
||||
abort_page(403, 'Diese Kür ist nicht freigegeben.');
|
||||
}
|
||||
render_page('routine', [
|
||||
'routine' => $routine,
|
||||
'can_edit' => routine_can_edit($routine, $user),
|
||||
'is_admin' => auth_is_admin($user),
|
||||
], $routine['title']);
|
||||
}
|
||||
|
||||
function page_routine_file(int $id, string $kind): void
|
||||
{
|
||||
$user = auth_require_login();
|
||||
$routine = routine_fetch($id);
|
||||
if ($routine === null) {
|
||||
abort_page(404, 'Diese Kür gibt es nicht.');
|
||||
}
|
||||
if (!routine_can_view($routine, $user)) {
|
||||
abort_page(403, 'Diese Kür ist nicht freigegeben.');
|
||||
}
|
||||
routine_send_file($routine, $kind);
|
||||
}
|
||||
|
||||
function page_upload(string $method): void
|
||||
{
|
||||
$user = auth_require_login();
|
||||
$errors = [];
|
||||
$input = [
|
||||
'description' => '',
|
||||
'music_title' => '',
|
||||
'music_artist' => '',
|
||||
];
|
||||
|
||||
if ($method === 'POST') {
|
||||
csrf_require();
|
||||
if (!routine_upload_quota_ok((int) $user['id'])) {
|
||||
$errors[] = 'Stündliches Upload-Limit erreicht. Bitte später erneut versuchen.';
|
||||
}
|
||||
if (($_POST['rights'] ?? '') !== '1') {
|
||||
$errors[] = 'Bitte bestätigen, dass du Kür und Musik teilen darfst.';
|
||||
}
|
||||
if (!$errors) {
|
||||
$package = routine_validate_package($_POST);
|
||||
if (!$package['ok']) {
|
||||
$errors = $package['errors'];
|
||||
} else {
|
||||
$duplicate = routine_duplicate_exists((int) $user['id'], $package);
|
||||
if ($duplicate !== null) {
|
||||
flash('info', 'Diese Kür ist bereits im Hub.');
|
||||
redirect('/routines/' . $duplicate);
|
||||
}
|
||||
try {
|
||||
$routineId = routine_create((int) $user['id'], $package);
|
||||
flash('success', 'Kür veröffentlicht.');
|
||||
redirect('/routines/' . $routineId);
|
||||
} catch (Throwable $error) {
|
||||
hub_log('Upload fehlgeschlagen: ' . $error->getMessage());
|
||||
$errors[] = 'Die Kür konnte nicht gespeichert werden.';
|
||||
}
|
||||
}
|
||||
}
|
||||
$input['description'] = post_string('description');
|
||||
$input['music_title'] = post_string('music_title');
|
||||
$input['music_artist'] = post_string('music_artist');
|
||||
}
|
||||
|
||||
render_page('upload', [
|
||||
'errors' => $errors,
|
||||
'input' => $input,
|
||||
'routine' => null,
|
||||
], 'Kür hochladen');
|
||||
}
|
||||
|
||||
function page_routine_revise(int $id, string $method): void
|
||||
{
|
||||
$user = auth_require_login();
|
||||
$routine = routine_fetch($id);
|
||||
if ($routine === null) {
|
||||
abort_page(404, 'Diese Kür gibt es nicht.');
|
||||
}
|
||||
if (!routine_can_edit($routine, $user)) {
|
||||
abort_page(403, 'Nur der Eigentümer oder ein Admin kann diese Kür ändern.');
|
||||
}
|
||||
$errors = [];
|
||||
$input = [
|
||||
'description' => (string) ($routine['description'] ?? ''),
|
||||
'music_title' => (string) ($routine['music_title'] ?? ''),
|
||||
'music_artist' => (string) ($routine['music_artist'] ?? ''),
|
||||
];
|
||||
|
||||
if ($method === 'POST') {
|
||||
csrf_require();
|
||||
if (!routine_upload_quota_ok((int) $user['id'])) {
|
||||
$errors[] = 'Stündliches Upload-Limit erreicht. Bitte später erneut versuchen.';
|
||||
}
|
||||
if (($_POST['rights'] ?? '') !== '1') {
|
||||
$errors[] = 'Bitte bestätigen, dass du Kür und Musik teilen darfst.';
|
||||
}
|
||||
if (!$errors) {
|
||||
$package = routine_validate_package($_POST);
|
||||
if (!$package['ok']) {
|
||||
$errors = $package['errors'];
|
||||
} else {
|
||||
try {
|
||||
$revision = routine_add_revision($id, (int) $user['id'], $package);
|
||||
flash('success', 'Neue Revision ' . $revision . ' gespeichert.');
|
||||
redirect('/routines/' . $id);
|
||||
} catch (Throwable $error) {
|
||||
hub_log('Revision fehlgeschlagen: ' . $error->getMessage());
|
||||
$errors[] = 'Die Revision konnte nicht gespeichert werden.';
|
||||
}
|
||||
}
|
||||
}
|
||||
$input['description'] = post_string('description');
|
||||
$input['music_title'] = post_string('music_title');
|
||||
$input['music_artist'] = post_string('music_artist');
|
||||
}
|
||||
|
||||
render_page('upload', [
|
||||
'errors' => $errors,
|
||||
'input' => $input,
|
||||
'routine' => $routine,
|
||||
], 'Neue Revision');
|
||||
}
|
||||
|
||||
function page_routine_status(int $id, string $action, string $method): void
|
||||
{
|
||||
$user = auth_require_login();
|
||||
if ($method !== 'POST') {
|
||||
redirect('/routines/' . $id);
|
||||
}
|
||||
csrf_require();
|
||||
$routine = routine_fetch($id);
|
||||
if ($routine === null) {
|
||||
abort_page(404, 'Diese Kür gibt es nicht.');
|
||||
}
|
||||
if (!routine_can_edit($routine, $user)) {
|
||||
abort_page(403, 'Nur der Eigentümer oder ein Admin kann diese Kür ändern.');
|
||||
}
|
||||
$status = $action === 'publish' ? 'published' : 'hidden';
|
||||
routine_set_status($id, $status);
|
||||
flash('success', $status === 'published' ? 'Kür ist wieder sichtbar.' : 'Kür wurde aus dem Hub genommen.');
|
||||
redirect('/routines/' . $id);
|
||||
}
|
||||
|
||||
function page_account(string $method): void
|
||||
{
|
||||
$user = auth_require_login();
|
||||
render_page('account', [
|
||||
'tokens' => tokens_list((int) $user['id']),
|
||||
], 'Konto');
|
||||
}
|
||||
|
||||
function page_account_password(string $method): void
|
||||
{
|
||||
$user = auth_require_login();
|
||||
if ($method !== 'POST') {
|
||||
redirect('/account');
|
||||
}
|
||||
csrf_require();
|
||||
$current = (string) ($_POST['current_password'] ?? '');
|
||||
$password = (string) ($_POST['password'] ?? '');
|
||||
$repeat = (string) ($_POST['password_repeat'] ?? '');
|
||||
$errors = [];
|
||||
|
||||
if (!password_verify($current, (string) $user['password_hash'])) {
|
||||
$errors[] = 'Das aktuelle Passwort ist falsch.';
|
||||
}
|
||||
$policy = password_policy_error($password, (string) $user['username']);
|
||||
if ($policy !== null) {
|
||||
$errors[] = $policy;
|
||||
}
|
||||
if ($password !== $repeat) {
|
||||
$errors[] = 'Die Passwortwiederholung passt nicht.';
|
||||
}
|
||||
if ($errors) {
|
||||
foreach ($errors as $error) {
|
||||
flash('error', $error);
|
||||
}
|
||||
redirect('/account');
|
||||
}
|
||||
|
||||
db()->prepare(
|
||||
'UPDATE users SET password_hash = ?, password_changed_at = ?, must_change_password = 0 WHERE id = ?'
|
||||
)->execute([hash_password($password), utc_now(), (int) $user['id']]);
|
||||
auth_revoke_sessions((int) $user['id']);
|
||||
audit('user.password_change', 'user', (int) $user['id']);
|
||||
flash('success', 'Passwort geändert. Andere Sitzungen wurden abgemeldet.');
|
||||
redirect('/account');
|
||||
}
|
||||
|
||||
function page_account_token_create(string $method): void
|
||||
{
|
||||
$user = auth_require_login();
|
||||
if ($method !== 'POST') {
|
||||
redirect('/account');
|
||||
}
|
||||
csrf_require();
|
||||
$name = post_string('name');
|
||||
if ($name === '') {
|
||||
$name = 'App';
|
||||
}
|
||||
$created = token_create((int) $user['id'], $name);
|
||||
flash_secret('Neuer API-Token – jetzt kopieren, er wird nicht erneut angezeigt', $created['token']);
|
||||
redirect('/account');
|
||||
}
|
||||
|
||||
function page_account_token_revoke(string $method): void
|
||||
{
|
||||
$user = auth_require_login();
|
||||
if ($method !== 'POST') {
|
||||
redirect('/account');
|
||||
}
|
||||
csrf_require();
|
||||
$tokenId = (int) post_string('token_id');
|
||||
if (token_revoke($tokenId, (int) $user['id'])) {
|
||||
audit('token.revoke', 'token', $tokenId);
|
||||
flash('success', 'Token widerrufen.');
|
||||
} else {
|
||||
flash('error', 'Token nicht gefunden.');
|
||||
}
|
||||
redirect('/account');
|
||||
}
|
||||
|
||||
function page_admin_invites(string $method): void
|
||||
{
|
||||
$admin = require_admin_page();
|
||||
if ($method === 'POST') {
|
||||
csrf_require();
|
||||
$note = post_string('note');
|
||||
$email = post_string('email');
|
||||
$days = (int) post_string('expires_days', '30');
|
||||
$errors = [];
|
||||
if ($email !== '' && filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
|
||||
$errors[] = 'Die E-Mail-Adresse ist nicht gültig.';
|
||||
}
|
||||
if ($errors) {
|
||||
foreach ($errors as $error) {
|
||||
flash('error', $error);
|
||||
}
|
||||
} else {
|
||||
$code = invite_create($note, $email, $days, (int) $admin['id']);
|
||||
$publicUrl = rtrim((string) config('app.public_url', ''), '/');
|
||||
$link = $publicUrl . '/register?code=' . rawurlencode($code);
|
||||
flash_secret('Einladungscode', $code . ' – Link: ' . $link);
|
||||
flash('success', 'Einladung erstellt.');
|
||||
}
|
||||
redirect('/admin/invites');
|
||||
}
|
||||
render_page('admin_invites', [
|
||||
'invites' => invites_list(),
|
||||
], 'Einladungen');
|
||||
}
|
||||
|
||||
function page_admin_invite_revoke(string $method): void
|
||||
{
|
||||
require_admin_page();
|
||||
if ($method !== 'POST') {
|
||||
redirect('/admin/invites');
|
||||
}
|
||||
csrf_require();
|
||||
$inviteId = (int) post_string('invite_id');
|
||||
if (invite_revoke($inviteId)) {
|
||||
audit('invite.revoke', 'invite', $inviteId);
|
||||
flash('success', 'Einladung widerrufen.');
|
||||
} else {
|
||||
flash('error', 'Einladung konnte nicht widerrufen werden.');
|
||||
}
|
||||
redirect('/admin/invites');
|
||||
}
|
||||
|
||||
function page_admin_users(string $method): void
|
||||
{
|
||||
require_admin_page();
|
||||
$users = db()->query(
|
||||
'SELECT u.*, (SELECT COUNT(*) FROM routines r WHERE r.owner_id = u.id) AS routine_count
|
||||
FROM users u ORDER BY u.created_at DESC, u.id DESC'
|
||||
)->fetchAll();
|
||||
render_page('admin_users', ['users' => $users], 'Benutzer');
|
||||
}
|
||||
|
||||
function page_admin_user_action(string $method): void
|
||||
{
|
||||
$admin = require_admin_page();
|
||||
if ($method !== 'POST') {
|
||||
redirect('/admin/users');
|
||||
}
|
||||
csrf_require();
|
||||
$targetId = (int) post_string('user_id');
|
||||
$action = post_string('action');
|
||||
$target = auth_user_by_id($targetId);
|
||||
if ($target === null) {
|
||||
flash('error', 'Benutzer nicht gefunden.');
|
||||
redirect('/admin/users');
|
||||
}
|
||||
if ($targetId === (int) $admin['id']) {
|
||||
flash('error', 'Das eigene Konto lässt sich hier nicht ändern.');
|
||||
redirect('/admin/users');
|
||||
}
|
||||
|
||||
if ($action === 'disable') {
|
||||
db()->prepare("UPDATE users SET status = 'disabled' WHERE id = ?")->execute([$targetId]);
|
||||
auth_revoke_sessions($targetId);
|
||||
audit('user.disable', 'user', $targetId, (string) $target['username']);
|
||||
flash('success', 'Benutzer deaktiviert.');
|
||||
} elseif ($action === 'enable') {
|
||||
db()->prepare("UPDATE users SET status = 'active' WHERE id = ?")->execute([$targetId]);
|
||||
audit('user.enable', 'user', $targetId, (string) $target['username']);
|
||||
flash('success', 'Benutzer aktiviert.');
|
||||
} elseif ($action === 'reset') {
|
||||
$alphabet = HUB_INVITE_ALPHABET;
|
||||
$temp = '';
|
||||
for ($i = 0; $i < 12; $i++) {
|
||||
$temp .= $alphabet[random_int(0, strlen($alphabet) - 1)];
|
||||
}
|
||||
db()->prepare(
|
||||
'UPDATE users SET password_hash = ?, must_change_password = 1, password_changed_at = ? WHERE id = ?'
|
||||
)->execute([hash_password($temp), utc_now(), $targetId]);
|
||||
auth_revoke_sessions($targetId);
|
||||
audit('user.password_reset', 'user', $targetId, (string) $target['username']);
|
||||
flash_secret('Temporäres Passwort für ' . $target['username'], $temp);
|
||||
flash('info', 'Der Benutzer muss das Passwort bei der nächsten Anmeldung ändern.');
|
||||
} elseif ($action === 'delete') {
|
||||
if (($_POST['confirm'] ?? '') !== '1') {
|
||||
flash('error', 'Löschen muss bestätigt werden.');
|
||||
redirect('/admin/users');
|
||||
}
|
||||
$stmt = db()->prepare('SELECT id FROM routines WHERE owner_id = ?');
|
||||
$stmt->execute([$targetId]);
|
||||
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $routineId) {
|
||||
routine_delete((int) $routineId);
|
||||
}
|
||||
db()->prepare('UPDATE invites SET revoked_at = ? WHERE used_by = ? AND revoked_at IS NULL')
|
||||
->execute([utc_now(), $targetId]);
|
||||
audit('user.delete', 'user', $targetId, (string) $target['username']);
|
||||
db()->prepare('DELETE FROM users WHERE id = ?')->execute([$targetId]);
|
||||
flash('success', 'Benutzer und zugehörige Küren gelöscht.');
|
||||
} else {
|
||||
flash('error', 'Unbekannte Aktion.');
|
||||
}
|
||||
redirect('/admin/users');
|
||||
}
|
||||
|
||||
function page_admin_routines(string $method): void
|
||||
{
|
||||
require_admin_page();
|
||||
$query = query_string('q');
|
||||
$page = max(1, query_int('page', 1));
|
||||
$result = routines_query($query, $page, 50, null, true);
|
||||
render_page('admin_routines', [
|
||||
'items' => $result['items'],
|
||||
'total' => $result['total'],
|
||||
'page' => $result['page'],
|
||||
'pages' => $result['pages'],
|
||||
'query' => $query,
|
||||
], 'Alle Küren');
|
||||
}
|
||||
|
||||
function page_admin_routine_action(string $method): void
|
||||
{
|
||||
require_admin_page();
|
||||
if ($method !== 'POST') {
|
||||
redirect('/admin/routines');
|
||||
}
|
||||
csrf_require();
|
||||
$routineId = (int) post_string('routine_id');
|
||||
$action = post_string('action');
|
||||
$routine = routine_fetch($routineId);
|
||||
if ($routine === null) {
|
||||
flash('error', 'Kür nicht gefunden.');
|
||||
redirect('/admin/routines');
|
||||
}
|
||||
if ($action === 'hide' || $action === 'publish') {
|
||||
routine_set_status($routineId, $action === 'publish' ? 'published' : 'hidden');
|
||||
flash('success', 'Status geändert.');
|
||||
} elseif ($action === 'delete') {
|
||||
if (($_POST['confirm'] ?? '') !== '1') {
|
||||
flash('error', 'Löschen muss bestätigt werden.');
|
||||
redirect('/admin/routines');
|
||||
}
|
||||
routine_delete($routineId);
|
||||
flash('success', 'Kür endgültig gelöscht.');
|
||||
} else {
|
||||
flash('error', 'Unbekannte Aktion.');
|
||||
}
|
||||
redirect('/admin/routines');
|
||||
}
|
||||
|
||||
function audit_list(int $limit = 200): array
|
||||
{
|
||||
$limit = max(1, min($limit, 500));
|
||||
return db()->query(
|
||||
"SELECT a.*, u.username AS actor_name
|
||||
FROM audit_log a LEFT JOIN users u ON u.id = a.actor_id
|
||||
ORDER BY a.created_at DESC, a.id DESC LIMIT $limit"
|
||||
)->fetchAll();
|
||||
}
|
||||
638
hub/app/routines.php
Normal file
638
hub/app/routines.php
Normal file
|
|
@ -0,0 +1,638 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Küren: Validierung, Ablage, Metadaten und Auslieferung.
|
||||
*
|
||||
* Eine Kür ist ein Paket aus JSON-Datei und optionaler Audiodatei. Beide
|
||||
* werden unter storage/uploads/<jahr>/<monat>/ mit Zufallsnamen abgelegt;
|
||||
* der ursprüngliche Dateiname steht nur in der Datenbank.
|
||||
*/
|
||||
|
||||
const HUB_AUDIO_EXTENSIONS = ['mp3', 'ogg', 'wav', 'm4a', 'aac'];
|
||||
|
||||
function storage_path(string $relative = ''): string
|
||||
{
|
||||
$root = rtrim((string) config('app.storage_path', HUB_ROOT . '/storage'), '/');
|
||||
if ($relative === '') {
|
||||
return $root;
|
||||
}
|
||||
return $root . '/' . ltrim($relative, '/');
|
||||
}
|
||||
|
||||
function storage_uploads_dir(): string
|
||||
{
|
||||
$relative = 'uploads/' . gmdate('Y/m');
|
||||
$absolute = storage_path($relative);
|
||||
if (!is_dir($absolute) && !mkdir($absolute, 0770, true) && !is_dir($absolute)) {
|
||||
throw new RuntimeException('Upload-Verzeichnis nicht anlegbar.');
|
||||
}
|
||||
return $absolute;
|
||||
}
|
||||
|
||||
function routine_music_name_valid(string $name): bool
|
||||
{
|
||||
if ($name === '' || mb_strlen($name, 'UTF-8') > 160) {
|
||||
return false;
|
||||
}
|
||||
if (str_contains($name, '/') || str_contains($name, '\\') || str_contains($name, ':')
|
||||
|| str_contains($name, '..') || str_starts_with($name, '.')
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
$extension = strtolower((string) pathinfo($name, PATHINFO_EXTENSION));
|
||||
return in_array($extension, HUB_AUDIO_EXTENSIONS, true);
|
||||
}
|
||||
|
||||
function upload_error_message(int $code): string
|
||||
{
|
||||
return match ($code) {
|
||||
UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE => 'Die Datei ist zu groß.',
|
||||
UPLOAD_ERR_PARTIAL => 'Der Upload wurde unterbrochen.',
|
||||
UPLOAD_ERR_NO_FILE => 'Es wurde keine Datei ausgewählt.',
|
||||
UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_CANT_WRITE, UPLOAD_ERR_EXTENSION => 'Die Datei konnte nicht gespeichert werden.',
|
||||
default => 'Unbekannter Upload-Fehler.',
|
||||
};
|
||||
}
|
||||
|
||||
function audio_sniff(string $tmpPath): ?string
|
||||
{
|
||||
$handle = @fopen($tmpPath, 'rb');
|
||||
if ($handle === false) {
|
||||
return null;
|
||||
}
|
||||
$head = (string) fread($handle, 12);
|
||||
fclose($handle);
|
||||
if ($head === '') {
|
||||
return null;
|
||||
}
|
||||
if (str_starts_with($head, 'ID3')) {
|
||||
return 'mp3';
|
||||
}
|
||||
if (strlen($head) >= 2 && ord($head[0]) === 0xFF && (ord($head[1]) & 0xE0) === 0xE0) {
|
||||
$second = ord($head[1]);
|
||||
if (($second & 0xF6) === 0xF0) {
|
||||
return 'aac';
|
||||
}
|
||||
return 'mp3';
|
||||
}
|
||||
if (str_starts_with($head, 'OggS')) {
|
||||
return 'ogg';
|
||||
}
|
||||
if (str_starts_with($head, 'RIFF') && substr($head, 8, 4) === 'WAVE') {
|
||||
return 'wav';
|
||||
}
|
||||
if (strlen($head) >= 8 && substr($head, 4, 4) === 'ftyp') {
|
||||
return 'm4a';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function audio_mime_for(string $extension): string
|
||||
{
|
||||
return match ($extension) {
|
||||
'mp3' => 'audio/mpeg',
|
||||
'ogg' => 'audio/ogg',
|
||||
'wav' => 'audio/wav',
|
||||
'm4a' => 'audio/mp4',
|
||||
'aac' => 'audio/aac',
|
||||
default => 'application/octet-stream',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Prüft Kür- und Audiodatei. Gibt bei Erfolg das Paket mit temporären Pfaden
|
||||
* zurück; gespeichert wird erst danach.
|
||||
*/
|
||||
function routine_validate_package(array $post): array
|
||||
{
|
||||
$errors = [];
|
||||
$maxRoutine = (int) config('app.max_routine_bytes', 8 * 1024 * 1024);
|
||||
$maxAudio = (int) config('app.max_audio_bytes', 50 * 1024 * 1024);
|
||||
|
||||
$routineFile = $_FILES['routine'] ?? null;
|
||||
if (!is_array($routineFile) || ($routineFile['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
|
||||
$errors[] = 'Bitte eine Kür-Datei (.json) auswählen.';
|
||||
return ['ok' => false, 'errors' => $errors];
|
||||
}
|
||||
$routineTmp = (string) $routineFile['tmp_name'];
|
||||
$routineBytes = (int) $routineFile['size'];
|
||||
if (!is_uploaded_file($routineTmp)) {
|
||||
return ['ok' => false, 'errors' => ['Ungültiger Upload.']];
|
||||
}
|
||||
if ($routineBytes <= 0 || $routineBytes > $maxRoutine) {
|
||||
$errors[] = 'Die Kür-Datei ist zu groß (max. ' . human_bytes($maxRoutine) . ').';
|
||||
}
|
||||
$routineName = clean_filename((string) ($routineFile['name'] ?? 'kuer.json'));
|
||||
if (!str_ends_with(strtolower($routineName), '.json')) {
|
||||
$errors[] = 'Kürdateien müssen im JSON-Format vorliegen (.json).';
|
||||
}
|
||||
if ($errors) {
|
||||
return ['ok' => false, 'errors' => $errors];
|
||||
}
|
||||
|
||||
$contents = file_get_contents($routineTmp);
|
||||
if (!is_string($contents)) {
|
||||
return ['ok' => false, 'errors' => ['Die Kür-Datei konnte nicht gelesen werden.']];
|
||||
}
|
||||
try {
|
||||
$json = json_decode($contents, true, 64, JSON_THROW_ON_ERROR);
|
||||
} catch (JsonException) {
|
||||
return ['ok' => false, 'errors' => ['Die Kür-Datei ist kein gültiges JSON.']];
|
||||
}
|
||||
if (!is_array($json)) {
|
||||
return ['ok' => false, 'errors' => ['Die Kür-Datei enthält kein JSON-Objekt.']];
|
||||
}
|
||||
if (($json['format'] ?? '') !== 'rinkplanner.routine') {
|
||||
return ['ok' => false, 'errors' => ['Das ist keine Rinkplanner-Kür (format fehlt oder ist falsch).']];
|
||||
}
|
||||
$formatVersion = (int) ($json['format_version'] ?? 0);
|
||||
if ($formatVersion !== 1) {
|
||||
return ['ok' => false, 'errors' => ['Diese Kür-Formatversion wird nicht unterstützt.']];
|
||||
}
|
||||
if (!is_array($json['sections'] ?? null)) {
|
||||
return ['ok' => false, 'errors' => ['Die Kür enthält keine Abschnittsliste.']];
|
||||
}
|
||||
if (count($json['sections']) > 500) {
|
||||
return ['ok' => false, 'errors' => ['Die Kür hat zu viele Abschnitte (max. 500).']];
|
||||
}
|
||||
|
||||
$title = trim((string) ($json['title'] ?? ''));
|
||||
if ($title === '') {
|
||||
$title = (string) pathinfo($routineName, PATHINFO_FILENAME);
|
||||
}
|
||||
if ($title === '') {
|
||||
return ['ok' => false, 'errors' => ['Die Kür braucht einen Titel.']];
|
||||
}
|
||||
$title = truncate_text($title, 190);
|
||||
$skater = truncate_text(trim((string) ($json['skater_name'] ?? '')), 190);
|
||||
$category = truncate_text(trim((string) ($json['adult_category'] ?? '')), 40);
|
||||
$musicFile = trim((string) ($json['music_file'] ?? ''));
|
||||
if ($musicFile !== '' && !routine_music_name_valid($musicFile)) {
|
||||
return ['ok' => false, 'errors' => ['Die Kür verweist auf einen ungültigen Musikdateinamen.']];
|
||||
}
|
||||
$fileRoutineId = trim((string) ($json['routine_id'] ?? ''));
|
||||
|
||||
$audio = null;
|
||||
$audioFile = $_FILES['audio'] ?? null;
|
||||
$hasAudioUpload = is_array($audioFile) && ($audioFile['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE;
|
||||
if ($musicFile !== '' && !$hasAudioUpload) {
|
||||
$errors[] = 'Die Kür verweist auf „' . $musicFile . '“. Bitte die passende Audiodatei mit hochladen.';
|
||||
}
|
||||
if ($musicFile === '' && $hasAudioUpload) {
|
||||
$errors[] = 'Die Kür verweist auf keine Musikdatei; die Audiodatei passt nicht dazu.';
|
||||
}
|
||||
if ($hasAudioUpload) {
|
||||
if (($audioFile['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
|
||||
$errors[] = upload_error_message((int) $audioFile['error']);
|
||||
} else {
|
||||
$audioTmp = (string) $audioFile['tmp_name'];
|
||||
$audioBytes = (int) $audioFile['size'];
|
||||
$audioName = clean_filename((string) ($audioFile['name'] ?? ''));
|
||||
if (!is_uploaded_file($audioTmp)) {
|
||||
$errors[] = 'Ungültiger Audio-Upload.';
|
||||
} elseif ($audioBytes <= 0 || $audioBytes > $maxAudio) {
|
||||
$errors[] = 'Die Audiodatei ist zu groß (max. ' . human_bytes($maxAudio) . ').';
|
||||
} elseif ($audioName !== $musicFile) {
|
||||
$errors[] = 'Die Audiodatei heißt „' . $audioName . '“, die Kür verweist aber auf „' . $musicFile . '“.';
|
||||
} else {
|
||||
$sniffed = audio_sniff($audioTmp);
|
||||
if ($sniffed === null) {
|
||||
$errors[] = 'Die Audiodatei ist kein unterstütztes Format (MP3, OGG, WAV, M4A, AAC).';
|
||||
} else {
|
||||
$audio = [
|
||||
'tmp' => $audioTmp,
|
||||
'name' => $audioName,
|
||||
'bytes' => $audioBytes,
|
||||
'sha256' => (string) hash_file('sha256', $audioTmp),
|
||||
'mime' => audio_mime_for($sniffed),
|
||||
'extension' => $sniffed,
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($errors) {
|
||||
return ['ok' => false, 'errors' => $errors];
|
||||
}
|
||||
|
||||
return [
|
||||
'ok' => true,
|
||||
'errors' => [],
|
||||
'meta' => [
|
||||
'title' => $title,
|
||||
'skater_name' => $skater !== '' ? $skater : null,
|
||||
'category' => $category !== '' ? $category : null,
|
||||
'music_title' => mb_substr(trim((string) ($post['music_title'] ?? '')), 0, 190, 'UTF-8') ?: null,
|
||||
'music_artist' => mb_substr(trim((string) ($post['music_artist'] ?? '')), 0, 190, 'UTF-8') ?: null,
|
||||
'description' => mb_substr(trim((string) ($post['description'] ?? '')), 0, 2000, 'UTF-8') ?: null,
|
||||
],
|
||||
'routine' => [
|
||||
'tmp' => $routineTmp,
|
||||
'name' => $routineName,
|
||||
'bytes' => $routineBytes,
|
||||
'sha256' => (string) hash_file('sha256', $routineTmp),
|
||||
'file_routine_id' => $fileRoutineId !== '' ? mb_substr($fileRoutineId, 0, 36, 'UTF-8') : null,
|
||||
],
|
||||
'audio' => $audio,
|
||||
];
|
||||
}
|
||||
|
||||
/** Verschiebt die geprüften Dateien und liefert relative Pfade. */
|
||||
function routine_store_files(array $package): array
|
||||
{
|
||||
$dir = storage_uploads_dir();
|
||||
$relativeDir = 'uploads/' . gmdate('Y/m');
|
||||
$routineName = bin2hex(random_bytes(16)) . '.json';
|
||||
$routinePath = $dir . '/' . $routineName;
|
||||
if (!move_uploaded_file((string) $package['routine']['tmp'], $routinePath)) {
|
||||
throw new RuntimeException('Kür-Datei konnte nicht gespeichert werden.');
|
||||
}
|
||||
@chmod($routinePath, 0640);
|
||||
|
||||
$audioPath = null;
|
||||
$audioRelative = null;
|
||||
if (is_array($package['audio'] ?? null)) {
|
||||
$audioName = bin2hex(random_bytes(16)) . '.' . $package['audio']['extension'];
|
||||
$audioPath = $dir . '/' . $audioName;
|
||||
if (!move_uploaded_file((string) $package['audio']['tmp'], $audioPath)) {
|
||||
@unlink($routinePath);
|
||||
throw new RuntimeException('Audiodatei konnte nicht gespeichert werden.');
|
||||
}
|
||||
@chmod($audioPath, 0640);
|
||||
$audioRelative = $relativeDir . '/' . $audioName;
|
||||
}
|
||||
|
||||
return [
|
||||
'routine' => $relativeDir . '/' . $routineName,
|
||||
'audio' => $audioRelative,
|
||||
];
|
||||
}
|
||||
|
||||
function routine_duplicate_exists(int $ownerId, array $package): ?int
|
||||
{
|
||||
$stmt = db()->prepare(
|
||||
'SELECT r.id FROM routines r
|
||||
JOIN routine_revisions v ON v.id = r.current_revision_id
|
||||
WHERE r.owner_id = ? AND v.routine_sha256 = ? AND v.audio_sha256 <=> ?
|
||||
LIMIT 1'
|
||||
);
|
||||
$stmt->execute([$ownerId, $package['routine']['sha256'], $package['audio']['sha256'] ?? null]);
|
||||
$id = $stmt->fetchColumn();
|
||||
return $id !== false ? (int) $id : null;
|
||||
}
|
||||
|
||||
function routine_create(int $userId, array $package): int
|
||||
{
|
||||
$files = routine_store_files($package);
|
||||
$meta = $package['meta'];
|
||||
$pdo = db();
|
||||
try {
|
||||
$pdo->beginTransaction();
|
||||
$stmt = $pdo->prepare(
|
||||
'INSERT INTO routines
|
||||
(owner_id, title, skater_name, category, music_title, music_artist, description,
|
||||
status, current_revision_id, download_count, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, 0, ?, ?)'
|
||||
);
|
||||
$now = utc_now();
|
||||
$stmt->execute([
|
||||
$userId,
|
||||
$meta['title'],
|
||||
$meta['skater_name'],
|
||||
$meta['category'],
|
||||
$meta['music_title'],
|
||||
$meta['music_artist'],
|
||||
$meta['description'],
|
||||
'published',
|
||||
$now,
|
||||
$now,
|
||||
]);
|
||||
$routineId = (int) $pdo->lastInsertId();
|
||||
$revisionId = routine_insert_revision($routineId, 1, $userId, $package, $files);
|
||||
$pdo->prepare('UPDATE routines SET current_revision_id = ? WHERE id = ?')
|
||||
->execute([$revisionId, $routineId]);
|
||||
$pdo->commit();
|
||||
} catch (Throwable $error) {
|
||||
if ($pdo->inTransaction()) {
|
||||
$pdo->rollBack();
|
||||
}
|
||||
@unlink(storage_path($files['routine']));
|
||||
if ($files['audio'] !== null) {
|
||||
@unlink(storage_path($files['audio']));
|
||||
}
|
||||
throw $error;
|
||||
}
|
||||
audit('routine.create', 'routine', $routineId, $meta['title'], $userId);
|
||||
return $routineId;
|
||||
}
|
||||
|
||||
function routine_add_revision(int $routineId, int $userId, array $package): int
|
||||
{
|
||||
$routine = routine_fetch($routineId);
|
||||
if ($routine === null) {
|
||||
throw new RuntimeException('Kür nicht gefunden.');
|
||||
}
|
||||
$files = routine_store_files($package);
|
||||
$meta = $package['meta'];
|
||||
$pdo = db();
|
||||
try {
|
||||
$pdo->beginTransaction();
|
||||
$stmt = $pdo->prepare('SELECT COALESCE(MAX(revision), 0) + 1 FROM routine_revisions WHERE routine_id = ?');
|
||||
$stmt->execute([$routineId]);
|
||||
$next = (int) $stmt->fetchColumn();
|
||||
$revisionId = routine_insert_revision($routineId, $next, $userId, $package, $files);
|
||||
$pdo->prepare(
|
||||
'UPDATE routines SET current_revision_id = ?, title = ?, skater_name = ?, category = ?,
|
||||
music_title = ?, music_artist = ?, description = ?, updated_at = ? WHERE id = ?'
|
||||
)->execute([
|
||||
$revisionId,
|
||||
$meta['title'],
|
||||
$meta['skater_name'],
|
||||
$meta['category'],
|
||||
$meta['music_title'],
|
||||
$meta['music_artist'],
|
||||
$meta['description'],
|
||||
utc_now(),
|
||||
$routineId,
|
||||
]);
|
||||
$pdo->commit();
|
||||
} catch (Throwable $error) {
|
||||
if ($pdo->inTransaction()) {
|
||||
$pdo->rollBack();
|
||||
}
|
||||
@unlink(storage_path($files['routine']));
|
||||
if ($files['audio'] !== null) {
|
||||
@unlink(storage_path($files['audio']));
|
||||
}
|
||||
throw $error;
|
||||
}
|
||||
audit('routine.revision', 'routine', $routineId, 'Revision ' . $next, $userId);
|
||||
return $next;
|
||||
}
|
||||
|
||||
function routine_insert_revision(
|
||||
int $routineId,
|
||||
int $revision,
|
||||
int $userId,
|
||||
array $package,
|
||||
array $files
|
||||
): int {
|
||||
$routine = $package['routine'];
|
||||
$audio = $package['audio'];
|
||||
$stmt = db()->prepare(
|
||||
'INSERT INTO routine_revisions
|
||||
(routine_id, revision, uploaded_by, routine_original_name, routine_path, routine_bytes, routine_sha256,
|
||||
file_routine_id, audio_original_name, audio_path, audio_bytes, audio_sha256, audio_mime, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
|
||||
);
|
||||
$stmt->execute([
|
||||
$routineId,
|
||||
$revision,
|
||||
$userId,
|
||||
$routine['name'],
|
||||
$files['routine'],
|
||||
$routine['bytes'],
|
||||
$routine['sha256'],
|
||||
$routine['file_routine_id'],
|
||||
$audio['name'] ?? null,
|
||||
$files['audio'],
|
||||
$audio['bytes'] ?? null,
|
||||
$audio['sha256'] ?? null,
|
||||
$audio['mime'] ?? null,
|
||||
utc_now(),
|
||||
]);
|
||||
return (int) db()->lastInsertId();
|
||||
}
|
||||
|
||||
function routine_fetch(int $id): ?array
|
||||
{
|
||||
$stmt = db()->prepare(
|
||||
'SELECT r.*, u.username AS owner_username, u.display_name AS owner_display_name,
|
||||
v.id AS revision_id, v.revision, v.uploaded_by,
|
||||
v.routine_original_name, v.routine_path, v.routine_bytes, v.routine_sha256, v.file_routine_id,
|
||||
v.audio_original_name, v.audio_path, v.audio_bytes, v.audio_sha256, v.audio_mime,
|
||||
v.created_at AS revision_created_at
|
||||
FROM routines r
|
||||
JOIN users u ON u.id = r.owner_id
|
||||
LEFT JOIN routine_revisions v ON v.id = r.current_revision_id
|
||||
WHERE r.id = ? LIMIT 1'
|
||||
);
|
||||
$stmt->execute([$id]);
|
||||
$row = $stmt->fetch();
|
||||
if (!$row) {
|
||||
return null;
|
||||
}
|
||||
foreach (['id', 'owner_id', 'download_count', 'revision_id', 'revision', 'uploaded_by',
|
||||
'routine_bytes', 'audio_bytes'] as $key) {
|
||||
if (array_key_exists($key, $row) && $row[$key] !== null) {
|
||||
$row[$key] = (int) $row[$key];
|
||||
}
|
||||
}
|
||||
return $row;
|
||||
}
|
||||
|
||||
function routines_query(
|
||||
string $query,
|
||||
int $page,
|
||||
int $perPage = 20,
|
||||
?int $ownerId = null,
|
||||
bool $includeHidden = false
|
||||
): array {
|
||||
$where = [];
|
||||
$params = [];
|
||||
if ($ownerId !== null) {
|
||||
$where[] = 'r.owner_id = ?';
|
||||
$params[] = $ownerId;
|
||||
}
|
||||
if (!$includeHidden) {
|
||||
$where[] = "r.status = 'published'";
|
||||
}
|
||||
if ($query !== '') {
|
||||
$like = '%' . addcslashes($query, '\\%_') . '%';
|
||||
$where[] = '(r.title LIKE ? OR r.skater_name LIKE ? OR r.music_title LIKE ? OR r.music_artist LIKE ?'
|
||||
. ' OR u.username LIKE ? OR u.display_name LIKE ?)';
|
||||
array_push($params, $like, $like, $like, $like, $like, $like);
|
||||
}
|
||||
$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';
|
||||
|
||||
$stmt = db()->prepare(
|
||||
"SELECT COUNT(*) FROM routines r JOIN users u ON u.id = r.owner_id $whereSql"
|
||||
);
|
||||
$stmt->execute($params);
|
||||
$total = (int) $stmt->fetchColumn();
|
||||
|
||||
$page = max(1, $page);
|
||||
$pages = max(1, (int) ceil($total / $perPage));
|
||||
$page = min($page, $pages);
|
||||
$offset = ($page - 1) * $perPage;
|
||||
|
||||
$sql = "SELECT r.id, r.title, r.skater_name, r.category, r.music_title, r.music_artist,
|
||||
r.status, r.download_count, r.updated_at,
|
||||
u.username AS owner_username, u.display_name AS owner_display_name,
|
||||
v.revision, v.routine_bytes, v.audio_bytes, v.audio_original_name
|
||||
FROM routines r
|
||||
JOIN users u ON u.id = r.owner_id
|
||||
LEFT JOIN routine_revisions v ON v.id = r.current_revision_id
|
||||
$whereSql
|
||||
ORDER BY r.updated_at DESC, r.id DESC
|
||||
LIMIT $perPage OFFSET $offset";
|
||||
$stmt = db()->prepare($sql);
|
||||
$stmt->execute($params);
|
||||
$items = $stmt->fetchAll();
|
||||
|
||||
return ['items' => $items, 'total' => $total, 'page' => $page, 'pages' => $pages];
|
||||
}
|
||||
|
||||
function routine_can_view(array $routine, ?array $user): bool
|
||||
{
|
||||
if ($routine['status'] === 'published') {
|
||||
return true;
|
||||
}
|
||||
return $user !== null
|
||||
&& ((int) $user['id'] === (int) $routine['owner_id'] || $user['role'] === 'admin');
|
||||
}
|
||||
|
||||
function routine_can_edit(array $routine, ?array $user): bool
|
||||
{
|
||||
return $user !== null
|
||||
&& ((int) $user['id'] === (int) $routine['owner_id'] || $user['role'] === 'admin');
|
||||
}
|
||||
|
||||
function routine_set_status(int $routineId, string $status): void
|
||||
{
|
||||
if (!in_array($status, ['published', 'hidden'], true)) {
|
||||
throw new InvalidArgumentException('Ungültiger Status.');
|
||||
}
|
||||
$stmt = db()->prepare('UPDATE routines SET status = ?, updated_at = ? WHERE id = ?');
|
||||
$stmt->execute([$status, utc_now(), $routineId]);
|
||||
audit('routine.status', 'routine', $routineId, $status);
|
||||
}
|
||||
|
||||
function routine_delete(int $routineId): void
|
||||
{
|
||||
$stmt = db()->prepare('SELECT routine_path, audio_path FROM routine_revisions WHERE routine_id = ?');
|
||||
$stmt->execute([$routineId]);
|
||||
$paths = $stmt->fetchAll();
|
||||
db()->prepare('DELETE FROM routines WHERE id = ?')->execute([$routineId]);
|
||||
foreach ($paths as $row) {
|
||||
if (!empty($row['routine_path'])) {
|
||||
@unlink(storage_path((string) $row['routine_path']));
|
||||
}
|
||||
if (!empty($row['audio_path'])) {
|
||||
@unlink(storage_path((string) $row['audio_path']));
|
||||
}
|
||||
}
|
||||
audit('routine.delete', 'routine', $routineId, '');
|
||||
}
|
||||
|
||||
function routine_upload_quota_ok(int $userId): bool
|
||||
{
|
||||
$limit = (int) config('app.uploads_per_hour', 20);
|
||||
$stmt = db()->prepare(
|
||||
'SELECT COUNT(*) FROM routine_revisions WHERE uploaded_by = ? AND created_at >= ?'
|
||||
);
|
||||
$stmt->execute([$userId, gmdate('Y-m-d H:i:s', time() - 3600)]);
|
||||
return (int) $stmt->fetchColumn() < $limit;
|
||||
}
|
||||
|
||||
function routine_send_file(array $routine, string $kind, ?array $user = null, bool $api = false): never
|
||||
{
|
||||
$kind = $kind === 'audio' ? 'audio' : 'routine';
|
||||
$revision = routine_fetch((int) $routine['id']);
|
||||
if ($revision === null || $revision['revision_id'] === null) {
|
||||
if ($api) {
|
||||
abort_api(404, 'no_file', 'Diese Kür hat noch keine Datei.');
|
||||
}
|
||||
abort_page(404, 'Diese Kür hat noch keine Datei.');
|
||||
}
|
||||
if ($kind === 'audio') {
|
||||
$path = (string) ($revision['audio_path'] ?? '');
|
||||
$name = (string) ($revision['audio_original_name'] ?? 'musik');
|
||||
$mime = (string) ($revision['audio_mime'] ?? 'application/octet-stream');
|
||||
} else {
|
||||
$path = (string) ($revision['routine_path'] ?? '');
|
||||
$name = (string) ($revision['routine_original_name'] ?? 'kuer.json');
|
||||
$mime = 'application/json';
|
||||
}
|
||||
$absolute = storage_path($path);
|
||||
if ($path === '' || !is_file($absolute)) {
|
||||
if ($api) {
|
||||
abort_api(404, 'file_missing', 'Die Datei fehlt im Speicher.');
|
||||
}
|
||||
abort_page(404, 'Die Datei fehlt im Speicher.');
|
||||
}
|
||||
$handle = fopen($absolute, 'rb');
|
||||
if ($handle === false) {
|
||||
if ($api) {
|
||||
abort_api(500, 'file_unreadable', 'Die Datei konnte nicht geöffnet werden.');
|
||||
}
|
||||
abort_page(500, 'Die Datei konnte nicht geöffnet werden.');
|
||||
}
|
||||
|
||||
$user ??= auth_user();
|
||||
db()->prepare(
|
||||
'INSERT INTO downloads (routine_id, revision_id, user_id, kind, ip, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)'
|
||||
)->execute([
|
||||
(int) $revision['id'],
|
||||
(int) $revision['revision_id'],
|
||||
$user ? (int) $user['id'] : null,
|
||||
$kind,
|
||||
client_ip(),
|
||||
utc_now(),
|
||||
]);
|
||||
if ($kind === 'routine') {
|
||||
db()->prepare('UPDATE routines SET download_count = download_count + 1 WHERE id = ?')
|
||||
->execute([(int) $revision['id']]);
|
||||
}
|
||||
|
||||
session_write_close();
|
||||
set_time_limit(0);
|
||||
while (ob_get_level() > 0) {
|
||||
ob_end_clean();
|
||||
}
|
||||
$size = (int) filesize($absolute);
|
||||
header('Content-Type: ' . $mime);
|
||||
header('Content-Disposition: ' . content_disposition($name));
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
header('Cache-Control: private, no-store');
|
||||
header('Accept-Ranges: bytes');
|
||||
|
||||
$start = 0;
|
||||
$end = $size - 1;
|
||||
$range = (string) ($_SERVER['HTTP_RANGE'] ?? '');
|
||||
if ($range !== '' && $kind === 'audio'
|
||||
&& preg_match('/^bytes=(\d*)-(\d*)$/', $range, $matches) === 1
|
||||
) {
|
||||
if ($matches[1] === '' && $matches[2] !== '') {
|
||||
$start = max(0, $size - (int) $matches[2]);
|
||||
} else {
|
||||
$start = (int) $matches[1];
|
||||
if ($matches[2] !== '') {
|
||||
$end = min($end, (int) $matches[2]);
|
||||
}
|
||||
}
|
||||
if ($start > $end || $start >= $size) {
|
||||
header('Content-Range: bytes */' . $size);
|
||||
http_response_code(416);
|
||||
exit;
|
||||
}
|
||||
http_response_code(206);
|
||||
header(sprintf('Content-Range: bytes %d-%d/%d', $start, $end, $size));
|
||||
}
|
||||
header('Content-Length: ' . ($end - $start + 1));
|
||||
|
||||
fseek($handle, $start);
|
||||
$remaining = $end - $start + 1;
|
||||
while ($remaining > 0 && !feof($handle)) {
|
||||
$chunk = fread($handle, min(65536, $remaining));
|
||||
if ($chunk === false || $chunk === '') {
|
||||
break;
|
||||
}
|
||||
echo $chunk;
|
||||
$remaining -= strlen($chunk);
|
||||
}
|
||||
fclose($handle);
|
||||
exit;
|
||||
}
|
||||
112
hub/app/tokens.php
Normal file
112
hub/app/tokens.php
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Persönliche API-Tokens für die Godot-App.
|
||||
*
|
||||
* Das Klartext-Token wird nur einmal ausgegeben; in der Datenbank liegt
|
||||
* ausschließlich der SHA-256-Hash. Format: rhub_ + 64 Hex-Zeichen.
|
||||
*/
|
||||
|
||||
function token_create(int $userId, string $name): array
|
||||
{
|
||||
$token = 'rhub_' . bin2hex(random_bytes(32));
|
||||
$prefix = substr($token, 0, 12);
|
||||
$stmt = db()->prepare(
|
||||
'INSERT INTO api_tokens (user_id, name, prefix, token_hash, created_at)
|
||||
VALUES (?, ?, ?, ?, ?)'
|
||||
);
|
||||
$stmt->execute([
|
||||
$userId,
|
||||
mb_substr($name !== '' ? $name : 'App', 0, 64, 'UTF-8'),
|
||||
$prefix,
|
||||
hash('sha256', $token),
|
||||
utc_now(),
|
||||
]);
|
||||
$tokenId = (int) db()->lastInsertId();
|
||||
audit('token.create', 'token', $tokenId, $name, $userId);
|
||||
return ['token' => $token, 'prefix' => $prefix, 'id' => $tokenId];
|
||||
}
|
||||
|
||||
function tokens_list(int $userId): array
|
||||
{
|
||||
$stmt = db()->prepare(
|
||||
'SELECT id, name, prefix, created_at, last_used_at, expires_at, revoked_at
|
||||
FROM api_tokens WHERE user_id = ? ORDER BY created_at DESC'
|
||||
);
|
||||
$stmt->execute([$userId]);
|
||||
return $stmt->fetchAll();
|
||||
}
|
||||
|
||||
function token_revoke(int $tokenId, int $userId): bool
|
||||
{
|
||||
$stmt = db()->prepare(
|
||||
'UPDATE api_tokens SET revoked_at = ? WHERE id = ? AND user_id = ? AND revoked_at IS NULL'
|
||||
);
|
||||
$stmt->execute([utc_now(), $tokenId, $userId]);
|
||||
return $stmt->rowCount() === 1;
|
||||
}
|
||||
|
||||
function bearer_token(): string
|
||||
{
|
||||
$header = (string) ($_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '');
|
||||
if ($header === '' && function_exists('apache_request_headers')) {
|
||||
$headers = apache_request_headers();
|
||||
foreach ($headers as $name => $value) {
|
||||
if (strtolower((string) $name) === 'authorization') {
|
||||
$header = (string) $value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (preg_match('/^Bearer\s+(\S+)$/i', trim($header), $matches) === 1) {
|
||||
return $matches[1];
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function token_user(string $token): ?array
|
||||
{
|
||||
if (!str_starts_with($token, 'rhub_') || strlen($token) !== 69) {
|
||||
return null;
|
||||
}
|
||||
$stmt = db()->prepare(
|
||||
'SELECT t.id AS token_id, t.prefix AS token_prefix, t.last_used_at AS token_last_used, u.*
|
||||
FROM api_tokens t
|
||||
JOIN users u ON u.id = t.user_id
|
||||
WHERE t.token_hash = ? AND t.revoked_at IS NULL
|
||||
AND (t.expires_at IS NULL OR t.expires_at > ?)
|
||||
AND u.status = ? LIMIT 1'
|
||||
);
|
||||
$stmt->execute([hash('sha256', $token), utc_now(), 'active']);
|
||||
$row = $stmt->fetch();
|
||||
if (!$row) {
|
||||
return null;
|
||||
}
|
||||
$lastUsed = $row['token_last_used'];
|
||||
if ($lastUsed === null || strtotime($lastUsed . ' UTC') < time() - 60) {
|
||||
db()->prepare('UPDATE api_tokens SET last_used_at = ? WHERE id = ?')
|
||||
->execute([utc_now(), (int) $row['token_id']]);
|
||||
}
|
||||
$row['id'] = (int) $row['id'];
|
||||
$row['auth_epoch'] = (int) $row['auth_epoch'];
|
||||
$row['must_change_password'] = (int) $row['must_change_password'];
|
||||
$row['token_id'] = (int) $row['token_id'];
|
||||
return $row;
|
||||
}
|
||||
|
||||
function api_require_user(): array
|
||||
{
|
||||
$token = bearer_token();
|
||||
if ($token === '') {
|
||||
abort_api(401, 'unauthorized', 'Bearer-Token fehlt.');
|
||||
}
|
||||
$user = token_user($token);
|
||||
if ($user === null) {
|
||||
abort_api(401, 'invalid_token', 'Token ist ungültig, abgelaufen oder widerrufen.');
|
||||
}
|
||||
if ($user['must_change_password'] === 1) {
|
||||
abort_api(403, 'password_change_required', 'Bitte zuerst im Web das Passwort ändern.');
|
||||
}
|
||||
return $user;
|
||||
}
|
||||
320
hub/app/util.php
Normal file
320
hub/app/util.php
Normal file
|
|
@ -0,0 +1,320 @@
|
|||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Kleine Helfer: Konfiguration, Session, CSRF, Ausgabe, Zeit und Dateien.
|
||||
*/
|
||||
|
||||
function config(string $key, mixed $default = null): mixed
|
||||
{
|
||||
$value = $GLOBALS['hub_config'] ?? [];
|
||||
foreach (explode('.', $key) as $part) {
|
||||
if (!is_array($value) || !array_key_exists($part, $value)) {
|
||||
return $default;
|
||||
}
|
||||
$value = $value[$part];
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
function is_https(): bool
|
||||
{
|
||||
if (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off') {
|
||||
return true;
|
||||
}
|
||||
return strtolower((string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https';
|
||||
}
|
||||
|
||||
function security_headers(): void
|
||||
{
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
header('X-Frame-Options: DENY');
|
||||
header('X-Robots-Tag: noindex, nofollow, noarchive');
|
||||
header('Referrer-Policy: same-origin');
|
||||
header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
|
||||
header(
|
||||
"Content-Security-Policy: default-src 'self'; img-src 'self' data:; "
|
||||
. "style-src 'self'; script-src 'none'; media-src 'self'; "
|
||||
. "form-action 'self'; frame-ancestors 'none'; base-uri 'none'"
|
||||
);
|
||||
header('Cache-Control: no-store');
|
||||
if (is_https()) {
|
||||
header('Strict-Transport-Security: max-age=15552000');
|
||||
}
|
||||
}
|
||||
|
||||
function start_session(): void
|
||||
{
|
||||
if (session_status() === PHP_SESSION_ACTIVE) {
|
||||
return;
|
||||
}
|
||||
$absolute = (int) config('app.session_absolute_seconds', 2592000);
|
||||
ini_set('session.use_strict_mode', '1');
|
||||
ini_set('session.use_only_cookies', '1');
|
||||
ini_set('session.cookie_httponly', '1');
|
||||
ini_set('session.cookie_samesite', 'Lax');
|
||||
ini_set('session.cookie_secure', is_https() ? '1' : '0');
|
||||
ini_set('session.cookie_path', '/');
|
||||
ini_set('session.gc_maxlifetime', (string) $absolute);
|
||||
session_name('RHUB_SESSION');
|
||||
session_start();
|
||||
}
|
||||
|
||||
function utc_now(): string
|
||||
{
|
||||
return gmdate('Y-m-d H:i:s');
|
||||
}
|
||||
|
||||
function utc_after(int $seconds): string
|
||||
{
|
||||
return gmdate('Y-m-d H:i:s', time() + $seconds);
|
||||
}
|
||||
|
||||
function e(mixed $value): string
|
||||
{
|
||||
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
}
|
||||
|
||||
function url(string $path = '/'): string
|
||||
{
|
||||
$base = rtrim((string) config('app.base_path', ''), '/');
|
||||
if ($path === '' || $path[0] !== '/') {
|
||||
$path = '/' . $path;
|
||||
}
|
||||
return $base . $path;
|
||||
}
|
||||
|
||||
function redirect(string $path, int $status = 303): never
|
||||
{
|
||||
header('Location: ' . url($path), true, $status);
|
||||
exit;
|
||||
}
|
||||
|
||||
function client_ip(): string
|
||||
{
|
||||
$ip = (string) ($_SERVER['REMOTE_ADDR'] ?? '');
|
||||
return $ip !== '' ? substr($ip, 0, 45) : '0.0.0.0';
|
||||
}
|
||||
|
||||
function user_agent(): string
|
||||
{
|
||||
return substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255);
|
||||
}
|
||||
|
||||
function request_method(): string
|
||||
{
|
||||
return strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));
|
||||
}
|
||||
|
||||
function is_post(): bool
|
||||
{
|
||||
return request_method() === 'POST';
|
||||
}
|
||||
|
||||
function post_string(string $key, string $default = ''): string
|
||||
{
|
||||
$value = $_POST[$key] ?? $default;
|
||||
return is_string($value) ? trim($value) : $default;
|
||||
}
|
||||
|
||||
function query_string(string $key, string $default = ''): string
|
||||
{
|
||||
$value = $_GET[$key] ?? $default;
|
||||
return is_string($value) ? trim($value) : $default;
|
||||
}
|
||||
|
||||
function query_int(string $key, int $default = 0): int
|
||||
{
|
||||
$value = $_GET[$key] ?? null;
|
||||
return is_numeric($value) ? (int) $value : $default;
|
||||
}
|
||||
|
||||
function e_attr(mixed $value): string
|
||||
{
|
||||
return e($value);
|
||||
}
|
||||
|
||||
function fmt_dt(?string $utc): string
|
||||
{
|
||||
if ($utc === null || $utc === '') {
|
||||
return '–';
|
||||
}
|
||||
try {
|
||||
$date = new DateTimeImmutable($utc, new DateTimeZone('UTC'));
|
||||
return $date->setTimezone(new DateTimeZone('Europe/Berlin'))->format('d.m.Y H:i');
|
||||
} catch (Throwable) {
|
||||
return '–';
|
||||
}
|
||||
}
|
||||
|
||||
function human_bytes(int|float|null $bytes): string
|
||||
{
|
||||
$bytes = (float) ($bytes ?? 0);
|
||||
if ($bytes < 1024) {
|
||||
return number_format($bytes, 0, ',', '.') . ' B';
|
||||
}
|
||||
$units = ['KB', 'MB', 'GB'];
|
||||
$index = -1;
|
||||
do {
|
||||
$bytes /= 1024;
|
||||
$index++;
|
||||
} while ($bytes >= 1024 && $index < count($units) - 1);
|
||||
return number_format($bytes, 1, ',', '.') . ' ' . $units[$index];
|
||||
}
|
||||
|
||||
function truncate_text(string $value, int $length): string
|
||||
{
|
||||
if (mb_strlen($value, 'UTF-8') <= $length) {
|
||||
return $value;
|
||||
}
|
||||
return mb_substr($value, 0, max(0, $length - 1), 'UTF-8') . '…';
|
||||
}
|
||||
|
||||
function clean_filename(string $name): string
|
||||
{
|
||||
$name = basename(str_replace('\\', '/', $name));
|
||||
$name = preg_replace('/[\x00-\x1F\x7F]/u', '', $name) ?? '';
|
||||
$name = trim($name);
|
||||
if ($name === '' || $name === '.' || $name === '..') {
|
||||
return 'datei';
|
||||
}
|
||||
return mb_substr($name, 0, 190, 'UTF-8');
|
||||
}
|
||||
|
||||
/** Dateiname für Content-Disposition: ASCII-Fallback plus UTF-8-Variante. */
|
||||
function content_disposition(string $filename): string
|
||||
{
|
||||
$filename = clean_filename($filename);
|
||||
$ascii = preg_replace('/[^\x20-\x7E]/', '_', $filename) ?? 'datei';
|
||||
$ascii = str_replace(['"', '\\', ';'], '_', $ascii);
|
||||
return 'attachment; filename="' . $ascii . '"; filename*=UTF-8\'\'' . rawurlencode($filename);
|
||||
}
|
||||
|
||||
function flash(string $type, string $message): void
|
||||
{
|
||||
$_SESSION['flash'][] = ['type' => $type, 'message' => $message];
|
||||
}
|
||||
|
||||
function flash_secret(string $label, string $value): void
|
||||
{
|
||||
$_SESSION['flash'][] = ['type' => 'secret', 'label' => $label, 'value' => $value];
|
||||
}
|
||||
|
||||
function flash_pull(): array
|
||||
{
|
||||
$items = $_SESSION['flash'] ?? [];
|
||||
unset($_SESSION['flash']);
|
||||
return is_array($items) ? $items : [];
|
||||
}
|
||||
|
||||
function csrf_token(): string
|
||||
{
|
||||
if (empty($_SESSION['csrf'])) {
|
||||
$_SESSION['csrf'] = bin2hex(random_bytes(32));
|
||||
}
|
||||
return (string) $_SESSION['csrf'];
|
||||
}
|
||||
|
||||
function csrf_field(): string
|
||||
{
|
||||
return '<input type="hidden" name="_csrf" value="' . e(csrf_token()) . '">';
|
||||
}
|
||||
|
||||
function csrf_valid(): bool
|
||||
{
|
||||
$sent = $_POST['_csrf'] ?? '';
|
||||
return is_string($sent) && $sent !== '' && hash_equals(csrf_token(), $sent);
|
||||
}
|
||||
|
||||
function csrf_require(): void
|
||||
{
|
||||
if (!csrf_valid()) {
|
||||
abort_page(419, 'Die Sitzung ist abgelaufen. Bitte die Seite neu laden.');
|
||||
}
|
||||
}
|
||||
|
||||
function wants_json(): bool
|
||||
{
|
||||
$path = (string) parse_url((string) ($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH);
|
||||
return str_starts_with($path, '/api/')
|
||||
|| str_contains(strtolower((string) ($_SERVER['HTTP_ACCEPT'] ?? '')), 'application/json');
|
||||
}
|
||||
|
||||
function json_response(mixed $data, int $status = 200): never
|
||||
{
|
||||
http_response_code($status);
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
exit;
|
||||
}
|
||||
|
||||
function json_input(): array
|
||||
{
|
||||
$raw = file_get_contents('php://input');
|
||||
if (is_string($raw) && $raw !== '') {
|
||||
$decoded = json_decode($raw, true);
|
||||
if (is_array($decoded)) {
|
||||
return $decoded;
|
||||
}
|
||||
}
|
||||
return $_POST;
|
||||
}
|
||||
|
||||
function render(string $view, array $data = []): string
|
||||
{
|
||||
$file = HUB_ROOT . '/views/' . $view . '.php';
|
||||
if (!is_file($file)) {
|
||||
throw new RuntimeException('View fehlt: ' . $view);
|
||||
}
|
||||
extract($data, EXTR_SKIP);
|
||||
ob_start();
|
||||
require $file;
|
||||
return (string) ob_get_clean();
|
||||
}
|
||||
|
||||
function render_page(string $view, array $data = [], string $title = 'Kür-Hub'): void
|
||||
{
|
||||
$content = render($view, $data);
|
||||
echo render('layout', [
|
||||
'title' => $title,
|
||||
'content' => $content,
|
||||
'user' => auth_user(),
|
||||
]);
|
||||
}
|
||||
|
||||
function abort_page(int $status, string $message): never
|
||||
{
|
||||
http_response_code($status);
|
||||
$content = render('error', ['status' => $status, 'message' => $message]);
|
||||
echo render('layout', [
|
||||
'title' => 'Fehler ' . $status,
|
||||
'content' => $content,
|
||||
'user' => auth_user(),
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
function abort_api(int $status, string $code, string $message): never
|
||||
{
|
||||
json_response(['error' => ['code' => $code, 'message' => $message]], $status);
|
||||
}
|
||||
|
||||
function password_policy_error(string $password, string $username = ''): ?string
|
||||
{
|
||||
$length = mb_strlen($password, 'UTF-8');
|
||||
if ($length < 10) {
|
||||
return 'Das Passwort muss mindestens 10 Zeichen lang sein.';
|
||||
}
|
||||
if ($length > 200) {
|
||||
return 'Das Passwort darf höchstens 200 Zeichen lang sein.';
|
||||
}
|
||||
if ($username !== '' && mb_strtolower($password) === mb_strtolower($username)) {
|
||||
return 'Das Passwort darf nicht dem Benutzernamen entsprechen.';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function hub_log(string $message): void
|
||||
{
|
||||
error_log('Hub: ' . $message);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue