Loheide-eu-mitarbeiterplatt.../app/Media/MediaUsages.php
Friederich Loheide 694ccf6ae0 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>
2026-09-26 20:05:50 +00:00

198 lines
7 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

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

<?php
namespace App\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');
}
}