HifiPlanet-Website/hifi/api/src/Controllers/DownloadController.php
Maaxxs 54928d1411 Add package badges/visibility and a download area, speed up the site
Customer feedback round (4 items):

- Packages: one-click "Sichtbar/Ausgeblendet" toggle per package (saved
  immediately). Hidden packages disappear from the model page; the tier
  look of the remaining cards is ranked across all packages so it stays
  stable.
- Packages: badge per card (Empfohlen, Am beliebtesten, Tipp, Coming soon
  or custom text) plus an optional video link shown as "Zum Video". Legacy
  is_featured maps to "Empfohlen".
- New download area (/downloads + Admin -> Downloads): upload with
  progress, inline audio player, allow-listed file types, optional access
  password, new permission downloads.manage. Files live in
  api/uploads/downloads/ (gitignored, created at runtime).
- Performance:
  - SetupGate no longer refetches and remounts the whole app on every
    navigation.
  - Page loader waits only for pending API calls and above-the-fold images
    (fixes an 8 s hang on /leistungen caused by lazy images inside the
    hidden container).
  - Admin pages lazy-loaded; icon library moved out of the main bundle
    (initial JS 2.2 MB -> 0.48 MB).
  - Background video loads only near the viewport and was re-encoded to
    720p (32 MB -> 8.5 MB).
  - Visitors without a session cookie get no PHP session, so their parallel
    API requests no longer queue on the session lock.
  - index.html is served with Cache-Control: no-cache so browsers don't
    keep a stale build after deploys.
- Fonts (Barlow, Barlow Condensed, Michroma) are self-hosted instead of
  loaded from Google Fonts; the default privacy policy mentions this, lists
  all local storage uses and uses the new TDDDG name.
- A code update that adds a table no longer sends the site into the setup
  wizard while an admin exists.

Run "Datenbankstruktur aktualisieren" after deploying (new package
columns, downloads table, app_settings.downloads_password).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 23:15:48 +02:00

345 lines
14 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Controllers;
use App\Config\Database;
use App\Middleware\AuthMiddleware;
use App\Support\Http;
/**
* Download-Bereich (/downloads): Dateien wie Songs oder Anleitungen, die der Betrieb seinen
* Kunden bereitstellt. Die Dateien liegen unter einem zufaelligen Namen in
* api/uploads/downloads/ und werden direkt vom Webserver ausgeliefert (dadurch klappt auch
* Vorspulen im Audio-Player ohne PHP) - der Originalname steht in downloads.file_name.
*
* Optional per Zugangspasswort geschuetzt (app_settings.downloads_password, leer =
* oeffentlich): dann liefert publicIndex() die Liste nur gegen das Passwort. Die Dateien
* selbst bleiben direkt abrufbar, sind aber nur ueber diese Liste auffindbar (zufaellige
* 128-Bit-Namen, kein Verzeichnis-Listing - /api/* ohne echte Datei landet im Router).
* Wer freigeschaltet war, kann also einzelne Direktlinks weitergeben - fuer einen kleinen
* Kundenbereich bewusst so gewaehlt, statt jede Datei (inkl. Spulen im Player) durch PHP
* zu streamen.
*
* Bewusst NICHT Teil des Daten-Exports (SettingsController): Songs koennen schnell mehrere
* hundert MB gross sein, der Export bettet Dateien aber als Base64 in eine JSON-Datei ein.
*/
class DownloadController
{
private const DIR = __DIR__ . '/../../uploads/downloads/';
// Positivliste statt "alles ausser ...": die Dateien liegen auf derselben Domain wie die
// Seite, HTML/SVG/JS o. Ae. wuerden dort als Seite ausgefuehrt (Angriff auf eingeloggte
// Admins). Alles andere laesst sich als ZIP hochladen.
private const ALLOWED_EXTENSIONS = [
'mp3', 'wav', 'flac', 'm4a', 'aac', 'ogg', 'opus', 'aif', 'aiff', 'wma',
'mp4', 'mov', 'webm',
'pdf', 'txt', 'rtf', 'doc', 'docx', 'xls', 'xlsx', 'odt', 'ods',
'jpg', 'jpeg', 'png', 'webp', 'gif',
'zip', 'rar', '7z',
];
// Wird beim ersten Upload in api/uploads/downloads/ angelegt statt versioniert, weil das
// Auto-Update (GitUpdateService) api/uploads/ bewusst nie anfasst.
private const HTACCESS = <<<'HTACCESS'
# Automatisch angelegt von DownloadController.php - Dateien hier nie als Seite oder Skript
# interpretieren (die Ausfuehrung von PHP verbietet bereits ../.htaccess).
<IfModule mod_headers.c>
Header set X-Content-Type-Options "nosniff"
</IfModule>
HTACCESS;
private static function urlPrefix(): string
{
$config = require __DIR__ . '/../../config/config.php';
return rtrim($config['app']['base_path'], '/') . '/api/uploads/downloads/';
}
/**
* Zugangspasswort des Bereichs oder null, wenn er oeffentlich ist. Bewusst im Klartext
* gespeichert: ein gemeinsamer Zugangscode, den der Betrieb an seine Kunden weitergibt und
* im Admin nachschlagen koennen soll - kein Konto-Passwort.
*/
private static function accessPassword(): ?string
{
try {
$password = Database::connection()
->query('SELECT downloads_password FROM app_settings WHERE id = 1')
->fetchColumn();
} catch (\Throwable $e) {
// Spalte existiert erst nach "Datenbankstruktur aktualisieren".
return null;
}
return is_string($password) && $password !== '' ? $password : null;
}
public static function isProtected(): bool
{
return self::accessPassword() !== null;
}
/**
* Antwortet immer mit 200 und { locked, items } statt 401 - "Passwort noetig" ist fuer
* diese Seite der Normalfall, kein Fehler (vgl. AuthController::me()).
*/
public static function publicIndex(): void
{
$password = self::accessPassword();
if ($password !== null && !self::isDownloadsAdmin()) {
// URL-kodiert, weil HTTP-Header nur ISO-8859-1 transportieren (Umlaute/Emoji).
$given = rawurldecode((string) ($_SERVER['HTTP_X_DOWNLOAD_PASSWORD'] ?? ''));
if ($given === '') {
Http::send(['locked' => true, 'wrong_password' => false, 'items' => []]);
}
if (!hash_equals($password, $given)) {
// Bremst simples Durchprobieren von Passwoertern aus.
sleep(1);
Http::send(['locked' => true, 'wrong_password' => true, 'items' => []]);
}
}
try {
$rows = Database::connection()->query(
'SELECT id, title, description, file_path, file_name, file_size
FROM downloads WHERE is_hidden = 0 ORDER BY sort_order, id'
)->fetchAll();
} catch (\Throwable $e) {
// Tabelle existiert erst nach "Datenbankstruktur aktualisieren".
$rows = [];
}
Http::send(['locked' => false, 'wrong_password' => false, 'items' => $rows]);
}
// Eingeloggte Verwalter sehen die Liste auch ohne Passwort (Vorschau aus dem Admin heraus).
private static function isDownloadsAdmin(): bool
{
return !empty($_SESSION['admin_id'])
&& AuthMiddleware::userHasPermission((int) $_SESSION['admin_id'], 'downloads.manage');
}
public static function settings(): void
{
Http::send(['password' => self::accessPassword()]);
}
public static function updateSettings(): void
{
$body = Http::jsonBody();
$password = trim((string) ($body['password'] ?? ''));
if (mb_strlen($password) > 100) {
Http::error('Das Passwort darf höchstens 100 Zeichen lang sein', 422);
}
$db = Database::connection();
$db->exec('INSERT IGNORE INTO app_settings (id) VALUES (1)');
$stmt = $db->prepare('UPDATE app_settings SET downloads_password = ? WHERE id = 1');
$stmt->execute([$password !== '' ? $password : null]);
Http::send(['password' => $password !== '' ? $password : null]);
}
/** Fuer Navbar/Footer (ueber SiteSettingsController): den Menuepunkt nur zeigen, wenn es etwas gibt. */
public static function hasVisible(): bool
{
try {
return (bool) Database::connection()
->query('SELECT 1 FROM downloads WHERE is_hidden = 0 LIMIT 1')
->fetchColumn();
} catch (\Throwable $e) {
return false;
}
}
public static function adminIndex(): void
{
$rows = Database::connection()->query(
'SELECT id, title, description, file_path, file_name, file_size, is_hidden, sort_order, created_at
FROM downloads ORDER BY sort_order, id'
)->fetchAll();
foreach ($rows as &$row) {
$row['is_hidden'] = (bool) $row['is_hidden'];
}
unset($row);
Http::send($rows);
}
public static function store(): void
{
$file = self::acceptUpload();
$title = mb_substr(trim((string) ($_POST['title'] ?? '')), 0, 150);
if ($title === '') {
// Ohne eigenen Titel: Dateiname ohne Endung ("Bass Test.mp3" -> "Bass Test").
$title = mb_substr(pathinfo($file['file_name'], PATHINFO_FILENAME), 0, 150) ?: $file['file_name'];
}
$description = trim((string) ($_POST['description'] ?? '')) ?: null;
$db = Database::connection();
// Neue Dateien ans Ende der Liste.
$sortOrder = (int) $db->query('SELECT COALESCE(MAX(sort_order), 0) + 10 FROM downloads')->fetchColumn();
$stmt = $db->prepare(
'INSERT INTO downloads (title, description, file_path, file_name, file_size, sort_order) VALUES (?, ?, ?, ?, ?, ?)'
);
$stmt->execute([$title, $description, $file['file_path'], $file['file_name'], $file['file_size'], $sortOrder]);
Http::send(['id' => (int) $db->lastInsertId()], 201);
}
public static function update(array $params): void
{
$id = (int) $params['id'];
$body = Http::jsonBody();
$title = mb_substr(trim((string) ($body['title'] ?? '')), 0, 150);
if ($title === '') {
Http::error('Titel erforderlich', 422);
}
$stmt = Database::connection()->prepare(
'UPDATE downloads SET title = ?, description = ?, sort_order = ? WHERE id = ?'
);
$stmt->execute([
$title,
trim((string) ($body['description'] ?? '')) ?: null,
(int) ($body['sort_order'] ?? 0),
$id,
]);
Http::send(['ok' => true]);
}
/** Ersetzt nur die Datei eines Eintrags (Titel, Beschreibung und Position bleiben). */
public static function replaceFile(array $params): void
{
$id = (int) $params['id'];
$old = self::find($id);
$file = self::acceptUpload();
$stmt = Database::connection()->prepare(
'UPDATE downloads SET file_path = ?, file_name = ?, file_size = ? WHERE id = ?'
);
$stmt->execute([$file['file_path'], $file['file_name'], $file['file_size'], $id]);
self::deleteFile($old['file_path']);
Http::send(['ok' => true]);
}
public static function setVisibility(array $params): void
{
$id = (int) $params['id'];
self::find($id);
$body = Http::jsonBody();
$hidden = !empty($body['is_hidden']);
$stmt = Database::connection()->prepare('UPDATE downloads SET is_hidden = ? WHERE id = ?');
$stmt->execute([$hidden ? 1 : 0, $id]);
Http::send(['ok' => true, 'is_hidden' => $hidden]);
}
public static function destroy(array $params): void
{
$id = (int) $params['id'];
$old = self::find($id);
$stmt = Database::connection()->prepare('DELETE FROM downloads WHERE id = ?');
$stmt->execute([$id]);
self::deleteFile($old['file_path']);
Http::send(['ok' => true]);
}
private static function find(int $id): array
{
$stmt = Database::connection()->prepare('SELECT id, file_path FROM downloads WHERE id = ?');
$stmt->execute([$id]);
$row = $stmt->fetch();
if (!$row) {
Http::error('Download nicht gefunden', 404);
}
return $row;
}
/**
* Prueft den Upload aus $_FILES['file'] und legt ihn unter zufaelligem Namen ab.
*
* @return array{file_path: string, file_name: string, file_size: int}
*/
private static function acceptUpload(): array
{
if (empty($_FILES['file'])) {
// Ueberschreitet der Request post_max_size, verwirft PHP $_FILES UND $_POST
// kommentarlos - dann lieber das echte Limit nennen als "keine Datei".
$contentLength = (int) ($_SERVER['CONTENT_LENGTH'] ?? 0);
if ($contentLength > 0) {
Http::error('Die Datei ist zu groß für diesen Server (Limit: ' . ini_get('post_max_size') . ').', 422);
}
Http::error('Keine Datei übermittelt', 422);
}
$file = $_FILES['file'];
if ($file['error'] === UPLOAD_ERR_INI_SIZE || $file['error'] === UPLOAD_ERR_FORM_SIZE) {
Http::error('Die Datei ist zu groß für diesen Server (Limit: ' . ini_get('upload_max_filesize') . ').', 422);
}
if ($file['error'] !== UPLOAD_ERR_OK) {
Http::error('Upload fehlgeschlagen (Fehlercode ' . $file['error'] . ')', 422);
}
if ((int) $file['size'] <= 0) {
Http::error('Die Datei ist leer', 422);
}
// Nur den reinen Dateinamen behalten (manche Browser schicken Pfade mit) und
// Steuerzeichen entfernen - er landet spaeter im download-Attribut des Links. Kein
// basename(): das ist locale-abhaengig und kann Umlaute am Namensanfang verschlucken.
$originalName = str_replace('\\', '/', (string) $file['name']);
$originalName = substr($originalName, strrpos($originalName, '/') === false ? 0 : strrpos($originalName, '/') + 1);
$originalName = preg_replace('/[\x00-\x1F\x7F]/', '', $originalName);
$originalName = mb_substr(trim((string) $originalName), 0, 255) ?: 'download';
$extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
if (!in_array($extension, self::ALLOWED_EXTENSIONS, true)) {
Http::error(
'Dieser Dateityp ist nicht erlaubt. Erlaubt sind: ' . implode(', ', self::ALLOWED_EXTENSIONS) .
' – andere Dateien bitte als ZIP hochladen.',
422
);
}
self::ensureDir();
$filename = bin2hex(random_bytes(16)) . '.' . $extension;
if (!move_uploaded_file($file['tmp_name'], self::DIR . $filename)) {
Http::error('Datei konnte nicht gespeichert werden', 500);
}
return [
'file_path' => self::urlPrefix() . $filename,
'file_name' => $originalName,
'file_size' => (int) $file['size'],
];
}
private static function ensureDir(): void
{
if (!is_dir(self::DIR) && !@mkdir(self::DIR, 0755, true) && !is_dir(self::DIR)) {
Http::error('Download-Ordner konnte nicht angelegt werden (Schreibrechte von api/uploads/ prüfen)', 500);
}
if (!is_file(self::DIR . '.htaccess')) {
@file_put_contents(self::DIR . '.htaccess', self::HTACCESS);
}
}
/** Loescht eine Download-Datei - nur innerhalb von api/uploads/downloads/ (kein Path-Traversal). */
private static function deleteFile(?string $path): void
{
$filename = basename((string) $path);
if ($filename === '' || $filename === '.' || $filename === '..' || $filename === '.htaccess') {
return;
}
$resolved = realpath(self::DIR . $filename);
$dir = realpath(self::DIR);
if ($resolved !== false && $dir !== false && str_starts_with($resolved, $dir . DIRECTORY_SEPARATOR) && is_file($resolved)) {
@unlink($resolved);
}
}
}