Stelle alle CMS-Bilder auf die zentrale Medienverwaltung um.
CI Feature / test (push) Successful in 48s
Deploy Test / test (push) Successful in 44s
Deploy Test / deploy (push) Successful in 37s

- Einstieg, Bild und Text, redaktionelle Karten, Premium-Karten und Abschnittshintergrund speichern die
  Kennung des Mediums (Bildschlüssel image) und lesen über WebsiteMedia; öffentlich nur mit Website-Freigabe,
  in der Redaktionsvorschau sonst das Vorschaubild mit Hinweis.
- Gemeinsame Felder: Medienpicker mit Vorschaubild und Status, Upload direkt über WebsiteIntake, Anzeige des
  gewählten Mediums mit Verweis auf den Medienmanager. Die CMS-eigene Bildauswahl entfällt.
- Frühere CMS-Bilder übernimmt ein Warteschlangen-Job (dedupliziert, nichts gelöscht); website_media_aliases
  ordnet frühere Pfade zu, wirksam erst nach der ersten Website-Freigabe; /medien/cms/ folgt danach der Freigabe.
- Medienansicht nennt die Website-Seiten, die ein Bild verwenden.
- Bewusst geändert: Der Alternativtext gehört zum Medium und ist im Widget nur noch eine optionale Abweichung;
  die Tests zur Alt-Text-Pflicht prüfen jetzt Übernahme und andere Registry-Fehler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Opus 5.5 committed 2026-11-18 22:32:29 +01:00
1 parent 7c63424ea6
commit 053a8d4648
35 files changed
+1170 -164

No files matched your search

+13 -8
View File
@@ -2,7 +2,9 @@
namespace App\Domain\Cms\Sections;
use App\Domain\Cms\Widgets\Support\ImageRefFields;
use App\Domain\Cms\Widgets\Support\PublicMedia;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetRegistry;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
@@ -145,7 +147,7 @@ public function mediaPaths(array $sections): array
foreach ($sections as $section) {
$style = SectionStyle::fromStored($section['style'] ?? []);
if ($style['image'] !== null && PublicMedia::isPublicPath($style['image'])) {
if (is_string($style['image']) && PublicMedia::isPublicPath($style['image'])) {
$paths[] = $style['image'];
}
}
@@ -335,14 +337,17 @@ private function normalizeStyle(array $style, string $prefix, array &$errors): a
$result[$key] = $value;
}
$upload = PublicMedia::fromUploadState($style['_upload'] ?? null);
$image = $upload ?? PublicMedia::fromUploadState($style['image'] ?? null);
if ($result['background'] === 'image') {
if ($image === null) {
$errors["$prefix.style.image"] = ['Bitte ein Hintergrundbild wählen oder hochladen.'];
} elseif (! PublicMedia::isPublicPath($image)) {
$errors["$prefix.style.image"] = ['Das Hintergrundbild liegt nicht im öffentlichen Medienbereich.'];
$widgetErrors = new WidgetErrors;
$refs = ImageRefFields::clean(['image' => $style['image'] ?? null, '_upload' => $style['_upload'] ?? null], $widgetErrors, errorKey: 'image');
$image = $refs['image'];
foreach ($widgetErrors->all() as $messages) {
$errors["$prefix.style.image"] = $messages;
}
if ($image === null && ! isset($errors["$prefix.style.image"])) {
$errors["$prefix.style.image"] = ['Bitte ein Hintergrundbild aus dem Medienmanager wählen oder hochladen.'];
}
$result['image'] = $image;
+7 -5
View File
@@ -3,7 +3,7 @@
namespace App\Domain\Cms\Sections;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Cms\Widgets\Support\PublicMedia;
use App\Domain\Cms\Widgets\Support\WebsiteImage;
use App\Domain\Cms\Widgets\WidgetRenderer;
use Illuminate\Support\HtmlString;
@@ -56,7 +56,7 @@ public function renderAll(array $sections, RenderContext $context): HtmlString
$last = count($rendered) - 1;
foreach ($rendered as $index => $item) {
$html .= $this->renderSection($item['section'], $item['cells'], $index);
$html .= $this->renderSection($item['section'], $item['cells'], $index, $context);
$divider = $item['section']['style']['divider'] ?? 'none';
if ($index < $last && in_array($divider, ['line', 'accent'], true)) {
@@ -71,11 +71,13 @@ public function renderAll(array $sections, RenderContext $context): HtmlString
* @param array<string, mixed> $section
* @param list<array{units: int, html: string}> $cells
*/
private function renderSection(array $section, array $cells, int $index): string
private function renderSection(array $section, array $cells, int $index, RenderContext $context): string
{
$style = SectionStyle::fromStored($section['style'] ?? []);
$columns = SectionLayouts::columns(array_column($cells, 'units'));
$hasImage = $style['background'] === 'image' && $style['image'] !== null && PublicMedia::isPublicPath($style['image']);
// Hintergrundbild aus dem Medienmanager: öffentlich nur mit Website-Freigabe (WebsiteImage → WebsiteMedia).
$imageUrl = $style['background'] === 'image' ? app(WebsiteImage::class)->url($style['image'], $context->preview) : null;
$hasImage = $imageUrl !== null;
$classes = [
'page-section',
@@ -109,7 +111,7 @@ private function renderSection(array $section, array $cells, int $index): string
if ($hasImage) {
// Das Bild des ersten Abschnitts ist meist das größte sichtbare Element und wird nicht verzögert geladen.
$loading = $index === 0 ? 'loading="eager" fetchpriority="high"' : 'loading="lazy"';
$html .= '<img class="page-section-image" src="'.e(PublicMedia::url($style['image'])).'" alt="" '.$loading.' decoding="async"'
$html .= '<img class="page-section-image" src="'.e($imageUrl).'" alt="" '.$loading.' decoding="async"'
.' style="object-position: '.e(SectionStyle::FOCUS_POSITIONS[$style['focus']]).'">';
}
+3 -3
View File
@@ -2,7 +2,7 @@
namespace App\Domain\Cms\Sections;
use App\Domain\Cms\Widgets\Support\PublicMedia;
use App\Domain\Cms\Widgets\Support\WebsiteImage;
/**
* Semantische Abschnittsgestaltung. Jeder Wert ist eine Aufzählung, die auf zentrale Design-Tokens
@@ -134,7 +134,7 @@ public static function fromStored(mixed $style): array
}
}
$result['image'] = $result['background'] === 'image' && is_string($style['image'] ?? null) ? $style['image'] : null;
$result['image'] = $result['background'] === 'image' ? WebsiteImage::normalize($style['image'] ?? null) : null;
return $result;
}
@@ -204,7 +204,7 @@ public static function migrateSpacing(array $sections, bool $byVersion = false):
$rendered = is_array($section['slots'] ?? null) && array_filter($section['slots'], 'is_array') !== [];
$background = is_string($style['background'] ?? null) && isset(self::BACKGROUNDS[$style['background']]) ? $style['background'] : 'default';
if ($background === 'image' && ! PublicMedia::isPublicPath($style['image'] ?? null)) {
if ($background === 'image' && WebsiteImage::normalize($style['image'] ?? null) === null) {
$background = 'default';
}
$divider = in_array($style['divider'] ?? null, ['line', 'accent'], true) ? $style['divider'] : 'none';
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Domain\Cms;
use App\Domain\Catalog\ContentElement;
use App\Domain\Media\WebsiteMediaAlias;
/**
* Wo ein Medium auf Website-Seiten als Bild verwendet wird (veröffentlichte Fassung und neuester Entwurf).
* Für den Medienmanager: Vor dem Zurücknehmen einer Website-Freigabe ist sichtbar, welche Seiten das Bild verlieren.
*/
class WebsiteImageUsage
{
/**
* @return list<array{path: string, published: bool, draft: bool}>
*/
public function pages(ContentElement $element): array
{
$legacy = WebsiteMediaAlias::query()->where('content_element_id', $element->id)->pluck('legacy_path')->all();
$usages = [];
foreach (Page::query()->with(['publishedRevision', 'latestRevision'])->orderBy('path')->get() as $page) {
$published = $page->publishedRevision !== null && $this->uses($page->publishedRevision->sections ?? [], $element->id, $legacy);
$draft = $page->latestRevision !== null && $page->latestRevision->id !== $page->published_revision_id
&& $this->uses($page->latestRevision->sections ?? [], $element->id, $legacy);
if ($published || $draft) {
$usages[] = ['path' => (string) $page->path, 'published' => $published, 'draft' => $draft];
}
}
return $usages;
}
/**
* @param list<string> $legacy
*/
private function uses(mixed $value, int $id, array $legacy): bool
{
if (! is_array($value)) {
return false;
}
foreach ($value as $key => $item) {
if ($key === 'image' && (($item === $id || (is_string($item) && ($item === (string) $id || in_array($item, $legacy, true)))))) {
return true;
}
if (is_array($item) && $this->uses($item, $id, $legacy)) {
return true;
}
}
return false;
}
}
@@ -5,40 +5,80 @@
use App\Domain\Cms\Widgets\WidgetErrors;
use Filament\Forms\Components\Field;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Select;
use Illuminate\Support\Str;
use Filament\Notifications\Notification;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Illuminate\Support\HtmlString;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
/**
* Gemeinsame Bildauswahl für Widgets: vorhandenes Bild aus dem öffentlichen Website-Bereich wählen
* oder ein neues hochladen. Keine eigene Medienverwaltung.
* Gemeinsame Bildauswahl aller Widgets und des Abschnittshintergrunds: Bilder aus dem zentralen Medienmanager
* (siehe WebsiteImage, docs/architektur/medienzugriff-fuer-komponenten.md). Keine eigene CMS-Medienverwaltung.
*
* - Auswahl: durchsuchbare Liste mit Vorschaubild, Titel und Website-Status.
* - Neu hochladen: Das Bild wird sofort als Medium im Medienmanager angelegt (WebsiteIntake) und ausgewählt.
* - Anzeige des gewählten Mediums mit Status und Verweis auf die Freigabe im Medienmanager.
*
* Das Bedienmuster folgt der Bildauswahl im Modul- und Programmeditor (Suche, Vorschaubild, Auswählen); jene ist an
* die Livewire-Seite des Editors gebunden und lässt sich nicht als Formularfeld im Widget-Dialog einhängen.
*/
final class ImageRefFields
{
/**
* @param bool $live Änderungen sofort an die Vorschau im Bearbeitungsdialog geben.
* @return list<Field>
* @param string|null $altField Name des Alternativtext-Felds im selben Formular (für neue Medien), falls vorhanden.
* @return list<Field|Placeholder>
*/
public static function fields(string $label = 'Bild', bool $live = false): array
public static function fields(string $label = 'Bild', bool $live = false, string $key = 'image', ?string $altField = null): array
{
return [
Select::make('image')
->live($live)
->label($label.': vorhandenes Bild')
->options(fn (): array => PublicMedia::imageOptions())
Select::make($key)
->live()
->label($label.' aus dem Medienmanager')
->searchable()
->allowHtml()
->options(fn (): array => app(WebsiteImage::class)->options())
->getSearchResultsUsing(fn (?string $search): array => app(WebsiteImage::class)->options($search))
->getOptionLabelUsing(fn (mixed $value): ?string => app(WebsiteImage::class)->optionHtml($value))
->placeholder('Kein Bild')
->helperText('Auswahl aus den Bildern, die bereits für die Website hochgeladen wurden.'),
->helperText('Alle Bilder des Medienmanagers. Öffentlich erscheint ein Bild nur mit Website-Freigabe.'),
FileUpload::make('_upload')
->live($live)
->label($label.': neu hochladen')
->disk('cms_incoming')
->directory('cms')
->live()
->label($label.': neues Bild hochladen')
->image()
->maxSize(8192)
->acceptedFileTypes(['image/jpeg', 'image/png', 'image/webp'])
->getUploadedFileNameForStorageUsing(fn (TemporaryUploadedFile $file): string => Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)).'-'.Str::lower(Str::random(6)).'.'.$file->guessExtension())
->helperText('Ein neues Bild ersetzt die Auswahl oben. Es wird beim Speichern im öffentlichen Bereich der Website abgelegt.'),
->storeFiles(false)
->afterStateUpdated(function (mixed $state, Set $set, Get $get) use ($key, $altField): void {
$file = is_array($state) ? (array_values($state)[0] ?? null) : $state;
if (! $file instanceof TemporaryUploadedFile) {
return;
}
$element = app(WebsiteImage::class)->accept($file, $altField !== null ? $get($altField) : null);
$set('_upload', null);
if ($element === null) {
Notification::make()->danger()->title('Das Bild konnte nicht übernommen werden.')->send();
return;
}
$set($key, $element->id);
Notification::make()
->success()
->title('Im Medienmanager angelegt: „'.($element->display_title ?: $element->working_title).'“')
->body('Das Bild ist ausgewählt. Nach der Verarbeitung wird es automatisch für die Website freigegeben.')
->send();
})
->helperText('Das Bild wird im Medienmanager angelegt und hier ausgewählt. Nur Bilder mit geklärten Rechten hochladen.'),
Placeholder::make('_media_status')
->label('Gewähltes Bild')
->visible(fn (Get $get): bool => WebsiteImage::normalize($get($key)) !== null)
->content(fn (Get $get): HtmlString => self::statusHtml($get($key))),
];
}
@@ -48,29 +88,49 @@ public static function fields(string $label = 'Bild', bool $live = false): array
public static function rules(): array
{
return [
'image' => ['nullable', 'string', 'max:255'],
'image' => ['nullable'],
'_upload' => ['nullable'],
];
}
/**
* Übernimmt einen neuen Upload als Bild und prüft, dass das Bild im öffentlichen Bereich liegt.
* Prüft das gewählte Bild. Ein früherer CMS-Pfad mit wirksamer Zuordnung wird zur Kennung des Mediums.
* Ein noch als Datei übergebener Upload (frühere Formulare) wird über den Medienmanager aufgenommen.
*
* @param array<string, mixed> $refs
* @return array<string, mixed>
*/
public static function clean(array $refs, WidgetErrors $errors, string $key = 'image', ?string $errorKey = null): array
{
$upload = PublicMedia::fromUploadState($refs['_upload'] ?? null);
$image = $upload ?? PublicMedia::fromUploadState($refs[$key] ?? null);
$images = app(WebsiteImage::class);
$upload = $refs['_upload'] ?? null;
$upload = is_array($upload) ? (array_values($upload)[0] ?? null) : $upload;
if ($image !== null && ! PublicMedia::isPublicPath($image)) {
$errors->add($errorKey ?? "refs.$key", 'Das Bild liegt nicht im öffentlichen Medienbereich.');
if ($upload instanceof TemporaryUploadedFile) {
$element = $images->accept($upload);
$refs[$key] = $element?->id ?? $refs[$key] ?? null;
}
$refs[$key] = $image;
$refs[$key] = $images->clean($refs[$key] ?? null, $errors, $errorKey ?? "refs.$key");
unset($refs['_upload']);
return $refs;
}
public static function statusHtml(mixed $value): HtmlString
{
$status = app(WebsiteImage::class)->status($value);
if ($status === null) {
return new HtmlString('');
}
$thumb = $status['thumb'] !== null ? '<img src="'.e($status['thumb']).'" alt="">' : '';
$link = $status['manageUrl'] !== null
? '<a href="'.e($status['manageUrl']).'" target="_blank" rel="noopener">Im Medienmanager öffnen</a>'
: '';
return new HtmlString('<div class="luf-media-status luf-media-status-'.e($status['state']).'">'.$thumb
.'<div><strong>'.e($status['title']).'</strong><p>'.e($status['note']).'</p>'.$link.'</div></div>');
}
}
@@ -98,10 +98,10 @@ public static function focusFields(int $defaultX = 50, int $defaultY = 50): arra
public static function altField(): TextInput
{
return TextInput::make('alt')
->label('Alternativtext des Bildes')
->label('Alternativtext (optional)')
->maxLength(300)
->live(onBlur: true)
->helperText('Beschreibt, was auf dem Bild zu sehen ist. Pflicht, sobald ein Bild gewählt ist.');
->helperText('Leer lassen, dann gilt der Alternativtext des Mediums aus dem Medienmanager. Nur ausfüllen, wenn das Bild hier etwas anderes aussagen soll.');
}
/**
@@ -127,10 +127,6 @@ public static function clean(array $data, WidgetErrors $errors, bool $hasImage):
$data[$key] = is_numeric($value) ? (int) round(max(0, min(100, (float) $value))) : null;
}
if ($hasImage && $data['alt'] === null) {
$errors->add('data.alt', 'Bitte einen Alternativtext für das Bild angeben.');
}
return $data;
}
+2 -65
View File
@@ -2,20 +2,14 @@
namespace App\Domain\Cms\Widgets\Support;
use Illuminate\Support\Facades\Storage;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Throwable;
/**
* Öffentlicher Medienbereich der Website ("cms/"). Nur Dateien aus diesem Bereich dürfen in Widgets
* verwendet werden. Geschützte Bibliotheksmedien (Inhaltsdateien, Vorschaubilder) sind hier nie wählbar.
* Frühere öffentliche CMS-Bilder („cms/“, Route media.public). Neue Bilder kommen aus dem Medienmanager (WebsiteImage);
* dieser Bereich bleibt nur für gespeicherte Revisionen mit früheren Pfaden, die (noch) keinem Medium zugeordnet sind.
*/
final class PublicMedia
{
public const PREFIX = 'cms/';
private const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'avif'];
public static function isPublicPath(mixed $path): bool
{
return is_string($path)
@@ -29,36 +23,6 @@ public static function url(string $path): string
return route('media.public', ['path' => $path]);
}
/**
* Bereits vorhandene Bilder im öffentlichen Bereich (veröffentlicht oder zur Veröffentlichung vorgemerkt).
*
* @return array<string, string>
*/
public static function imageOptions(): array
{
$options = [];
foreach (['media_public', 'cms_incoming'] as $disk) {
try {
$files = Storage::disk($disk)->allFiles(rtrim(self::PREFIX, '/'));
} catch (Throwable) {
$files = [];
}
foreach ($files as $file) {
$extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (self::isPublicPath($file) && in_array($extension, self::IMAGE_EXTENSIONS, true)) {
$options[$file] = substr($file, strlen(self::PREFIX));
}
}
}
ksort($options);
return $options;
}
/**
* Pfad aus dem Zustand eines Upload-Felds (Zeichenkette oder Liste).
*/
@@ -70,31 +34,4 @@ public static function fromUploadState(mixed $state): ?string
return is_string($state) && $state !== '' ? $state : null;
}
/**
* Bildadresse für Darstellung und Blockvorschau. In der Vorschau kann ein noch nicht gespeicherter Upload vorliegen.
*
* @param array<string, mixed> $refs
*/
public static function imageUrl(array $refs, string $key = 'image'): ?string
{
$upload = $refs['_upload'] ?? null;
$upload = is_array($upload) ? (array_values($upload)[0] ?? null) : $upload;
if ($upload instanceof TemporaryUploadedFile) {
try {
return $upload->temporaryUrl();
} catch (Throwable) {
return null;
}
}
if (self::isPublicPath($upload)) {
return self::url($upload);
}
$path = $refs[$key] ?? null;
return self::isPublicPath($path) ? self::url($path) : null;
}
}
@@ -0,0 +1,349 @@
<?php
namespace App\Domain\Cms\Widgets\Support;
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\EditorialContentKind;
use App\Domain\Cms\Catalog\PublicMaterialReader;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Media\ThumbnailRef;
use App\Domain\Media\WebsiteIntake;
use App\Domain\Media\WebsiteMedia;
use App\Domain\Media\WebsiteMediaAlias;
use App\Domain\Media\WebsitePresentation;
use App\Filament\Resources\ContentElements\ContentElementResource;
use App\Models\User;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Throwable;
/**
* Bilder in CMS-Widgets und Abschnittshintergründen aus dem zentralen Medienbestand
* (docs/architektur/medienzugriff-fuer-komponenten.md).
*
* Gespeichert wird im jeweiligen Bildschlüssel (refs.image, style.image, data.items[].image) die Kennung des
* Inhaltselements (int). Frühere Werte sind Pfade unter cms/ (string):
* - mit wirksamer Zuordnung (WebsiteMediaAlias) gelten sie als das zugeordnete Medium,
* - ohne Zuordnung gelten sie weiter als öffentliches CMS-Bild (PublicMedia), bis das Widget umgestellt ist.
*
* Öffentlich erscheint ein Medium nur über WebsiteMedia (Website-Freigabe, Route website.media). In der
* Redaktionsvorschau erscheint ein nicht freigegebenes Bild als Vorschaubild der Bibliothek (Route editorial.card)
* mit Hinweis. Eine CMS-Verwendung gibt nichts frei.
*
* Je Anfrage gebunden (scoped): Ergebnisse werden innerhalb einer Anfrage zwischengespeichert.
*/
class WebsiteImage
{
/** @var array<string, int|string|null> */
private array $resolved = [];
/** @var array<int, WebsitePresentation|false> */
private array $presentations = [];
public function __construct(private readonly WebsiteMedia $media) {}
/**
* Gespeicherter oder eingegebener Wert → Kennung (int), früherer Pfad (string) oder null.
*/
public static function normalize(mixed $value): int|string|null
{
if (is_array($value)) {
$value = array_values($value)[0] ?? null;
}
if (is_int($value) && $value > 0) {
return $value;
}
if (is_string($value) && preg_match('/^[1-9][0-9]*$/', $value) === 1) {
return (int) $value;
}
return PublicMedia::isPublicPath($value) ? $value : null;
}
/**
* Kennung des Mediums: gespeicherte Kennung oder wirksam zugeordneter früherer Pfad; sonst null.
*/
public function elementId(mixed $value): ?int
{
$value = self::normalize($value);
if (is_int($value)) {
return $value;
}
if ($value === null) {
return null;
}
if (! array_key_exists($value, $this->resolved)) {
$this->resolved[$value] = WebsiteMediaAlias::effectiveFor($value)?->content_element_id;
}
$id = $this->resolved[$value];
return is_int($id) ? $id : null;
}
public function presentation(mixed $value): ?WebsitePresentation
{
$id = $this->elementId($value);
if ($id === null) {
return null;
}
if (! array_key_exists($id, $this->presentations)) {
$this->presentations[$id] = $this->media->present($id) ?? false;
}
return $this->presentations[$id] ?: null;
}
/**
* Bildadresse für die Darstellung. Öffentlich nur freigegebene Medien (oder frühere CMS-Bilder ohne Zuordnung);
* in der Redaktionsvorschau zusätzlich das Vorschaubild eines nicht freigegebenen Mediums.
*/
public function url(mixed $value, bool $preview = false): ?string
{
$presentation = $this->presentation($value);
if ($presentation !== null) {
return $presentation->kind === 'bild' ? $presentation->url : null;
}
$id = $this->elementId($value);
if ($id !== null) {
if (! $preview) {
return null;
}
$element = ContentElement::query()->find($id);
return $element === null ? null : ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path);
}
$legacy = self::normalize($value);
return is_string($legacy) ? PublicMedia::url($legacy) : null;
}
/** Alternativtext: Angabe im Widget, sonst der Alternativtext des Mediums. */
public function alt(mixed $value, mixed $override = null): string
{
if (is_string($override) && trim($override) !== '') {
return trim($override);
}
return $this->presentation($value)?->alt ?? '';
}
/** Öffentliche Quellenzeile des Mediums (nur solange es freigegeben ist). */
public function credit(mixed $value): ?string
{
return $this->presentation($value)?->credit;
}
/**
* Hinweis für die Redaktionsvorschau, wenn das gewählte Bild öffentlich nicht erscheint; sonst null.
*/
public function previewNotice(mixed $value, string $label = 'Das gewählte Bild'): ?string
{
$status = $this->status($value);
if ($status === null || $status['public']) {
return null;
}
return $label.' „'.$status['title'].'“ erscheint öffentlich nicht: '.$status['note'];
}
/**
* Zustand für Editor und Vorschau.
*
* @return array{public: bool, state: string, title: string, note: string, thumb: ?string, manageUrl: ?string}|null
*/
public function status(mixed $value): ?array
{
$value = self::normalize($value);
if ($value === null) {
return null;
}
$id = $this->elementId($value);
if ($id === null) {
return [
'public' => true,
'state' => 'legacy',
'title' => basename((string) $value),
'note' => 'Früheres CMS-Bild, noch nicht in den Medienmanager übernommen.',
'thumb' => PublicMedia::url((string) $value),
'manageUrl' => null,
];
}
$element = ContentElement::query()->with('editorialContentKind')->find($id);
if ($element === null) {
return ['public' => false, 'state' => 'missing', 'title' => 'Medium '.$id, 'note' => 'Das Medium gibt es nicht mehr.', 'thumb' => null, 'manageUrl' => null];
}
$title = (string) ($element->display_title ?: $element->working_title);
$thumb = ThumbnailRef::url('editorial.card', 'element', $element->id, $element->thumbnail_path);
$manageUrl = ContentElementResource::getUrl('view', ['record' => $element]);
$public = $this->presentation($id) !== null;
$note = match (true) {
$public => 'Für die Website freigegeben.',
$element->archived_at !== null => 'Das Medium ist archiviert.',
filled($element->thumbnail_error) => 'Die Datei ließ sich nicht verarbeiten: '.Str::limit((string) $element->thumbnail_error, 120),
$element->thumbnail_path === null => 'Wird gerade verarbeitet. Danach wird es automatisch für die Website freigegeben.',
default => 'Nicht für die Website freigegeben. Die Freigabe steht im Medienmanager beim Medium unter „Beschreibung“ (Website-Freigabe).',
};
return [
'public' => $public,
'state' => $public ? 'released' : ($element->thumbnail_path === null && ! filled($element->thumbnail_error) ? 'pending' : 'unreleased'),
'title' => $title,
'note' => $note,
'thumb' => $thumb,
'manageUrl' => $manageUrl,
];
}
/**
* Prüft einen Wert beim Speichern. Ein früherer Pfad mit wirksamer Zuordnung wird zur Kennung des Mediums.
*/
public function clean(mixed $value, WidgetErrors $errors, string $errorKey): int|string|null
{
$raw = is_array($value) ? (array_values($value)[0] ?? null) : $value;
$value = self::normalize($raw);
if ($value === null) {
if ($raw !== null && $raw !== '') {
$errors->add($errorKey, 'Bitte ein Bild aus dem Medienmanager wählen.');
}
return null;
}
if (is_string($value)) {
return $this->elementId($value) ?? $value;
}
$element = ContentElement::query()->find($value);
if ($element === null || ! self::isSelectable($element)) {
$errors->add($errorKey, 'Dieses Medium ist kein Bild für die Website (nur Bilder aus dem Medienmanager, keine Traineranleitungen).');
return null;
}
return $element->id;
}
public static function isSelectable(ContentElement $element): bool
{
if ($element->output_class !== 'bild' || $element->archived_at !== null) {
return false;
}
$slug = $element->editorialContentKind?->slug
?? ($element->editorial_content_kind_id !== null ? EditorialContentKind::query()->whereKey($element->editorial_content_kind_id)->value('slug') : null);
return ! in_array($slug, PublicMaterialReader::CONFIDENTIAL_KINDS, true);
}
/**
* Auswahl für den Medienpicker: Bilder aus dem Medienmanager mit Vorschaubild, Titel und Freigabestatus (HTML).
*
* @return array<int, string>
*/
public function options(?string $search = null, int $limit = 60): array
{
$search = trim((string) $search);
$elements = ContentElement::query()
->with('editorialContentKind')
->where('output_class', 'bild')
->whereNull('archived_at')
->when($search !== '', function ($query) use ($search): void {
$like = '%'.mb_strtolower($search).'%';
$query->where(fn ($inner) => $inner
->whereRaw('LOWER(working_title) LIKE ?', [$like])
->orWhereRaw('LOWER(COALESCE(display_title, \'\')) LIKE ?', [$like]));
})
->orderByDesc('id')
->limit($limit)
->get();
$options = [];
foreach ($elements as $element) {
if (self::isSelectable($element)) {
$options[$element->id] = $this->optionHtml($element->id);
}
}
return $options;
}
/** HTML-Bezeichnung einer Option oder des gewählten Werts (auch für frühere Pfade). */
public function optionHtml(mixed $value): ?string
{
$status = $this->status($value);
if ($status === null) {
return null;
}
$badge = match ($status['state']) {
'released' => ['ok', 'Website: freigegeben'],
'pending' => ['wait', 'Wird verarbeitet'],
'legacy' => ['quiet', 'Früheres CMS-Bild'],
default => ['warn', 'Website: nicht freigegeben'],
};
$thumb = $status['thumb'] !== null
? '<img src="'.e($status['thumb']).'" alt="" loading="lazy">'
: '<span class="luf-media-option-empty" aria-hidden="true"></span>';
return '<span class="luf-media-option">'.$thumb
.'<span class="luf-media-option-text"><strong>'.e($status['title']).'</strong>'
.'<span class="luf-media-badge luf-media-badge-'.$badge[0].'">'.e($badge[1]).'</span></span></span>';
}
/**
* Neues Bild direkt aus dem CMS: Datei in den Eingang legen und über WebsiteIntake als Medium anlegen.
* Die Warteschlange leitet das Bild ab und gibt die Ableitung für die Website frei.
*/
public function accept(TemporaryUploadedFile $file, ?string $alt = null): ?ContentElement
{
$base = Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)) ?: 'bild';
$name = $base.'-'.Str::lower(Str::random(6)).'.'.($file->guessExtension() ?: 'jpg');
try {
$path = $file->storeAs('cms', $name, 'cms_incoming');
} catch (Throwable $exception) {
report($exception);
return null;
}
if (! is_string($path) || $path === '') {
return null;
}
$actor = auth('staff')->user();
return app(WebsiteIntake::class)->acceptImage(
$path,
Str::title(str_replace(['-', '_'], ' ', $base)),
null,
filled($alt) ? trim((string) $alt) : null,
$actor instanceof User ? $actor : null,
);
}
}
+12 -4
View File
@@ -6,6 +6,7 @@
use App\Domain\Cms\Widgets\Support\ImageRefFields;
use App\Domain\Cms\Widgets\Support\PublicMedia;
use App\Domain\Cms\Widgets\Support\SafeUrl;
use App\Domain\Cms\Widgets\Support\WebsiteImage;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\Repeater;
@@ -84,14 +85,14 @@ public function dataRules(): array
'items.*.title' => ['required', 'string', 'max:120'],
'items.*.text' => ['nullable', 'string', 'max:500'],
'items.*.url' => ['nullable', 'string', 'max:500'],
'items.*.image' => ['nullable', 'string', 'max:255'],
'items.*.image' => ['nullable'],
'items.*._upload' => ['nullable'],
];
}
public function dataFields(): array
{
[$image, $upload] = ImageRefFields::fields('Bild (optional)');
[$image, $upload, $status] = ImageRefFields::fields('Bild (optional)');
return [
Repeater::make('items')
@@ -106,6 +107,7 @@ public function dataFields(): array
->helperText('Seitenpfad wie /praevention oder eine http(s)-Adresse. Leer lassen für eine Karte ohne Link.'),
$image,
$upload,
$status,
])
->minItems(1)
->maxItems(12)
@@ -139,7 +141,9 @@ public function clean(array $data, array $refs, WidgetErrors $errors): array
public function resolve(array $widget, RenderContext $context): array
{
$images = app(WebsiteImage::class);
$items = [];
$notices = [];
foreach ($widget['data']['items'] ?? [] as $item) {
if (! is_array($item) || ! filled($item['title'] ?? null)) {
@@ -150,11 +154,15 @@ public function resolve(array $widget, RenderContext $context): array
'title' => $item['title'],
'text' => $item['text'] ?? null,
'url' => SafeUrl::isSafe($item['url'] ?? null) ? $item['url'] : null,
'imageUrl' => PublicMedia::imageUrl($item),
'imageUrl' => $images->url($item['image'] ?? null, $context->preview),
];
if ($context->preview && ($notice = $images->previewNotice($item['image'] ?? null, 'Das Bild der Karte „'.$item['title'].'“')) !== null) {
$notices[] = $notice;
}
}
return ['items' => $items];
return ['items' => $items, 'imageNotice' => $notices === [] ? null : implode(' ', $notices)];
}
public function mediaPaths(array $widget): array
+7 -1
View File
@@ -6,6 +6,7 @@
use App\Domain\Cms\Widgets\Support\ImageRefFields;
use App\Domain\Cms\Widgets\Support\PremiumFields;
use App\Domain\Cms\Widgets\Support\PublicMedia;
use App\Domain\Cms\Widgets\Support\WebsiteImage;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\Textarea;
@@ -202,8 +203,13 @@ public function resolve(array $widget, RenderContext $context): array
{
$actions = PremiumFields::actions($widget['data']);
$images = app(WebsiteImage::class);
$image = $widget['refs']['image'] ?? null;
return [
'imageUrl' => PublicMedia::imageUrl($widget['refs']),
'imageUrl' => $images->url($image, $context->preview),
'imageAlt' => $images->alt($image, $widget['data']['alt'] ?? null),
'imageNotice' => $context->preview ? $images->previewNotice($image) : null,
'actions' => $actions,
'action' => $actions[0] ?? null,
'focus' => PremiumFields::focus($widget['data'], 68, 50),
@@ -7,6 +7,7 @@
use App\Domain\Cms\Widgets\Support\PremiumFields;
use App\Domain\Cms\Widgets\Support\PublicMedia;
use App\Domain\Cms\Widgets\Support\RichText;
use App\Domain\Cms\Widgets\Support\WebsiteImage;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\RichEditor;
@@ -229,8 +230,13 @@ public function resolve(array $widget, RenderContext $context): array
{
$surface = $widget['settings']['surface'] ?? 'cream';
$images = app(WebsiteImage::class);
$image = $widget['refs']['image'] ?? null;
return [
'imageUrl' => PublicMedia::imageUrl($widget['refs']),
'imageUrl' => $images->url($image, $context->preview),
'imageAlt' => $images->alt($image, $widget['data']['alt'] ?? null),
'imageNotice' => $context->preview ? $images->previewNotice($image) : null,
'body' => RichText::sanitize(is_string($widget['data']['body'] ?? null) ? $widget['data']['body'] : ''),
'actions' => PremiumFields::actions($widget['data']),
'focus' => PremiumFields::focus($widget['data'], 64, 43),
@@ -7,6 +7,7 @@
use App\Domain\Cms\Widgets\Support\ImageRefFields;
use App\Domain\Cms\Widgets\Support\PremiumFields;
use App\Domain\Cms\Widgets\Support\PublicMedia;
use App\Domain\Cms\Widgets\Support\WebsiteImage;
use App\Domain\Cms\Widgets\WidgetErrors;
use App\Domain\Cms\Widgets\WidgetType;
use Filament\Forms\Components\Select;
@@ -213,10 +214,6 @@ public function clean(array $data, array $refs, WidgetErrors $errors): array
$data[$field] = is_numeric($value) ? (int) round(max(0, min(100, (float) $value))) : null;
}
if ($refs['image'] !== null && $data['alt'] === null) {
$errors->add('data.alt', 'Bitte einen Alternativtext für das Bild angeben.');
}
return [$data, $refs];
}
@@ -231,8 +228,9 @@ public function resolve(array $widget, RenderContext $context): array
return [
'subject' => $subject,
'cardStyle' => $subject?->style ?? $this->cardStyle(),
'imageUrl' => PublicMedia::imageUrl($widget['refs']),
'alt' => is_string($data['alt'] ?? null) ? $data['alt'] : '',
'imageUrl' => app(WebsiteImage::class)->url($widget['refs']['image'] ?? null, $context->preview),
'alt' => app(WebsiteImage::class)->alt($widget['refs']['image'] ?? null, $data['alt'] ?? null),
'imageNotice' => $context->preview ? app(WebsiteImage::class)->previewNotice($widget['refs']['image'] ?? null, 'Das Kartenbild') : null,
'focus' => PremiumFields::focus($data, 66, 45),
'format' => $option('format', 'landscape'),
'fit' => $option('fit', 'cover'),
+59
View File
@@ -0,0 +1,59 @@
<?php
namespace App\Domain\Media;
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\IdentityChange;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Früherer CMS-Bildpfad (cms/…), der in den Medienmanager übernommen wurde.
*
* Wirksam ist die Zuordnung erst, wenn das Medium mindestens einmal für die Website freigegeben war. Bis dahin
* (Ableitung läuft noch oder ist fehlgeschlagen) bleibt der frühere Pfad gültig, damit keine Seite ihr Bild verliert.
* Danach entscheidet allein die Website-Freigabe des Mediums, auch über die frühere Adresse /medien/cms/….
*/
class WebsiteMediaAlias extends Model
{
protected $fillable = ['legacy_path', 'content_element_id', 'sha256'];
public function element(): BelongsTo
{
return $this->belongsTo(ContentElement::class, 'content_element_id');
}
/**
* Wirksame Zuordnung für einen früheren Pfad, sonst null. Zwischengespeichert wird im Aufrufer (WebsiteImage, je Anfrage).
*/
public static function effectiveFor(mixed $path): ?self
{
if (! is_string($path) || $path === '') {
return null;
}
$alias = self::query()->with('element')->where('legacy_path', $path)->first();
return $alias instanceof self && $alias->everReleased() ? $alias : null;
}
public function everReleased(): bool
{
$element = $this->element;
if ($element === null) {
return false;
}
if ($element->website_released_at !== null) {
return true;
}
return IdentityChange::query()
->where('subject_type', $element->getMorphClass())
->where('subject_id', $element->id)
->where('field', 'website_released_at')
->whereNotNull('after')
->exists();
}
}
@@ -13,6 +13,7 @@
use App\Domain\Catalog\IdentityProfile;
use App\Domain\Catalog\PillarService;
use App\Domain\Cms\Catalog\PublicMaterialReader;
use App\Domain\Cms\WebsiteImageUsage;
use App\Domain\Cms\Widgets\RenderContext;
use App\Domain\Media\ThumbnailRef;
use App\Domain\Media\WebsiteMedia;
@@ -513,6 +514,19 @@ public function withdrawWebsite(): void
$this->fillEditorial();
}
/**
* Website-Seiten, die dieses Medium als Bild verwenden (CMS-Widgets und Abschnittshintergründe).
*
* @return list<array{path: string, published: bool, draft: bool}>
*/
public function websitePages(): array
{
/** @var ContentElement $element */
$element = $this->getRecord();
return app(WebsiteImageUsage::class)->pages($element);
}
public function websiteIsPublic(): bool
{
/** @var ContentElement $element */
+5 -22
View File
@@ -5,10 +5,9 @@
use App\Domain\Cms\Sections\PageSections;
use App\Domain\Cms\Sections\SectionLayouts;
use App\Domain\Cms\Sections\SectionStyle;
use App\Domain\Cms\Widgets\Support\PublicMedia;
use App\Domain\Cms\Widgets\Support\ImageRefFields;
use App\Domain\Cms\Widgets\WidgetRegistry;
use Filament\Actions\Action;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
@@ -20,7 +19,6 @@
use Filament\Schemas\Components\Utilities\Set;
use Illuminate\Support\HtmlString;
use Illuminate\Support\Str;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
/**
* Seiteneditor für Abschnitte und Slots.
@@ -166,25 +164,10 @@ private static function styleFields(): array
->options(SectionStyle::DIVIDERS)
->default('none')
->selectablePlaceholder(false),
Select::make('image')
->label('Hintergrundbild: vorhandenes Bild')
->options(fn (): array => PublicMedia::imageOptions())
->searchable()
->placeholder('Bitte wählen')
->helperText('Nur Bilder aus dem öffentlichen Website-Bereich. Geschützte Filmbilder sind hier nicht wählbar.')
->visible(fn (Get $get): bool => $get('background') === 'image')
->columnSpan(['default' => 1, 'md' => 2]),
FileUpload::make('_upload')
->label('Hintergrundbild: neu hochladen')
->disk('cms_incoming')
->directory('cms')
->image()
->maxSize(8192)
->acceptedFileTypes(['image/jpeg', 'image/png', 'image/webp'])
->getUploadedFileNameForStorageUsing(fn (TemporaryUploadedFile $file): string => Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)).'-'.Str::lower(Str::random(6)).'.'.$file->guessExtension())
->helperText('Ersetzt die Auswahl links. Nur Bilder mit geklärter Veröffentlichungsfreigabe hochladen.')
->visible(fn (Get $get): bool => $get('background') === 'image')
->columnSpan(['default' => 1, 'md' => 2]),
...array_map(
fn ($field) => $field->visible(fn (Get $get): bool => $get('background') === 'image')->columnSpan(['default' => 1, 'md' => 2]),
ImageRefFields::fields('Hintergrundbild'),
),
Select::make('focus')
->label('Bildausschnitt (Fokuspunkt)')
->options(SectionStyle::FOCUS)
@@ -2,15 +2,21 @@
namespace App\Http\Controllers;
use App\Domain\Media\WebsiteMedia;
use App\Domain\Media\WebsiteMediaAlias;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;
class PublicMediaController extends Controller
{
public function show(string $path): StreamedResponse
public function show(string $path, WebsiteMedia $media): StreamedResponse
{
abort_if(str_contains($path, '..') || ! str_starts_with($path, 'cms/'), 404);
// Ein in den Medienmanager übernommenes Bild folgt dessen Website-Freigabe, auch unter der früheren Adresse.
$alias = WebsiteMediaAlias::effectiveFor($path);
abort_if($alias !== null && $media->present($alias->content_element_id) === null, 404);
foreach (['media_public', 'cms_incoming'] as $disk) {
if (Storage::disk($disk)->exists($path)) {
return Storage::disk($disk)->response($path);
+83
View File
@@ -0,0 +1,83 @@
<?php
namespace App\Jobs;
use App\Domain\Media\WebsiteIntake;
use App\Domain\Media\WebsiteMediaAlias;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Throwable;
/**
* Übernimmt die bisherigen CMS-Bilder (media_public, cms/…) in den Medienmanager.
*
* - Bytegleiche Dateien werden ein Medium (SHA-256); jeder frühere Pfad erhält eine Zuordnung (WebsiteMediaAlias).
* - Neue Medien entstehen über WebsiteIntake: Die Warteschlange leitet das Bild ab und gibt genau diese Ableitung
* für die Website frei. Erst danach wird die Zuordnung wirksam; bis dahin bleibt der frühere Pfad gültig.
* - Wiederholbar: Bereits zugeordnete Pfade werden übersprungen. Es wird nichts gelöscht; die Dateien unter cms/
* bleiben liegen (frühere Revisionen, Rückweg).
*/
class ImportCmsImages implements ShouldQueue
{
use Queueable;
private const EXTENSIONS = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
public function handle(WebsiteIntake $intake): void
{
$public = Storage::disk('media_public');
try {
$files = $public->allFiles('cms');
} catch (Throwable) {
return;
}
sort($files);
foreach ($files as $path) {
if (! $this->isImage($path) || WebsiteMediaAlias::query()->where('legacy_path', $path)->exists()) {
continue;
}
$bytes = $public->get($path);
if (! is_string($bytes) || $bytes === '') {
continue;
}
$hash = hash('sha256', $bytes);
$twin = WebsiteMediaAlias::query()->where('sha256', $hash)->first();
if ($twin instanceof WebsiteMediaAlias) {
WebsiteMediaAlias::query()->create(['legacy_path' => $path, 'content_element_id' => $twin->content_element_id, 'sha256' => $hash]);
continue;
}
Storage::disk('cms_incoming')->put($path, $bytes);
$element = $intake->acceptImage($path, self::titleFor($path));
WebsiteMediaAlias::query()->create(['legacy_path' => $path, 'content_element_id' => $element->id, 'sha256' => $hash]);
}
}
/** „cms/platzhalter-karte-1-liyjqa.jpg“ → „Platzhalter Karte 1“ (ohne die angehängte Zufallskennung). */
public static function titleFor(string $path): string
{
$name = pathinfo($path, PATHINFO_FILENAME);
$name = preg_replace('/-[a-z0-9]{6}$/', '', $name) ?? $name;
$title = trim(str_replace(['-', '_'], ' ', $name));
return $title === '' ? 'Website-Bild' : Str::title($title);
}
private function isImage(string $path): bool
{
return str_starts_with($path, 'cms/')
&& ! str_contains($path, '..')
&& preg_match('#^cms/[A-Za-z0-9._\-/]+$#', $path) === 1
&& in_array(strtolower(pathinfo($path, PATHINFO_EXTENSION)), self::EXTENSIONS, true);
}
}
+2
View File
@@ -7,6 +7,7 @@
use App\Domain\Cms\NavigationItemPolicy;
use App\Domain\Cms\Page;
use App\Domain\Cms\PagePolicy;
use App\Domain\Cms\Widgets\Support\WebsiteImage;
use App\Domain\Cms\Widgets\WidgetRegistry;
use App\Domain\Media\FfmpegFilmTranscoder;
use App\Domain\Media\FilmTranscoder;
@@ -26,6 +27,7 @@ public function register(): void
$this->app->bind(FilmTranscoder::class, FfmpegFilmTranscoder::class);
// Je Anfrage einmal den Index der öffentlich genannten Medien bilden, nicht je Karte.
$this->app->scoped(PublicMaterialReader::class);
$this->app->scoped(WebsiteImage::class);
$this->app->singleton(WidgetRegistry::class, fn ($app): WidgetRegistry => new WidgetRegistry(
array_map(fn (string $class) => $app->make($class), config('cms.widgets', [])),
));
@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Zuordnung früherer CMS-Bildpfade (cms/…) zu Medien im Medienmanager. Additiv: Gespeicherte Revisionen und
* die Dateien unter cms/ bleiben unverändert; die Zuordnung wird beim Darstellen gelesen.
*/
return new class extends Migration
{
public function up(): void
{
Schema::create('website_media_aliases', function (Blueprint $table) {
$table->id();
$table->string('legacy_path')->unique();
$table->foreignId('content_element_id')->constrained()->restrictOnDelete();
$table->string('sha256', 64)->index();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('website_media_aliases');
}
};
@@ -0,0 +1,27 @@
<?php
use App\Jobs\ImportCmsImages;
use Illuminate\Database\Migrations\Migration;
/**
* Übernimmt die bisherigen CMS-Bilder (media_public, cms/…) in den Medienmanager. Die Migration läuft im
* App-Container, der keine Medien schreibt; sie stößt deshalb nur den Job der Hintergrundverarbeitung an.
* Der Job ist wiederholbar und löscht nichts.
*/
return new class extends Migration
{
public function up(): void
{
// In Tests liegen echte Medien nicht vor; die Übernahme prüfen eigene Tests mit Testplatten.
if (app()->runningUnitTests()) {
return;
}
ImportCmsImages::dispatch();
}
public function down(): void
{
// Nichts zurückzunehmen: Die übernommenen Medien und Zuordnungen bleiben; die Tabelle entfernt die vorige Migration.
}
};
@@ -60,6 +60,7 @@ ## Übersicht der Architekturentscheidungen
| ADR-37 | n8n-Anbindung | Option / nicht beschlossen | n8n allenfalls für externe Kanäle, ohne direkten Datenbankzugang |
| ADR-38 | Layoutvertrag der Widgets | Umgesetzt auf Test (18.11.2026); UX-Abnahme offen | Zulässige Rasterbreiten, Höhen und Verhalten bei wenig Platz je Widget-Art in der bestehenden Registry; Darstellung nach realer Containerbreite |
| ADR-39 | Premium-Karten mit Fachbezug | Umgesetzt auf Test (18.11.2026); gestalterische Freigabe v1.7 offen | Eine Karte je Platz im Abschnittsraster; Inhalte und Linkziel aus Thema, Medium oder Programm/Modul; keine Preise, keine Freigabe geschützter Medien |
| ADR-40 | Zentrale Medienverwaltung im CMS | Umgesetzt auf Test (19.11.2026); Abnahme offen | CMS-Bilder sind Medien des Medienmanagers (Kennung statt Pfad), öffentlich nur mit Website-Freigabe; frühere CMS-Bilder übernommen |
---
@@ -516,3 +517,12 @@ ## ADR-39 – Premium-Karten mit Fachbezug
**Offene Entscheidungen.** (1) Freigabe von Vorschaubildern für die Website und öffentliche Filmvorschauen (minimaler Erweiterungsbedarf in `cms-widget-registry.md` §13). (2) Ob bei Traineranleitungen schon der Titel auf der Programmseite öffentlich sein soll (Programmseite, nicht Karte).
**Folgen und offene Prüfung.** Keine Migration; bestehende Seiten und Widgets unverändert (gemessen). Mit ADR-29 ersetzen öffentliche Profile die Übergangsregeln in `PublicCatalogReader` und `PublicMaterialReader`; die gespeicherten Karten ändern sich dadurch nicht. Offen: gestalterische Freigabe v1.7, freigegebene Motive statt Platzhaltern, eine kaufbare Angebotskarte (eigenes Fachobjekt „Angebot“ mit Umfang, Zweck und Lizenzbedingungen, nicht Teil dieser Karten).
**Quelle.** Brand-UI-Kit v1.7 (`docs/Brand-UI-Kit/13_premium_karten_v1.7_entwurf`, README, `docs/design-config.json`); `docs/architektur/cms-widget-registry.md` §§4, 6, 11, 13; ADR-29, ADR-30, ADR-38.
## ADR-40 – Zentrale Medienverwaltung im CMS
**Status am 19.11.2026:** Umgesetzt auf `develop`/Testinstanz (Branch `feature/cms-medienverwaltung`); Abnahme durch den Betreiber offen. Baut auf der Website-Freigabe des Medienmanagers auf (`medienzugriff-fuer-komponenten.md`).
**Kontext.** Das CMS hatte eine eigene Bildablage (`cms/`, `PublishPublicMedia`). Redakteure sollen Bilder im Medienmanager, im Modul-/Programmeditor und in CMS-Widgets aus demselben Bestand verwenden; öffentlich darf nur erscheinen, was für die Website freigegeben ist.
**Entscheidung.** Alle Bildstellen (Einstieg, Bild und Text, redaktionelle Karten, Premium-Karten, Abschnittshintergrund) speichern die Kennung des Inhaltselements im bisherigen Bildschlüssel `image` und lesen über `WebsiteMedia`. Uploads im Widget-Dialog laufen über `WebsiteIntake`. Frühere CMS-Bilder werden per Warteschlangen-Job übernommen (dedupliziert, nichts gelöscht) und über `website_media_aliases` zugeordnet; die Zuordnung wird erst nach der ersten Website-Freigabe wirksam. Ein nicht freigegebenes Bild entfällt öffentlich, das Widget bleibt.
**Alternativen.** Schlüssel `refs.element` wie im Dokument (verworfen: kollidiert mit dem Fachobjekt der Medienkarte); Revisionen per Migration umschreiben (verworfen: Revisionen bleiben unverändert, Rollback); ganzes Widget bei fehlender Freigabe ausblenden (verworfen bis zur Entscheidung: entfernt Überschriften und H1).
**Folgen und offene Prüfung.** Rollback zeigt nach der Umstellung gespeicherte Bilder nicht (Registry §9). Website-Bilder werden bis 2400 px abgeleitet. Offen: Entscheidung „Bild entfällt“ vs. „Widget entfällt“; übernommene Medien tragen Dateinamen als Titel und keine Quellenzeile; ein unter `cms/` liegendes Originalmotiv (`lara-felix-park-original`) wurde mit übernommen und ist damit ein freigegebenes Medium – prüfen und gegebenenfalls zurücknehmen.
**Quelle.** `docs/architektur/medienzugriff-fuer-komponenten.md`; `cms-widget-registry.md` §§7, 9; ADR-30, ADR-38, ADR-39.
+11 -3
View File
@@ -140,9 +140,12 @@ ## 6. Öffentliche Freigabe von Programmen und Modulen (Übergangsregel)
## 7. Medien
- Wählbar sind nur Bilder im öffentlichen Website-Bereich `cms/` (`media_public` bzw. noch nicht übertragene Uploads in `cms_incoming`). Bibliotheksmedien und Filmstandbilder erscheinen nicht, auch nicht als Abschnittshintergrund.
- Neue Uploads (Widgets und Abschnittshintergründe) landen im Webprozess in `cms_incoming` (privater Speicher); `PublishPublicMedia` überträgt sie in der Hintergrundverarbeitung nach `media_public`. Der Web-Prozess schreibt nicht in den Medienbestand.
- Widget-Bilder sind an einen Alternativtext gebunden (Ausnahme: Kartenbilder gelten als dekorativ, `alt=""`). Abschnittshintergründe sind dekorativ (`alt=""`); tragende Aussagen stehen als HTML-Text in den Widgets.
Alle Bilder kommen aus dem zentralen Medienmanager (`docs/architektur/medienzugriff-fuer-komponenten.md`, Abschnitt
„Umsetzung im CMS“). Gespeichert wird die Kennung des Mediums in `refs.image`, `data.items[].image` bzw.
`style.image`; öffentlich erscheint ein Bild nur mit Website-Freigabe (`WebsiteMedia`, Route `website.media`).
Gemeinsame Felder: `ImageRefFields` (Auswahl mit Vorschaubild und Status, Upload über `WebsiteIntake`, Anzeige des
gewählten Mediums). Frühere Pfade unter `cms/` gelten über `WebsiteMediaAlias` als das übernommene Medium, ohne
Zuordnung weiter als öffentliches CMS-Bild. Bibliotheksmedien ohne Website-Freigabe erscheinen öffentlich nie.
## 8. Editor und Vorschau
@@ -164,6 +167,11 @@ ## 8. Editor und Vorschau
## 9. Rollback und Datenformat (wichtig vor dem Merge nach `main`)
**Medien aus dem Medienmanager (ADR-40).** Revisionen, die nach der Umstellung gespeichert werden, enthalten im
Bildschlüssel eine Kennung (Zahl) statt eines Pfads. Ein Code-Rollback auf eine Fassung davor zeigt diese Bilder nicht
(die ältere Fassung kennt nur `cms/`-Pfade); Texte und Gestaltung bleiben. Die Dateien unter `cms/` und frühere
Revisionen bleiben unverändert, die Zuordnungstabelle `website_media_aliases` ist additiv.
**Speicherung.** Jede neue Revision schreibt zwei Spalten:
| Spalte | Inhalt | Wer liest sie |
@@ -88,3 +88,44 @@ ## Was eine Komponente einhält
5. Der Web-Prozess schreibt nicht nach `originals/` und nicht nach `derived/` oder `public/`.
Eine Karte oder eine Komponente begründet keine Berechtigung.
## Umsetzung im CMS (19.11.2026, ADR-40)
Alle Bildstellen des CMS lesen den zentralen Medienbestand: Einstieg (Hero), Bild und Text, redaktionelle Karten,
Premium-Karten (Kartenbild) und Abschnittshintergrund. Das CMS hat keine eigene Medienverwaltung mehr.
- **Gespeichert** wird die Kennung des Inhaltselements im jeweiligen Bildschlüssel: `refs.image` (Einstieg, Bild und
Text, Premium-Karten), `data.items[].image` (redaktionelle Karten), `style.image` (Abschnittshintergrund).
**Abweichung von `refs.element`:** Die Medienkarte verwendet `refs.element` bereits für ihr Fachobjekt; ein
gemeinsamer Bildschlüssel `image` hält alle Widgets gleich und ändert die gespeicherte Struktur nicht.
- **Lesen:** `App\Domain\Cms\Widgets\Support\WebsiteImage` ruft `WebsiteMedia::present` auf. Öffentlich erscheint
ein Bild nur über `website.media`. In der Redaktionsvorschau erscheint ein nicht freigegebenes Bild als
Vorschaubild über `editorial.card` mit Hinweis; öffentlich nie.
- **Nicht freigegeben:** Es entfällt nur das Bild; das Widget erscheint mit seiner Darstellung ohne Bild (Überschrift,
Text, Schaltflächen bleiben). Das ist eine bewusste Auslegung von „gibt das Widget nichts aus“, damit eine
zurückgenommene Freigabe keine Überschrift (auch keine H1) von einer Seite entfernt. Entscheidung offen für Lars.
- **Neu hochladen im Widget-Dialog:** Die Datei geht über `WebsiteIntake::acceptImage` sofort in den Medienmanager
und wird ausgewählt. Titel aus dem Dateinamen, ohne Quellenzeile; beides ist im Medienmanager änderbar. Die
Warteschlange leitet ab und gibt frei (wie dokumentiert).
- **Auswahl:** alle Bilder (`output_class = bild`, nicht archiviert, keine Traineranleitung) mit Vorschaubild, Titel
und Website-Status; das gewählte Medium mit Status und Verweis auf den Medienmanager. Die Bildauswahl des
Modul-/Programmeditors ist an dessen Livewire-Seite gebunden und lässt sich nicht als Formularfeld einhängen; das
Bedienmuster (Suche, Vorschaubild, Auswahl) ist übernommen.
- **Alternativtext:** aus dem Medium (`website_alt`, sonst Titel). Das Feld im Widget ist eine optionale Abweichung.
- **Website-Ableitung:** Bilder werden bis 2400 px breit abgeleitet (vorher 640 px), nie vergrößert.
- **Medienmanager:** Die Medienansicht nennt die Website-Seiten, auf denen ein Bild verwendet wird
(`WebsiteImageUsage`), damit vor dem Zurücknehmen sichtbar ist, welche Seiten das Bild verlieren.
### Übernahme der früheren CMS-Bilder
- Der Job `ImportCmsImages` (angestoßen von einer Migration, ausgeführt von der Warteschlange) nimmt jede Bilddatei
unter `media_public/cms/` über `WebsiteIntake` auf. Bytegleiche Dateien werden ein Medium (SHA-256). Der Titel
kommt aus dem Dateinamen ohne Zufallskennung. Nichts wird gelöscht; der Job ist wiederholbar.
- `website_media_aliases` ordnet jeden früheren Pfad seinem Medium zu. **Wirksam** wird die Zuordnung erst, wenn das
Medium einmal für die Website freigegeben war; bis dahin (oder wenn die Ableitung scheitert) gilt der frühere Pfad
weiter, damit keine Seite ihr Bild verliert.
- Danach entscheidet die Website-Freigabe des Mediums allein, auch über die frühere Adresse `/medien/cms/…`
(404, wenn zurückgenommen).
- Gespeicherte Revisionen bleiben unverändert; frühere Pfade werden beim Darstellen zugeordnet und beim nächsten
Speichern durch die Kennung ersetzt. Frühere Pfade ohne Zuordnung bleiben über `PublicMedia` gültig.
- Eine Slideshow gibt es im CMS nicht; `WebsiteMedia::presentMany` ist für sie vorbereitet und noch unbenutzt.
@@ -54,6 +54,23 @@
.luf-sections .fi-fo-repeater-item-header .fi-icon-btn,
.luf-sections .fi-fo-builder-item-header .fi-icon-btn { min-width: 2.25rem; min-height: 2.25rem; opacity: 1; }
.luf-sections .fi-fo-builder-item-header { flex-wrap: wrap; }
/* Medienpicker (Bilder aus dem Medienmanager): Vorschaubild, Titel und Website-Status in der Auswahl. */
.luf-media-option { display: flex; align-items: center; gap: .75rem; min-width: 0; }
.luf-media-option img, .luf-media-option-empty { flex: none; width: 4.5rem; height: 2.75rem; object-fit: cover; border-radius: .375rem; background: #eef1ee; }
.luf-media-option-text { display: flex; flex-direction: column; gap: .15rem; min-width: 0; }
.luf-media-option-text strong { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.luf-media-badge { align-self: flex-start; padding: 0 .45rem; border-radius: 999px; font-size: .72rem; line-height: 1.35rem; }
.luf-media-badge-ok { background: #e3f0d8; color: #2d5c07; }
.luf-media-badge-warn { background: #fff1c7; color: #6b4b00; }
.luf-media-badge-wait { background: #e5eef8; color: #18456f; }
.luf-media-badge-quiet { background: #eceff1; color: #3e4c5c; }
.luf-media-status { display: flex; gap: 1rem; align-items: flex-start; padding: .75rem; border: 1px solid #d5ddd6; border-radius: .5rem; }
.luf-media-status img { width: 10rem; height: auto; border-radius: .375rem; }
.luf-media-status strong { display: block; }
.luf-media-status p { margin: .25rem 0 .4rem; font-size: .875rem; }
.luf-media-status a { font-size: .875rem; text-decoration: underline; }
.luf-media-status-unreleased, .luf-media-status-missing { border-color: #e7c35a; background: #fffaeb; }
.luf-media-status-pending { border-color: #9cbbe0; background: #f3f8fd; }
</style>
<script>
// Vorschau-Iframes an ihren Inhalt anpassen (nach Bildern und Schriften erneut), Höhe begrenzen.
@@ -81,6 +81,20 @@
</p>
<p class="luf-editor-lead">{{ $this->websiteFeedback !== '' ? $this->websiteFeedback : ($this->websiteIsPublic() ? 'Für die Website freigegeben. Öffentliche Seiten lesen nur diese Ableitung.' : 'Noch nicht für die Website freigegeben. Der interne Vermerk bleibt intern.') }}</p>
@endif
@php($webPages = $this->websitePages())
<p class="luf-editor-lead">
@if ($webPages === [])
Auf keiner Website-Seite als Bild verwendet.
@else
Als Bild auf der Website verwendet:
@foreach ($webPages as $usage)
{{ $usage['path'] }} ({{ $usage['published'] ? 'veröffentlicht' : '' }}{{ $usage['published'] && $usage['draft'] ? ', ' : '' }}{{ $usage['draft'] ? 'Entwurf' : '' }}){{ $loop->last ? '' : ',' }}
@endforeach
@if ($this->websiteIsPublic())
– Zurücknehmen entfernt das Bild dort von der öffentlichen Seite.
@endif
@endif
</p>
@php($history = $this->editorialHistory())
@if ($history !== [])
<details>
+1
View File
@@ -35,3 +35,4 @@
@endforeach
</ul>
@endif
@include('widgets.partials.image-notice')
+2 -1
View File
@@ -14,7 +14,7 @@
<div class="lf-hero lf-hero--{{ $layout }} lf-hero--height-{{ $heightClass }} lf-hero--accent-{{ $accent }}"
style="--lf-hero-focus-x: {{ $focus['x'] }}%; --lf-hero-focus-y: {{ $focus['y'] }}%">
@if ($layout === 'photo-split' && $imageUrl)
<img class="lf-hero__photo" src="{{ $imageUrl }}" alt="{{ $data['alt'] ?? '' }}" {!! $loading !!} decoding="async">
<img class="lf-hero__photo" src="{{ $imageUrl }}" alt="{{ $imageAlt ?? '' }}" {!! $loading !!} decoding="async">
@endif
<div class="lf-hero__inner">
<div class="lf-hero__copy">
@@ -43,3 +43,4 @@
<span class="lf-hero__bottom" aria-hidden="true"></span>
</div>
</div>
@include('widgets.partials.image-notice')
+2 -1
View File
@@ -40,8 +40,9 @@
</div>
@if ($imageUrl)
<div class="lf-bt__media">
<img class="lf-bt__image" src="{{ $imageUrl }}" alt="{{ $data['alt'] ?? '' }}" @if (! empty($first)) loading="eager" fetchpriority="high" @else loading="lazy" @endif decoding="async">
<img class="lf-bt__image" src="{{ $imageUrl }}" alt="{{ $imageAlt ?? '' }}" @if (! empty($first)) loading="eager" fetchpriority="high" @else loading="lazy" @endif decoding="async">
</div>
@endif
</div>
</div>
@include('widgets.partials.image-notice')
@@ -0,0 +1,4 @@
{{-- Nur Redaktionsvorschau: Das gewählte Bild erscheint öffentlich nicht (fehlende Website-Freigabe, Verarbeitung). --}}
@if (! empty($imageNotice) && $context->preview)
<p class="preview-note">{{ $imageNotice }}</p>
@endif
@@ -104,4 +104,5 @@
@endif
</div>
</article>
@include('widgets.partials.image-notice')
@endif
+5 -4
View File
@@ -2,6 +2,7 @@
namespace Tests\Feature;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\PillarService;
use App\Domain\Cms\NavigationItem;
use App\Domain\Cms\Page;
@@ -269,15 +270,15 @@ public function test_unsafe_link_is_reported_at_the_section_and_nothing_is_saved
public function test_errors_found_only_by_the_registry_are_announced_with_the_section(): void
{
Storage::fake('media_public');
Storage::fake('cms_incoming');
Storage::disk('media_public')->put('cms/bild.jpg', 'bild');
// Bewusst geändert: Der Alternativtext ist keine Pflicht mehr (er gehört zum Medium). Fehler, den nur die Registry
// findet: ein Medium, das kein Website-Bild ist.
$film = app(ContentService::class)->createElement('film', 'film', 'Ein Film');
$page = Page::query()->where('path', '/')->firstOrFail();
$revisions = $page->revisions()->count();
$component = Livewire::actingAs($this->editor(), 'staff')->test(EditPage::class, ['record' => $page->id]);
$state = $component->get('data.sections');
$state[(string) Str::uuid()] = $this->sectionState('u4', [
['type' => 'hero', 'data' => ['variant' => 'photo_split', 'data' => ['heading' => 'Mit Bild'], 'refs' => ['image' => 'cms/bild.jpg']]],
['type' => 'hero', 'data' => ['variant' => 'photo_split', 'data' => ['heading' => 'Mit Bild'], 'refs' => ['image' => $film->id]]],
]);
$component->set('data.sections', $state)
+1 -1
View File
@@ -283,7 +283,7 @@ public function test_cards_reject_unpublished_or_unreleased_objects_and_require_
[$this->card('topic_card', ['pillar' => 999999]), 'refs.pillar'],
[$this->card('program_card', ['composition' => $archivedProgram->composition_id]), 'refs.composition'],
[$this->card('media_card', ['element' => $archived->id]), 'refs.element'],
[$this->card('topic_card', ['pillar' => $published->id, 'image' => 'cms/karte.jpg']), 'data.alt'],
[$this->card('topic_card', ['pillar' => $published->id, 'image' => 'bibliothek/geschuetzt.jpg']), 'refs.image'],
[$this->card('topic_card', ['pillar' => $published->id], settings: ['format' => 'panorama']), 'settings.format'],
[$this->card('topic_card', []), 'refs.pillar'],
];
+275
View File
@@ -0,0 +1,275 @@
<?php
namespace Tests\Feature;
use App\Domain\Catalog\ContentElement;
use App\Domain\Catalog\ContentService;
use App\Domain\Cms\Page;
use App\Domain\Cms\PageRevision;
use App\Domain\Cms\PageService;
use App\Domain\Cms\WebsiteImageUsage;
use App\Domain\Cms\Widgets\Support\WebsiteImage;
use App\Domain\Media\WebsiteIntake;
use App\Domain\Media\WebsiteMediaAlias;
use App\Domain\Media\WebsiteRelease;
use App\Filament\Resources\Pages\Pages\EditPage;
use App\Jobs\ImportCmsImages;
use App\Models\User;
use Filament\Actions\Testing\TestAction;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Livewire\Livewire;
use Tests\TestCase;
/**
* CMS-Bilder aus dem zentralen Medienmanager (docs/architektur/medienzugriff-fuer-komponenten.md):
* Auswahl per Kennung, öffentliche Ausgabe nur mit Website-Freigabe, Übernahme früherer CMS-Bilder.
*/
class CmsWebsiteMediaTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Storage::fake('cms_incoming');
Storage::fake('media_derived');
Storage::fake('media_public');
Storage::fake('media_originals');
Filament::setCurrentPanel(Filament::getPanel('verwaltung'));
}
public function test_a_released_medium_is_shown_in_every_widget_through_the_website_route(): void
{
$medium = $this->releasedImage('Lara im Park', 'Lara sitzt auf einer Parkbank');
$url = route('website.media', $medium);
$revision = $this->publish('/medien-ueberall', [
['layout' => 'u4', 'style' => ['background' => 'image', 'image' => $medium->id, 'overlay' => 'light'], 'slots' => [
['type' => 'hero', 'v' => 2, 'variant' => 'photo_split', 'data' => ['heading' => 'Einstieg'], 'refs' => ['image' => $medium->id]],
]],
['layout' => 'u2_2', 'style' => [], 'slots' => [
['type' => 'image_text', 'v' => 3, 'variant' => 'image_left', 'data' => ['title' => 'Bild und Text', 'body' => '<p>Text</p>', 'alt' => 'Eigene Beschreibung'], 'refs' => ['image' => $medium->id]],
['type' => 'cards', 'v' => 1, 'data' => ['items' => [['title' => 'Karte', 'image' => $medium->id]]]],
]],
]);
$this->assertSame($medium->id, $revision->sections[0]['slots'][0]['refs']['image'], 'Gespeichert wird die Kennung, keine Kopie.');
$this->assertSame($medium->id, $revision->sections[0]['style']['image']);
$main = $this->main($this->get('/medien-ueberall')->assertOk()->getContent());
$this->assertSame(4, substr_count($main, 'src="'.$url.'"'), 'Hintergrund, Einstieg, Bild und Text, Karte verwenden dasselbe Medium.');
$this->assertStringContainsString('alt="Lara sitzt auf einer Parkbank"', $main, 'Alternativtext des Mediums.');
$this->assertStringContainsString('alt="Eigene Beschreibung"', $main, 'Abweichender Alternativtext im Widget.');
$this->assertStringNotContainsString('/redaktion/', $main);
$this->assertStringNotContainsString('/medien/cms/', $main);
$this->assertSame([['path' => '/medien-ueberall', 'published' => true, 'draft' => false]], app(WebsiteImageUsage::class)->pages($medium), 'Der Medienmanager zeigt die Verwendung auf Website-Seiten.');
}
public function test_an_unreleased_medium_is_only_shown_in_the_preview_with_a_notice(): void
{
$medium = $this->unreleasedImage('Noch nicht freigegeben');
$revision = $this->publish('/nicht-freigegeben', [
['layout' => 'u4', 'style' => [], 'slots' => [
['type' => 'image_text', 'v' => 3, 'variant' => 'image_left', 'data' => ['title' => 'Mit Bild', 'body' => '<p>Text bleibt sichtbar.</p>'], 'refs' => ['image' => $medium->id]],
]],
]);
$main = $this->main($this->get('/nicht-freigegeben')->assertOk()->getContent());
$this->assertStringContainsString('Text bleibt sichtbar.', $main, 'Nur das Bild entfällt, nicht das Widget.');
$this->assertStringNotContainsString('<img', $main);
$this->assertStringContainsString('lf-bt--without-image', $main);
$preview = $this->actingAs(User::factory()->redakteur()->create(), 'staff')->get(route('pages.preview', $revision))->assertOk()->getContent();
$this->assertStringContainsString('src="'.route('editorial.card', ['kind' => 'element', 'subject' => $medium->id]).'"', $preview);
$this->assertStringContainsString('Das gewählte Bild „Noch nicht freigegeben“ erscheint öffentlich nicht: Nicht für die Website freigegeben.', $preview);
}
public function test_withdrawing_the_release_removes_the_image_from_pages_and_closes_the_former_address(): void
{
Storage::disk('media_public')->put('cms/altbild-abc123.jpg', $this->jpeg(1200, 600));
$this->publish('/altbild', [
['layout' => 'u4', 'style' => [], 'slots' => [
['type' => 'hero', 'v' => 2, 'variant' => 'photo_split', 'data' => ['heading' => 'Früher'], 'refs' => ['image' => 'cms/altbild-abc123.jpg']],
]],
]);
(new ImportCmsImages)->handle(app(WebsiteIntake::class));
$medium = WebsiteMediaAlias::query()->where('legacy_path', 'cms/altbild-abc123.jpg')->firstOrFail()->element;
$this->assertNotNull($medium->website_released_at);
$this->refreshScoped();
$this->get('/altbild')->assertSee('src="'.route('website.media', $medium).'"', false)->assertDontSee('/medien/cms/altbild', false);
$this->get('/medien/cms/altbild-abc123.jpg')->assertOk();
app(WebsiteRelease::class)->withdraw($medium);
$this->refreshScoped();
$this->assertStringNotContainsString('<img', $this->main($this->get('/altbild')->assertOk()->getContent()));
$this->get('/medien/cms/altbild-abc123.jpg')->assertNotFound();
$this->get(route('website.media', $medium))->assertNotFound();
Storage::disk('media_public')->assertExists('cms/altbild-abc123.jpg');
}
public function test_former_cms_images_are_imported_once_deduplicated_and_without_deleting_files(): void
{
$same = $this->jpeg(800, 400);
Storage::disk('media_public')->put('cms/platzhalter-karte-1-aaaaaa.jpg', $same);
Storage::disk('media_public')->put('cms/platzhalter-karte-1-bbbbbb.jpg', $same);
Storage::disk('media_public')->put('cms/markenbuehne-cccccc.png', $this->jpeg(900, 300));
Storage::disk('media_public')->put('cms/notiz.txt', 'kein Bild');
(new ImportCmsImages)->handle(app(WebsiteIntake::class));
(new ImportCmsImages)->handle(app(WebsiteIntake::class));
$this->assertSame(3, WebsiteMediaAlias::query()->count());
$this->assertSame(2, ContentElement::query()->where('output_class', 'bild')->count(), 'Bytegleiche Dateien werden ein Medium.');
$this->assertSame(['Markenbuehne', 'Platzhalter Karte 1'], ContentElement::query()->orderBy('working_title')->pluck('working_title')->all());
$this->assertSame(
WebsiteMediaAlias::query()->where('legacy_path', 'cms/platzhalter-karte-1-aaaaaa.jpg')->value('content_element_id'),
WebsiteMediaAlias::query()->where('legacy_path', 'cms/platzhalter-karte-1-bbbbbb.jpg')->value('content_element_id'),
);
foreach (['cms/platzhalter-karte-1-aaaaaa.jpg', 'cms/platzhalter-karte-1-bbbbbb.jpg', 'cms/markenbuehne-cccccc.png'] as $path) {
Storage::disk('media_public')->assertExists($path);
}
$this->assertTrue(ContentElement::query()->get()->every(fn (ContentElement $element): bool => $element->website_released_at !== null));
}
public function test_an_alias_takes_effect_only_after_the_medium_was_released(): void
{
Storage::disk('media_public')->put('cms/kaputt-dddddd.jpg', 'keine Bilddaten');
$this->publish('/kaputt', [
['layout' => 'u4', 'style' => [], 'slots' => [
['type' => 'hero', 'v' => 2, 'variant' => 'photo_split', 'data' => ['heading' => 'Bild bleibt'], 'refs' => ['image' => 'cms/kaputt-dddddd.jpg']],
]],
]);
(new ImportCmsImages)->handle(app(WebsiteIntake::class));
$this->refreshScoped();
$this->assertNotNull(WebsiteMediaAlias::query()->where('legacy_path', 'cms/kaputt-dddddd.jpg')->first());
$this->get('/kaputt')->assertSee('/medien/cms/kaputt-dddddd.jpg', false);
}
public function test_saving_converts_an_imported_path_to_the_medium_and_rejects_other_media(): void
{
Storage::disk('media_public')->put('cms/umzug-eeeeee.jpg', $this->jpeg(1000, 500));
(new ImportCmsImages)->handle(app(WebsiteIntake::class));
$medium = WebsiteMediaAlias::query()->firstOrFail()->element;
$revision = $this->publish('/umzug', [
['layout' => 'u4', 'style' => [], 'slots' => [
['type' => 'hero', 'v' => 2, 'variant' => 'photo_split', 'data' => ['heading' => 'Umzug'], 'refs' => ['image' => 'cms/umzug-eeeeee.jpg']],
]],
]);
$this->assertSame($medium->id, $revision->sections[0]['slots'][0]['refs']['image']);
$film = app(ContentService::class)->createElement('film', 'film', 'Film');
try {
app(PageService::class)->saveRevision(Page::query()->create(['path' => '/film-als-bild']), [
['layout' => 'u4', 'style' => [], 'slots' => [['type' => 'hero', 'v' => 2, 'data' => ['heading' => 'X'], 'refs' => ['image' => $film->id]]]],
], null, null, null);
$this->fail('Ein Film wurde als Bild angenommen.');
} catch (ValidationException $exception) {
$this->assertArrayHasKey('sections.0.slots.0.refs.image', $exception->errors());
}
}
public function test_an_image_uploaded_in_the_widget_dialog_becomes_a_medium_and_is_selected(): void
{
$editor = User::factory()->redakteur()->create();
$editor->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP');
$page = Page::query()->create(['path' => '/upload']);
app(PageService::class)->saveRevision($page, [
['layout' => 'u4', 'style' => [], 'slots' => [['type' => 'hero', 'v' => 2, 'variant' => 'photo_split', 'data' => ['heading' => 'Upload'], 'refs' => []]]],
], null, null, null);
$component = Livewire::actingAs($editor, 'staff')->test(EditPage::class, ['record' => $page->id]);
$sectionKey = array_key_first($component->get('data.sections'));
$slotKey = array_key_first($component->get("data.sections.$sectionKey.slots"));
$itemKey = array_key_first($component->get("data.sections.$sectionKey.slots.$slotKey.widget"));
$component->mountAction(TestAction::make('edit')->schemaComponent("sections.$sectionKey.slots.$slotKey.widget")->arguments(['item' => $itemKey]))
->fillForm(['refs._upload' => UploadedFile::fake()->image('lara-im-park.jpg', 1600, 900)])
->callMountedAction()
->assertHasNoErrors();
$medium = ContentElement::query()->where('output_class', 'bild')->latest('id')->firstOrFail();
$this->assertSame('Lara Im Park', $medium->display_title);
$this->assertNotNull($medium->website_released_at, 'Neue Bilder werden nach der Verarbeitung für die Website freigegeben.');
$this->assertSame($medium->id, (int) $component->get("data.sections.$sectionKey.slots.$slotKey.widget.$itemKey.data.refs.image"));
$component->call('save')->assertHasNoFormErrors();
$this->assertSame($medium->id, $page->refresh()->latestRevision->sections[0]['slots'][0]['refs']['image']);
}
public function test_the_picker_lists_website_images_with_their_release_state(): void
{
$released = $this->releasedImage('Freigegeben', null);
$unreleased = $this->unreleasedImage('Unfreigegeben');
app(ContentService::class)->createElement('film', 'film', 'Film taucht nicht auf');
$options = app(WebsiteImage::class)->options();
$this->assertSame([$unreleased->id, $released->id], array_keys($options));
$this->assertStringContainsString('Website: freigegeben', $options[$released->id]);
$this->assertStringContainsString('Website: nicht freigegeben', $options[$unreleased->id]);
$this->assertStringContainsString(route('editorial.card', ['kind' => 'element', 'subject' => $released->id]), $options[$released->id]);
}
private function releasedImage(string $title, ?string $alt): ContentElement
{
$path = 'cms/'.Str::slug($title).'.jpg';
Storage::disk('cms_incoming')->put($path, $this->jpeg(1600, 800));
return app(WebsiteIntake::class)->acceptImage($path, $title, 'Foto: Lara und Felix', $alt)->refresh();
}
private function unreleasedImage(string $title): ContentElement
{
$element = app(ContentService::class)->createElement('bild', 'bild', $title);
$element->forceFill(['thumbnail_path' => 'vorschau/element-'.$element->id.'.jpg'])->save();
Storage::disk('media_derived')->put($element->thumbnail_path, $this->jpeg(640, 320));
return $element->refresh();
}
/**
* @param list<array<string, mixed>> $sections
*/
private function publish(string $path, array $sections): PageRevision
{
$page = Page::query()->firstOrCreate(['path' => $path]);
$service = app(PageService::class);
$revision = $service->saveRevision($page, $sections, null, null, null);
$service->publish($page, $revision);
return $revision;
}
private function refreshScoped(): void
{
$this->app->forgetScopedInstances();
}
private function main(string $html): string
{
preg_match('#<main[^>]*>(.*)</main>#s', $html, $match);
return $match[1] ?? '';
}
private function jpeg(int $width, int $height): string
{
$image = imagecreatetruecolor($width, $height);
imagefill($image, 0, 0, imagecolorallocate($image, 200, 120, 40));
ob_start();
imagejpeg($image);
return (string) ob_get_clean();
}
}
+3
View File
@@ -7,11 +7,14 @@
use App\Domain\Cms\Sections\SectionStyle;
use App\Domain\Cms\Widgets\WidgetRegistry;
use App\Filament\Support\SectionEditor;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Validation\ValidationException;
use Tests\TestCase;
class PageSectionsTest extends TestCase
{
use RefreshDatabase;
private function sections(): PageSections
{
return app(PageSections::class);
+13 -9
View File
@@ -9,12 +9,15 @@
use App\Domain\Cms\Widgets\WidgetType;
use App\Filament\Support\WidgetEditor;
use Filament\Forms\Components\TextInput;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
use Tests\TestCase;
class WidgetRegistryTest extends TestCase
{
use RefreshDatabase;
private function registry(): WidgetRegistry
{
return app(WidgetRegistry::class);
@@ -166,16 +169,17 @@ public function test_free_settings_are_rejected(): void
]);
}
public function test_image_text_requires_an_alternative_text_when_an_image_is_set(): void
/**
* Bewusst geändert (zentrale Medienverwaltung): Der Alternativtext gehört zum Medium im Medienmanager. Im Widget ist er
* eine optionale Abweichung und deshalb keine Pflicht mehr; ein früheres CMS-Bild ohne Zuordnung bleibt gültig.
*/
public function test_image_text_takes_the_alternative_text_from_the_medium_and_keeps_legacy_images(): void
{
try {
$this->registry()->normalize([
['type' => 'image_text', 'v' => 2, 'data' => ['body' => '<p>Text</p>'], 'refs' => ['image' => 'cms/bild.jpg']],
]);
$this->fail('Bild ohne Alternativtext wurde angenommen.');
} catch (ValidationException $exception) {
$this->assertArrayHasKey('blocks.0.data.alt', $exception->errors());
}
$stored = $this->registry()->normalize([
['type' => 'image_text', 'v' => 2, 'data' => ['body' => '<p>Text</p>'], 'refs' => ['image' => 'cms/bild.jpg']],
]);
$this->assertSame('cms/bild.jpg', $stored[0]['refs']['image']);
$this->assertNull($stored[0]['data']['alt']);
$stored = $this->registry()->normalize([
['type' => 'image_text', 'v' => 2, 'data' => ['body' => '<p>Ohne Bild</p>'], 'refs' => []],