presseportale/app/Services/PressRelease/PressReleaseAttachmentStorage.php
Kevin Adametz 6250b0bab4 media: PM-Medien privat ausliefern + Vorschau-Signatur (M4, M5, Fix#4/#5)
- Neue PM-Bilder/Anhänge liegen auf der privaten local-Disk; Auslieferung
  über kontrollierte Media-Routen mit gemeinsamer Zugriffslogik
  (AuthorizesPressReleaseMediaAccess). Öffentliche Medien werden aus den
  geladenen Modellen ermittelt (weniger Queries) und länger gecacht.
- Anonyme Token-Vorschau lädt Bilder über temporär signierte URLs (Fix#5).
- API-Resource baut Variant-URLs über die Media-Route statt /storage
  (Fix#4). Storage-Schicht prüft zusätzlich den serverseitigen MIME-Type (M5).
- press-releases:privatize-media migriert Bestandsmedien.

Deployment: einmalig `php artisan press-releases:privatize-media` ausführen.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 13:48:06 +00:00

119 lines
3.9 KiB
PHP

<?php
namespace App\Services\PressRelease;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use RuntimeException;
/**
* Storage for press release attachments (PDFs and other documents).
*
* Files are stored on the private `local` disk under
* press-releases/{id}/attachments/{uuid}-{slug}.{ext}
*
* Access is served through a controller which checks publication state or the
* authenticated user's policy.
*/
class PressReleaseAttachmentStorage
{
public const MAX_BYTES = 25 * 1024 * 1024;
/** @var list<string> */
public const ALLOWED_EXTENSIONS = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'zip', 'txt'];
/** @var list<string> */
public const ALLOWED_MIMES = [
'application/pdf',
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.ms-powerpoint',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/zip',
'application/x-zip-compressed',
'text/plain',
];
/**
* Store the uploaded attachment for the given press release.
*
* @return array{disk:string,path:string,original_name:string,mime:string,size:int}
*/
public function store(UploadedFile $upload, int $pressReleaseId, string $diskName = 'local'): array
{
$this->assertValidUpload($upload);
$extension = strtolower($upload->getClientOriginalExtension() ?: $upload->extension());
$originalName = $upload->getClientOriginalName();
$baseSlug = Str::slug(pathinfo($originalName, PATHINFO_FILENAME)) ?: 'attachment';
$baseSlug = Str::limit($baseSlug, 60, '');
$directory = sprintf('press-releases/%d/attachments', $pressReleaseId);
$filename = Str::uuid()->toString().'-'.$baseSlug.'.'.$extension;
$relativePath = $directory.'/'.$filename;
$disk = $this->disk($diskName);
$stream = fopen($upload->getRealPath(), 'r');
if ($stream === false) {
throw new RuntimeException('Could not open uploaded file stream.');
}
try {
$disk->put($relativePath, $stream, $diskName === 'public' ? 'public' : 'private');
} finally {
if (is_resource($stream)) {
fclose($stream);
}
}
return [
'disk' => $diskName,
'path' => $relativePath,
'original_name' => $originalName,
'mime' => $upload->getMimeType() ?: 'application/octet-stream',
'size' => $upload->getSize() ?: 0,
];
}
public function delete(string $disk, string $path): void
{
if (blank($path)) {
return;
}
try {
Storage::disk($disk)->delete($path);
} catch (\Throwable) {
// Swallow — deletion is best-effort; a missing file is acceptable.
}
}
private function assertValidUpload(UploadedFile $upload): void
{
$extension = strtolower($upload->getClientOriginalExtension() ?: $upload->extension());
if (! in_array($extension, self::ALLOWED_EXTENSIONS, true)) {
throw new RuntimeException('Unsupported attachment extension: '.$extension);
}
$mime = $upload->getMimeType();
if ($mime === null || ! in_array($mime, self::ALLOWED_MIMES, true)) {
throw new RuntimeException('Unsupported attachment MIME type: '.($mime ?? 'unknown'));
}
if ($upload->getSize() > self::MAX_BYTES) {
throw new RuntimeException('Attachment exceeds maximum size.');
}
}
private function disk(string $diskName): Filesystem
{
return Storage::disk($diskName);
}
}