diff --git a/app/Editorial/Editorial.php b/app/Editorial/Editorial.php index 690565ee..caa19623 100644 --- a/app/Editorial/Editorial.php +++ b/app/Editorial/Editorial.php @@ -31,10 +31,13 @@ class Editorial unset($this->sections[$key]); } - public function visibleFor(User $user): bool + /** + * @param string|null $except diesen Abschnitt nicht mitprüfen (verhindert Zirkelschlüsse, z. B. „media“) + */ + public function visibleFor(User $user, ?string $except = null): bool { - foreach ($this->sections as $section) { - if (($section['visible'])($user)) { + foreach ($this->sections as $key => $section) { + if ($key !== $except && ($section['visible'])($user)) { return true; } } diff --git a/app/Http/Controllers/MediaController.php b/app/Http/Controllers/MediaController.php new file mode 100644 index 00000000..a3e6bb2d --- /dev/null +++ b/app/Http/Controllers/MediaController.php @@ -0,0 +1,232 @@ + (object) $request->only(['q', 'von', 'zeitraum', 'status', 'in']), + 'uploaders' => User::query()->whereIn('id', Media::query()->whereNotNull('uploaded_by')->distinct()->select('uploaded_by')) + ->orderBy('last_name')->orderBy('first_name')->get()->map(fn (User $user) => ['value' => (string) $user->id, 'label' => $user->name])->values(), + 'sources' => collect($this->usages->labels())->map(fn (string $label, string $type) => ['value' => $type, 'label' => $label])->values(), + 'canManage' => $request->user()->can('media.manage'), + ]); + } + + public function list(Request $request): JsonResponse + { + $filters = $request->validate([ + 'q' => ['nullable', 'string', 'max:100'], + 'von' => ['nullable', 'integer'], + 'zeitraum' => ['nullable', Rule::in(['7', '30', '365'])], + 'status' => ['nullable', Rule::in(['unbenutzt', 'verwendet'])], + 'in' => ['nullable', 'string', 'max:60'], + 'sortierung' => ['nullable', Rule::in(['neu', 'verwendet', 'name'])], + 'pfade' => ['nullable', 'array', 'max:500'], + 'pfade.*' => ['string', 'max:255'], + 'page' => ['nullable', 'integer', 'min:1'], + ]); + + $query = Media::query()->with('uploader:id,name')->withCount('usages'); + $this->applyFilters($query, $filters); + + $page = $query->simplePaginate(self::PER_PAGE); + + return response()->json([ + 'items' => $page->getCollection()->map(fn (Media $media) => $media->toLibraryArray())->values(), + 'next_page' => $page->hasMorePages() ? $page->currentPage() + 1 : null, + 'total' => $page->currentPage() === 1 ? $this->countFor($filters) : null, + ]); + } + + public function store(Request $request): JsonResponse + { + $request->validate(['image' => ['required', File::image()->types(['jpg', 'jpeg', 'png', 'webp', 'gif'])->max(15 * 1024)]]); + + $media = $this->library->store($request->file('image'), MediaLibrary::DIRECTORY, $request->user()); + $media->load('uploader:id,name')->loadCount('usages'); + + return response()->json(['media' => $media->toLibraryArray()], 201); + } + + public function show(Media $media): JsonResponse + { + $media->load('uploader:id,name')->loadCount('usages'); + $labels = $this->usages->labels(); + + return response()->json([ + 'media' => $media->toLibraryArray(), + 'usages' => $media->usages()->orderBy('draft')->orderBy('source_type')->orderBy('label')->get()->map(fn (MediaUsage $usage) => [ + 'id' => $usage->id, + 'type' => $usage->source_type, + 'type_label' => $labels[$usage->source_type] ?? $usage->source_type, + 'context' => $usage->context, + 'label' => $usage->label, + 'url' => $usage->url, + 'draft' => $usage->draft, + ])->values(), + ]); + } + + public function update(Request $request, Media $media): JsonResponse + { + $data = $request->validate([ + 'alt' => ['nullable', 'string', 'max:300'], + 'caption' => ['nullable', 'string', 'max:500'], + 'tags' => ['nullable', 'array', 'max:20'], + 'tags.*' => ['string', 'max:40'], + ]); + + $tags = isset($data['tags']) ? array_values(array_unique(array_filter(array_map(fn ($tag) => trim((string) $tag), $data['tags'])))) : ($media->tags ?? []); + + $media->forceFill([ + 'alt' => array_key_exists('alt', $data) ? (trim((string) $data['alt']) ?: null) : $media->alt, + 'caption' => array_key_exists('caption', $data) ? (trim((string) $data['caption']) ?: null) : $media->caption, + 'tags' => $tags ?: null, + ]); + + // Nur Metadaten: updated_at nicht anfassen, sonst ändern sich alle Bildadressen („?v=“). + Media::withoutTimestamps(fn () => $media->save()); + + return response()->json(['media' => $media->loadCount('usages')->load('uploader:id,name')->toLibraryArray()]); + } + + public function replace(Request $request, Media $media): JsonResponse + { + Gate::authorize('media.manage'); + $request->validate(['image' => ['required', File::image()->types(['jpg', 'jpeg', 'png', 'webp', 'gif'])->max(15 * 1024)]]); + + $this->library->replace($media, $request->file('image')); + Audit::log('media.replaced', ['media' => $media->id, 'path' => $media->path]); + + return response()->json(['media' => $media->loadCount('usages')->load('uploader:id,name')->toLibraryArray()]); + } + + public function destroy(Media $media): JsonResponse + { + Gate::authorize('media.manage'); + + $usages = $media->usages()->count(); + $this->library->delete($media); + Audit::log('media.deleted', ['media' => $media->id, 'path' => $media->path, 'usages' => $usages]); + + return response()->json(['deleted' => 1]); + } + + public function bulkDestroy(Request $request): JsonResponse + { + Gate::authorize('media.manage'); + $data = $request->validate([ + 'ids' => ['required', 'array', 'max:500'], + 'ids.*' => ['integer'], + 'only_unused' => ['boolean'], + ]); + + $deleted = 0; + + Media::query()->whereIn('id', $data['ids']) + ->when($data['only_unused'] ?? false, fn (Builder $q) => $q->doesntHave('usages')) + ->get()->each(function (Media $media) use (&$deleted) { + $this->library->delete($media); + $deleted++; + }); + + Audit::log('media.bulk_deleted', ['count' => $deleted]); + + return response()->json(['deleted' => $deleted]); + } + + public function download(Media $media): StreamedResponse + { + $disk = Storage::disk($media->disk ?: MediaLibrary::DISK); + abort_unless($disk->exists($media->path), 404); + + $extension = pathinfo($media->path, PATHINFO_EXTENSION); + $name = pathinfo($media->displayName(), PATHINFO_FILENAME) ?: 'bild'; + + return $disk->download($media->path, $name.'.'.$extension); + } + + public function rebuild(): JsonResponse + { + Gate::authorize('media.manage'); + + $result = $this->library->rebuild(); + Audit::log('media.rebuilt', $result); + + return response()->json($result); + } + + /** + * @param Builder $query + * @param array $filters + */ + private function applyFilters(Builder $query, array $filters, bool $sort = true): void + { + if ($term = trim((string) ($filters['q'] ?? ''))) { + $like = '%'.str_replace(['\\', '%', '_'], ['\\\\', '\%', '\_'], $term).'%'; + $query->where(fn (Builder $q) => $q + ->where('original_name', 'like', $like) + ->orWhere('alt', 'like', $like) + ->orWhere('caption', 'like', $like) + ->orWhere('tags', 'like', $like) + ->orWhere('path', 'like', $like)); + } + + $query->when($filters['von'] ?? null, fn (Builder $q, $id) => $q->where('uploaded_by', $id)) + ->when($filters['zeitraum'] ?? null, fn (Builder $q, $days) => $q->where('created_at', '>=', now()->subDays((int) $days))) + ->when(($filters['status'] ?? null) === 'unbenutzt', fn (Builder $q) => $q->doesntHave('usages')) + ->when(($filters['status'] ?? null) === 'verwendet', fn (Builder $q) => $q->has('usages')) + ->when($filters['in'] ?? null, fn (Builder $q, $type) => $q->whereHas('usages', fn (Builder $u) => $u->where('source_type', $type))) + ->when(array_key_exists('pfade', $filters), fn (Builder $q) => $q->whereIn('path', $filters['pfade'] ?: [''])); + + if (! $sort) { + return; + } + + match ($filters['sortierung'] ?? 'neu') { + // Zuletzt verwendet: jüngste Einbindung zuerst (wird bei jedem Speichern der Quelle neu erfasst) + 'verwendet' => $query->orderByDesc(MediaUsage::query()->selectRaw('MAX(created_at)')->whereColumn('media_usages.media_id', 'media.id'))->orderByDesc('id'), + 'name' => $query->orderBy('original_name')->orderBy('id'), + default => $query->orderByDesc('id'), + }; + } + + /** + * @param array $filters + */ + private function countFor(array $filters): int + { + $query = Media::query(); + $this->applyFilters($query, $filters, false); + + return $query->count(); + } +} diff --git a/app/Media/EditorialMedia.php b/app/Media/EditorialMedia.php new file mode 100644 index 00000000..29b4d5f3 --- /dev/null +++ b/app/Media/EditorialMedia.php @@ -0,0 +1,29 @@ + + */ + 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(), + ]; + } +} diff --git a/app/Media/ImagePaths.php b/app/Media/ImagePaths.php new file mode 100644 index 00000000..44192b97 --- /dev/null +++ b/app/Media/ImagePaths.php @@ -0,0 +1,148 @@ + '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 + */ + public static function fromHtml(?string $html): array + { + if (! $html || ! str_contains($html, ' + 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|null $content + * @return array> 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); + } +} diff --git a/app/Media/MediaLibrary.php b/app/Media/MediaLibrary.php new file mode 100644 index 00000000..8df911ab --- /dev/null +++ b/app/Media/MediaLibrary.php @@ -0,0 +1,189 @@ +|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 $paths + * @return array 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, + ]; + } +} diff --git a/app/Media/MediaUsages.php b/app/Media/MediaUsages.php new file mode 100644 index 00000000..cedac4d6 --- /dev/null +++ b/app/Media/MediaUsages.php @@ -0,0 +1,198 @@ +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 */ + private array $sources = []; + + private bool $ready = false; + + public function __construct(private readonly Dispatcher $events) {} + + /** + * @param callable(Model): list, 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 + * @param list $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 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'); + } +} diff --git a/app/Models/DashboardTile.php b/app/Models/DashboardTile.php index 6eb59f6d..620c5c27 100644 --- a/app/Models/DashboardTile.php +++ b/app/Models/DashboardTile.php @@ -3,12 +3,12 @@ namespace App\Models; use App\Pagebuilder\Field; +use App\Support\Images; use App\Support\Permissions\Audiences; use App\Support\RichText; use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; -use Illuminate\Support\Facades\Storage; /** * Eigene Kachel auf der Startseite („Administration → Portal → Startseite“). @@ -46,7 +46,7 @@ class DashboardTile extends Model } }); - static::deleted(fn (DashboardTile $tile) => $tile->image_path && Storage::disk('uploads')->delete($tile->image_path)); + // Das Bild bleibt in der Mediathek (evtl. auch anderswo eingebunden) – aufräumen lässt es sich dort. } protected function casts(): array @@ -82,7 +82,7 @@ class DashboardTile extends Model 'tile' => [ 'type' => $this->type, 'title' => $this->title, - 'image_url' => $this->image_path ? Storage::disk('uploads')->url($this->image_path) : null, + 'image_url' => app(Images::class)->url($this->image_path, null), 'url' => $this->url, 'new_tab' => $this->new_tab, 'alt' => $this->alt ?: '', diff --git a/app/Models/Media.php b/app/Models/Media.php new file mode 100644 index 00000000..c997e3d1 --- /dev/null +++ b/app/Models/Media.php @@ -0,0 +1,98 @@ + 'array', + 'size' => 'integer', + 'width' => 'integer', + 'height' => 'integer', + ]; + } + + /** + * @return BelongsTo + */ + public function uploader(): BelongsTo + { + return $this->belongsTo(User::class, 'uploaded_by'); + } + + /** + * @return HasMany + */ + public function usages(): HasMany + { + return $this->hasMany(MediaUsage::class); + } + + public function fileExists(): bool + { + return Storage::disk($this->disk ?: 'uploads')->exists($this->path); + } + + /** + * Adresse des Bilds – null, wenn die Datei fehlt. + * + * @param string|null $variant „thumb“, „large“ oder null für das Original + */ + public function url(?string $variant = null): ?string + { + // „?v=“ folgt dem Änderungszeitpunkt der Datei (Ersetzen setzt ihn weiter) – so + // haben Mediathek, Seiten und Beiträge dieselbe Adresse und teilen sich den Cache. + return app(Images::class)->url($this->path, $variant); + } + + public function displayName(): string + { + return $this->original_name ?: basename($this->path); + } + + /** + * Für Mediathek und Bildauswahl. + * + * @return array + */ + public function toLibraryArray(): array + { + $url = $this->url(); + + return [ + 'id' => $this->id, + 'path' => $this->path, + 'url' => $url, + 'thumb_url' => $url ? $this->url('thumb') : null, + 'name' => $this->displayName(), + 'alt' => $this->alt ?? '', + 'caption' => $this->caption ?? '', + 'tags' => $this->tags ?? [], + 'mime' => $this->mime, + 'size' => $this->size, + 'width' => $this->width, + 'height' => $this->height, + 'missing' => $url === null, + 'uploader' => $this->relationLoaded('uploader') && $this->uploader ? ['id' => $this->uploader->id, 'name' => $this->uploader->name] : null, + 'usage_count' => $this->usages_count ?? null, + 'created_at' => $this->created_at?->toIso8601String(), + 'updated_at' => $this->updated_at?->toIso8601String(), + ]; + } +} diff --git a/app/Models/MediaUsage.php b/app/Models/MediaUsage.php new file mode 100644 index 00000000..05f31a51 --- /dev/null +++ b/app/Models/MediaUsage.php @@ -0,0 +1,34 @@ + 'boolean', + 'source_id' => 'integer', + 'created_at' => 'datetime', + ]; + } + + /** + * @return BelongsTo + */ + public function media(): BelongsTo + { + return $this->belongsTo(Media::class); + } +} diff --git a/app/Pagebuilder/Blocks.php b/app/Pagebuilder/Blocks.php index fd11e8c5..09333197 100644 --- a/app/Pagebuilder/Blocks.php +++ b/app/Pagebuilder/Blocks.php @@ -5,7 +5,7 @@ namespace App\Pagebuilder; use App\Http\Resources\PersonResource; use App\Models\User; use App\Plugins\Hooks; -use Illuminate\Support\Facades\Storage; +use App\Support\Images; /** * Registry der Pagebuilder-Blöcke. Der Kern bringt Layout- und Inhaltsblöcke @@ -66,9 +66,13 @@ class Blocks return array_values(array_map(fn (BlockType $type) => $type->toArray(), $this->all())); } + /** + * Adresse eines Bilds – null, wenn die Datei fehlt (z. B. in der Mediathek + * gelöscht): Der Block zeigt dann seinen Platzhalter. + */ public static function imageUrl(?string $path): ?string { - return $path ? Storage::disk('uploads')->url($path) : null; + return app(Images::class)->url($path, null); } private function registerLayout(): void diff --git a/app/Pagebuilder/Content.php b/app/Pagebuilder/Content.php index ea9af10b..ca7ec0f1 100644 --- a/app/Pagebuilder/Content.php +++ b/app/Pagebuilder/Content.php @@ -2,6 +2,7 @@ namespace App\Pagebuilder; +use App\Media\ImagePaths; use App\Models\User; use App\Plugins\PluginAccess; use App\Support\Permissions\Audiences; @@ -138,7 +139,7 @@ class Content $texts = []; array_walk_recursive($block['data'], function ($value) use (&$texts) { - if (is_string($value) && ! str_starts_with($value, 'pagebuilder/')) { + if (is_string($value) && ! ImagePaths::isCandidate($value)) { $texts[] = strip_tags($value); } }); diff --git a/app/Pagebuilder/Field.php b/app/Pagebuilder/Field.php index b57bec22..409c1f0e 100644 --- a/app/Pagebuilder/Field.php +++ b/app/Pagebuilder/Field.php @@ -2,6 +2,7 @@ namespace App\Pagebuilder; +use App\Media\ImagePaths; use App\Support\Icons; use App\Support\RichText; use Closure; @@ -62,7 +63,7 @@ final class Field return new self($name, 'url', $label, ['default' => $default]); } - /** Hochgeladenes Bild (Pfad im Upload-Speicher). */ + /** Hochgeladenes Bild bzw. Bild aus der Mediathek (Pfad im Upload-Speicher). */ public static function image(string $name, string $label): self { return new self($name, 'image', $label, ['default' => null]); @@ -140,7 +141,7 @@ final class Field 'toggle' => (bool) $value, 'number' => max($this->options['min'], min($this->options['max'], is_numeric($value) ? (int) $value : $this->options['default'])), 'url' => self::safeUrl($value), - 'image' => is_string($value) && preg_match('#^pagebuilder/[A-Za-z0-9/_.-]+$#', $value) && ! str_contains($value, '..') ? $value : null, + 'image' => ImagePaths::isCandidate($value) ? $value : null, 'people', 'ids' => array_values(array_slice(array_unique(array_filter(array_map('intval', is_array($value) ? $value : []))), 0, $this->options['max'])), 'table' => $this->sanitizeTable($value), 'icon' => Icons::has($value) ? $value : $this->options['default'], diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index cca666de..05b90cf1 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -7,6 +7,11 @@ use App\Dashboard\Widgets; use App\Editorial\Editorial; use App\Identity\Entra\EntraDriver; use App\Identity\IdentityDrivers; +use App\Media\EditorialMedia; +use App\Media\ImagePaths; +use App\Media\MediaLibrary; +use App\Media\MediaUsages; +use App\Models\DashboardTile; use App\Models\IdentityProvider; use App\Models\User; use App\Pagebuilder\Blocks; @@ -69,6 +74,8 @@ class AppServiceProvider extends ServiceProvider return $drivers; }); $this->app->singleton(Editorial::class); + $this->app->singleton(MediaUsages::class); + $this->app->singleton(MediaLibrary::class); $this->app->singleton(BackgroundTasks::class); $this->app->singleton(InstalledVersion::class); $this->app->singleton(UpdateProgress::class); @@ -79,9 +86,11 @@ class AppServiceProvider extends ServiceProvider { CoreWidgets::register($this->app->make(Widgets::class)); - $this->app->make(Navigation::class)->add('editorial', 'Redaktion', '/redaktion', active: ['editorial', 'pages.editor', 'news.editor.*', 'forms.builder'], sort: 85, + $this->app->make(Navigation::class)->add('editorial', 'Redaktion', '/redaktion', active: ['editorial', 'pages.editor', 'news.editor.*', 'forms.builder', 'media.*'], sort: 85, visible: fn (User $user) => $this->app->make(Editorial::class)->visibleFor($user)); + $this->registerMedia(); + // N+1-Abfragen in Entwicklung und Tests sofort sichtbar machen (docs/PLAN.md, Performance). Model::preventLazyLoading(! $this->app->isProduction()); @@ -115,4 +124,30 @@ class AppServiceProvider extends ServiceProvider } } } + + /** + * Mediathek: Zugang für alle, die in der Redaktion arbeiten, Abschnitt in der + * Redaktion und die Startseiten-Kacheln als Quelle für „Eingebunden in“. + */ + private function registerMedia(): void + { + $editorial = $this->app->make(Editorial::class); + + // Bildauswahl und Hochladen: wer irgendwo in der Redaktion arbeitet (Seiten, Beiträge …) oder die Mediathek verwaltet. + Gate::define('media.use', fn (User $user) => $user->can('media.manage') || $editorial->visibleFor($user, except: 'media')); + + // Abschnitt nur neben anderen Redaktionsbereichen – sonst erschiene „Redaktion“ ohne Inhalte. + $editorial->add('media', 'Mediathek', 'core::EditorialMedia', 90, + fn (User $user) => $editorial->visibleFor($user, except: 'media'), + fn (User $user) => EditorialMedia::props($user)); + + $usages = $this->app->make(MediaUsages::class); + $usages->add('dashboard_tiles', 'Startseiten-Kacheln', + fn (DashboardTile $tile) => [ + ['context' => 'Kachelbild', 'label' => $tile->name ?: (string) $tile->title, 'url' => '/admin/kacheln', 'draft' => $tile->is_active === false, 'paths' => [$tile->image_path]], + ['context' => ImagePaths::HTML_CONTEXT, 'label' => $tile->name ?: (string) $tile->title, 'url' => '/admin/kacheln', 'draft' => $tile->is_active === false, 'paths' => ImagePaths::fromHtml($tile->body_html)], + ], + fn (callable $each) => DashboardTile::query()->chunkById(100, fn ($tiles) => $tiles->each($each))); + $usages->watch('dashboard_tiles', DashboardTile::class, ['image_path', 'body_html', 'name', 'title', 'is_active']); + } } diff --git a/app/Providers/Filament/AdminPanelProvider.php b/app/Providers/Filament/AdminPanelProvider.php index 31b35592..7f80f85e 100644 --- a/app/Providers/Filament/AdminPanelProvider.php +++ b/app/Providers/Filament/AdminPanelProvider.php @@ -57,6 +57,13 @@ class AdminPanelProvider extends PanelProvider ->url(fn () => Feedback::getUrl()), ]) ->navigationItems([ + // Die Mediathek lebt im Portal (Redaktion) – hier nur der Weg dorthin. + NavigationItem::make('Mediathek') + ->url('/redaktion/mediathek') + ->icon(Heroicon::OutlinedPhoto) + ->group('Inhalte') + ->sort(90) + ->visible(fn () => auth()->user()?->can('media.use') ?? false), NavigationItem::make('Zum Portal') ->url('/') ->icon(Heroicon::OutlinedArrowTopRightOnSquare) diff --git a/app/Support/Abilities.php b/app/Support/Abilities.php index 665cd40d..f5c1d1c6 100644 --- a/app/Support/Abilities.php +++ b/app/Support/Abilities.php @@ -27,6 +27,7 @@ class Abilities $this->define('updates.manage', 'Aktualisierungen, Lizenz und Systemzustand', 'System'); $this->define('mail.manage', 'E-Mail-Versand einrichten', 'System'); $this->define('feedback.send', 'Rückmeldungen an den Hersteller senden', 'System'); + $this->define('media.manage', 'Mediathek verwalten: ersetzen, löschen, aufräumen', 'Mediathek'); } public function define(string $ability, string $label, string $group, ?string $resource = null): void diff --git a/app/Support/Demo/DemoContent.php b/app/Support/Demo/DemoContent.php index 77914157..49f9fdd9 100644 --- a/app/Support/Demo/DemoContent.php +++ b/app/Support/Demo/DemoContent.php @@ -2,13 +2,13 @@ namespace App\Support\Demo; +use App\Media\MediaLibrary; use App\Models\DashboardTile; use App\Models\Setting; use App\Models\User; use App\Pagebuilder\Content; use App\Plugins\PluginManager; use App\Support\Branding; -use App\Support\Images; use App\Support\Settings; use Illuminate\Database\Eloquent\Model; use Illuminate\Http\Client\Pool; @@ -170,7 +170,7 @@ class DemoContent } $files = 0; - $images = app(Images::class); + $library = app(MediaLibrary::class); foreach ((array) ($state['files'] ?? []) as $file) { try { @@ -180,7 +180,8 @@ class DemoContent $files++; } - ! empty($file['image']) ? $images->deleteWithVariants((string) $file['path']) : $disk->delete((string) $file['path']); + // Bilder samt Eintrag in der Mediathek entfernen + ! empty($file['image']) ? $library->deletePath((string) $file['path']) : $disk->delete((string) $file['path']); } catch (Throwable) { $warnings[] = "Datei {$file['path']} konnte nicht gelöscht werden."; } diff --git a/app/Support/Images.php b/app/Support/Images.php index b5ac8b4a..8f41b955 100644 --- a/app/Support/Images.php +++ b/app/Support/Images.php @@ -6,6 +6,9 @@ use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; use Intervention\Image\Drivers\Gd\Driver; +use Intervention\Image\Encoders\GifEncoder; +use Intervention\Image\Encoders\JpegEncoder; +use Intervention\Image\Encoders\PngEncoder; use Intervention\Image\Encoders\WebpEncoder; use Intervention\Image\ImageManager; use Throwable; @@ -23,7 +26,10 @@ class Images private const VARIANTS_LARGEST_FIRST = ['large', 'thumb']; - public function createVariants(string $path): void + /** + * @param list|null $only nur diese Varianten (z. B. ['thumb'] für die Mediathek) + */ + public function createVariants(string $path, ?array $only = null): void { $disk = Storage::disk('uploads'); @@ -39,6 +45,10 @@ class Images $image = ImageManager::usingDriver(Driver::class)->decodePath($disk->path($path)); foreach (self::VARIANTS_LARGEST_FIRST as $variant) { + if ($only !== null && ! in_array($variant, $only, true)) { + continue; + } + [$width, $height] = self::VARIANTS[$variant]; $image->coverDown($width, $height); $disk->put($this->variantPath($path, $variant), $image->encode(new WebpEncoder(quality: 82))->toString()); @@ -48,12 +58,6 @@ class Images } } - /** - * Bild für Inhalte (Pagebuilder, Beiträge): Seitenverhältnis bleibt, höchstens - * 2000 Pixel breit, als WebP. GIFs bleiben unverändert (Animationen). - * - * @return string Pfad im Speicher „uploads“ - */ /** * Führt $callback mit dem Pfad einer lokalen Kopie des Uploads aus. * @@ -83,6 +87,12 @@ class Images } } + /** + * Bild für Inhalte (Pagebuilder, Beiträge): Seitenverhältnis bleibt, höchstens + * 2000 Pixel breit, als WebP. GIFs bleiben unverändert (Animationen). + * + * @return string Pfad im Speicher „uploads“ + */ public function storeContentImage(UploadedFile $file, string $directory): string { $disk = Storage::disk('uploads'); @@ -104,6 +114,50 @@ class Images return $name.'.webp'; } + /** + * Datei an Ort und Stelle austauschen (Mediathek „Ersetzen“): Der Pfad bleibt, + * damit jede Einbindung automatisch das neue Bild zeigt. Das Format folgt der + * Dateiendung des bestehenden Pfads; vorhandene Varianten werden neu erzeugt. + */ + public function overwrite(string $path, UploadedFile $file): void + { + $disk = Storage::disk('uploads'); + $previous = (int) @filemtime($disk->path($path)); + $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION)); + $variants = array_values(array_filter(array_keys(self::VARIANTS), fn (string $variant) => $disk->exists($this->variantPath($path, $variant)))); + + if ($extension === 'gif' && $file->getMimeType() === 'image/gif') { + self::withLocalCopy($file, fn (string $local) => $disk->put($path, (string) file_get_contents($local))); + } else { + self::withLocalCopy($file, function (string $local) use ($disk, $path, $extension) { + self::raiseMemoryLimitFor($local); + $image = ImageManager::usingDriver(Driver::class)->decodePath($local); + $image->scaleDown(width: 2000); + $encoded = match ($extension) { + 'jpg', 'jpeg' => $image->encode(new JpegEncoder(quality: 85)), + 'png' => $image->encode(new PngEncoder), + 'gif' => $image->encode(new GifEncoder), + default => $image->encode(new WebpEncoder(quality: 84)), + }; + $disk->put($path, $encoded->toString()); + }); + } + + if ($variants !== []) { + $this->createVariants($path, $variants); + } + + // Der Änderungszeitpunkt steckt in „?v=“ der Adressen (siehe url()): muss sich + // auch beim Ersetzen in derselben Sekunde ändern, damit Browser neu laden. + $modified = max(time(), $previous + 1); + + foreach ([$path, ...array_map(fn (string $variant) => $this->variantPath($path, $variant), $variants)] as $file) { + @touch($disk->path($file), $modified); + } + + clearstatcache(); + } + public function deleteWithVariants(?string $path): void { if (! $path) { @@ -118,16 +172,30 @@ class Images } } - public function url(?string $path, string $variant = 'large'): ?string + /** + * Öffentliche Adresse – null, wenn die Datei fehlt (z. B. in der Mediathek + * gelöscht): Komponenten zeigen dann ihren Platzhalter statt eines kaputten Bilds. + * „?v=“ ändert sich beim Ersetzen, damit Browser trotz langem Cache das neue Bild laden. + * + * @param string|null $variant null = Original + */ + public function url(?string $path, ?string $variant = 'large'): ?string { if (! $path) { return null; } $disk = Storage::disk('uploads'); - $variantPath = $this->variantPath($path, $variant); + $variantPath = $variant ? $this->variantPath($path, $variant) : null; + $file = $variantPath && $disk->exists($variantPath) ? $variantPath : $path; - return $disk->url($disk->exists($variantPath) ? $variantPath : $path); + if ($file === $path && ! $disk->exists($path)) { + return null; + } + + $modified = @filemtime($disk->path($file)); + + return $disk->url($file).($modified ? '?v='.$modified : ''); } /** @@ -170,7 +238,7 @@ class Images }; } - private function variantPath(string $path, string $variant): string + public function variantPath(string $path, string $variant): string { return preg_replace('/\.[^.\/]+$/', '', $path)."-{$variant}.webp"; } diff --git a/database/migrations/2026_10_01_000001_create_media_tables.php b/database/migrations/2026_10_01_000001_create_media_tables.php new file mode 100644 index 00000000..2886fed2 --- /dev/null +++ b/database/migrations/2026_10_01_000001_create_media_tables.php @@ -0,0 +1,53 @@ +id(); + $table->string('disk', 40)->default('uploads'); + $table->string('path')->unique(); + $table->string('original_name')->nullable(); + $table->string('mime', 100)->nullable(); + $table->unsignedBigInteger('size')->nullable(); + $table->unsignedInteger('width')->nullable(); + $table->unsignedInteger('height')->nullable(); + $table->string('alt', 300)->nullable(); + $table->string('caption', 500)->nullable(); + $table->json('tags')->nullable(); + $table->foreignId('uploaded_by')->nullable()->constrained('users')->nullOnDelete(); + $table->timestamps(); + + $table->index('created_at'); + }); + + Schema::create('media_usages', function (Blueprint $table) { + $table->id(); + $table->foreignId('media_id')->constrained('media')->cascadeOnDelete(); + $table->string('source_type', 60); + $table->unsignedBigInteger('source_id'); + $table->string('context', 80); + $table->string('label')->nullable(); + $table->string('url', 1000)->nullable(); + $table->boolean('draft')->default(false); + $table->timestamp('created_at')->nullable(); + + $table->index(['source_type', 'source_id']); + $table->index(['media_id', 'created_at']); + }); + } + + public function down(): void + { + Schema::dropIfExists('media_usages'); + Schema::dropIfExists('media'); + } +}; diff --git a/database/migrations/2026_10_01_000002_import_media_library.php b/database/migrations/2026_10_01_000002_import_media_library.php new file mode 100644 index 00000000..90ca764b --- /dev/null +++ b/database/migrations/2026_10_01_000002_import_media_library.php @@ -0,0 +1,24 @@ +rebuild(); + } catch (Throwable $e) { + Log::warning('Mediathek konnte nicht eingelesen werden: '.$e->getMessage(), ['exception' => $e]); + } + } + + public function down(): void {} +}; diff --git a/plugins-core/events/src/EventsPlugin.php b/plugins-core/events/src/EventsPlugin.php index 4cbfb77a..c6bd6d03 100644 --- a/plugins-core/events/src/EventsPlugin.php +++ b/plugins-core/events/src/EventsPlugin.php @@ -3,6 +3,8 @@ namespace Inhaus\Plugins\Events; use App\Dashboard\Widgets; +use App\Media\ImagePaths; +use App\Media\MediaUsages; use App\Models\User; use App\Pagebuilder\Blocks; use App\Pagebuilder\BlockType; @@ -26,6 +28,14 @@ class EventsPlugin extends Plugin $this->app->make(Abilities::class)->define('events.manage', 'Termine verwalten', 'Termine'); Gate::policy(Event::class, EventPolicy::class); + // Mediathek „Eingebunden in“ + $usages = $this->app->make(MediaUsages::class); + $usages->add('events', 'Termine', fn (Event $event) => [ + ['context' => 'Titelbild', 'label' => $event->title, 'url' => route('events.show', $event, false), 'draft' => $event->is_published === false, 'paths' => [$event->image_path]], + ['context' => ImagePaths::HTML_CONTEXT, 'label' => $event->title, 'url' => route('events.show', $event, false), 'draft' => $event->is_published === false, 'paths' => ImagePaths::fromHtml($event->description_html)], + ], fn (callable $each) => Event::query()->chunkById(100, fn ($events) => $events->each($each))); + $usages->watch('events', Event::class, ['image_path', 'description_html', 'title', 'is_published']); + $this->app->make(Widgets::class)->add('events.upcoming', 'events::Upcoming', 'aside', sort: 20, props: fn (User $user) => [ 'events' => EventResource::collection(Event::query()->upcoming()->visibleTo($user)->limit(4)->get())->resolve(), ], label: 'Termine', mobileSort: 30); diff --git a/plugins-core/events/src/Models/Event.php b/plugins-core/events/src/Models/Event.php index 049a414b..3c468721 100644 --- a/plugins-core/events/src/Models/Event.php +++ b/plugins-core/events/src/Models/Event.php @@ -34,24 +34,17 @@ class Event extends Model } }); - // Bildvarianten erzeugen bzw. beim Austausch die alten Dateien entfernen. + // Bildvarianten erzeugen. Alte Bilder bleiben in der Mediathek (sie können + // auch anderswo eingebunden sein) und lassen sich dort als „nicht verwendet“ aufräumen. static::saved(function (Event $event): void { if (! $event->wasRecentlyCreated && ! $event->wasChanged('image_path')) { return; } - $previous = $event->wasRecentlyCreated ? null : $event->getOriginal('image_path'); - - if ($previous && $previous !== $event->image_path) { - app(Images::class)->deleteWithVariants($previous); - } - if ($event->image_path) { app(Images::class)->createVariants($event->image_path); } }); - - static::deleted(fn (Event $event) => app(Images::class)->deleteWithVariants($event->image_path)); } protected function casts(): array diff --git a/plugins-core/news/src/Models/NewsPost.php b/plugins-core/news/src/Models/NewsPost.php index cee9feb9..d2cb0d26 100644 --- a/plugins-core/news/src/Models/NewsPost.php +++ b/plugins-core/news/src/Models/NewsPost.php @@ -54,24 +54,17 @@ class NewsPost extends Model } }); - // Bildvarianten erzeugen bzw. beim Austausch die alten Dateien entfernen. + // Bildvarianten erzeugen. Alte Bilder bleiben in der Mediathek (sie können + // auch anderswo eingebunden sein) und lassen sich dort als „nicht verwendet“ aufräumen. static::saved(function (NewsPost $post): void { if (! $post->wasRecentlyCreated && ! $post->wasChanged('cover_path')) { return; } - $previous = $post->wasRecentlyCreated ? null : $post->getOriginal('cover_path'); - - if ($previous && $previous !== $post->cover_path) { - app(Images::class)->deleteWithVariants($previous); - } - if ($post->cover_path) { app(Images::class)->createVariants($post->cover_path); } }); - - static::deleted(fn (NewsPost $post) => app(Images::class)->deleteWithVariants($post->cover_path)); } protected function casts(): array diff --git a/plugins-core/news/src/NewsPlugin.php b/plugins-core/news/src/NewsPlugin.php index 3f72043a..ae8651c6 100644 --- a/plugins-core/news/src/NewsPlugin.php +++ b/plugins-core/news/src/NewsPlugin.php @@ -4,6 +4,8 @@ namespace Inhaus\Plugins\News; use App\Dashboard\Widgets; use App\Editorial\Editorial; +use App\Media\ImagePaths; +use App\Media\MediaUsages; use App\Models\User; use App\Pagebuilder\Blocks; use App\Pagebuilder\BlockType; @@ -15,6 +17,7 @@ use App\Support\Navigation; use Illuminate\Database\Eloquent\Collection; use Illuminate\Http\Request; use Illuminate\Support\Facades\Gate; +use Illuminate\Support\Facades\Schema; use Inhaus\Plugins\News\Http\Resources\NewsPostResource; use Inhaus\Plugins\News\Models\NewsCategory; use Inhaus\Plugins\News\Models\NewsPost; @@ -39,6 +42,7 @@ class NewsPlugin extends Plugin Gate::policy(NewsPost::class, NewsPostPolicy::class); $this->registerWidgets($this->app->make(Widgets::class)); + $this->registerMediaUsages($this->app->make(MediaUsages::class)); $this->app->make(Editorial::class)->add( 'news', @@ -69,6 +73,41 @@ class NewsPlugin extends Plugin })); } + /** + * Mediathek „Eingebunden in“: Titelbild, Bilder im Text und – sobald Beiträge + * mit dem Pagebuilder geschrieben werden – Bilder in der Spalte „content“. + */ + private function registerMediaUsages(MediaUsages $usages): void + { + $usages->add('news', 'Neuigkeiten', function (NewsPost $post) { + $base = ['label' => $post->title, 'url' => route('news.editor.edit', $post, false), 'draft' => $post->status !== NewsPost::PUBLISHED]; + $entries = [ + [...$base, 'context' => 'Titelbild', 'paths' => [$post->cover_path]], + [...$base, 'context' => ImagePaths::HTML_CONTEXT, 'paths' => [...ImagePaths::fromHtml($post->body_html), ...ImagePaths::fromHtml($post->body)]], + ]; + + if (self::hasContentColumn()) { + $content = $post->getAttribute('content'); + $content = is_string($content) ? json_decode($content, true) : $content; + + foreach (ImagePaths::fromContent(is_array($content) ? $content : null) as $context => $paths) { + $entries[] = [...$base, 'context' => $context, 'paths' => $paths]; + } + } + + return $entries; + }, fn (callable $each) => NewsPost::query()->chunkById(100, fn ($posts) => $posts->each($each))); + + $usages->watch('news', NewsPost::class); + } + + private static function hasContentColumn(): bool + { + static $has; + + return $has ??= Schema::hasColumn('news_posts', 'content'); + } + private function registerWidgets(Widgets $widgets): void { // Slider: hervorgehobene Beiträge mit Bild, sonst die neuesten mit Bild. diff --git a/plugins-core/pages/resources/js/pages/Editor.vue b/plugins-core/pages/resources/js/pages/Editor.vue index ae16bfea..3ee38148 100644 --- a/plugins-core/pages/resources/js/pages/Editor.vue +++ b/plugins-core/pages/resources/js/pages/Editor.vue @@ -37,6 +37,9 @@ import BlockSettings from '@/pagebuilder/editor/BlockSettings.vue'; import EditorBlockList from '@/pagebuilder/editor/EditorBlockList.vue'; import { clone, createBlock, duplicate as duplicateBlock, locate, walk } from '@/pagebuilder/editor/tree'; import { http } from '@/lib/http'; +import MediaPickerHost from '@/components/media/MediaPickerHost.vue'; +import { collectImagePaths, uploadWithProgress } from '@/components/media/api'; +import { useMediaPicker } from '@/components/media/useMediaPicker'; import { formatTime } from '@/lib/format'; import PublishDialog from '../components/PublishDialog.vue'; import RevisionsDialog from '../components/RevisionsDialog.vue'; @@ -133,14 +136,18 @@ function containsActive(item) { return candidates.some((block) => block.items?.includes(item) || locate(item.blocks, block.id)); } -// ——— Hochladen ——— -async function uploadImage(file) { - const body = new FormData(); - body.append('image', file); - - return http.post(`${base}/bilder`, body); +// ——— Hochladen und Mediathek ——— +// Bilder landen im Verzeichnis der Seite und zugleich in der Mediathek. +async function uploadImage(file, onProgress) { + return uploadWithProgress(`${base}/bilder`, file, { onProgress }); } +const mediaPicker = useMediaPicker({ + upload: uploadImage, + contextLabel: 'Auf dieser Seite', + contextPaths: () => collectImagePaths(working.content), +}); + async function uploadFile(file) { const body = new FormData(); body.append('file', file); @@ -170,6 +177,8 @@ provide('pagebuilder:editor', { containsActive, uploadImage, uploadFile, + // Bildauswahl „Aus der Mediathek“: ({ multiple?, title? }) => Promise<[{ id, path, url, alt, caption, width, height }] | null> + pickMedia: (options) => mediaPicker.pick(options), imageUrl: (path) => `${props.uploadsUrl}/${path}`, }); provide('pagebuilder:list', EditorBlockList); @@ -632,5 +641,6 @@ const canvasWidth = computed(() => devices.find((d) => d.key === device.value).w + diff --git a/plugins-core/pages/src/Http/Controllers/PageEditorController.php b/plugins-core/pages/src/Http/Controllers/PageEditorController.php index bfdfe1f4..4f13d0c1 100644 --- a/plugins-core/pages/src/Http/Controllers/PageEditorController.php +++ b/plugins-core/pages/src/Http/Controllers/PageEditorController.php @@ -3,13 +3,13 @@ namespace Inhaus\Plugins\Pages\Http\Controllers; use App\Http\Controllers\Controller; +use App\Media\MediaLibrary; use App\Models\Role; use App\Models\User; use App\Notifications\PortalNotification; use App\Pagebuilder\Blocks; use App\Pagebuilder\Content; use App\Support\Audit; -use App\Support\Images; use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; @@ -312,14 +312,15 @@ class PageEditorController extends Controller return response()->json(['ok' => true]); } - public function uploadImage(Request $request, Page $page, Images $images): JsonResponse + public function uploadImage(Request $request, Page $page, MediaLibrary $library): JsonResponse { Gate::authorize('update', $page); $request->validate(['image' => ['required', File::image()->types(['jpg', 'jpeg', 'png', 'webp', 'gif'])->max(15 * 1024)]]); - $path = $images->storeContentImage($request->file('image'), 'pagebuilder/pages/'.$page->id); + // Landet zugleich in der Mediathek. + $media = $library->store($request->file('image'), 'pagebuilder/pages/'.$page->id, $request->user()); - return response()->json(['path' => $path, 'url' => Blocks::imageUrl($path)]); + return response()->json(['path' => $media->path, 'url' => Blocks::imageUrl($media->path), 'media' => $media->toLibraryArray()]); } public function uploadFile(Request $request, Page $page): JsonResponse diff --git a/plugins-core/pages/src/PagesPlugin.php b/plugins-core/pages/src/PagesPlugin.php index 1167c7b3..3225e603 100644 --- a/plugins-core/pages/src/PagesPlugin.php +++ b/plugins-core/pages/src/PagesPlugin.php @@ -3,6 +3,8 @@ namespace Inhaus\Plugins\Pages; use App\Editorial\Editorial; +use App\Media\ImagePaths; +use App\Media\MediaUsages; use App\Models\User; use App\Pagebuilder\Blocks; use App\Pagebuilder\BlockType; @@ -88,6 +90,7 @@ class PagesPlugin extends Plugin ); $this->registerBlocks($this->app->make(Blocks::class)); + $this->registerMediaUsages($this->app->make(MediaUsages::class)); } public function boot(): void @@ -98,6 +101,33 @@ class PagesPlugin extends Plugin })->everyMinute()->name('pages-scheduled')->withoutOverlapping(5); } + /** + * Mediathek „Eingebunden in“: veröffentlichter Inhalt, Entwurf und geplanter Stand. + */ + private function registerMediaUsages(MediaUsages $usages): void + { + $usages->add('pages', 'Seiten', function (Page $page) { + $entries = []; + $url = route('pages.editor', $page, false); + + foreach (['content' => false, 'scheduled_content' => true, 'draft' => true] as $column => $draft) { + $title = match ($column) { + 'draft' => $page->draft_title ?? $page->title, + 'scheduled_content' => $page->scheduled_title ?? $page->title, + default => $page->title, + }; + + foreach (ImagePaths::fromContent($page->{$column}) as $context => $paths) { + $entries[] = ['context' => $context, 'label' => $title, 'url' => $url, 'draft' => $draft, 'paths' => $paths]; + } + } + + return $entries; + }, fn (callable $each) => Page::query()->chunkById(50, fn ($pages) => $pages->each($each))); + + $usages->watch('pages', Page::class, ['content', 'draft', 'scheduled_content', 'title', 'draft_title', 'scheduled_title']); + } + private function registerBlocks(Blocks $blocks): void { $blocks->add(BlockType::make('downloads', 'Downloads', 'file-down', 'media', 'pages::Downloads') diff --git a/resources/js/components/RichTextEditor.vue b/resources/js/components/RichTextEditor.vue index 6d02dc05..937866d4 100644 --- a/resources/js/components/RichTextEditor.vue +++ b/resources/js/components/RichTextEditor.vue @@ -10,6 +10,7 @@ import { Heading2, Heading3, ImagePlus, + Images, Italic, Link as LinkIcon, List, @@ -25,13 +26,16 @@ import { /** * Formatierter Text (TipTap). Liefert HTML – bereinigt wird auf dem Server - * (App\Support\RichText::sanitize). Bilder nur, wenn uploadImage übergeben wird. + * (App\Support\RichText::sanitize). Bilder nur, wenn uploadImage übergeben wird; + * mit pickImage (z. B. editor.pickMedia der Bildauswahl) zusätzlich „Aus der Mediathek“. */ const props = defineProps({ modelValue: { type: String, default: '' }, placeholder: { type: String, default: '' }, headings: { type: Array, default: () => [2, 3] }, uploadImage: { type: Function, default: null }, + /** ({ multiple }) => Promise<[{ url, alt }] | null> */ + pickImage: { type: Function, default: null }, minHeight: { type: String, default: '' }, bordered: { type: Boolean, default: false }, }); @@ -110,6 +114,16 @@ async function insertImage(event) { } } +async function pickImages() { + const items = await props.pickImage({ multiple: true }); + + if (!items?.length) return; + + const chain = editor.value.chain().focus(); + items.forEach((item) => chain.setImage({ src: item.url, alt: item.alt ?? '' })); + chain.run(); +} + const buttonClass = (active) => [ 'grid size-8 place-items-center rounded-md transition-colors disabled:opacity-40', active ? 'bg-brand-soft text-brand-soft-foreground' : 'text-muted-foreground hover:bg-accent hover:text-foreground', @@ -144,6 +158,7 @@ const buttonClass = (active) => [ + diff --git a/resources/js/components/editorial/EditorialMedia.vue b/resources/js/components/editorial/EditorialMedia.vue new file mode 100644 index 00000000..b1ecfbf3 --- /dev/null +++ b/resources/js/components/editorial/EditorialMedia.vue @@ -0,0 +1,37 @@ + + + diff --git a/resources/js/components/media/MediaDetails.vue b/resources/js/components/media/MediaDetails.vue new file mode 100644 index 00000000..728e00be --- /dev/null +++ b/resources/js/components/media/MediaDetails.vue @@ -0,0 +1,218 @@ + + +