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:
parent
3b72b5327e
commit
694ccf6ae0
46 changed files with 3101 additions and 89 deletions
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
232
app/Http/Controllers/MediaController.php
Normal file
232
app/Http/Controllers/MediaController.php
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Media\MediaLibrary;
|
||||
use App\Media\MediaUsages;
|
||||
use App\Models\Media;
|
||||
use App\Models\MediaUsage;
|
||||
use App\Models\User;
|
||||
use App\Support\Audit;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Rules\File;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
* Mediathek im Portal (Redaktion) und JSON-Schnittstelle der Bildauswahl.
|
||||
* Benutzen und Hochladen: „media.use“, Ersetzen und Löschen: „media.manage“.
|
||||
*/
|
||||
class MediaController extends Controller
|
||||
{
|
||||
public const PER_PAGE = 48;
|
||||
|
||||
public function __construct(private readonly MediaLibrary $library, private readonly MediaUsages $usages) {}
|
||||
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
return Inertia::render('Media/Index', [
|
||||
'filters' => (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<Media> $query
|
||||
* @param array<string, mixed> $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<string, mixed> $filters
|
||||
*/
|
||||
private function countFor(array $filters): int
|
||||
{
|
||||
$query = Media::query();
|
||||
$this->applyFilters($query, $filters, false);
|
||||
|
||||
return $query->count();
|
||||
}
|
||||
}
|
||||
29
app/Media/EditorialMedia.php
Normal file
29
app/Media/EditorialMedia.php
Normal 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
148
app/Media/ImagePaths.php
Normal 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
189
app/Media/MediaLibrary.php
Normal 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
198
app/Media/MediaUsages.php
Normal 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');
|
||||
}
|
||||
}
|
||||
|
|
@ -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 ?: '',
|
||||
|
|
|
|||
98
app/Models/Media.php
Normal file
98
app/Models/Media.php
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Support\Images;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* Ein Bild der Mediathek. Eingebunden wird es überall über seinen Pfad im
|
||||
* Speicher „uploads“ – Inhalte speichern weiterhin den Pfad, nicht die ID.
|
||||
*/
|
||||
#[Fillable(['disk', 'path', 'original_name', 'mime', 'size', 'width', 'height', 'alt', 'caption', 'tags', 'uploaded_by'])]
|
||||
class Media extends Model
|
||||
{
|
||||
protected $table = 'media';
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'tags' => 'array',
|
||||
'size' => 'integer',
|
||||
'width' => 'integer',
|
||||
'height' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
public function uploader(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'uploaded_by');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<MediaUsage, $this>
|
||||
*/
|
||||
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<string, mixed>
|
||||
*/
|
||||
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(),
|
||||
];
|
||||
}
|
||||
}
|
||||
34
app/Models/MediaUsage.php
Normal file
34
app/Models/MediaUsage.php
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* „Eingebunden in“: eine Stelle, an der ein Bild der Mediathek verwendet wird.
|
||||
* Wird von App\Media\MediaUsages bei jedem Speichern der Quelle neu berechnet.
|
||||
*/
|
||||
#[Fillable(['media_id', 'source_type', 'source_id', 'context', 'label', 'url', 'draft', 'created_at'])]
|
||||
class MediaUsage extends Model
|
||||
{
|
||||
public const UPDATED_AT = null;
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'draft' => 'boolean',
|
||||
'source_id' => 'integer',
|
||||
'created_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Media, $this>
|
||||
*/
|
||||
public function media(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Media::class);
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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'],
|
||||
|
|
|
|||
|
|
@ -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']);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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.";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<string>|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";
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue