rinkplanner/hub/app/routines.php
torsten 9819311403 feat: Website und Hub zweisprachig (Deutsch/Englisch)
Website (rinkplanner.programmschmiede.de) liegt jetzt im Repo unter web/:
Sprachweiche nach Accept-Language (der User-Agent enthält keine Sprache),
/de/ und /en/ als eigene URLs mit hreflang, Cookie für die manuelle Wahl,
Texte in web/i18n.php, Markup in web/template.php. Deployment über
tools/deploy_web.sh (--sync, --check, --all); /index.html leitet weiter.

Hub: optionale englische Oberfläche über den DE/EN-Umschalter, Cookie
RHUB_LANG, Route /language. Alle Texte (Views, Meldungen, Validierung,
API-messages) stehen in hub/app/i18n_strings.php und laufen über t();
Datum und Zahlen folgen der Sprache. Die API behält ihre code-Felder und
antwortet ohne Cookie weiter deutsch.

deploy_hub.sh --check prüft jetzt Schlüsselparität und fehlende t()-Schlüssel.
Doku: docs/website.md neu, docs/hub.md und AGENTS.md ergänzt.
2026-11-12 22:38:32 +01:00

638 lines
22 KiB
PHP

<?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 => t('upload.file_too_large'),
UPLOAD_ERR_PARTIAL => t('upload.interrupted'),
UPLOAD_ERR_NO_FILE => t('upload.no_file_chosen'),
UPLOAD_ERR_NO_TMP_DIR, UPLOAD_ERR_CANT_WRITE, UPLOAD_ERR_EXTENSION => t('upload.store_failed'),
default => t('upload.unknown_error'),
};
}
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[] = t('upload.select_routine');
return ['ok' => false, 'errors' => $errors];
}
$routineTmp = (string) $routineFile['tmp_name'];
$routineBytes = (int) $routineFile['size'];
if (!is_uploaded_file($routineTmp)) {
return ['ok' => false, 'errors' => [t('upload.invalid')]];
}
if ($routineBytes <= 0 || $routineBytes > $maxRoutine) {
$errors[] = t('upload.routine_too_large', ['max' => human_bytes($maxRoutine)]);
}
$routineName = clean_filename((string) ($routineFile['name'] ?? 'kuer.json'));
if (!str_ends_with(strtolower($routineName), '.json')) {
$errors[] = t('upload.routine_not_json');
}
if ($errors) {
return ['ok' => false, 'errors' => $errors];
}
$contents = file_get_contents($routineTmp);
if (!is_string($contents)) {
return ['ok' => false, 'errors' => [t('upload.read_failed')]];
}
try {
$json = json_decode($contents, true, 64, JSON_THROW_ON_ERROR);
} catch (JsonException) {
return ['ok' => false, 'errors' => [t('upload.invalid_json')]];
}
if (!is_array($json)) {
return ['ok' => false, 'errors' => [t('upload.no_json_object')]];
}
if (($json['format'] ?? '') !== 'rinkplanner.routine') {
return ['ok' => false, 'errors' => [t('upload.not_rinkplanner')]];
}
$formatVersion = (int) ($json['format_version'] ?? 0);
if ($formatVersion !== 1) {
return ['ok' => false, 'errors' => [t('upload.unsupported_version')]];
}
if (!is_array($json['sections'] ?? null)) {
return ['ok' => false, 'errors' => [t('upload.no_sections')]];
}
if (count($json['sections']) > 500) {
return ['ok' => false, 'errors' => [t('upload.too_many_sections')]];
}
$title = trim((string) ($json['title'] ?? ''));
if ($title === '') {
$title = (string) pathinfo($routineName, PATHINFO_FILENAME);
}
if ($title === '') {
return ['ok' => false, 'errors' => [t('upload.title_required')]];
}
$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' => [t('upload.bad_music_name')]];
}
$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[] = t('upload.music_missing', ['name' => $musicFile]);
}
if ($musicFile === '' && $hasAudioUpload) {
$errors[] = t('upload.music_unexpected');
}
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[] = t('upload.audio_invalid');
} elseif ($audioBytes <= 0 || $audioBytes > $maxAudio) {
$errors[] = t('upload.audio_too_large', ['max' => human_bytes($maxAudio)]);
} elseif ($audioName !== $musicFile) {
$errors[] = t('upload.audio_name_mismatch', ['actual' => $audioName, 'expected' => $musicFile]);
} else {
$sniffed = audio_sniff($audioTmp);
if ($sniffed === null) {
$errors[] = t('upload.audio_format');
} 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', t('routine.no_file_yet'));
}
abort_page(404, t('routine.no_file_yet'));
}
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', t('routine.file_missing'));
}
abort_page(404, t('routine.file_missing'));
}
$handle = fopen($absolute, 'rb');
if ($handle === false) {
if ($api) {
abort_api(500, 'file_unreadable', t('routine.file_unreadable'));
}
abort_page(500, t('routine.file_unreadable'));
}
$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;
}