Phase 5: Erscheinungsbild mit Entwurf, Vorschau und Veröffentlichen
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 2m7s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 2m11s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 2m16s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 2m18s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 2m49s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 2m46s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 2m41s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 2m33s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m0s

- Theme in den Einstellungen (Entwurf/veröffentlicht), Übernahme der
  Einstellungen aus Phase 0; statische CSS-Datei mit Hash beim Veröffentlichen
- Logos hell/dunkel, Signet, App-Symbol → Favicon, Homescreen-Symbole,
  Web-App-Manifest; SVG-Bereinigung
- Markenfarbe exakt, zweite Akzentfarbe, Kopfleiste hell/Marke/dunkel,
  Kontrastprüfung (WCAG AA) mit automatisch lesbarer Linkfarbe
- Lokale Schriften (Latein), Überschriften-Schrift, eigene WOFF2-Schrift,
  Ecken, Dichte, Dunkelmodus-Regel
- Anmeldeseite (geteilt/zentriert, Bild, Texte), Fußzeile, E-Mails im Design
- Admin: Live-Vorschau (Startseite, Anmeldung, Beispielseite; hell/dunkel),
  Veröffentlichen, Verwerfen, Export/Import, Zurücksetzen, eigenes CSS
- Admin-Bereich übernimmt Logo, Farbe und Favicon; Whitelabel

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 10:46:05 +00:00
parent ee8dde93c0
commit 82bbeef31b
148 changed files with 2884 additions and 362 deletions

View file

@ -2,11 +2,15 @@
namespace App\Support;
use App\Support\Theme\Icons;
use App\Support\Theme\Theme;
use App\Support\Theme\ThemeCompiler;
use Illuminate\Support\Facades\Storage;
use Throwable;
/**
* Basis-Branding der Installation (Phase 0): Portalname, Logo, Primärfarbe.
* Das vollständige Erscheinungsbild folgt in Phase 5 (docs/PLAN.md, Abschnitt 12).
* Das aktive Erscheinungsbild (docs/PLAN.md, Abschnitt 12): der veröffentlichte
* Stand – oder der Entwurf, wenn eine berechtigte Person gerade die Vorschau nutzt.
*/
class Branding
{
@ -14,31 +18,84 @@ class Branding
public const DEFAULT_PRIMARY_COLOR = '#0F4C5C';
public function __construct(private readonly Settings $settings) {}
public const PREVIEW_SESSION_KEY = 'theme_preview';
/** @var array<string, mixed>|null */
private ?array $active = null;
private ?bool $previewing = null;
public function __construct(
private readonly Settings $settings,
private readonly Theme $theme,
private readonly ThemeCompiler $compiler,
) {}
/**
* @return array<string, mixed>
*/
public function active(): array
{
return $this->active ??= $this->isPreviewing() ? ($this->theme->draft() ?? $this->theme->published()) : $this->theme->published();
}
public function isPreviewing(): bool
{
if ($this->previewing !== null) {
return $this->previewing;
}
try {
$request = request();
return $this->previewing = $request->hasSession()
&& $request->session()->get(self::PREVIEW_SESSION_KEY) === true
&& (bool) $request->user()?->can('appearance.manage')
&& $this->theme->hasDraft();
} catch (Throwable) {
return $this->previewing = false;
}
}
/** Nach dem Speichern eines Entwurfs oder Veröffentlichen neu lesen. */
public function refresh(): void
{
$this->active = null;
$this->previewing = null;
}
public function get(string $key): mixed
{
return $this->active()[$key] ?? null;
}
public function portalName(): string
{
return $this->settings->get('branding.portal_name') ?: self::DEFAULT_NAME;
return $this->get('portal_name') ?: self::DEFAULT_NAME;
}
public function primaryColor(): string
{
$color = $this->settings->get('branding.primary_color');
return is_string($color) && preg_match('/^#[0-9a-fA-F]{6}$/', $color)
? strtoupper($color)
: self::DEFAULT_PRIMARY_COLOR;
return $this->get('primary_color') ?: self::DEFAULT_PRIMARY_COLOR;
}
public function logoPath(): ?string
{
return $this->settings->get('branding.logo_path') ?: null;
return $this->get('logo_light');
}
public function logoUrl(): ?string
{
$path = $this->logoPath();
return $this->url($this->get('logo_light'));
}
public function logoDarkUrl(): ?string
{
return $this->url($this->get('logo_dark')) ?? $this->logoUrl();
}
public function url(?string $path): ?string
{
return $path ? Storage::disk('uploads')->url($path) : null;
}
@ -51,33 +108,80 @@ class Branding
}
/**
* CSS-Variablen für das Portal. Werden serverseitig in die Seite geschrieben –
* ohne Build und ohne Farbberechnung im Browser.
* Stylesheet des veröffentlichten Stands; null = inline ausgeben (Vorschau, noch nie veröffentlicht).
*/
public function cssVariables(): string
public function stylesheetUrl(): ?string
{
$color = $this->primaryColor();
$variables = [
'--brand' => $color,
'--brand-foreground' => ColorPalette::foregroundFor($color),
];
$path = $this->isPreviewing() ? null : $this->get('stylesheet');
foreach ($this->palette() as $shade => $hex) {
$variables["--brand-{$shade}"] = $hex;
}
return $path && Storage::disk('uploads')->exists($path) ? $this->url($path) : null;
}
return collect($variables)->map(fn (string $value, string $name) => "{$name}:{$value}")->implode(';');
public function inlineCss(): string
{
return $this->compiler->css($this->active());
}
/**
* @return array{portal_name: string, primary_color: string, logo_url: string|null}
* @deprecated Nur noch für Übergänge – das Theme liefert alle Variablen.
*/
public function cssVariables(): string
{
return '--brand:'.$this->primaryColor();
}
public function faviconUrl(): string
{
$icons = $this->get('icons') ?? [];
return isset($icons[32]) ? $this->url($icons[32]) : Icons::monogram($this->portalName(), $this->primaryColor(), ColorPalette::foregroundFor($this->primaryColor()));
}
public function appleTouchIconUrl(): ?string
{
return isset(($this->get('icons') ?? [])[180]) ? $this->url($this->get('icons')[180]) : null;
}
/**
* Welche Darstellung gilt für eine Person? null = selbst gewählt/Systemeinstellung.
*/
public function forcedColorMode(): ?string
{
return match ($this->get('dark_mode')) {
'light' => 'light',
'dark' => 'dark',
default => null,
};
}
/**
* Für das Portal (Inertia).
*
* @return array<string, mixed>
*/
public function toArray(): array
{
$theme = $this->active();
return [
'portal_name' => $this->portalName(),
'primary_color' => $this->primaryColor(),
'logo_url' => $this->logoUrl(),
'logo_dark_url' => $this->logoDarkUrl(),
'logo_mark_url' => $this->url($theme['logo_mark']),
'header_style' => $theme['header_style'],
'color_mode' => $this->forcedColorMode(),
'login' => [
'layout' => $theme['login_layout'],
'title' => $theme['login_title'],
'text' => $theme['login_text'],
'image_url' => $this->url($theme['login_image']),
],
'footer' => [
'text' => $theme['footer_text'],
'links' => $theme['footer_links'],
],
'preview' => $this->isPreviewing(),
];
}
}

View file

@ -0,0 +1,91 @@
<?php
namespace App\Support\Theme;
use App\Support\ColorPalette;
/**
* Kontrastprüfung nach WCAG 2.1 (AA: 4,5:1 für Text, 3:1 für große Schrift und Bedienelemente).
* Warnt und schlägt vor – blockiert nichts.
*/
final class Contrast
{
public const LIGHT_BACKGROUND = '#FFFFFF';
public const DARK_BACKGROUND = '#171A1E';
public const AA = 4.5;
/**
* Farbe für Links und Akzenttext auf hellem Grund: die Markenfarbe selbst,
* sonst die erste dunklere Abstufung mit ausreichendem Kontrast.
*/
public static function textShadeOnLight(string $hex): int
{
$palette = ColorPalette::fromHex($hex);
foreach ([600, 700, 800, 900, 950] as $shade) {
if (ColorPalette::contrast($palette[$shade], self::LIGHT_BACKGROUND) >= self::AA) {
return $shade;
}
}
return 950;
}
/**
* Farbe für Links und Akzenttext auf dunklem Grund.
*/
public static function textShadeOnDark(string $hex): int
{
$palette = ColorPalette::fromHex($hex);
foreach ([300, 200, 100, 50] as $shade) {
if (ColorPalette::contrast($palette[$shade], self::DARK_BACKGROUND) >= self::AA) {
return $shade;
}
}
return 50;
}
/**
* Hinweise für die Seite „Erscheinungsbild“.
*
* @return list<array{level: string, text: string}>
*/
public static function report(string $primary, ?string $secondary = null): array
{
$notes = [];
$foreground = ColorPalette::foregroundFor($primary);
$onButton = ColorPalette::contrast($primary, $foreground);
$onWhite = ColorPalette::contrast($primary, self::LIGHT_BACKGROUND);
$palette = ColorPalette::fromHex($primary);
$notes[] = $onButton >= self::AA
? ['level' => 'ok', 'text' => sprintf('Schrift auf Schaltflächen (%s): Kontrast %s:1 – gut lesbar.', $foreground === '#FFFFFF' ? 'weiß' : 'schwarz', self::format($onButton))]
: ['level' => 'warning', 'text' => sprintf('Schrift auf Schaltflächen erreicht nur %s:1 (empfohlen mindestens 4,5:1). Eine etwas dunklere oder hellere Markenfarbe wäre besser lesbar, z. B. %s.', self::format($onButton), $palette[700])];
if ($onWhite >= self::AA) {
$notes[] = ['level' => 'ok', 'text' => sprintf('Links auf hellem Grund: Kontrast %s:1 – die Markenfarbe wird unverändert verwendet.', self::format($onWhite))];
} else {
$shade = self::textShadeOnLight($primary);
$notes[] = ['level' => 'info', 'text' => sprintf('Die Markenfarbe ist auf Weiß als Textfarbe zu hell (%s:1). Für Links und Akzenttexte wird automatisch die dunklere Abstufung %s verwendet. Schaltflächen und Flächen behalten die Markenfarbe.', self::format($onWhite), $palette[$shade])];
}
if ($secondary !== null) {
$onWhite2 = ColorPalette::contrast($secondary, self::LIGHT_BACKGROUND);
if ($onWhite2 < 3) {
$notes[] = ['level' => 'info', 'text' => sprintf('Die zweite Akzentfarbe ist auf Weiß sehr hell (%s:1). Für Beschriftungen wird automatisch eine dunklere Abstufung verwendet.', self::format($onWhite2))];
}
}
return $notes;
}
private static function format(float $ratio): string
{
return number_format($ratio, 1, ',', '');
}
}

View file

@ -0,0 +1,55 @@
<?php
namespace App\Support\Theme;
/**
* Mitgelieferte Schriften – lokal ausgeliefert (resources/css/fonts.css,
* erzeugt von scripts/generate-fonts-css.py), nie von Google Fonts.
*/
final class Fonts
{
public const FALLBACK_SANS = 'ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif';
public const FALLBACK_SERIF = 'ui-serif, Georgia, Cambria, "Times New Roman", serif';
/** Schlüssel => [Bezeichnung, CSS-Familie, serif?] */
public const FONTS = [
'inter' => ['Inter', 'Inter Variable', false],
'source-sans-3' => ['Source Sans 3', 'Source Sans 3 Variable', false],
'open-sans' => ['Open Sans', 'Open Sans Variable', false],
'nunito-sans' => ['Nunito Sans', 'Nunito Sans Variable', false],
'roboto' => ['Roboto', 'Roboto Variable', false],
'ibm-plex-sans' => ['IBM Plex Sans', 'IBM Plex Sans Variable', false],
'figtree' => ['Figtree', 'Figtree Variable', false],
'atkinson' => ['Atkinson Hyperlegible (besonders gut lesbar)', 'Atkinson Hyperlegible', false],
'source-serif-4' => ['Source Serif 4 (Serifen)', 'Source Serif 4 Variable', true],
'merriweather' => ['Merriweather (Serifen)', 'Merriweather Variable', true],
'lora' => ['Lora (Serifen)', 'Lora Variable', true],
'system' => ['Systemschrift des Geräts', null, false],
];
/** Familienname einer hochgeladenen Schrift. */
public const CUSTOM_FAMILY = 'Portal Eigene Schrift';
/**
* @return array<string, string>
*/
public static function options(bool $withCustom = false): array
{
$options = array_map(fn (array $font) => $font[0], self::FONTS);
return $withCustom ? $options + ['custom' => 'Eigene Schrift (hochgeladen)'] : $options;
}
public static function stack(string $key): string
{
if ($key === 'custom') {
return '"'.self::CUSTOM_FAMILY.'", '.self::FALLBACK_SANS;
}
[, $family, $serif] = self::FONTS[$key] ?? self::FONTS['inter'];
$fallback = $serif ? self::FALLBACK_SERIF : self::FALLBACK_SANS;
return $family ? '"'.$family.'", '.$fallback : $fallback;
}
}

View file

@ -0,0 +1,66 @@
<?php
namespace App\Support\Theme;
use App\Support\Images;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\Encoders\PngEncoder;
use Intervention\Image\ImageManager;
use Throwable;
/**
* Favicon und App-Symbole (Homescreen, Web-App) aus einem quadratischen Bild –
* in allen üblichen Größen. Ohne Bild: Monogramm in der Markenfarbe (SVG).
*/
class Icons
{
public const SIZES = [32, 180, 192, 512];
/**
* @param array<string, mixed> $theme
* @return array<int, string> Größe => Pfad im Speicher „uploads“
*/
public function generate(array $theme): array
{
$source = $theme['app_icon'] ?? null;
$disk = Storage::disk('uploads');
if (! $source || ! $disk->exists($source)) {
return [];
}
try {
Images::raiseMemoryLimitFor($disk->path($source));
$manager = ImageManager::usingDriver(Driver::class);
$hash = substr(sha1((string) $disk->get($source)), 0, 10);
$result = [];
foreach (self::SIZES as $size) {
$image = $manager->decodePath($disk->path($source));
$image->cover($size, $size);
$path = "theme/icons/icon-{$hash}-{$size}.png";
$disk->put($path, $image->encode(new PngEncoder)->toString());
$result[$size] = $path;
}
return $result;
} catch (Throwable $e) {
report($e);
return [];
}
}
/**
* Monogramm als SVG-Favicon (Daten-URL), wenn kein Symbol hochgeladen ist.
*/
public static function monogram(string $name, string $color, string $foreground): string
{
$letter = htmlspecialchars(mb_strtoupper(mb_substr(trim($name), 0, 1)) ?: 'P', ENT_XML1);
$svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="'.$color.'"/>'
.'<text x="32" y="44" font-family="Arial,Helvetica,sans-serif" font-size="34" font-weight="700" text-anchor="middle" fill="'.$foreground.'">'.$letter.'</text></svg>';
return 'data:image/svg+xml;base64,'.base64_encode($svg);
}
}

View file

@ -0,0 +1,62 @@
<?php
namespace App\Support\Theme;
use DOMDocument;
use DOMElement;
use DOMXPath;
use Illuminate\Support\Facades\Storage;
/**
* Entfernt aus hochgeladenen SVG-Dateien alles Ausführbare (Skripte,
* Ereignis-Attribute, javascript:-Links, eingebettetes HTML). Logos werden
* öffentlich ausgeliefert und dürfen niemals Code enthalten.
*/
final class SvgSanitizer
{
public static function sanitizeFile(?string $path): void
{
if (! $path || ! str_ends_with(strtolower($path), '.svg')) {
return;
}
$disk = Storage::disk('uploads');
if (! $disk->exists($path)) {
return;
}
$clean = self::sanitize((string) $disk->get($path));
$clean === null ? $disk->delete($path) : $disk->put($path, $clean);
}
public static function sanitize(string $svg): ?string
{
$dom = new DOMDocument;
// Keine externen Entitäten, kein Netzwerkzugriff.
if (str_contains($svg, '<!ENTITY') || ! @$dom->loadXML($svg, LIBXML_NONET) || $dom->documentElement?->localName !== 'svg') {
return null;
}
$xpath = new DOMXPath($dom);
foreach (iterator_to_array($xpath->query('//*[local-name()="script" or local-name()="foreignObject" or local-name()="iframe" or local-name()="object" or local-name()="embed"]')) as $node) {
$node->parentNode->removeChild($node);
}
foreach (iterator_to_array($xpath->query('//*')) as $element) {
/** @var DOMElement $element */
foreach (iterator_to_array($element->attributes) as $attribute) {
$name = strtolower($attribute->nodeName);
$value = strtolower(preg_replace('/\s+/', '', $attribute->nodeValue));
if (str_starts_with($name, 'on') || (in_array($name, ['href', 'xlink:href', 'src'], true) && ! str_starts_with($value, '#') && ! str_starts_with($value, 'data:image/'))) {
$element->removeAttributeNode($attribute);
}
}
}
return $dom->saveXML($dom->documentElement);
}
}

191
app/Support/Theme/Theme.php Normal file
View file

@ -0,0 +1,191 @@
<?php
namespace App\Support\Theme;
use App\Support\Settings;
use Illuminate\Support\Arr;
/**
* Erscheinungsbild der Installation: veröffentlichter Stand und Entwurf.
* Gespeichert in den Einstellungen (Datenbank) – überlebt jedes Update.
* Bilder und Schriften liegen im Speicher „uploads“ unter theme/.
*/
class Theme
{
public const DEFAULTS = [
'portal_name' => 'Inhaus',
'logo_light' => null,
'logo_dark' => null,
'logo_mark' => null,
'app_icon' => null,
'icons' => [],
'primary_color' => '#0F4C5C',
'secondary_color' => null,
'header_style' => 'light',
'font_body' => 'inter',
'font_heading' => 'same',
'custom_font' => null,
'radius' => 'medium',
'density' => 'normal',
'dark_mode' => 'user',
'login_layout' => 'split',
'login_title' => 'Alles Wichtige für Ihren Arbeitsalltag – an einem Ort.',
'login_text' => null,
'login_image' => null,
'footer_text' => null,
'footer_links' => [],
'email_footer' => null,
'custom_css' => null,
'stylesheet' => null,
];
public const HEADER_STYLES = ['light' => 'Hell', 'brand' => 'In der Markenfarbe', 'dark' => 'Dunkel'];
public const RADII = ['none' => ['Eckig', '0rem'], 'small' => ['Leicht gerundet', '0.25rem'], 'medium' => ['Gerundet', '0.5rem'], 'large' => ['Stark gerundet', '0.75rem'], 'round' => ['Rund', '1rem']];
public const DENSITIES = ['compact' => ['Kompakt', '0.225rem'], 'normal' => ['Normal', '0.25rem'], 'comfortable' => ['Luftig', '0.275rem']];
public const DARK_MODES = [
'user' => 'Jede Person wählt selbst (Standard: wie im System)',
'light' => 'Immer hell',
'dark' => 'Immer dunkel',
];
public const LOGIN_LAYOUTS = ['split' => 'Geteilt: Bild bzw. Markenfarbe links, Anmeldung rechts', 'centered' => 'Zentriert: Anmeldung vor dem Hintergrundbild'];
private const PUBLISHED = 'theme.published';
private const DRAFT = 'theme.draft';
public function __construct(private readonly Settings $settings) {}
/**
* @return array<string, mixed>
*/
public function published(): array
{
$stored = $this->settings->get(self::PUBLISHED);
return self::normalize(is_array($stored) ? $stored : $this->legacy());
}
/**
* @return array<string, mixed>|null
*/
public function draft(): ?array
{
$stored = $this->settings->get(self::DRAFT);
return is_array($stored) ? self::normalize($stored) : null;
}
public function hasDraft(): bool
{
return $this->draft() !== null;
}
/**
* Entwurf, sonst der veröffentlichte Stand – Ausgangspunkt für das Formular.
*
* @return array<string, mixed>
*/
public function working(): array
{
return $this->draft() ?? $this->published();
}
/**
* @param array<string, mixed> $values
*/
public function saveDraft(array $values): void
{
$theme = self::normalize([...$this->working(), ...$values]);
foreach (['logo_light', 'logo_dark', 'logo_mark'] as $logo) {
SvgSanitizer::sanitizeFile($theme[$logo]);
}
$this->settings->set(self::DRAFT, $theme);
}
public function discardDraft(): void
{
$this->settings->set(self::DRAFT, null);
}
/**
* Entwurf veröffentlichen: statische CSS-Datei erzeugen, Symbole berechnen.
*/
public function publish(ThemeCompiler $compiler, Icons $icons): void
{
$theme = $this->working();
$theme['icons'] = $icons->generate($theme);
$theme['stylesheet'] = $compiler->write($theme);
$this->settings->setMany([self::PUBLISHED => $theme, self::DRAFT => null]);
}
/**
* Auf die Standardwerte zurücksetzen – als Entwurf, damit man es erst ansehen kann.
*/
public function resetToDefaults(): void
{
$this->settings->set(self::DRAFT, self::normalize([...self::DEFAULTS, 'portal_name' => $this->published()['portal_name']]));
}
/**
* Nur bekannte Schlüssel, gültige Werte.
*
* @param array<string, mixed> $theme
* @return array<string, mixed>
*/
public static function normalize(array $theme): array
{
$theme = [...self::DEFAULTS, ...Arr::only($theme, array_keys(self::DEFAULTS))];
$hex = fn ($value) => is_string($value) && preg_match('/^#[0-9a-fA-F]{6}$/', $value) ? strtoupper($value) : null;
$theme['portal_name'] = mb_substr(trim((string) $theme['portal_name']), 0, 60) ?: self::DEFAULTS['portal_name'];
$theme['primary_color'] = $hex($theme['primary_color']) ?? self::DEFAULTS['primary_color'];
$theme['secondary_color'] = $hex($theme['secondary_color']);
$theme['header_style'] = array_key_exists($theme['header_style'], self::HEADER_STYLES) ? $theme['header_style'] : 'light';
$theme['font_body'] = array_key_exists($theme['font_body'], Fonts::FONTS) || ($theme['font_body'] === 'custom' && $theme['custom_font']) ? $theme['font_body'] : 'inter';
$theme['font_heading'] = $theme['font_heading'] === 'same' || array_key_exists($theme['font_heading'], Fonts::FONTS) || ($theme['font_heading'] === 'custom' && $theme['custom_font']) ? $theme['font_heading'] : 'same';
$theme['radius'] = array_key_exists($theme['radius'], self::RADII) ? $theme['radius'] : 'medium';
$theme['density'] = array_key_exists($theme['density'], self::DENSITIES) ? $theme['density'] : 'normal';
$theme['dark_mode'] = array_key_exists($theme['dark_mode'], self::DARK_MODES) ? $theme['dark_mode'] : 'user';
$theme['login_layout'] = array_key_exists($theme['login_layout'], self::LOGIN_LAYOUTS) ? $theme['login_layout'] : 'split';
$theme['footer_links'] = array_values(array_filter(array_map(
fn ($link) => is_array($link) && filled($link['label'] ?? null) && filled($link['url'] ?? null)
? ['label' => mb_substr(trim($link['label']), 0, 60), 'url' => mb_substr(trim($link['url']), 0, 500)]
: null,
(array) $theme['footer_links'],
)));
$theme['icons'] = is_array($theme['icons']) ? $theme['icons'] : [];
foreach (['login_title', 'login_text', 'footer_text', 'email_footer'] as $text) {
$theme[$text] = filled($theme[$text]) ? mb_substr(trim((string) $theme[$text]), 0, 500) : null;
}
foreach (['logo_light', 'logo_dark', 'logo_mark', 'app_icon', 'login_image', 'custom_font'] as $file) {
$theme[$file] = is_string($theme[$file]) && preg_match('#^(theme|branding)/[A-Za-z0-9/_.-]+$#', $theme[$file]) && ! str_contains($theme[$file], '..') ? $theme[$file] : null;
}
$theme['custom_css'] = filled($theme['custom_css']) ? mb_substr((string) $theme['custom_css'], 0, 50000) : null;
return $theme;
}
/**
* Einstellungen aus Phase 0 (Portalname, Logo, Markenfarbe) übernehmen.
*
* @return array<string, mixed>
*/
private function legacy(): array
{
return array_filter([
'portal_name' => $this->settings->get('branding.portal_name'),
'primary_color' => $this->settings->get('branding.primary_color'),
'logo_light' => $this->settings->get('branding.logo_path'),
]);
}
}

View file

@ -0,0 +1,98 @@
<?php
namespace App\Support\Theme;
use App\Support\ColorPalette;
use Illuminate\Support\Facades\Storage;
/**
* Baut aus dem Theme eine CSS-Datei mit Variablen (Farben, Schriften, Form)
* und dem eigenen CSS. Beim Veröffentlichen wird sie mit Hash im Namen
* gespeichert – kein Build, keine Rechenarbeit pro Seitenaufruf.
*/
class ThemeCompiler
{
/**
* @param array<string, mixed> $theme
*/
public function css(array $theme): string
{
$primary = $theme['primary_color'];
$palette = ColorPalette::fromHex($primary);
$secondary = $theme['secondary_color'] ?? $primary;
$palette2 = ColorPalette::fromHex($secondary);
$light = [
'--brand' => $primary,
'--brand-foreground' => ColorPalette::foregroundFor($primary),
'--brand-text' => $palette[Contrast::textShadeOnLight($primary)],
'--accent2' => $secondary,
'--accent2-foreground' => ColorPalette::foregroundFor($secondary),
'--accent2-text' => $palette2[Contrast::textShadeOnLight($secondary)],
'--radius' => Theme::RADII[$theme['radius']][1],
'--spacing' => Theme::DENSITIES[$theme['density']][1],
'--font-body' => Fonts::stack($theme['font_body']),
'--font-heading' => Fonts::stack($theme['font_heading'] === 'same' ? $theme['font_body'] : $theme['font_heading']),
];
foreach ($palette as $shade => $hex) {
$light["--brand-{$shade}"] = $hex;
}
foreach ($palette2 as $shade => $hex) {
$light["--accent2-{$shade}"] = $hex;
}
$dark = [
'--brand-text' => $palette[Contrast::textShadeOnDark($primary)],
'--accent2-text' => $palette2[Contrast::textShadeOnDark($secondary)],
];
$css = ':root{'.$this->declarations($light).'}'."\n"
.'.dark{'.$this->declarations($dark).'}'."\n";
if ($theme['custom_font']) {
$url = Storage::disk('uploads')->url($theme['custom_font']);
$css .= '@font-face{font-family:"'.Fonts::CUSTOM_FAMILY.'";src:url("'.$url.'") format("woff2");font-weight:100 900;font-display:swap}'."\n";
}
if ($theme['custom_css']) {
// Eigenes CSS steht in einer eigenen CSS-Datei; ein schließendes </style> ist dort bedeutungslos,
// wird aber für die Vorschau (inline) trotzdem entschärft.
$css .= "/* Eigenes CSS */\n".str_ireplace('</style', '<\/style', $theme['custom_css'])."\n";
}
return $css;
}
/**
* CSS-Datei schreiben und ihren Pfad im Speicher „uploads“ liefern.
*
* @param array<string, mixed> $theme
*/
public function write(array $theme): string
{
$css = $this->css($theme);
$path = 'theme/theme-'.substr(sha1($css), 0, 12).'.css';
$disk = Storage::disk('uploads');
if (! $disk->exists($path)) {
$disk->put($path, $css);
}
// Ältere Fassungen aufräumen (die aktuelle und die vorherige bleiben für offene Seiten).
$old = collect($disk->files('theme'))->filter(fn ($f) => preg_match('#^theme/theme-[0-9a-f]{12}\.css$#', $f) && $f !== $path)
->sortByDesc(fn ($f) => $disk->lastModified($f))->slice(1);
$disk->delete($old->all());
return $path;
}
/**
* @param array<string, string> $values
*/
private function declarations(array $values): string
{
return collect($values)->map(fn ($value, $name) => $name.':'.$value)->implode(';');
}
}

View file

@ -0,0 +1,92 @@
<?php
namespace App\Support\Theme;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RuntimeException;
/**
* Erscheinungsbild als Datei – z. B. vom Test- auf das Produktivsystem.
* Bilder und Schrift reisen als Daten-URLs mit.
*/
class ThemeTransfer
{
public const FORMAT = 'inhaus-theme';
private const FILES = ['logo_light', 'logo_dark', 'logo_mark', 'app_icon', 'login_image', 'custom_font'];
private const MIME = [
'image/svg+xml' => 'svg', 'image/png' => 'png', 'image/jpeg' => 'jpg', 'image/webp' => 'webp', 'font/woff2' => 'woff2',
];
/**
* @param array<string, mixed> $theme
* @return array<string, mixed>
*/
public function export(array $theme): array
{
$disk = Storage::disk('uploads');
$files = [];
foreach (self::FILES as $key) {
if ($theme[$key] && $disk->exists($theme[$key])) {
$mime = $key === 'custom_font' ? 'font/woff2' : ($disk->mimeType($theme[$key]) ?: 'application/octet-stream');
$files[$key] = 'data:'.$mime.';base64,'.base64_encode((string) $disk->get($theme[$key]));
}
}
return [
'format' => self::FORMAT,
'version' => 1,
'exported_at' => now()->toIso8601String(),
'theme' => collect($theme)->except([...self::FILES, 'icons', 'stylesheet'])->all(),
'files' => $files,
];
}
/**
* @return array<string, mixed> Werte für den Entwurf
*/
public function import(string $json): array
{
$data = json_decode($json, true);
if (! is_array($data) || ($data['format'] ?? null) !== self::FORMAT || ! is_array($data['theme'] ?? null)) {
throw new RuntimeException('Die Datei ist kein exportiertes Erscheinungsbild.');
}
$values = collect($data['theme'])->except([...self::FILES, 'icons', 'stylesheet'])->all();
foreach (self::FILES as $key) {
$values[$key] = null;
$uri = $data['files'][$key] ?? null;
if (! is_string($uri) || ! preg_match('#^data:([a-z0-9.+/-]+);base64,(.+)$#i', $uri, $m)) {
continue;
}
$extension = self::MIME[strtolower($m[1])] ?? null;
$binary = base64_decode($m[2], true);
if (! $extension || $binary === false || strlen($binary) > 8 * 1024 * 1024) {
continue;
}
// Inhalt prüfen: Bilder müssen sich lesen lassen, SVG wird von allem Ausführbaren befreit.
if ($extension === 'svg' && ($binary = SvgSanitizer::sanitize($binary)) === null) {
continue;
}
if (in_array($extension, ['png', 'jpg', 'webp'], true) && @getimagesizefromstring($binary) === false) {
continue;
}
$path = ($key === 'custom_font' ? 'theme/fonts/' : 'theme/').'import-'.Str::random(20).'.'.$extension;
Storage::disk('uploads')->put($path, $binary);
$values[$key] = $path;
}
return Theme::normalize([...Theme::DEFAULTS, ...$values]);
}
}