HifiPlanet-Website/hifi/api/src/Support/SiteImages.php
max.olchov 296c196d06
Bilder im Admin austauschbar: Link-Vorschau, Einblicke, Startseite, Hintergruende, Paketkacheln
Neue Seite Einstellungen > Bilder (Titelbild und Logos dorthin verschoben) plus
"Bild tauschen" im Live-Bearbeiten-Modus. Gespeichert als JSON in
app_settings.site_images (Auto-Migration). Startseite und SPA-Fallback laufen
ueber api/public/page.php, das og:image und Favicon serverseitig ins HTML setzt.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PBCD1KUwiqh1kdMwDSwVfD
2026-10-20 16:12:15 +00:00

166 lines
6.4 KiB
PHP

<?php
namespace App\Support;
use App\Config\Database;
/**
* Austauschbare Bilder der Website, die bisher fest im Frontend-Build steckten (Link-Vorschau,
* Startseiten-Fotos, "Einblicke in unsere Umbauten", Kontakt-/Countdown-Hintergrund,
* Paketkacheln, Favicon). Alles zusammen als JSON in app_settings.site_images, damit nicht fuer
* jedes Bild eine eigene Spalte noetig ist. Leer/fehlend = das eingebaute Standardbild.
*
* Gepflegt unter Einstellungen > Bilder (/site-settings) und im Live-Bearbeiten-Modus
* (LiveEditController, entity "site_images", id = Schluessel bzw. "liste.index").
*/
class SiteImages
{
// Einzelbilder - die Schluessel muessen zu hifi-src/src/constants/siteImages.js passen.
public const SLOTS = [
'og_image', 'favicon', 'craft', 'advice', 'youtube_poster', 'more',
'contact_bg_light', 'contact_bg_dark', 'countdown_bg',
];
// Bilderlisten mit Hoechstzahl. package_tiers hat feste Positionen (Stufe 1-8), leere
// Eintraege bleiben dort als null stehen; insights ist eine frei lange Liste, in der
// "default:N" fuer das N-te eingebaute Foto steht (so lassen sich die Standardfotos
// einzeln behalten, entfernen oder umsortieren). Ohne gespeicherte Liste gelten alle.
public const LISTS = ['insights' => 24, 'package_tiers' => 8];
public const INSIGHTS_DEFAULT_COUNT = 6;
/** Gespeichertes JSON auf bekannte Schluessel und gueltige Upload-Pfade filtern. */
public static function decode($raw): array
{
$decoded = is_string($raw) ? json_decode($raw, true) : (is_array($raw) ? $raw : null);
$decoded = is_array($decoded) ? $decoded : [];
$result = [];
foreach (self::SLOTS as $slot) {
$path = self::cleanPath($decoded[$slot] ?? null);
if ($path !== null) {
$result[$slot] = $path;
}
}
foreach (self::LISTS as $list => $max) {
$items = is_array($decoded[$list] ?? null) ? array_slice(array_values($decoded[$list]), 0, $max) : [];
if ($list === 'insights') {
$items = array_values(array_filter(array_map([self::class, 'cleanInsight'], $items)));
// Auch eine leere Liste speichern - dann sind alle Fotos bewusst entfernt.
if (array_key_exists($list, $decoded) && is_array($decoded[$list])) {
$result[$list] = $items;
}
continue;
}
$items = array_map([self::class, 'cleanPath'], $items);
if (array_filter($items)) {
$result[$list] = $items;
}
}
return $result;
}
/** Alle in den Bildern verwendeten Upload-Pfade (fuer Export und Aufraeumen). */
public static function paths(array $images): array
{
$paths = [];
foreach ($images as $value) {
foreach ((array) $value as $path) {
if (is_string($path) && self::cleanPath($path) !== null) {
$paths[] = $path;
}
}
}
return $paths;
}
public static function load(): array
{
try {
$raw = Database::connection()->query('SELECT site_images FROM app_settings WHERE id = 1')->fetchColumn();
} catch (\Throwable $e) {
return []; // Spalte fehlt noch - es gelten die eingebauten Bilder
}
return self::decode($raw);
}
/** Speichert die komplette Bilderliste und loescht dabei nicht mehr verwendete Uploads. */
public static function save(\PDO $db, array $images): array
{
$old = self::load();
$images = self::decode($images);
$db->exec('INSERT IGNORE INTO app_settings (id) VALUES (1)');
$db->prepare('UPDATE app_settings SET site_images = ? WHERE id = 1')
->execute([$images ? json_encode($images, JSON_UNESCAPED_SLASHES) : null]);
$stillUsed = self::paths($images);
foreach (self::paths($old) as $path) {
if (!in_array($path, $stillUsed, true)) {
Uploads::deleteIfOrphaned($path, null);
}
}
return $images;
}
/**
* Prueft einen Schluessel aus dem Live-Bearbeiten-Modus: "craft" oder "insights.3".
* Liefert [schluessel, index|null] oder null, wenn er unbekannt ist.
*/
public static function parseKey(string $key): ?array
{
if (in_array($key, self::SLOTS, true)) {
return [$key, null];
}
if (preg_match('/^([a-z_]+)\.(\d{1,2})$/', $key, $m) && isset(self::LISTS[$m[1]]) && (int) $m[2] < self::LISTS[$m[1]]) {
return [$m[1], (int) $m[2]];
}
return null;
}
/** Setzt ein einzelnes Bild (Live-Bearbeiten); leerer Pfad = Standardbild. */
public static function set(array $images, string $slot, ?int $index, string $path): array
{
$path = self::cleanPath($path);
if ($index === null) {
$images[$slot] = $path;
return $images;
}
$list = $images[$slot] ?? ($slot === 'insights' ? self::defaultInsights() : []);
if ($slot === 'insights' && $path === null) {
// Leeren heisst bei den Einblicken: wieder das eingebaute Foto an dieser Stelle.
$path = $index < self::INSIGHTS_DEFAULT_COUNT ? "default:$index" : null;
}
// Die eingebauten Standardbilder fuellen die Luecken (null) - so kann ein einzelnes
// Bild in der Mitte getauscht werden, ohne dass die anderen verrutschen.
while (count($list) <= $index) {
$list[] = null;
}
$list[$index] = $path;
$images[$slot] = $list;
return $images;
}
public static function defaultInsights(): array
{
return array_map(fn($i) => "default:$i", range(0, self::INSIGHTS_DEFAULT_COUNT - 1));
}
private static function cleanInsight($value): ?string
{
if (is_string($value) && preg_match('/^default:(\d+)$/', $value, $m) && (int) $m[1] < self::INSIGHTS_DEFAULT_COUNT) {
return $value;
}
return self::cleanPath($value);
}
/** Nur Bilder aus dem eigenen Upload-Ordner - keine fremden URLs, kein Path-Traversal. */
private static function cleanPath($path): ?string
{
if (!is_string($path)) {
return null;
}
$path = trim($path);
if (!preg_match('#^(/[A-Za-z0-9_\-/]*)?/api/uploads/[A-Za-z0-9_\-]+\.(jpg|jpeg|png|webp)$#', $path)) {
return null;
}
return $path;
}
}