Upload PDFs to the library, link them from any link target, show them in a viewer

PDFs go through the same upload field as images, are checked by their content and kept
unchanged in their own table. Every link field can pick one, and a page that links a PDF
opens it in a dialog with the browser's own viewer; touch devices and browsers without a
viewer get a new tab instead.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
kantarciandClaude Opus 5 committed 2026-09-22 07:56:29 +02:00
1 parent 04927b9563
commit e8a9dcdf5c
20 files changed
+667 -30

No files matched your search

+114 -6
View File
@@ -2,6 +2,7 @@
namespace App\Controller;
use App\Content\DocumentLibrary;
use App\Content\MediaLibrary;
use App\Content\SiteSettings;
use App\Domain\StaleWrite;
@@ -10,12 +11,13 @@ use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
final class MediaController extends AbstractController
{
public function __construct(private MediaLibrary $media, private CsrfTokenManagerInterface $csrf, private SiteSettings $siteSettings)
public function __construct(private MediaLibrary $media, private CsrfTokenManagerInterface $csrf, private SiteSettings $siteSettings, private DocumentLibrary $documents)
{
}
@@ -27,7 +29,7 @@ final class MediaController extends AbstractController
$archived = $request->query->getBoolean('archiv');
$query = mb_substr(trim($request->query->getString('q')), 0, 160);
$library = $this->media->page($request->query->getInt('seite', 1), $archived, query: $query);
$view = ['library' => $library, 'archived' => $archived, 'query' => $query];
$view = ['library' => $library, 'archived' => $archived, 'query' => $query, 'documents' => $this->documents->list($archived)];
if ($request->isXmlHttpRequest()) {
return $this->json([
'html' => $this->renderView('admin/media-results.html.twig', $view),
@@ -53,16 +55,18 @@ final class MediaController extends AbstractController
$done = 0;
foreach ($files as $file) {
try {
$this->media->upload($file);
// Bilder und PDFs gehen durch dasselbe Feld. Welche Art es ist, entscheidet der
// Inhalt der Datei; die Endung zaehlt nur, wenn der Inhalt nichts sagt.
$this->isPdf($file) ? $this->documents->upload($file) : $this->media->upload($file);
++$done;
} catch (\InvalidArgumentException $error) {
return $this->back($request, sprintf('%s (%s)%s', $error->getMessage(), $file->getClientOriginalName(), $done > 0 ? sprintf(' %d Bild(er) davor wurden hochgeladen.', $done) : ''));
return $this->back($request, sprintf('%s (%s)%s', $error->getMessage(), $file->getClientOriginalName(), $done > 0 ? sprintf(' %d Datei(en) davor wurden hochgeladen.', $done) : ''));
} catch (\RuntimeException) {
return $this->back($request, 'Das Bild konnte nicht verarbeitet werden. GD/WebP und die Schreibrechte des Medienordners prüfen.');
return $this->back($request, sprintf('%s konnte nicht verarbeitet werden. GD/WebP und die Schreibrechte des Medienordners prüfen.', $file->getClientOriginalName()));
}
}
return $this->back($request, sprintf('%d Bild(er) hochgeladen.', $done), 'success');
return $this->back($request, sprintf('%d Datei(en) hochgeladen.', $done), 'success');
}
#[Route('/%kant.admin_path%/media/{id}', name: 'admin_media_save', requirements: ['id' => '[a-f0-9]{32}'], methods: ['POST'])]
@@ -91,6 +95,38 @@ final class MediaController extends AbstractController
return $this->back($request, 'Die Bildangaben wurden gespeichert.', 'success');
}
#[Route('/%kant.admin_path%/media/dokument/{id}', name: 'admin_document_save', requirements: ['id' => '[a-f0-9]{32}'], methods: ['POST'])]
public function formUpdateDocument(Request $request, string $id): Response
{
$this->denyAccessUnlessGranted('ROLE_EDITOR');
if (!$this->isCsrfTokenValid('media-form', $request->request->getString('_csrf_token'))) {
return $this->back($request, 'Deine Sitzung ist abgelaufen. Bitte melde dich erneut an.');
}
if (!$this->documents->find($id)) {
throw $this->createNotFoundException();
}
try {
$this->documents->update($id, [
'title' => $request->request->getString('title'),
'archived' => $request->request->getBoolean('archived'),
'version' => $request->request->getInt('version'),
]);
} catch (StaleWrite) {
return $this->back($request, 'Das Dokument wurde inzwischen anderswo geändert. Lade die Seite neu und trage die Angaben erneut ein.');
} catch (\InvalidArgumentException $error) {
return $this->back($request, $error->getMessage());
}
return $this->back($request, 'Die Angaben zum Dokument wurden gespeichert.', 'success');
}
private function isPdf(UploadedFile $file): bool
{
$mime = $file->getMimeType();
return 'application/pdf' === $mime || (!str_starts_with((string) $mime, 'image/') && 'pdf' === strtolower($file->getClientOriginalExtension()));
}
/** Back to the page the form was on, so a change does not jump to the first page. */
private function back(Request $request, string $message, string $type = 'error'): Response
{
@@ -112,6 +148,53 @@ final class MediaController extends AbstractController
return $this->json(['items' => $this->media->list(), 'csrfToken' => $this->csrf->getToken('media')->getValue()]);
}
/** Die PDFs fuer die Auswahl im Link-Feld. Wenige genug, um sie auf einmal zu schicken. */
#[Route('/%kant.admin_path%/api/dokumente', methods: ['GET'])]
public function listDocuments(): Response
{
$this->denyAccessUnlessGranted('ROLE_EDITOR');
return $this->json(['items' => $this->documents->list(), 'csrfToken' => $this->csrf->getToken('media')->getValue()]);
}
#[Route('/%kant.admin_path%/api/dokumente/upload', methods: ['POST'])]
#[Route('/%kant.admin_path%/api/dokumente/{id}', requirements: ['id' => '[a-f0-9]{32}'], methods: ['POST'])]
public function writeDocument(Request $request, ?string $id = null): Response
{
$this->denyAccessUnlessGranted('ROLE_EDITOR');
if (!$this->isCsrfTokenValid('media', $request->headers->get('X-CSRF-Token'))) {
return $this->json(['error' => 'Sitzung abgelaufen. Bitte erneut anmelden.'], 403);
}
try {
if (null === $id) {
$file = $request->files->get('file');
if (!$file instanceof UploadedFile) {
throw new \InvalidArgumentException('Keine Datei empfangen. Bitte das PHP-Uploadlimit und die Dateigröße prüfen.');
}
return $this->json(['item' => $this->documents->upload($file)], 201);
}
if (!$this->documents->find($id)) {
throw $this->createNotFoundException();
}
if (strlen($request->getContent()) > 4096) {
throw new \InvalidArgumentException('Angaben zum Dokument sind zu groß.');
}
$data = json_decode($request->getContent(), true, 16, JSON_THROW_ON_ERROR);
if (!is_array($data)) {
throw new \InvalidArgumentException('Ungültige Angaben zum Dokument.');
}
return $this->json(['item' => $this->documents->update($id, $data)]);
} catch (StaleWrite) {
return $this->json(['error' => 'Das Dokument wurde inzwischen geändert. Die Auswahl bitte neu öffnen.'], 409);
} catch (\InvalidArgumentException|\JsonException $error) {
return $this->json(['error' => $error->getMessage()], 422);
} catch (\RuntimeException) {
return $this->json(['error' => 'Das Dokument konnte nicht gespeichert werden. Schreibrechte des Medienordners prüfen.'], 503);
}
}
#[Route('/%kant.admin_path%/api/media/{id}', requirements: ['id' => '[a-f0-9]{32}'], methods: ['GET'])]
public function read(string $id): Response
{
@@ -240,4 +323,29 @@ final class MediaController extends AbstractController
return new BinaryFileResponse($path, headers: ['Content-Type' => 'image/webp', 'X-Content-Type-Options' => 'nosniff', 'Cache-Control' => 'public, max-age=31536000, immutable', 'Content-Security-Policy' => "default-src 'none'"]);
}
/**
* Ein PDF, so wie es hochgeladen wurde.
*
* inline, damit der Browser es anzeigt statt es abzulegen - mit dem Titel als Dateinamen fuer
* den Fall, dass jemand es speichert. Einbetten darf es nur die eigene Website: der
* Betrachter zeigt es in einem Rahmen, eine fremde Seite soll das nicht koennen.
*/
#[Route('/media/{id}.pdf', name: 'document_serve', requirements: ['id' => '[a-f0-9]{32}'], methods: ['GET'])]
public function serveDocument(string $id): Response
{
$path = $this->documents->file($id) ?? throw $this->createNotFoundException();
$name = trim(preg_replace('/[\\\\\/\x00-\x1F\x7F"]+/u', ' ', $this->documents->find($id)['title'])).'.pdf';
$fallback = trim(preg_replace('/[^A-Za-z0-9 ._-]+/', '-', (string) iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $name)), '- ');
$response = new BinaryFileResponse($path, headers: [
'Content-Type' => 'application/pdf',
'X-Content-Type-Options' => 'nosniff',
'Cache-Control' => 'public, max-age=86400',
'Content-Security-Policy' => "frame-ancestors 'self'",
'X-Robots-Tag' => 'noindex',
]);
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $name, str_ends_with($fallback, '.pdf') && '.pdf' !== $fallback ? $fallback : 'dokument.pdf');
return $response;
}
}