Mediathek: zentrale Bildverwaltung mit Verwendungsnachweis und Bildauswahl

- Tabellen media und media_usages, Modelle Media/MediaUsage
- App\Media\MediaLibrary (store/register/replace/delete/rebuild) und
  Registry App\Media\MediaUsages (Quellen: Seiten, Neuigkeiten inkl.
  künftiger content-Spalte, Termine, Startseiten-Kacheln), ImagePaths-Extraktor
- Alle Uploads landen in der Mediathek (Seiten-Editor direkt, übrige über
  Beobachter beim Speichern); Daten-Migration und media:rebuild übernehmen
  bestehende Bilder
- Recht media.manage, Zugang media.use für alle Redaktionsbereiche
- /redaktion/mediathek (Suche, Filter, Upload mit Fortschritt, Details,
  Eingebunden in, Ersetzen, Löschen mit Warnung, Mehrfachauswahl),
  Abschnitt in der Redaktion und Menüpunkt im Admin-Bereich
- MediaPicker (Hochladen/Mediathek) im Pagebuilder: Bildfelder und
  Galerie (Mehrfachauswahl), editor.pickMedia im provide-API
- Bild-URLs mit ?v=Änderungszeit, null bei fehlender Datei; Modelle löschen
  geteilte Bilder nicht mehr selbst

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 20:05:50 +00:00
parent 3b72b5327e
commit 694ccf6ae0
46 changed files with 3101 additions and 89 deletions

View file

@ -0,0 +1,29 @@
<?php
namespace App\Media;
use App\Models\Media;
use App\Models\User;
/**
* „Redaktion → Mediathek“: Überblick mit den neuesten Bildern.
*/
final class EditorialMedia
{
/**
* @return array<string, mixed>
*/
public static function props(User $user): array
{
return [
'total' => Media::query()->count(),
'unused' => $user->can('media.manage') ? Media::query()->doesntHave('usages')->count() : null,
'recent' => Media::query()->latest('id')->limit(8)->get()->map(fn (Media $media) => [
'id' => $media->id,
'name' => $media->displayName(),
'alt' => $media->alt ?? '',
'thumb_url' => $media->url('thumb'),
])->all(),
];
}
}

148
app/Media/ImagePaths.php Normal file
View file

@ -0,0 +1,148 @@
<?php
namespace App\Media;
use App\Pagebuilder\Blocks;
use Illuminate\Support\Facades\Storage;
/**
* Findet Bildpfade im Speicher „uploads“ in Inhalten: in Pagebuilder-JSON
* (jeder String, der wie ein Upload-Pfad aussieht) und in HTML
* (src="/uploads/…"). Grundlage für „Eingebunden in“ der Mediathek.
*/
final class ImagePaths
{
/** Bezeichnung der Stelle je Blockart. */
public const BLOCK_CONTEXTS = [
'image' => 'Bild-Block',
'gallery' => 'Galerie',
'hero' => 'Hero',
'text' => 'Im Text',
];
public const HTML_CONTEXT = 'Im Text';
/**
* Sieht der Wert wie ein Bildpfad im Upload-Speicher aus (relativ, ohne „..“)?
*/
public static function isCandidate(mixed $value): bool
{
return is_string($value)
&& strlen($value) <= 255
&& preg_match('#^[A-Za-z0-9_-][A-Za-z0-9/_.\-]*\.(webp|jpe?g|png|gif)$#i', $value) === 1
&& ! str_contains($value, '..')
&& ! str_contains($value, '//');
}
/**
* Pfade aus src-Attributen, die auf den Upload-Speicher zeigen.
*
* @return list<string>
*/
public static function fromHtml(?string $html): array
{
if (! $html || ! str_contains($html, '<img')) {
return [];
}
preg_match_all('/\ssrc\s*=\s*(["\'])(.*?)\1/i', $html, $matches);
$paths = [];
foreach ($matches[2] as $src) {
if ($path = self::fromUrl(html_entity_decode($src))) {
$paths[] = $path;
}
}
// Anhänge des Filament-Editors: <img data-id="news/inline/…">
preg_match_all('/\sdata-id\s*=\s*(["\'])(.*?)\1/i', $html, $ids);
foreach ($ids[2] as $id) {
if (self::isCandidate($id = html_entity_decode($id))) {
$paths[] = $id;
}
}
return array_values(array_unique($paths));
}
/**
* Pfad im Upload-Speicher zu einer Adresse („/uploads/news/a.webp?v=1“), sonst null.
*/
public static function fromUrl(string $url): ?string
{
$parts = parse_url(trim($url));
if ($parts === false || ! isset($parts['path'])) {
return null;
}
if (isset($parts['host'])) {
$ownHost = parse_url((string) Storage::disk('uploads')->url(''), PHP_URL_HOST);
if ($ownHost && strcasecmp($parts['host'], $ownHost) !== 0) {
return null;
}
}
$position = strpos($parts['path'], '/uploads/');
if ($position === false) {
return null;
}
$path = rawurldecode(substr($parts['path'], $position + strlen('/uploads/')));
return self::isCandidate($path) ? $path : null;
}
/**
* Alle Bildpfade eines Pagebuilder-Inhalts, gruppiert nach Stelle
* („Bild-Block“, „Galerie“, „Hero“, „Im Text“ oder die Blockbezeichnung).
*
* @param array<mixed>|null $content
* @return array<string, list<string>> Stelle => Pfade
*/
public static function fromContent(?array $content): array
{
$result = [];
$blocks = app(Blocks::class);
$walkBlocks = function (mixed $list, int $depth) use (&$walkBlocks, &$result, $blocks): void {
if (! is_array($list) || $depth > 10) {
return;
}
foreach ($list as $block) {
if (! is_array($block)) {
continue;
}
$type = (string) ($block['type'] ?? '');
$context = self::BLOCK_CONTEXTS[$type] ?? ($blocks->get($type)?->label ?? 'Inhalt');
$data = is_array($block['data'] ?? null) ? $block['data'] : [];
array_walk_recursive($data, function ($value) use (&$result, $context) {
if (self::isCandidate($value)) {
$result[$context][] = $value;
} elseif (is_string($value) && str_contains($value, '<')) {
foreach (self::fromHtml($value) as $path) {
$result[self::HTML_CONTEXT][] = $path;
}
}
});
foreach ((array) ($block['items'] ?? []) as $item) {
$walkBlocks(is_array($item) ? ($item['blocks'] ?? []) : [], $depth + 1);
}
}
};
if (is_array($content)) {
$walkBlocks($content['blocks'] ?? [], 1);
}
return array_map(fn (array $paths) => array_values(array_unique($paths)), $result);
}
}

189
app/Media/MediaLibrary.php Normal file
View file

@ -0,0 +1,189 @@
<?php
namespace App\Media;
use App\Models\Media;
use App\Models\User;
use App\Support\Images;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Throwable;
/**
* Mediathek: jedes hochgeladene Bild wird hier als App\Models\Media erfasst.
* Inhalte speichern weiterhin den Pfad im Speicher „uploads“ – deshalb
* ersetzt replace() die Datei am selben Pfad, und jede Einbindung zeigt sofort
* das neue Bild.
*/
class MediaLibrary
{
public const DISK = 'uploads';
/** Verzeichnis für Uploads direkt in der Mediathek bzw. über die Bildauswahl. */
public const DIRECTORY = 'mediathek';
public function __construct(private readonly Images $images) {}
/**
* Vorhandene Datei erfassen (idempotent über den Pfad).
*
* @param array{original_name?: string|null, alt?: string|null, caption?: string|null, tags?: list<string>|null, created_at?: mixed} $meta
*/
public function register(string $path, array $meta = [], ?User $user = null): Media
{
$existing = Media::query()->where('path', $path)->first();
if ($existing) {
return $existing;
}
$attributes = [
...$this->fileInfo($path),
'disk' => self::DISK,
'path' => $path,
'original_name' => isset($meta['original_name']) ? Str::limit((string) $meta['original_name'], 250, '') : null,
'alt' => $meta['alt'] ?? null,
'caption' => $meta['caption'] ?? null,
'tags' => $meta['tags'] ?? null,
'uploaded_by' => $user?->id,
];
try {
$media = new Media($attributes);
if (isset($meta['created_at'])) {
$media->created_at = Carbon::parse($meta['created_at']);
}
$media->save();
return $media;
} catch (UniqueConstraintViolationException) {
// Gleichzeitig von einer anderen Anfrage erfasst.
return Media::query()->where('path', $path)->firstOrFail();
}
}
/**
* Pfade auf Mediathek-IDs abbilden; vorhandene, noch unbekannte Bilddateien
* werden dabei erfasst (z. B. aus Admin-Formularen oder älteren Versionen).
*
* @param list<string> $paths
* @return array<string, int> Pfad => Media-ID
*/
public function ensureRegistered(array $paths): array
{
$paths = array_values(array_filter(array_unique($paths), fn ($path) => ImagePaths::isCandidate($path)));
if ($paths === []) {
return [];
}
$known = Media::query()->whereIn('path', $paths)->pluck('id', 'path')->all();
$disk = Storage::disk(self::DISK);
$user = Auth::user();
foreach (array_diff($paths, array_keys($known)) as $path) {
if (! $disk->exists($path)) {
continue;
}
try {
$modified = @filemtime($disk->path($path));
$known[$path] = $this->register($path, ['created_at' => $modified ? Carbon::createFromTimestamp($modified) : null], $user instanceof User ? $user : null)->id;
} catch (Throwable $e) {
report($e);
}
}
return $known;
}
/**
* Upload speichern (höchstens 2000 px breit, WebP; GIFs unverändert) und erfassen.
*/
public function store(UploadedFile $file, string $directory = self::DIRECTORY, ?User $user = null, array $meta = []): Media
{
$name = $file->getClientOriginalName();
$path = $this->images->storeContentImage($file, trim($directory, '/'));
// Vorschaubild für Mediathek und Bildauswahl
$this->images->createVariants($path, ['thumb']);
return $this->register($path, ['original_name' => $name, ...$meta], $user);
}
/**
* Datei austauschen – Pfad, Alternativtext und alle Einbindungen bleiben.
*/
public function replace(Media $media, UploadedFile $file): Media
{
$name = $file->getClientOriginalName();
$this->images->overwrite($media->path, $file);
if (! Storage::disk(self::DISK)->exists($this->images->variantPath($media->path, 'thumb'))) {
$this->images->createVariants($media->path, ['thumb']);
}
$media->forceFill([...$this->fileInfo($media->path), 'original_name' => Str::limit($name, 250, ''), 'updated_at' => now()])->save();
return $media;
}
/**
* Bild samt Varianten löschen. Einbindungen zeigen danach ihren Platzhalter.
*/
public function delete(Media $media): void
{
$this->images->deleteWithVariants($media->path);
$media->delete();
}
/**
* Datei über ihren Pfad entfernen – mit Eintrag in der Mediathek, falls vorhanden.
*/
public function deletePath(string $path): void
{
$media = Media::query()->where('path', $path)->first();
$media ? $this->delete($media) : $this->images->deleteWithVariants($path);
}
/**
* Bereits verwendete Bilder übernehmen und alle Verwendungen neu erfassen.
*
* @return array{sources: int, media: int}
*/
public function rebuild(): array
{
@set_time_limit(0);
$sources = app(MediaUsages::class)->rebuild();
return ['sources' => $sources, 'media' => Media::query()->count()];
}
/**
* @return array{mime: string|null, size: int|null, width: int|null, height: int|null}
*/
private function fileInfo(string $path): array
{
$disk = Storage::disk(self::DISK);
if (! $disk->exists($path)) {
return ['mime' => null, 'size' => null, 'width' => null, 'height' => null];
}
$size = @getimagesize($disk->path($path));
return [
'mime' => $size['mime'] ?? ($disk->mimeType($path) ?: null),
'size' => $disk->size($path),
'width' => $size[0] ?? null,
'height' => $size[1] ?? null,
];
}
}

198
app/Media/MediaUsages.php Normal file
View file

@ -0,0 +1,198 @@
<?php
namespace App\Media;
use App\Models\MediaUsage;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Throwable;
/**
* Registry „Wo ist das Bild eingebunden?“. Kern und Plugins melden ihre
* Quellen an (Seiten, Neuigkeiten, Termine …):
*
* $usages->add('news', 'Neuigkeiten',
* scan: fn (NewsPost $post) => [
* ['context' => 'Titelbild', 'label' => $post->title, 'url' => '/…', 'draft' => false, 'paths' => [$post->cover_path]],
* ],
* all: fn (callable $each) => NewsPost::query()->chunkById(100, fn ($posts) => $posts->each($each)),
* );
* $usages->watch('news', NewsPost::class, ['cover_path', 'body_html']);
*
* scan() liefert je Stelle Pfade im Speicher „uploads“ (ImagePaths hilft beim
* Auslesen von Pagebuilder-JSON und HTML). Unbekannte, aber vorhandene
* Bilddateien werden dabei automatisch in die Mediathek übernommen – so landen
* auch Uploads aus Formularen, die die Mediathek nicht kennen, dort.
*/
class MediaUsages
{
/** @var array<string, array{label: string, scan: callable, all: callable|null}> */
private array $sources = [];
private bool $ready = false;
public function __construct(private readonly Dispatcher $events) {}
/**
* @param callable(Model): list<array{context: string, label: string, url?: string|null, draft?: bool, paths: list<string|null>, source_id?: int}> $scan
* @param (callable(callable(Model): void): void)|null $all ruft $each für jede Quelle auf (für „Neu einlesen“)
*/
public function add(string $type, string $label, callable $scan, ?callable $all = null): void
{
$this->sources[$type] = ['label' => $label, 'scan' => $scan, 'all' => $all];
}
/**
* Verwendungen bei jedem Speichern/Löschen des Modells aktualisieren.
*
* @param class-string<Model> $model
* @param list<string> $columns nur neu berechnen, wenn sich eine dieser Spalten ändert (leer = immer)
*/
public function watch(string $type, string $model, array $columns = []): void
{
$this->events->listen("eloquent.saved: {$model}", function (Model $record) use ($type, $columns) {
if ($columns === [] || $record->wasRecentlyCreated || $record->wasChanged($columns)) {
$this->sync($type, $record);
}
});
$this->events->listen("eloquent.deleted: {$model}", fn (Model $record) => $this->forget($type, (int) $record->getKey()));
}
/**
* @return array<string, string> Typ => Bezeichnung (z. B. „pages“ => „Seiten“)
*/
public function labels(): array
{
return array_map(fn (array $source) => $source['label'], $this->sources);
}
public function has(string $type): bool
{
return isset($this->sources[$type]);
}
/**
* Verwendungen einer Quelle neu erfassen. Fehler werden nur protokolliert –
* Speichern von Inhalten darf nie an der Mediathek scheitern.
*/
public function sync(string $type, Model $record): void
{
if (! isset($this->sources[$type]) || ! $this->tablesReady()) {
return;
}
try {
$entries = ($this->sources[$type]['scan'])($record);
$paths = [];
foreach ($entries as $entry) {
foreach ($entry['paths'] ?? [] as $path) {
if (is_string($path) && $path !== '') {
$paths[] = $path;
}
}
}
$ids = app(MediaLibrary::class)->ensureRegistered(array_values(array_unique($paths)));
$rows = [];
$now = now();
// Nicht-Entwürfe zuerst, damit dieselbe Stelle nicht doppelt als Entwurf erscheint.
usort($entries, fn (array $a, array $b) => (int) ($a['draft'] ?? false) <=> (int) ($b['draft'] ?? false));
foreach ($entries as $entry) {
foreach (array_unique(array_filter((array) ($entry['paths'] ?? []), 'is_string')) as $path) {
if (! isset($ids[$path])) {
continue;
}
$sourceId = (int) ($entry['source_id'] ?? $record->getKey());
$key = $ids[$path].'|'.$sourceId.'|'.$entry['context'];
if (isset($rows[$key])) {
continue;
}
$rows[$key] = [
'media_id' => $ids[$path],
'source_type' => $type,
'source_id' => $sourceId,
'context' => mb_substr((string) $entry['context'], 0, 80),
'label' => mb_substr((string) ($entry['label'] ?? ''), 0, 250),
'url' => isset($entry['url']) ? mb_substr((string) $entry['url'], 0, 1000) : null,
'draft' => (bool) ($entry['draft'] ?? false),
'created_at' => $now,
];
}
}
DB::transaction(function () use ($type, $record, $rows) {
MediaUsage::query()->where('source_type', $type)->where('source_id', $record->getKey())->delete();
foreach (array_chunk(array_values($rows), 200) as $chunk) {
MediaUsage::query()->insert($chunk);
}
});
} catch (Throwable $e) {
report($e);
}
}
public function forget(string $type, int $id): void
{
if (! $this->tablesReady()) {
return;
}
try {
MediaUsage::query()->where('source_type', $type)->where('source_id', $id)->delete();
} catch (Throwable $e) {
report($e);
}
}
/**
* Alle Verwendungen neu erfassen (dabei referenzierte Dateien übernehmen).
*
* @return int Anzahl der durchsuchten Quellen
*/
public function rebuild(): int
{
if (! $this->tablesReady()) {
return 0;
}
$count = 0;
// Verwendungen von Quellen, die es nicht mehr gibt (z. B. Plugin entfernt), fallen weg.
MediaUsage::query()->whereNotIn('source_type', array_keys($this->sources) ?: [''])->delete();
foreach ($this->sources as $type => $source) {
if (! $source['all']) {
continue;
}
try {
MediaUsage::query()->where('source_type', $type)->delete();
($source['all'])(function (Model $record) use ($type, &$count) {
$this->sync($type, $record);
$count++;
});
} catch (Throwable $e) {
report($e);
}
}
return $count;
}
private function tablesReady(): bool
{
// Nur „ja“ merken: Während eines Updates entstehen die Tabellen erst mittendrin.
return $this->ready = $this->ready || Schema::hasTable('media_usages');
}
}