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

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 20:05:50 +00:00

245 lines
8.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

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

<?php
namespace App\Support;
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;
/**
* Erzeugt aus hochgeladenen Titelbildern feste Größen im 16:9-Format (WebP),
* damit Listen und Startseite keine Originalbilder laden müssen.
*/
class Images
{
public const VARIANTS = [
'thumb' => [480, 270],
'large' => [1600, 900],
];
private const VARIANTS_LARGEST_FIRST = ['large', 'thumb'];
/**
* @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');
if (! $disk->exists($path)) {
return;
}
try {
// Nur eine Kopie in voller Auflösung im Speicher: erst auf die größte
// Variante verkleinern, daraus dann die kleineren ableiten.
// Wichtig bei Shared Hosting mit 128 MB memory_limit und Handyfotos.
self::raiseMemoryLimitFor($disk->path($path));
$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());
}
} catch (Throwable $e) {
report($e);
}
}
/**
* Führt $callback mit dem Pfad einer lokalen Kopie des Uploads aus.
*
* Die Datei wird erst per move_uploaded_file ins eigene storage verschoben:
* Auf Shared Hosting sperrt open_basedir oft das direkte Lesen im
* PHP-Upload-Verzeichnis (getRealPath() liefert dann false).
*
* @template T
*
* @param callable(string): T $callback
* @return T
*/
public static function withLocalCopy(UploadedFile $file, callable $callback): mixed
{
$directory = storage_path('app/tmp');
if (! is_dir($directory)) {
@mkdir($directory, 0775, true);
}
$path = $file->move($directory, 'upload-'.Str::random(16))->getPathname();
try {
return $callback($path);
} finally {
@unlink($path);
}
}
/**
* 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');
$name = $directory.'/'.now()->format('Y/m').'/'.Str::random(24);
if ($file->getMimeType() === 'image/gif') {
$disk->putFileAs(dirname($name), $file, basename($name).'.gif');
return $name.'.gif';
}
self::withLocalCopy($file, function (string $path) use ($disk, $name) {
self::raiseMemoryLimitFor($path);
$image = ImageManager::usingDriver(Driver::class)->decodePath($path);
$image->scaleDown(width: 2000);
$disk->put($name.'.webp', $image->encode(new WebpEncoder(quality: 84))->toString());
});
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) {
return;
}
$disk = Storage::disk('uploads');
$disk->delete($path);
foreach (array_keys(self::VARIANTS) as $variant) {
$disk->delete($this->variantPath($path, $variant));
}
}
/**
* Ö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 = $variant ? $this->variantPath($path, $variant) : null;
$file = $variantPath && $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 : '');
}
/**
* GD hält Bilder unkomprimiert im Speicher (4 Byte je Pixel) – ein Handyfoto
* mit 12 Megapixeln braucht so allein ~48 MB. Wie WordPress heben wir das
* Limit für die Bildverarbeitung bei Bedarf auf mindestens 256 MB an.
*/
public static function raiseMemoryLimitFor(string $file): void
{
$size = @getimagesize($file);
$needed = $size ? (int) ($size[0] * $size[1] * 4 * 1.8) : 0;
$current = self::bytes((string) ini_get('memory_limit'));
if ($current === -1) {
return;
}
$target = max(256 * 1024 * 1024, memory_get_usage() + $needed);
if ($current < $target) {
@ini_set('memory_limit', (string) $target);
}
}
private static function bytes(string $value): int
{
$value = trim($value);
if ($value === '' || $value === '-1') {
return -1;
}
$number = (int) $value;
return match (strtolower(substr($value, -1))) {
'g' => $number * 1024 ** 3,
'm' => $number * 1024 ** 2,
'k' => $number * 1024,
default => $number,
};
}
public function variantPath(string $path, string $variant): string
{
return preg_replace('/\.[^.\/]+$/', '', $path)."-{$variant}.webp";
}
}