Biete Tabellen und Bilder im gemeinsamen Texteditor an und setze sie in Ansicht und PDF
Tabellen und Bilder gehören zur festen Auswahl von FormattedText. Ein Bild ist ein Verweis auf eine freigegebene Bildfassung und kommt per Picker aus dem Medienbestand; der Stand schreibt die Bildfassung mit fest, die Rechte entscheidet DecideAccess. Der PDF-Satz (PdfFlow) ist für Übung und kommende Dokumente gemeinsam; PdfDocument kann zusätzlich Bilder, Flächen, Verweise und Lesezeichen, Belege bleiben byte-gleich. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
219962daff
commit
c57a506f85
27 files changed
+1729
-219
No files matched your search
@@ -23,7 +23,7 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
'path' => $path !== '' ? $path : $node->element->working_title,
|
||||
'requirement' => CompositionMember::REQUIRED,
|
||||
'variant' => null,
|
||||
]];
|
||||
], ...$this->embeddedImages($node, $path !== '' ? $path : $node->element->working_title, null)];
|
||||
}
|
||||
|
||||
if (in_array($node->composition_id, $stack, true)) {
|
||||
@@ -51,6 +51,10 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
'variant' => $variantKey,
|
||||
];
|
||||
|
||||
foreach ($this->embeddedImages($member->contentElementVersion, $segment, $variantKey) as $image) {
|
||||
$rows[] = $image;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -79,6 +83,34 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bilder, auf die ein Text verweist, gehören zum Inhalt des Stands: Nur was im Stand steht, darf ein Mitglied sehen
|
||||
* (`DecideAccess`), und eine Sperre des Bildes wirkt über denselben Weg. Ein fehlendes Bild macht den Text nicht
|
||||
* unbrauchbar, daher „ergänzend“.
|
||||
*
|
||||
* @return list<array{version_id: int, role: string, path: string, requirement: string, variant: string|null}>
|
||||
*/
|
||||
private function embeddedImages(?ContentElementVersion $text, string $path, ?string $variantKey): array
|
||||
{
|
||||
if ($text === null || trim((string) $text->body) === '' || ! str_contains((string) $text->body, 'img')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rows = [];
|
||||
|
||||
foreach (FormattedText::imageIds($text->body) as $id) {
|
||||
$rows[] = [
|
||||
'version_id' => $id,
|
||||
'role' => 'Bild',
|
||||
'path' => $path.' / Bild',
|
||||
'requirement' => CompositionMember::SUPPLEMENTARY,
|
||||
'variant' => $variantKey,
|
||||
];
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
public function resolvedHash(ContentElementVersion|CompositionVersion $node): string
|
||||
{
|
||||
$ids = array_values(array_unique(array_column($this->expand($node), 'version_id')));
|
||||
|
||||
@@ -190,6 +190,44 @@ public function elementReleaseProblem(ContentElementVersion $version): ?string
|
||||
return 'Der Text braucht einen Inhalt.';
|
||||
}
|
||||
|
||||
if ($version->element?->output_class === 'text') {
|
||||
return $this->imageProblem((string) $version->body);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Text verweist auf Bildfassungen des Medienbestands. Festgeschrieben werden kann er nur, wenn jede davon
|
||||
* vorhanden, ein Bild und freigegeben ist; sonst wäre die Ausgabe der Fassung nicht festgelegt.
|
||||
*/
|
||||
public function imageProblem(?string $body): ?string
|
||||
{
|
||||
$ids = FormattedText::imageIds($body);
|
||||
|
||||
if ($ids === []) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$versions = ContentElementVersion::query()->with('element')->whereKey($ids)->get()->keyBy('id');
|
||||
|
||||
foreach ($ids as $id) {
|
||||
$image = $versions->get($id);
|
||||
$title = $image?->element === null ? 'Bild' : (string) ($image->element->display_title ?: $image->element->working_title);
|
||||
|
||||
if ($image === null || $image->element === null || $image->element->output_class !== 'bild') {
|
||||
return 'Der Text verweist auf ein Bild, das es nicht mehr gibt.';
|
||||
}
|
||||
|
||||
if ($image->status === ContentVersionStatus::Gesperrt) {
|
||||
return 'Das Bild „'.$title.'“ ist deaktiviert und kann nicht festgeschrieben werden.';
|
||||
}
|
||||
|
||||
if ($image->status !== ContentVersionStatus::Bereit) {
|
||||
return 'Das Bild „'.$title.'“ ist noch nicht freigegeben.';
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Entitlement\DecideAccess;
|
||||
use App\Domain\Entitlement\Grant;
|
||||
use App\Domain\Media\PdfImage;
|
||||
use App\Http\SignedLink;
|
||||
use App\Models\User;
|
||||
use Closure;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* Bilder in formatierten Texten (ADR-51). Ein Text verweist auf eine Bildfassung; ob und wie sie erscheint, entscheidet
|
||||
* hier wie überall `DecideAccess` für den Stand des Mitglieds: Die Bildfassung gehört zum festgeschriebenen Inhalt des
|
||||
* Stands ({@see ContentResolver}), eine Sperre wirkt, die Berechtigung des Kontos für Bilder gilt.
|
||||
*
|
||||
* - Ansicht: ein kurzlebiger, signierter Link auf die Ausgabe des Bildes (`member.media`, Aktion `ansehen`).
|
||||
* - PDF: das Bild wird mit `laden` entschieden, aus dem abgeleiteten Bestand gelesen und für das PDF aufbereitet.
|
||||
*
|
||||
* Ein Bild ohne Berechtigung ersetzt ein Hinweis an seiner Stelle; der übrige Text bleibt unverändert lesbar.
|
||||
*/
|
||||
final class EmbeddedImages
|
||||
{
|
||||
public function __construct(private readonly DecideAccess $access) {}
|
||||
|
||||
/**
|
||||
* Auflösung für die Vorschau der Redaktion: Bilder zeigt die Verwaltung über ihre eigene Dateiausgabe.
|
||||
*
|
||||
* @return Closure(int): ?array{src: string}
|
||||
*/
|
||||
public static function staff(): Closure
|
||||
{
|
||||
return fn (int $id): array => ['src' => self::staffSource($id)];
|
||||
}
|
||||
|
||||
/** Adresse einer Bildfassung für den Editor und die Vorschau der Verwaltung. */
|
||||
public static function staffSource(int $id): string
|
||||
{
|
||||
return route('content.file', ['version' => $id], false);
|
||||
}
|
||||
|
||||
/** Text für einen Editor der Verwaltung: Bilder tragen ihre Adresse, damit der Editor sie zeigt. */
|
||||
public static function forEditor(?string $value): string
|
||||
{
|
||||
return FormattedText::forEditor(FormattedText::canonical($value), fn (int $id): string => self::staffSource($id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Auflösung für {@see FormattedText::html()}.
|
||||
*
|
||||
* @return Closure(int): ?array{src?: string, alt?: string, note?: string}
|
||||
*/
|
||||
public function forView(User $user, LicenseArticle $article, ArticleRelease $release): Closure
|
||||
{
|
||||
return function (int $id) use ($user, $article, $release): ?array {
|
||||
$decision = $this->decide($user, $article, $release, $id, 'ansehen');
|
||||
|
||||
if ($decision === null) {
|
||||
return ['note' => 'Dieses Bild gibt es nicht mehr.'];
|
||||
}
|
||||
|
||||
if (! $decision['allowed']) {
|
||||
return ['note' => 'Dieses Bild ist derzeit nicht verfügbar.'];
|
||||
}
|
||||
|
||||
return ['src' => SignedLink::temporary('member.media', now()->addMinutes(10), [
|
||||
'article' => $article->id,
|
||||
'release' => $release->id,
|
||||
'version' => $id,
|
||||
'action' => 'ansehen',
|
||||
'reader' => $user->id,
|
||||
])];
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Auflösung für das PDF. Die Bilder, die tatsächlich im PDF stehen, sammelt {@see PdfImages::used()} für den
|
||||
* Ausgabenachweis.
|
||||
*/
|
||||
public function forPdf(User $user, LicenseArticle $article, ArticleRelease $release): PdfImages
|
||||
{
|
||||
return new PdfImages(function (int $id) use ($user, $article, $release): ?array {
|
||||
$decision = $this->decide($user, $article, $release, $id, 'laden');
|
||||
|
||||
if ($decision === null) {
|
||||
return ['note' => 'Bild nicht mehr vorhanden', 'grant' => null, 'version' => null];
|
||||
}
|
||||
|
||||
if (! $decision['allowed']) {
|
||||
return ['note' => 'Bild nicht verfügbar', 'grant' => null, 'version' => null];
|
||||
}
|
||||
|
||||
$file = $decision['version']->metadata['file'] ?? null;
|
||||
$disk = Storage::disk('media_derived');
|
||||
$prepared = is_string($file) && $file !== '' && ! str_contains($file, '..') && $disk->exists($file)
|
||||
? PdfImage::fromBytes((string) $disk->get($file))
|
||||
: null;
|
||||
|
||||
if ($prepared === null) {
|
||||
return ['note' => 'Bild kann nicht gedruckt werden', 'grant' => null, 'version' => null];
|
||||
}
|
||||
|
||||
return $prepared + ['grant' => $decision['grant'], 'version' => $decision['version']];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{allowed: bool, version: ContentElementVersion, grant: ?Grant}|null
|
||||
*/
|
||||
private function decide(User $user, LicenseArticle $article, ArticleRelease $release, int $id, string $action): ?array
|
||||
{
|
||||
$version = ContentElementVersion::query()->with('element')->find($id);
|
||||
|
||||
if (! $version instanceof ContentElementVersion || $version->element === null || $version->element->output_class !== 'bild') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$decision = ($this->access)($user, $article, $release, $version, $action);
|
||||
|
||||
return ['allowed' => $decision->allowed, 'version' => $version, 'grant' => $decision->grant];
|
||||
}
|
||||
}
|
||||
@@ -114,6 +114,7 @@ public function build(User $user, LicenseArticle $article, ArticleRelease $relea
|
||||
{
|
||||
$exercise->loadMissing(['composition', 'variants', 'members.variant', 'members.contentElementVersion.element']);
|
||||
$library = app(LibraryCatalog::class);
|
||||
$images = app(EmbeddedImages::class)->forView($user, $article, $release);
|
||||
$offered = $exercise->variants->filter(fn (CompositionVersionVariant $variant): bool => $selection === null || in_array($variant->key, $selection, true))->values();
|
||||
$chosen = $offered->firstWhere('key', $variantKey) ?? $offered->first();
|
||||
$entries = [];
|
||||
@@ -146,7 +147,7 @@ public function build(User $user, LicenseArticle $article, ArticleRelease $relea
|
||||
'download_grant' => $download?->grant,
|
||||
'state' => $decision->allowed ? 'ok' : ($version->status === ContentVersionStatus::Gesperrt ? 'gesperrt' : 'nicht_lizenziert'),
|
||||
'blocks' => $decision->allowed && $class === 'text' ? FormattedText::blocks($version->body) : null,
|
||||
'html' => $decision->allowed && $class === 'text' ? FormattedText::html($version->body) : null,
|
||||
'html' => $decision->allowed && $class === 'text' ? FormattedText::html($version->body, $images) : null,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Commerce\Receipt\PdfDocument;
|
||||
use Closure;
|
||||
use Transliterator;
|
||||
|
||||
/**
|
||||
@@ -23,7 +24,7 @@ class ExercisePdf
|
||||
|
||||
private PdfDocument $pdf;
|
||||
|
||||
private float $y = self::TOP;
|
||||
private PdfFlow $flow;
|
||||
|
||||
private int $page = 0;
|
||||
|
||||
@@ -64,32 +65,36 @@ public function sections(array $guide): ?array
|
||||
* @param array<string, mixed> $guide
|
||||
* @param list<array<string, mixed>> $sections
|
||||
*/
|
||||
public function render(array $guide, array $sections, string $licensee, string $copyId, string $variantName, string $guideUrl): string
|
||||
public function render(array $guide, array $sections, string $licensee, string $copyId, string $variantName, string $guideUrl, ?PdfImages $images = null): string
|
||||
{
|
||||
$this->pdf = new PdfDocument;
|
||||
$this->page = 0;
|
||||
$this->footer = self::printable('Lizenziert für '.$licensee.' · Lizenzkopie '.$copyId);
|
||||
$this->flow = new PdfFlow($this->pdf, self::LEFT, self::RIGHT, self::TOP, self::BOTTOM, function (): void {
|
||||
$this->closePage();
|
||||
$this->newPage();
|
||||
}, $images === null ? null : Closure::fromCallable($images));
|
||||
$this->newPage();
|
||||
|
||||
$this->write(self::printable((string) $guide['title']), 18, true, 8);
|
||||
$this->flow->write(self::printable((string) $guide['title']), 18, true, 8);
|
||||
|
||||
if ($variantName !== '') {
|
||||
$this->write(self::printable('Variante: '.$variantName), 11, true, 6);
|
||||
$this->flow->write(self::printable('Variante: '.$variantName), 11, true, 6);
|
||||
}
|
||||
|
||||
$this->fact('Lernziel', $guide['learning_goal']);
|
||||
|
||||
if ($guide['duration_minutes'] !== null) {
|
||||
$this->write(self::printable('Dauer: '.$guide['duration_minutes'].($guide['duration_max'] !== null ? ' bis '.$guide['duration_max'] : '').' Minuten'), 10.5, false, 4);
|
||||
$this->flow->write(self::printable('Dauer: '.$guide['duration_minutes'].($guide['duration_max'] !== null ? ' bis '.$guide['duration_max'] : '').' Minuten'), 10.5, false, 4);
|
||||
}
|
||||
|
||||
if (filled($guide['prerequisites'])) {
|
||||
$this->write(self::printable('Voraussetzungen: '.$guide['prerequisites']), 10.5, false, 4);
|
||||
$this->flow->write(self::printable('Voraussetzungen: '.$guide['prerequisites']), 10.5, false, 4);
|
||||
}
|
||||
|
||||
$this->fact('Ausstattung', $guide['material_note']);
|
||||
|
||||
$this->y -= 6;
|
||||
$this->flow->y -= 6;
|
||||
|
||||
foreach ($sections as $section) {
|
||||
$this->section($section, $guideUrl);
|
||||
@@ -108,16 +113,7 @@ public function render(array $guide, array $sections, string $licensee, string $
|
||||
*/
|
||||
public static function printable(string $text): string
|
||||
{
|
||||
$text = strtr($text, ['→' => '->', '←' => '<-', '≥' => '>=', '≤' => '<=', '✓' => '+', '✗' => 'x', '≠' => '!=', '≈' => '~']);
|
||||
$latin = Transliterator::create('Any-Latin; Latin-ASCII');
|
||||
$out = '';
|
||||
|
||||
foreach (mb_str_split($text) as $char) {
|
||||
$encoded = mb_convert_encoding($char, 'Windows-1252', 'UTF-8');
|
||||
$out .= $encoded === '?' && $char !== '?' ? ($latin?->transliterate($char) ?: '?') : $char;
|
||||
}
|
||||
|
||||
return $out;
|
||||
return PdfFlow::printable($text);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -131,16 +127,16 @@ private function section(array $section, string $guideUrl): void
|
||||
$label = in_array($section['class'], ['film', 'audio'], true)
|
||||
? 'Film: '.$title.' - online abrufbar im Mitgliederbereich (geschützte Wiedergabe): '.$guideUrl
|
||||
: 'Material: '.$title.' - im Mitgliederbereich abrufbar: '.$guideUrl;
|
||||
$this->write(self::printable($label), 10, false, 6);
|
||||
$this->flow->write(self::printable($label), 10, false, 6);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->write($title, 12.5, true, 5);
|
||||
$this->flow->write($title, 12.5, true, 5, keep: 40);
|
||||
|
||||
$this->formatted($section['blocks'] ?? []);
|
||||
$this->flow->formatted($section['blocks'] ?? []);
|
||||
|
||||
$this->y -= 4;
|
||||
$this->flow->y -= 4;
|
||||
}
|
||||
|
||||
/** Angabe mit Bezeichnung; formatierte Angaben stehen unter der Bezeichnung, einfache dahinter. */
|
||||
@@ -153,177 +149,20 @@ private function fact(string $label, ?string $value): void
|
||||
}
|
||||
|
||||
if (count($blocks) === 1 && $blocks[0]['type'] === 'paragraph') {
|
||||
$this->runs([['text' => $label.': ', 'bold' => true, 'italic' => false, 'href' => null], ...$blocks[0]['runs']], self::LEFT, 10.5, after: 4);
|
||||
$this->flow->runs([['text' => $label.': ', 'bold' => true, 'italic' => false, 'href' => null], ...$blocks[0]['runs']], self::LEFT, 10.5, after: 4);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->write(self::printable($label.':'), 10.5, true, 2);
|
||||
$this->formatted($blocks);
|
||||
}
|
||||
|
||||
/**
|
||||
* Blöcke aus {@see FormattedText::blocks()}: Absatz, Zwischenüberschrift, Zitat und Listen mit fett und kursiv.
|
||||
*
|
||||
* @param list<array<string, mixed>> $blocks
|
||||
*/
|
||||
private function formatted(array $blocks): void
|
||||
{
|
||||
foreach ($blocks as $block) {
|
||||
match ($block['type']) {
|
||||
'heading' => $this->runs($block['runs'], self::LEFT, 11, bold: true, after: 4),
|
||||
'quote' => $this->runs($block['runs'], self::LEFT + 14, 10.5, italic: true, after: 5),
|
||||
'bullets' => $this->listItems($block['items'], fn (int $n): string => '•'),
|
||||
'numbered' => $this->listItems($block['items'], fn (int $n): string => $n.'.'),
|
||||
default => $this->runs($block['runs'] ?? [], self::LEFT, 10.5, after: 5),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<list<array{text: string, bold: bool, italic: bool, href: ?string}>> $items
|
||||
*/
|
||||
private function listItems(array $items, callable $marker): void
|
||||
{
|
||||
foreach ($items as $index => $item) {
|
||||
$this->room(14);
|
||||
$this->pdf->text(self::LEFT + 4, $this->y, $marker($index + 1), 10.5);
|
||||
$this->runs($item, self::LEFT + 18, 10.5, after: 1);
|
||||
}
|
||||
|
||||
$this->y -= 3;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setzt Textabschnitte mit fett und kursiv in Zeilen um. Die Breite kommt aus den Schriftbreiten der Helvetica
|
||||
* ({@see PdfDocument::exactWidth()}), damit verschiedene Schnitte in einer Zeile ohne Lücken aneinanderstoßen.
|
||||
* Links erscheinen mit ausgeschriebener Adresse, weil sie auf Papier sonst verloren gehen.
|
||||
*
|
||||
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
|
||||
*/
|
||||
private function runs(array $runs, float $x, float $size, bool $bold = false, bool $italic = false, float $after = 0): void
|
||||
{
|
||||
$maxWidth = self::RIGHT - $x;
|
||||
$lines = [];
|
||||
$line = [];
|
||||
$width = 0.0;
|
||||
$pendingSpace = false;
|
||||
$count = count($runs);
|
||||
|
||||
$flush = function () use (&$lines, &$line, &$width, &$pendingSpace): void {
|
||||
if ($line !== []) {
|
||||
$lines[] = $line;
|
||||
}
|
||||
|
||||
$line = [];
|
||||
$width = 0.0;
|
||||
$pendingSpace = false;
|
||||
};
|
||||
|
||||
$place = function (string $word, bool $isBold, bool $isItalic) use (&$line, &$width, &$pendingSpace, $maxWidth, $size, $flush): void {
|
||||
$space = $pendingSpace && $line !== [] ? ' ' : '';
|
||||
$need = PdfDocument::exactWidth($space.$word, $size, $isBold);
|
||||
|
||||
if ($line !== [] && $width + $need > $maxWidth) {
|
||||
$flush();
|
||||
$space = '';
|
||||
$need = PdfDocument::exactWidth($word, $size, $isBold);
|
||||
}
|
||||
|
||||
while ($need > $maxWidth && mb_strlen($word) > 1) {
|
||||
$cut = mb_strlen($word) - 1;
|
||||
|
||||
while ($cut > 1 && PdfDocument::exactWidth(mb_substr($word, 0, $cut), $size, $isBold) > $maxWidth) {
|
||||
$cut--;
|
||||
}
|
||||
|
||||
$line[] = [mb_substr($word, 0, $cut), $isBold, $isItalic];
|
||||
$flush();
|
||||
$word = mb_substr($word, $cut);
|
||||
$need = PdfDocument::exactWidth($word, $size, $isBold);
|
||||
}
|
||||
|
||||
$last = $line === [] ? null : $line[array_key_last($line)];
|
||||
|
||||
if ($last !== null && $last[1] === $isBold && $last[2] === $isItalic) {
|
||||
$line[array_key_last($line)][0] .= $space.$word;
|
||||
} else {
|
||||
$line[] = [$space.$word, $isBold, $isItalic];
|
||||
}
|
||||
|
||||
$width += $need;
|
||||
$pendingSpace = false;
|
||||
};
|
||||
|
||||
foreach ($runs as $index => $run) {
|
||||
$isBold = $bold || $run['bold'];
|
||||
$isItalic = $italic || $run['italic'];
|
||||
|
||||
foreach (preg_split('/(\s+)/u', self::printable($run['text']), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) ?: [] as $token) {
|
||||
if (trim($token) !== '') {
|
||||
$place($token, $isBold, $isItalic);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (str_contains($token, "\n")) {
|
||||
$flush();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$pendingSpace = true;
|
||||
}
|
||||
|
||||
$nextHref = $index + 1 < $count ? $runs[$index + 1]['href'] : null;
|
||||
|
||||
if ($run['href'] !== null && $nextHref !== $run['href'] && ! str_contains($run['text'], $run['href'])) {
|
||||
$pendingSpace = true;
|
||||
$place('('.self::printable($run['href']).')', false, false);
|
||||
}
|
||||
}
|
||||
|
||||
$flush();
|
||||
|
||||
foreach ($lines as $row) {
|
||||
$this->room($size + 4);
|
||||
$cursor = $x;
|
||||
|
||||
foreach ($row as [$text, $isBold, $isItalic]) {
|
||||
$this->pdf->text($cursor, $this->y, $text, $size, $isBold, $isItalic);
|
||||
$cursor += PdfDocument::exactWidth($text, $size, $isBold);
|
||||
}
|
||||
|
||||
$this->y -= $size + 4;
|
||||
}
|
||||
|
||||
$this->y -= $after;
|
||||
}
|
||||
|
||||
private function write(string $text, float $size, bool $bold, float $after): void
|
||||
{
|
||||
foreach (PdfDocument::wrap($text, self::RIGHT - self::LEFT, $size, $bold) as $line) {
|
||||
$this->room($size + 4);
|
||||
$this->pdf->text(self::LEFT, $this->y, $line, $size, $bold);
|
||||
$this->y -= $size + 4;
|
||||
}
|
||||
|
||||
$this->y -= $after;
|
||||
}
|
||||
|
||||
private function room(float $needed): void
|
||||
{
|
||||
if ($this->y - $needed < self::BOTTOM) {
|
||||
$this->closePage();
|
||||
$this->newPage();
|
||||
}
|
||||
$this->flow->write(self::printable($label.':'), 10.5, true, 2);
|
||||
$this->flow->formatted($blocks);
|
||||
}
|
||||
|
||||
private function newPage(): void
|
||||
{
|
||||
$this->pdf->addPage();
|
||||
$this->page++;
|
||||
$this->y = self::TOP;
|
||||
$this->flow->restart();
|
||||
}
|
||||
|
||||
private function closePage(): void
|
||||
|
||||
@@ -8,11 +8,15 @@
|
||||
use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig;
|
||||
|
||||
/**
|
||||
* Formatierter Text in der Verwaltung und im Mitgliederbereich (ADR-50).
|
||||
* Formatierter Text in der Verwaltung und im Mitgliederbereich (ADR-50, ADR-51).
|
||||
*
|
||||
* Gespeichert wird bereinigtes HTML aus einer festen Auswahl: Absatz, Zwischenüberschrift (h3), fett, kursiv, Aufzählung,
|
||||
* nummerierte Liste, Zitat, Link und Zeilenumbruch. Alles andere fällt beim Speichern weg, auch Skripte, Ereignisattribute
|
||||
* und Links auf andere Schemata als http, https und mailto.
|
||||
* nummerierte Liste, Zitat, Link, Zeilenumbruch, Tabelle und Bild. Alles andere fällt beim Speichern weg, auch Skripte,
|
||||
* Ereignisattribute und Links auf andere Schemata als http, https und mailto.
|
||||
*
|
||||
* Ein Bild ist nie eine Adresse, sondern ein Verweis auf eine Bildfassung des Medienbestands (`<img data-id="…" alt="…">`).
|
||||
* Die Adresse entsteht erst bei der Ausgabe, je nach Leser (Verwaltung, Mitglied mit Berechtigung, PDF). Ohne Auflösung
|
||||
* zeigt die Ausgabe kein Bild.
|
||||
*
|
||||
* Klartext aus dem Altbestand bleibt unverändert in der Datenbank. Er wird erst beim Anzeigen oder Bearbeiten in dieselbe
|
||||
* Form gebracht ({@see self::html()}) und erst beim Speichern als HTML abgelegt. Erkannt wird HTML an einer Regel: Der
|
||||
@@ -25,7 +29,7 @@
|
||||
final class FormattedText
|
||||
{
|
||||
/** Blockelemente, mit denen gespeichertes HTML beginnt. */
|
||||
private const BLOCKS = ['p', 'h3', 'ul', 'ol', 'blockquote'];
|
||||
private const BLOCKS = ['p', 'h3', 'ul', 'ol', 'blockquote', 'table', 'img'];
|
||||
|
||||
/** Angaben der Redaktion, die formatiert gespeichert werden. Suchbegriffe, Titel und Teaser bleiben Klartext. */
|
||||
public const FIELDS = ['summary', 'description'];
|
||||
@@ -33,7 +37,13 @@ final class FormattedText
|
||||
private static ?HtmlSanitizer $sanitizer = null;
|
||||
|
||||
/** Symbolleiste der Editoren; muss zur Auswahl oben passen. */
|
||||
public const TOOLBAR = [['bold', 'italic', 'link'], ['h3'], ['bulletList', 'orderedList', 'blockquote'], ['undo', 'redo']];
|
||||
public const TOOLBAR = [
|
||||
['bold', 'italic', 'link'],
|
||||
['h3'],
|
||||
['bulletList', 'orderedList', 'blockquote'],
|
||||
['table', 'tableAddRowAfter', 'tableAddColumnAfter', 'tableDeleteRow', 'tableDeleteColumn', 'tableToggleHeaderRow', 'tableDelete'],
|
||||
['undo', 'redo'],
|
||||
];
|
||||
|
||||
/** Wird der Wert als HTML gelesen (sonst als Klartext des Altbestands)? */
|
||||
public static function isHtml(?string $value): bool
|
||||
@@ -66,21 +76,121 @@ public static function canonicalHtml(?string $html): string
|
||||
return $html === '' ? '' : self::normalize($html);
|
||||
}
|
||||
|
||||
/** Sicheres HTML zur Ausgabe (für `{!! !!}`); Klartext des Altbestands wird dabei umgewandelt. */
|
||||
public static function html(?string $value): string
|
||||
/**
|
||||
* Sicheres HTML zur Ausgabe (für `{!! !!}`); Klartext des Altbestands wird dabei umgewandelt.
|
||||
*
|
||||
* Bilder erscheinen nur, wenn `$images` sie auflöst: Die Funktion bekommt die Kennung der Bildfassung und liefert
|
||||
* `['src' => Adresse, 'alt' => Text]` (Bild), `['note' => Text]` (Hinweis an der Stelle des Bilds) oder null (Bild
|
||||
* entfällt). Ohne Funktion entfallen alle Bilder; so zeigt keine Ausgabe versehentlich ein Bild ohne Rechteprüfung.
|
||||
*
|
||||
* @param (callable(int): ?array{src?: string, alt?: string, note?: string})|null $images
|
||||
*/
|
||||
public static function html(?string $value, ?callable $images = null): string
|
||||
{
|
||||
return self::canonical($value);
|
||||
return self::renderImages(self::canonical($value), $images);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sicheres HTML zur Ausgabe an Stellen, die Klartext des Altbestands bisher mit Zeilenumbrüchen zeigten: HTML wird
|
||||
* bereinigt ausgegeben, Klartext bleibt, wie er war (maskiert, Zeilenumbrüche erhalten).
|
||||
*
|
||||
* @param (callable(int): ?array{src?: string, alt?: string, note?: string})|null $images
|
||||
*/
|
||||
public static function display(?string $value): string
|
||||
public static function display(?string $value, ?callable $images = null): string
|
||||
{
|
||||
$value = (string) $value;
|
||||
|
||||
return self::isHtml($value) ? self::canonical($value) : nl2br(e($value));
|
||||
return self::isHtml($value) ? self::renderImages(self::canonical($value), $images) : nl2br(e($value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Die Bildfassungen, auf die ein Text verweist, in der Reihenfolge ihres Auftretens (ohne Wiederholung).
|
||||
*
|
||||
* @return list<int>
|
||||
*/
|
||||
public static function imageIds(?string $value): array
|
||||
{
|
||||
$html = self::canonical($value);
|
||||
|
||||
if ($html === '' || ! str_contains($html, '<img')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$ids = [];
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
|
||||
foreach ($document->querySelectorAll('img[data-id]') as $image) {
|
||||
$id = (int) $image->getAttribute('data-id');
|
||||
|
||||
if ($id > 0 && ! in_array($id, $ids, true)) {
|
||||
$ids[] = $id;
|
||||
}
|
||||
}
|
||||
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fügt die Adresse an jedes Bild, damit der Editor es zeigt. Die Adresse gehört nicht zum gespeicherten Wert: Die
|
||||
* Bereinigung entfernt sie beim Übernehmen aus dem Editor wieder.
|
||||
*
|
||||
* @param callable(int): ?string $source
|
||||
*/
|
||||
public static function forEditor(string $html, callable $source): string
|
||||
{
|
||||
if (! str_contains($html, '<img')) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
|
||||
foreach ($document->querySelectorAll('img[data-id]') as $image) {
|
||||
$src = $source((int) $image->getAttribute('data-id'));
|
||||
|
||||
if ($src !== null) {
|
||||
$image->setAttribute('src', $src);
|
||||
}
|
||||
}
|
||||
|
||||
return trim($document->body->innerHTML);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param (callable(int): ?array{src?: string, alt?: string, note?: string})|null $images
|
||||
*/
|
||||
private static function renderImages(string $html, ?callable $images): string
|
||||
{
|
||||
if ($html === '' || ! str_contains($html, '<img')) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
|
||||
foreach (iterator_to_array($document->querySelectorAll('img')) as $image) {
|
||||
$found = $images === null ? null : $images((int) $image->getAttribute('data-id'));
|
||||
|
||||
if (isset($found['src'])) {
|
||||
$image->removeAttribute('data-id');
|
||||
$image->setAttribute('src', (string) $found['src']);
|
||||
$image->setAttribute('alt', (string) ($found['alt'] ?? $image->getAttribute('alt')));
|
||||
$image->setAttribute('loading', 'lazy');
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isset($found['note'])) {
|
||||
$note = $document->createElement('p');
|
||||
$note->setAttribute('class', 'mb-bildhinweis');
|
||||
$note->textContent = (string) $found['note'];
|
||||
$image->replaceWith($note);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$image->remove();
|
||||
}
|
||||
|
||||
return trim($document->body->innerHTML);
|
||||
}
|
||||
|
||||
public static function isBlank(?string $value): bool
|
||||
@@ -103,16 +213,37 @@ public static function plain(?string $value): string
|
||||
$out = [];
|
||||
|
||||
foreach (self::blocks($value) as $block) {
|
||||
$out[] = match ($block['type']) {
|
||||
'bullets' => implode("\n", array_map(fn (array $item): string => '- '.self::runsText($item), $block['items'])),
|
||||
'numbered' => implode("\n", array_map(fn (array $item, int $n): string => ($n + 1).'. '.self::runsText($item), $block['items'], array_keys($block['items']))),
|
||||
default => self::runsText($block['runs']),
|
||||
};
|
||||
$text = self::plainBlock($block);
|
||||
|
||||
if ($text !== '') {
|
||||
$out[] = $text;
|
||||
}
|
||||
}
|
||||
|
||||
return trim(implode("\n\n", $out));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $block
|
||||
*/
|
||||
private static function plainBlock(array $block): string
|
||||
{
|
||||
return match ($block['type']) {
|
||||
'bullets' => implode("\n", array_map(fn (array $item): string => '- '.self::runsText($item), $block['items'])),
|
||||
'numbered' => implode("\n", array_map(fn (array $item, int $n): string => ($n + 1).'. '.self::runsText($item), $block['items'], array_keys($block['items']))),
|
||||
'table' => implode("\n", array_map(
|
||||
fn (array $row): string => implode(' | ', array_map(
|
||||
fn (array $cell): string => trim((string) preg_replace('/\s+/u', ' ', implode(' ', array_filter(array_map(fn (array $inner): string => self::plainBlock($inner), $cell['blocks']))))),
|
||||
$row,
|
||||
)),
|
||||
$block['rows'],
|
||||
)),
|
||||
// Ein Bild hat im Klartext keinen Platz (Listen, Auszüge, Meta-Beschreibung).
|
||||
'image' => '',
|
||||
default => self::runsText($block['runs']),
|
||||
};
|
||||
}
|
||||
|
||||
/** Kurzer Text für Listen und Karten. */
|
||||
public static function excerpt(?string $value, int $length = 120): string
|
||||
{
|
||||
@@ -123,9 +254,10 @@ public static function excerpt(?string $value, int $length = 120): string
|
||||
|
||||
/**
|
||||
* Zerlegung in Blöcke mit Textabschnitten für das PDF. Ein Textabschnitt (Run) trägt `text`, `bold`, `italic` und
|
||||
* `href`.
|
||||
* `href`. Eine Tabelle besteht aus Zeilen mit Zellen (`header`, `colspan`, `rowspan`, `blocks`); ein Bild trägt die
|
||||
* Kennung seiner Bildfassung (`id`) und den Alternativtext.
|
||||
*
|
||||
* @return list<array{type: 'paragraph'|'heading'|'quote'|'bullets'|'numbered', runs?: list<array{text: string, bold: bool, italic: bool, href: ?string}>, items?: list<list<array{text: string, bold: bool, italic: bool, href: ?string}>>}>
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
public static function blocks(?string $value): array
|
||||
{
|
||||
@@ -136,9 +268,18 @@ public static function blocks(?string $value): array
|
||||
}
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
|
||||
return self::extractBlocks($document->body);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
private static function extractBlocks(Node $parent): array
|
||||
{
|
||||
$blocks = [];
|
||||
|
||||
foreach ($document->body->childNodes as $node) {
|
||||
foreach ($parent->childNodes as $node) {
|
||||
if ($node->nodeType !== XML_ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
@@ -159,6 +300,41 @@ public static function blocks(?string $value): array
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($name === 'img') {
|
||||
$blocks[] = ['type' => 'image', 'id' => (int) $node->getAttribute('data-id'), 'alt' => (string) $node->getAttribute('alt')];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($name === 'table') {
|
||||
$rows = [];
|
||||
|
||||
foreach ($node->querySelectorAll('tr') as $row) {
|
||||
$cells = [];
|
||||
|
||||
foreach ($row->childNodes as $cell) {
|
||||
if ($cell->nodeType !== XML_ELEMENT_NODE || ! in_array(strtolower($cell->nodeName), ['th', 'td'], true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$cells[] = [
|
||||
'header' => strtolower($cell->nodeName) === 'th',
|
||||
'colspan' => max(1, (int) $cell->getAttribute('colspan')),
|
||||
'rowspan' => max(1, (int) $cell->getAttribute('rowspan')),
|
||||
'blocks' => self::extractBlocks($cell),
|
||||
];
|
||||
}
|
||||
|
||||
if ($cells !== []) {
|
||||
$rows[] = $cells;
|
||||
}
|
||||
}
|
||||
|
||||
$blocks[] = ['type' => 'table', 'rows' => $rows];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$blocks[] = [
|
||||
'type' => match ($name) {
|
||||
'h3' => 'heading',
|
||||
@@ -203,6 +379,14 @@ private static function normalize(string $html): string
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
$body = $document->body;
|
||||
|
||||
// Ein Bild steht zwischen den Absätzen (der Editor setzt es als Block) und braucht seine Bildfassung.
|
||||
foreach (iterator_to_array($document->querySelectorAll('img')) as $image) {
|
||||
if ($image->parentNode !== $body || (int) $image->getAttribute('data-id') < 1) {
|
||||
$image->remove();
|
||||
}
|
||||
}
|
||||
|
||||
$out = '';
|
||||
$loose = '';
|
||||
|
||||
@@ -229,7 +413,7 @@ private static function normalize(string $html): string
|
||||
|
||||
$flush();
|
||||
|
||||
return self::hasText($out) ? $out : '';
|
||||
return self::hasText($out) || str_contains($out, '<img') ? $out : '';
|
||||
}
|
||||
|
||||
/** Ein Blockelement ohne Leerraum zwischen den Kindern; Listenpunkte tragen ihren Text immer in einem Absatz. */
|
||||
@@ -237,6 +421,16 @@ private static function block(Node $node): string
|
||||
{
|
||||
$name = strtolower($node->nodeName);
|
||||
|
||||
if ($name === 'img') {
|
||||
$id = (int) $node->getAttribute('data-id');
|
||||
|
||||
return $id > 0 ? '<img data-id="'.$id.'" alt="'.e(trim((string) $node->getAttribute('alt'))).'">' : '';
|
||||
}
|
||||
|
||||
if ($name === 'table') {
|
||||
return self::table($node);
|
||||
}
|
||||
|
||||
if (in_array($name, ['ul', 'ol'], true)) {
|
||||
$items = '';
|
||||
|
||||
@@ -268,6 +462,45 @@ private static function block(Node $node): string
|
||||
return self::hasText($inner) ? '<'.$name.'>'.$inner.'</'.$name.'>' : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Eine Tabelle in der festen Form des Editors: Zeilen mit Kopf- (`th`) und Datenzellen (`td`), Zellen mit Absätzen,
|
||||
* Verbindungen nur als `colspan` und `rowspan` über 1. Breiten, Gestaltung und Zwischenebenen entfallen.
|
||||
*/
|
||||
private static function table(Node $table): string
|
||||
{
|
||||
$rows = '';
|
||||
|
||||
foreach ($table->querySelectorAll('tr') as $row) {
|
||||
$cells = '';
|
||||
|
||||
foreach ($row->childNodes as $cell) {
|
||||
if ($cell->nodeType !== XML_ELEMENT_NODE || ! in_array(strtolower($cell->nodeName), ['th', 'td'], true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = strtolower($cell->nodeName);
|
||||
$attributes = '';
|
||||
|
||||
foreach (['colspan', 'rowspan'] as $span) {
|
||||
$value = (int) $cell->getAttribute($span);
|
||||
|
||||
if ($value > 1) {
|
||||
$attributes .= ' '.$span.'="'.min($value, 50).'"';
|
||||
}
|
||||
}
|
||||
|
||||
$inner = self::inner($cell);
|
||||
$cells .= '<'.$name.$attributes.'>'.($inner === '' ? '<p></p>' : (preg_match('/^<(?:p|ul|ol|blockquote|h3)[\s>]/', $inner) === 1 ? $inner : '<p>'.$inner.'</p>')).'</'.$name.'>';
|
||||
}
|
||||
|
||||
if ($cells !== '') {
|
||||
$rows .= '<tr>'.$cells.'</tr>';
|
||||
}
|
||||
}
|
||||
|
||||
return $rows !== '' && self::hasText($rows) ? '<table><tbody>'.$rows.'</tbody></table>' : '';
|
||||
}
|
||||
|
||||
private static function inner(Node $node): string
|
||||
{
|
||||
$html = '';
|
||||
@@ -365,6 +598,14 @@ private static function sanitizer(): HtmlSanitizer
|
||||
->allowElement('ol')
|
||||
->allowElement('li')
|
||||
->allowElement('blockquote')
|
||||
->allowElement('table')
|
||||
->allowElement('thead')
|
||||
->allowElement('tbody')
|
||||
->allowElement('tfoot')
|
||||
->allowElement('tr')
|
||||
->allowElement('th', ['colspan', 'rowspan'])
|
||||
->allowElement('td', ['colspan', 'rowspan'])
|
||||
->allowElement('img', ['data-id', 'alt'])
|
||||
->allowElement('a', ['href'])
|
||||
->allowLinkSchemes(['http', 'https', 'mailto'])
|
||||
->allowRelativeLinks(false)
|
||||
|
||||
@@ -0,0 +1,587 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Commerce\Receipt\PdfDocument;
|
||||
use Closure;
|
||||
use Transliterator;
|
||||
|
||||
/**
|
||||
* Satz für gedruckte Ausgaben (Übung, Dokument): Überschriften, Absätze mit fett und kursiv, Listen, Tabellen und Bilder
|
||||
* aus den Blöcken von {@see FormattedText::blocks()}. Übung und Dokument setzen mit demselben Baustein; so sehen
|
||||
* Tabellen und Bilder in beiden gleich aus.
|
||||
*
|
||||
* Der Satz kennt weder Seitenkopf noch Fußzeile: Passt etwas nicht mehr auf die Seite, ruft er `$breakPage` auf. Diese
|
||||
* Funktion schließt die Seite und öffnet die nächste; danach beginnt der Satz wieder am oberen Rand.
|
||||
*/
|
||||
final class PdfFlow
|
||||
{
|
||||
public float $y;
|
||||
|
||||
/** Schachtelungstiefe beim Setzen einer Tabelle (Zelleninhalt setzt nie wieder eine Tabelle). */
|
||||
private int $depth = 0;
|
||||
|
||||
/**
|
||||
* @param Closure(): void $breakPage
|
||||
* @param (Closure(int): ?array{jpeg?: string, width?: int, height?: int, note?: string})|null $images Löst ein Bild auf: JPEG mit Maßen,
|
||||
* ein Hinweistext oder null (entfällt)
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly PdfDocument $pdf,
|
||||
private readonly float $left,
|
||||
private readonly float $right,
|
||||
private readonly float $top,
|
||||
private readonly float $bottom,
|
||||
private readonly Closure $breakPage,
|
||||
private readonly ?Closure $images = null,
|
||||
) {
|
||||
$this->y = $top;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeichen außerhalb von Windows-1252 werden, wo möglich, lesbar ersetzt (Pfeil, Ungleichheitszeichen, andere
|
||||
* lateinische Buchstaben); sonst bleibt „?“.
|
||||
*/
|
||||
public static function printable(string $text): string
|
||||
{
|
||||
$text = strtr($text, ['→' => '->', '←' => '<-', '≥' => '>=', '≤' => '<=', '✓' => '+', '✗' => 'x', '≠' => '!=', '≈' => '~']);
|
||||
$latin = Transliterator::create('Any-Latin; Latin-ASCII');
|
||||
$out = '';
|
||||
|
||||
foreach (mb_str_split($text) as $char) {
|
||||
$encoded = mb_convert_encoding($char, 'Windows-1252', 'UTF-8');
|
||||
$out .= $encoded === '?' && $char !== '?' ? ($latin?->transliterate($char) ?: '?') : $char;
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** Beginn einer neuen Seite: der Satz steht wieder am oberen Rand. */
|
||||
public function restart(): void
|
||||
{
|
||||
$this->y = $this->top;
|
||||
}
|
||||
|
||||
public function room(float $needed): void
|
||||
{
|
||||
if ($this->y - $needed < $this->bottom) {
|
||||
($this->breakPage)();
|
||||
$this->y = $this->top;
|
||||
}
|
||||
}
|
||||
|
||||
/** Eine Überschrift oder ein kurzer Text in Zeilen nach {@see PdfDocument::wrap()}. `$keep` hält Platz für folgenden Text frei. */
|
||||
public function write(string $text, float $size, bool $bold, float $after, float $keep = 0, ?float $x = null): void
|
||||
{
|
||||
$x ??= $this->left;
|
||||
$lines = PdfDocument::wrap($text, $this->right - $x, $size, $bold);
|
||||
|
||||
if ($keep > 0 && $lines !== []) {
|
||||
$this->room(count($lines) * ($size + 4) + $keep);
|
||||
}
|
||||
|
||||
foreach ($lines as $line) {
|
||||
$this->room($size + 4);
|
||||
$this->pdf->text($x, $this->y, $line, $size, $bold);
|
||||
$this->y -= $size + 4;
|
||||
}
|
||||
|
||||
$this->y -= $after;
|
||||
}
|
||||
|
||||
/**
|
||||
* Blöcke aus {@see FormattedText::blocks()}: Absatz, Zwischenüberschrift, Zitat, Listen, Tabelle und Bild.
|
||||
*
|
||||
* @param list<array<string, mixed>> $blocks
|
||||
*/
|
||||
public function formatted(array $blocks, ?float $x = null, float $size = 10.5): void
|
||||
{
|
||||
$x ??= $this->left;
|
||||
|
||||
foreach ($blocks as $block) {
|
||||
match ($block['type']) {
|
||||
'heading' => $this->headingBlock($block, $x, $size),
|
||||
'quote' => $this->runs($block['runs'], $x + 14, $size, italic: true, after: 5),
|
||||
'bullets' => $this->listItems($block['items'], fn (int $n): string => '•', $x, $size),
|
||||
'numbered' => $this->listItems($block['items'], fn (int $n): string => $n.'.', $x, $size),
|
||||
'table' => $this->table($block['rows'], $x),
|
||||
'image' => $this->image($block, $x),
|
||||
default => $this->runs($block['runs'] ?? [], $x, $size, after: 5),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $block
|
||||
*/
|
||||
private function headingBlock(array $block, float $x, float $size): void
|
||||
{
|
||||
// Eine Zwischenüberschrift bleibt bei ihrem Text: mindestens zwei Zeilen müssen mit auf die Seite.
|
||||
$this->room(($size + 0.5) + 4 + 2 * ($size + 4));
|
||||
$this->runs($block['runs'], $x, $size + 0.5, bold: true, after: 4);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<list<array{text: string, bold: bool, italic: bool, href: ?string}>> $items
|
||||
* @param callable(int): string $marker
|
||||
*/
|
||||
public function listItems(array $items, callable $marker, ?float $x = null, float $size = 10.5): void
|
||||
{
|
||||
$x ??= $this->left;
|
||||
|
||||
foreach ($items as $index => $item) {
|
||||
$this->room(14);
|
||||
$this->pdf->text($x + 4, $this->y, $marker($index + 1), $size);
|
||||
$this->runs($item, $x + 18, $size, after: 1);
|
||||
}
|
||||
|
||||
$this->y -= 3;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setzt Textabschnitte mit fett und kursiv in Zeilen um und zeichnet sie. Links erscheinen mit ausgeschriebener
|
||||
* Adresse, weil sie auf Papier sonst verloren gehen.
|
||||
*
|
||||
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
|
||||
*/
|
||||
public function runs(array $runs, float $x, float $size, bool $bold = false, bool $italic = false, float $after = 0): void
|
||||
{
|
||||
foreach ($this->lines($runs, $this->right - $x, $size, $bold, $italic) as $row) {
|
||||
$this->room($size + 4);
|
||||
$cursor = $x;
|
||||
|
||||
foreach ($row as [$text, $isBold, $isItalic]) {
|
||||
$this->pdf->text($cursor, $this->y, $text, $size, $isBold, $isItalic);
|
||||
$cursor += PdfDocument::exactWidth($text, $size, $isBold);
|
||||
}
|
||||
|
||||
$this->y -= $size + 4;
|
||||
}
|
||||
|
||||
$this->y -= $after;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeilen aus Textabschnitten für eine Breite. Die Breite kommt aus den Schriftbreiten der Helvetica
|
||||
* ({@see PdfDocument::exactWidth()}), damit verschiedene Schnitte in einer Zeile ohne Lücken aneinanderstoßen.
|
||||
*
|
||||
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
|
||||
* @return list<list<array{0: string, 1: bool, 2: bool}>>
|
||||
*/
|
||||
public function lines(array $runs, float $maxWidth, float $size, bool $bold = false, bool $italic = false): array
|
||||
{
|
||||
$lines = [];
|
||||
$line = [];
|
||||
$width = 0.0;
|
||||
$pendingSpace = false;
|
||||
$count = count($runs);
|
||||
|
||||
$flush = function () use (&$lines, &$line, &$width, &$pendingSpace): void {
|
||||
if ($line !== []) {
|
||||
$lines[] = $line;
|
||||
}
|
||||
|
||||
$line = [];
|
||||
$width = 0.0;
|
||||
$pendingSpace = false;
|
||||
};
|
||||
|
||||
$place = function (string $word, bool $isBold, bool $isItalic) use (&$line, &$width, &$pendingSpace, $maxWidth, $size, $flush): void {
|
||||
$space = $pendingSpace && $line !== [] ? ' ' : '';
|
||||
$need = PdfDocument::exactWidth($space.$word, $size, $isBold);
|
||||
|
||||
if ($line !== [] && $width + $need > $maxWidth) {
|
||||
$flush();
|
||||
$space = '';
|
||||
$need = PdfDocument::exactWidth($word, $size, $isBold);
|
||||
}
|
||||
|
||||
while ($need > $maxWidth && mb_strlen($word) > 1) {
|
||||
$cut = mb_strlen($word) - 1;
|
||||
|
||||
while ($cut > 1 && PdfDocument::exactWidth(mb_substr($word, 0, $cut), $size, $isBold) > $maxWidth) {
|
||||
$cut--;
|
||||
}
|
||||
|
||||
$line[] = [mb_substr($word, 0, $cut), $isBold, $isItalic];
|
||||
$flush();
|
||||
$word = mb_substr($word, $cut);
|
||||
$need = PdfDocument::exactWidth($word, $size, $isBold);
|
||||
}
|
||||
|
||||
$last = $line === [] ? null : $line[array_key_last($line)];
|
||||
|
||||
if ($last !== null && $last[1] === $isBold && $last[2] === $isItalic) {
|
||||
$line[array_key_last($line)][0] .= $space.$word;
|
||||
} else {
|
||||
$line[] = [$space.$word, $isBold, $isItalic];
|
||||
}
|
||||
|
||||
$width += $need;
|
||||
$pendingSpace = false;
|
||||
};
|
||||
|
||||
foreach ($runs as $index => $run) {
|
||||
$isBold = $bold || $run['bold'];
|
||||
$isItalic = $italic || $run['italic'];
|
||||
|
||||
foreach (preg_split('/(\s+)/u', self::printable($run['text']), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) ?: [] as $token) {
|
||||
if (trim($token) !== '') {
|
||||
$place($token, $isBold, $isItalic);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (str_contains($token, "\n")) {
|
||||
$flush();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$pendingSpace = true;
|
||||
}
|
||||
|
||||
$nextHref = $index + 1 < $count ? $runs[$index + 1]['href'] : null;
|
||||
|
||||
if ($run['href'] !== null && $nextHref !== $run['href'] && ! str_contains($run['text'], $run['href'])) {
|
||||
$pendingSpace = true;
|
||||
$place('('.self::printable($run['href']).')', false, false);
|
||||
}
|
||||
}
|
||||
|
||||
$flush();
|
||||
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Bild in Breite der Spalte, höchstens 320 Punkt hoch. Ein Bild lässt sich nicht teilen: Es steht ganz auf einer
|
||||
* Seite. Kann das Bild nicht gezeigt werden, steht an seiner Stelle der Hinweis.
|
||||
*
|
||||
* @param array<string, mixed> $block
|
||||
*/
|
||||
private function image(array $block, float $x): void
|
||||
{
|
||||
$found = $this->images === null ? null : ($this->images)((int) $block['id']);
|
||||
|
||||
if ($found === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! isset($found['jpeg'])) {
|
||||
$this->runs([['text' => '['.($found['note'] ?? 'Bild nicht verfügbar').']', 'bold' => false, 'italic' => true, 'href' => null]], $x, 9.5, after: 5);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$available = $this->right - $x;
|
||||
$scale = min(1.0, $available / max(1, $found['width']), 320.0 / max(1, $found['height']));
|
||||
$width = max(1.0, $found['width'] * $scale);
|
||||
$height = max(1.0, $found['height'] * $scale);
|
||||
|
||||
$this->room($height + 8);
|
||||
$this->pdf->image($x, $this->y - $height, $width, $height, $found['jpeg'], $found['width'], $found['height']);
|
||||
$this->y -= $height + 8;
|
||||
}
|
||||
|
||||
/**
|
||||
* Eine Tabelle mit Rahmen. Die Spaltenbreiten folgen dem Inhalt (Spalten mit kurzem Text bleiben schmal), Verbindungen
|
||||
* über Spalten und Zeilen werden gesetzt. Eine Zeile bleibt zusammen; auf jeder Folgeseite stehen die Kopfzeilen
|
||||
* erneut. Ist eine einzelne Zeile höher als eine Seite, erscheint ihr Inhalt als Fließtext.
|
||||
*
|
||||
* @param list<list<array<string, mixed>>> $rows
|
||||
*/
|
||||
private function table(array $rows, float $x): void
|
||||
{
|
||||
if ($this->depth > 0 || $rows === []) {
|
||||
// Tabellen in Tabellen kennt der Editor nicht; sicherheitshalber als Fließtext.
|
||||
foreach ($rows as $row) {
|
||||
foreach ($row as $cell) {
|
||||
$this->formatted($cell['blocks'], $x);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$size = 9.5;
|
||||
$pad = 3.5;
|
||||
$lineHeight = $size + 3;
|
||||
$grid = $this->grid($rows);
|
||||
$columns = $grid['columns'];
|
||||
$widths = $this->columnWidths($grid['cells'], $columns, $this->right - $x, $size, $pad);
|
||||
$headRows = 0;
|
||||
|
||||
foreach ($rows as $row) {
|
||||
if ($row !== [] && count(array_filter($row, fn (array $cell): bool => $cell['header'])) === count($row)) {
|
||||
$headRows++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
$headRows = $headRows === count($rows) ? 0 : $headRows;
|
||||
$prepared = [];
|
||||
|
||||
foreach ($grid['cells'] as $cell) {
|
||||
$inner = array_sum(array_slice($widths, $cell['column'], $cell['colspan'])) - 2 * $pad;
|
||||
$this->depth++;
|
||||
$cell['lines'] = $this->cellLines($cell['blocks'], max(10.0, $inner), $size, $cell['header']);
|
||||
$this->depth--;
|
||||
$cell['height'] = max(1, count($cell['lines'])) * $lineHeight + 2 * $pad;
|
||||
$prepared[] = $cell;
|
||||
}
|
||||
|
||||
$rowCount = count($rows);
|
||||
$heights = array_fill(0, $rowCount, $lineHeight + 2 * $pad);
|
||||
|
||||
foreach ($prepared as $cell) {
|
||||
if ($cell['rowspan'] === 1) {
|
||||
$heights[$cell['row']] = max($heights[$cell['row']], $cell['height']);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($prepared as $cell) {
|
||||
if ($cell['rowspan'] > 1) {
|
||||
$last = min($rowCount - 1, $cell['row'] + $cell['rowspan'] - 1);
|
||||
$have = array_sum(array_slice($heights, $cell['row'], $last - $cell['row'] + 1));
|
||||
$heights[$last] += max(0.0, $cell['height'] - $have);
|
||||
}
|
||||
}
|
||||
|
||||
$pageHeight = $this->top - $this->bottom;
|
||||
|
||||
if (max($heights) > $pageHeight - 8) {
|
||||
foreach ($rows as $row) {
|
||||
foreach ($row as $cell) {
|
||||
$this->formatted($cell['blocks'], $x);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$drawRows = function (int $from, int $to) use ($prepared, $widths, $heights, $x, $size, $pad, $lineHeight): void {
|
||||
$y = $this->y;
|
||||
|
||||
for ($r = $from; $r <= $to; $r++) {
|
||||
foreach ($prepared as $cell) {
|
||||
if ($cell['row'] !== $r) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$cellLeft = $x + array_sum(array_slice($widths, 0, $cell['column']));
|
||||
$cellWidth = array_sum(array_slice($widths, $cell['column'], $cell['colspan']));
|
||||
$cellHeight = array_sum(array_slice($heights, $r, $cell['rowspan']));
|
||||
$this->frame($cellLeft, $y - $cellHeight, $cellWidth, $cellHeight, $cell['header']);
|
||||
$textY = $y - $pad - $size;
|
||||
|
||||
foreach ($cell['lines'] as $line) {
|
||||
if ($line['marker'] !== null) {
|
||||
$this->pdf->text($cellLeft + $pad + $line['indent'] - 12, $textY, $line['marker'], $size, $cell['header']);
|
||||
}
|
||||
|
||||
$cursor = $cellLeft + $pad + $line['indent'];
|
||||
|
||||
foreach ($line['segments'] as [$text, $isBold, $isItalic]) {
|
||||
$this->pdf->text($cursor, $textY, $text, $size, $isBold || $cell['header'], $isItalic);
|
||||
$cursor += PdfDocument::exactWidth($text, $size, $isBold || $cell['header']);
|
||||
}
|
||||
|
||||
$textY -= $lineHeight;
|
||||
}
|
||||
}
|
||||
|
||||
$y -= $heights[$r];
|
||||
}
|
||||
|
||||
$this->y = $y;
|
||||
};
|
||||
|
||||
$this->room($heights[0] + ($rowCount > 1 ? min($heights[1], 40.0) : 0));
|
||||
|
||||
for ($r = 0; $r < $rowCount; $r++) {
|
||||
// Zeilen, die eine Verbindung über Zeilen zusammenhält, werden gemeinsam gesetzt.
|
||||
$end = $r;
|
||||
|
||||
do {
|
||||
$before = $end;
|
||||
|
||||
foreach ($prepared as $cell) {
|
||||
if ($cell['row'] <= $end && $end < $cell['row'] + $cell['rowspan'] - 1) {
|
||||
$end = min($rowCount - 1, $cell['row'] + $cell['rowspan'] - 1);
|
||||
}
|
||||
}
|
||||
} while ($end !== $before);
|
||||
|
||||
$span = $end - $r + 1;
|
||||
$need = array_sum(array_slice($heights, $r, $span));
|
||||
|
||||
if ($this->y - $need < $this->bottom) {
|
||||
($this->breakPage)();
|
||||
$this->y = $this->top;
|
||||
|
||||
if ($headRows > 0 && $r >= $headRows) {
|
||||
$drawRows(0, $headRows - 1);
|
||||
}
|
||||
}
|
||||
|
||||
$drawRows($r, $r + $span - 1);
|
||||
$r += $span - 1;
|
||||
}
|
||||
|
||||
$this->y -= 8;
|
||||
}
|
||||
|
||||
private function frame(float $x, float $y, float $w, float $h, bool $header): void
|
||||
{
|
||||
if ($header) {
|
||||
$this->pdf->fillRect($x, $y, $w, $h, 0.92);
|
||||
}
|
||||
|
||||
$this->pdf->line($x, $y, $x + $w, $y, 0.4);
|
||||
$this->pdf->line($x, $y + $h, $x + $w, $y + $h, 0.4);
|
||||
$this->pdf->line($x, $y, $x, $y + $h, 0.4);
|
||||
$this->pdf->line($x + $w, $y, $x + $w, $y + $h, 0.4);
|
||||
}
|
||||
|
||||
/**
|
||||
* Weist jeder Zelle ihre Spalte zu; Verbindungen über Zeilen belegen die Spalte in den Folgezeilen mit.
|
||||
*
|
||||
* @param list<list<array<string, mixed>>> $rows
|
||||
* @return array{columns: int, cells: list<array<string, mixed>>}
|
||||
*/
|
||||
private function grid(array $rows): array
|
||||
{
|
||||
$occupied = [];
|
||||
$cells = [];
|
||||
$columns = 0;
|
||||
|
||||
foreach ($rows as $r => $row) {
|
||||
$column = 0;
|
||||
|
||||
foreach ($row as $cell) {
|
||||
while (isset($occupied[$r][$column])) {
|
||||
$column++;
|
||||
}
|
||||
|
||||
$colspan = max(1, (int) $cell['colspan']);
|
||||
$rowspan = max(1, (int) $cell['rowspan']);
|
||||
|
||||
for ($dr = 0; $dr < $rowspan; $dr++) {
|
||||
for ($dc = 0; $dc < $colspan; $dc++) {
|
||||
$occupied[$r + $dr][$column + $dc] = true;
|
||||
}
|
||||
}
|
||||
|
||||
$cells[] = $cell + ['row' => $r, 'column' => $column] + ['colspan' => $colspan, 'rowspan' => $rowspan];
|
||||
$column += $colspan;
|
||||
$columns = max($columns, $column);
|
||||
}
|
||||
}
|
||||
|
||||
return ['columns' => max(1, $columns), 'cells' => $cells];
|
||||
}
|
||||
|
||||
/**
|
||||
* Spaltenbreiten nach Inhalt: Jede Spalte braucht mindestens ihr längstes Wort und wünscht sich die Breite ihres
|
||||
* längsten Zelltexts. Reicht der Platz, wird der Rest gleichmäßig verteilt; sonst teilt sich der Mangel nach Wunsch auf.
|
||||
*
|
||||
* @param list<array<string, mixed>> $cells
|
||||
* @return list<float>
|
||||
*/
|
||||
private function columnWidths(array $cells, int $columns, float $available, float $size, float $pad): array
|
||||
{
|
||||
$min = array_fill(0, $columns, 24.0);
|
||||
$want = array_fill(0, $columns, 24.0);
|
||||
|
||||
foreach ($cells as $cell) {
|
||||
if ($cell['colspan'] !== 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$text = self::printable($this->cellText($cell['blocks']));
|
||||
$widest = 0.0;
|
||||
|
||||
foreach (preg_split('/\s+/u', $text) ?: [] as $word) {
|
||||
$widest = max($widest, PdfDocument::exactWidth($word, $size, (bool) $cell['header']));
|
||||
}
|
||||
|
||||
$c = $cell['column'];
|
||||
$min[$c] = max($min[$c], $widest + 2 * $pad + 1);
|
||||
$want[$c] = max($want[$c], PdfDocument::exactWidth($text, $size, (bool) $cell['header']) + 2 * $pad + 1);
|
||||
}
|
||||
|
||||
$want = array_map(fn (float $w, float $m): float => max($w, $m), $want, $min);
|
||||
|
||||
if (array_sum($min) >= $available) {
|
||||
$scale = $available / array_sum($min);
|
||||
|
||||
return array_map(fn (float $w): float => $w * $scale, $min);
|
||||
}
|
||||
|
||||
if (array_sum($want) <= $available) {
|
||||
$extra = ($available - array_sum($want)) / $columns;
|
||||
|
||||
return array_map(fn (float $w): float => $w + $extra, $want);
|
||||
}
|
||||
|
||||
$room = $available - array_sum($min);
|
||||
$wishes = array_sum($want) - array_sum($min);
|
||||
|
||||
return array_map(fn (float $m, float $w): float => $m + $room * (($w - $m) / max(1.0, $wishes)), $min, $want);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<string, mixed>> $blocks
|
||||
*/
|
||||
private function cellText(array $blocks): string
|
||||
{
|
||||
$out = [];
|
||||
|
||||
foreach ($blocks as $block) {
|
||||
$out[] = match ($block['type']) {
|
||||
'bullets', 'numbered' => implode(' ', array_map(fn (array $item): string => implode('', array_column($item, 'text')), $block['items'])),
|
||||
'table', 'image' => '',
|
||||
default => implode('', array_column($block['runs'] ?? [], 'text')),
|
||||
};
|
||||
}
|
||||
|
||||
return trim((string) preg_replace('/\s+/u', ' ', implode(' ', $out)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeilen einer Tabellenzelle: Absätze, Aufzählungen und Zwischenüberschriften; ein Bild in der Zelle entfällt.
|
||||
*
|
||||
* @param list<array<string, mixed>> $blocks
|
||||
* @return list<array{segments: list<array{0: string, 1: bool, 2: bool}>, indent: float, marker: ?string}>
|
||||
*/
|
||||
private function cellLines(array $blocks, float $width, float $size, bool $header): array
|
||||
{
|
||||
$out = [];
|
||||
|
||||
foreach ($blocks as $block) {
|
||||
if (in_array($block['type'], ['bullets', 'numbered'], true)) {
|
||||
foreach ($block['items'] as $index => $item) {
|
||||
foreach ($this->lines($item, $width - 12, $size, $header) as $i => $segments) {
|
||||
$out[] = ['segments' => $segments, 'indent' => 12.0, 'marker' => $i === 0 ? ($block['type'] === 'bullets' ? '•' : ($index + 1).'.') : null];
|
||||
}
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! isset($block['runs'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($this->lines($block['runs'], $width, $size, $header || $block['type'] === 'heading', $block['type'] === 'quote') as $segments) {
|
||||
$out[] = ['segments' => $segments, 'indent' => 0.0, 'marker' => null];
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use App\Domain\Entitlement\Grant;
|
||||
use Closure;
|
||||
|
||||
/**
|
||||
* Die Bilder eines PDF: löst jedes Bild einmal auf und merkt sich, welche Bildfassungen tatsächlich gedruckt wurden,
|
||||
* damit der Ausgabenachweis sie wie jede andere Fassung des PDF führt.
|
||||
*/
|
||||
final class PdfImages
|
||||
{
|
||||
/** @var array<int, array{jpeg?: string, width?: int, height?: int, note?: string, grant: ?Grant, version: ?ContentElementVersion}|null> */
|
||||
private array $resolved = [];
|
||||
|
||||
/**
|
||||
* @param Closure(int): ?array{jpeg?: string, width?: int, height?: int, note?: string, grant: ?Grant, version: ?ContentElementVersion} $resolve
|
||||
*/
|
||||
public function __construct(private readonly Closure $resolve) {}
|
||||
|
||||
/**
|
||||
* @return array{jpeg?: string, width?: int, height?: int, note?: string}|null
|
||||
*/
|
||||
public function __invoke(int $id): ?array
|
||||
{
|
||||
if (! array_key_exists($id, $this->resolved)) {
|
||||
$this->resolved[$id] = ($this->resolve)($id);
|
||||
}
|
||||
|
||||
return $this->resolved[$id];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{version: ContentElementVersion, grant: Grant}>
|
||||
*/
|
||||
public function used(): array
|
||||
{
|
||||
$used = [];
|
||||
|
||||
foreach ($this->resolved as $found) {
|
||||
if ($found !== null && isset($found['jpeg']) && $found['version'] instanceof ContentElementVersion && $found['grant'] instanceof Grant) {
|
||||
$used[] = ['version' => $found['version'], 'grant' => $found['grant']];
|
||||
}
|
||||
}
|
||||
|
||||
return $used;
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,10 @@
|
||||
* WinAnsi). Absichtlich ohne Abhängigkeit: Ein Zahlungsbeleg ist ein Text mit Linien. Der Inhalt ist unkomprimiert und
|
||||
* enthält keinen Zeitstempel, damit dasselbe Dokument bei jedem Abruf byte-gleich ist und Tests den Text prüfen können.
|
||||
* Zeichen außerhalb von Windows-1252 werden durch „?“ ersetzt (das Minuszeichen U+2212 durch „-“).
|
||||
*
|
||||
* Für längere Dokumente (Handbuch) kann der Schreiber zusätzlich Flächen, JPEG-Bilder, Verweise innerhalb des Dokuments
|
||||
* (Inhaltsverzeichnis) und Lesezeichen setzen. Wer sie nicht nutzt, erhält dieselben Bytes wie zuvor: Die zusätzlichen
|
||||
* Objekte entstehen nur bei Bedarf und nach allen bisherigen.
|
||||
*/
|
||||
final class PdfDocument
|
||||
{
|
||||
@@ -20,6 +24,21 @@ final class PdfDocument
|
||||
/** Schräge Schnitte werden nur eingebunden, wenn das Dokument sie braucht (Belege bleiben unverändert). */
|
||||
private bool $usesItalic = false;
|
||||
|
||||
/** @var list<array{bytes: string, width: int, height: int}> */
|
||||
private array $images = [];
|
||||
|
||||
/** @var array<string, int> Prüfsumme der Bilddatei => Index in {@see self::$images} */
|
||||
private array $imageIndex = [];
|
||||
|
||||
/** @var array<int, array<int, true>> Seite => Bilder, die sie zeigt */
|
||||
private array $pageImages = [];
|
||||
|
||||
/** @var array<int, list<array{x: float, y: float, w: float, h: float, page: int, top: float}>> */
|
||||
private array $links = [];
|
||||
|
||||
/** @var list<array{title: string, page: int, top: float, level: int}> */
|
||||
private array $outline = [];
|
||||
|
||||
/** Breiten der Helvetica (Tausendstel der Schrifthöhe) für Zeichen 32 bis 126; schräg wie aufrecht. */
|
||||
private const REGULAR = [278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584];
|
||||
|
||||
@@ -31,6 +50,60 @@ public function addPage(): void
|
||||
$this->pages[] = '';
|
||||
}
|
||||
|
||||
/** Anzahl der bisher angelegten Seiten. */
|
||||
public function pageCount(): int
|
||||
{
|
||||
return count($this->pages);
|
||||
}
|
||||
|
||||
/** Gefüllte Fläche in einem Grauwert (0 schwarz, 1 weiß), zum Beispiel für Tabellenköpfe. */
|
||||
public function fillRect(float $x, float $y, float $w, float $h, float $gray): void
|
||||
{
|
||||
$this->append(sprintf("q %s g %s %s %s %s re f Q\n", $this->n($gray), $this->n($x), $this->n($y), $this->n($w), $this->n($h)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Setzt ein JPEG (RGB, aus `imagejpeg`) mit seiner linken unteren Ecke bei `$x`/`$y`. Dasselbe Bild wird nur einmal
|
||||
* im Dokument abgelegt.
|
||||
*/
|
||||
public function image(float $x, float $y, float $w, float $h, string $jpeg, int $pixelWidth, int $pixelHeight): void
|
||||
{
|
||||
$key = md5($jpeg);
|
||||
|
||||
if (! isset($this->imageIndex[$key])) {
|
||||
$this->imageIndex[$key] = count($this->images);
|
||||
$this->images[] = ['bytes' => $jpeg, 'width' => $pixelWidth, 'height' => $pixelHeight];
|
||||
}
|
||||
|
||||
$index = $this->imageIndex[$key];
|
||||
|
||||
if ($this->pages === []) {
|
||||
$this->addPage();
|
||||
}
|
||||
|
||||
$this->pageImages[array_key_last($this->pages)][$index] = true;
|
||||
$this->append(sprintf("q %s 0 0 %s %s %s cm /Im%d Do Q\n", $this->n($w), $this->n($h), $this->n($x), $this->n($y), $index + 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* Anklickbarer Bereich auf der aktuellen Seite, der zu einer Stelle im Dokument springt (Seitenindex ab 0, `$top` ist
|
||||
* die Höhe des Ziels auf der Zielseite).
|
||||
*/
|
||||
public function link(float $x, float $y, float $w, float $h, int $page, float $top): void
|
||||
{
|
||||
if ($this->pages === []) {
|
||||
$this->addPage();
|
||||
}
|
||||
|
||||
$this->links[array_key_last($this->pages)][] = ['x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'page' => $page, 'top' => $top];
|
||||
}
|
||||
|
||||
/** Lesezeichen (Ebene 1 oder 2) für die Gliederung in PDF-Betrachtern. */
|
||||
public function bookmark(string $title, int $page, float $top, int $level = 1): void
|
||||
{
|
||||
$this->outline[] = ['title' => $title, 'page' => $page, 'top' => $top, 'level' => $level >= 2 ? 2 : 1];
|
||||
}
|
||||
|
||||
public function text(float $x, float $y, string $text, float $size = 10, bool $bold = false, bool $italic = false): void
|
||||
{
|
||||
$font = $italic ? ($bold ? 'F4' : 'F3') : ($bold ? 'F2' : 'F1');
|
||||
@@ -145,9 +218,39 @@ public function output(string $title, ?string $keywords = null): string
|
||||
$kids = [];
|
||||
$next = 6;
|
||||
|
||||
foreach ($pages as $stream) {
|
||||
// Nummern der zusätzlichen Objekte: nach den Seiten und Schriften, in fester Reihenfolge (Verweise, Bilder, Gliederung).
|
||||
$cursor = 6 + 2 * count($pages) + ($this->usesItalic ? 2 : 0);
|
||||
$annotations = [];
|
||||
|
||||
foreach ($this->links as $pageIndex => $links) {
|
||||
foreach ($links as $link) {
|
||||
$annotations[$pageIndex][] = ['number' => $cursor++] + $link;
|
||||
}
|
||||
}
|
||||
|
||||
$imageNumbers = [];
|
||||
|
||||
foreach (array_keys($this->images) as $index) {
|
||||
$imageNumbers[$index] = $cursor++;
|
||||
}
|
||||
|
||||
$outlineRoot = $this->outline === [] ? null : $cursor++;
|
||||
$outlineNumbers = [];
|
||||
|
||||
foreach (array_keys($this->outline) as $index) {
|
||||
$outlineNumbers[$index] = $cursor++;
|
||||
}
|
||||
|
||||
foreach ($pages as $pageIndex => $stream) {
|
||||
$kids[] = $next.' 0 R';
|
||||
$objects[$next] = '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 '.self::WIDTH.' '.self::HEIGHT.'] /Resources << /Font << /F1 3 0 R /F2 4 0 R'.($this->usesItalic ? ' /F3 %ITALIC% 0 R /F4 %BOLDITALIC% 0 R' : '').' >> >> /Contents '.($next + 1).' 0 R >>';
|
||||
$xobjects = '';
|
||||
|
||||
foreach (array_keys($this->pageImages[$pageIndex] ?? []) as $index) {
|
||||
$xobjects .= ' /Im'.($index + 1).' '.$imageNumbers[$index].' 0 R';
|
||||
}
|
||||
|
||||
$annots = isset($annotations[$pageIndex]) ? ' /Annots ['.implode(' ', array_map(fn (array $link): string => $link['number'].' 0 R', $annotations[$pageIndex])).']' : '';
|
||||
$objects[$next] = '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 '.self::WIDTH.' '.self::HEIGHT.'] /Resources << /Font << /F1 3 0 R /F2 4 0 R'.($this->usesItalic ? ' /F3 %ITALIC% 0 R /F4 %BOLDITALIC% 0 R' : '').' >>'.($xobjects === '' ? '' : ' /XObject <<'.$xobjects.' >>').' >> /Contents '.($next + 1).' 0 R'.$annots.' >>';
|
||||
$objects[$next + 1] = '<< /Length '.strlen($stream)." >>\nstream\n".$stream.'endstream';
|
||||
$next += 2;
|
||||
}
|
||||
@@ -161,6 +264,32 @@ public function output(string $title, ?string $keywords = null): string
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($annotations as $links) {
|
||||
foreach ($links as $link) {
|
||||
$objects[$link['number']] = sprintf(
|
||||
'<< /Type /Annot /Subtype /Link /Rect [%s %s %s %s] /Border [0 0 0] /Dest [%d 0 R /XYZ 0 %s null] >>',
|
||||
$this->n($link['x']),
|
||||
$this->n($link['y']),
|
||||
$this->n($link['x'] + $link['w']),
|
||||
$this->n($link['y'] + $link['h']),
|
||||
6 + 2 * min($link['page'], count($pages) - 1),
|
||||
$this->n($link['top']),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($this->images as $index => $image) {
|
||||
$objects[$imageNumbers[$index]] = '<< /Type /XObject /Subtype /Image /Width '.$image['width'].' /Height '.$image['height'].' /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length '.strlen($image['bytes'])." >>\nstream\n".$image['bytes']."\nendstream";
|
||||
}
|
||||
|
||||
if ($outlineRoot !== null) {
|
||||
$objects[1] = '<< /Type /Catalog /Pages 2 0 R /Outlines '.$outlineRoot.' 0 R /PageMode /UseOutlines >>';
|
||||
|
||||
foreach ($this->outlineObjects($outlineRoot, $outlineNumbers, count($pages)) as $number => $body) {
|
||||
$objects[$number] = $body;
|
||||
}
|
||||
}
|
||||
|
||||
$objects[2] = '<< /Type /Pages /Kids ['.implode(' ', $kids).'] /Count '.count($pages).' >>';
|
||||
$objects[3] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>';
|
||||
$objects[4] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>';
|
||||
@@ -186,6 +315,46 @@ public function output(string $title, ?string $keywords = null): string
|
||||
return $pdf.'trailer'."\n<< /Size ".(count($objects) + 1).' /Root 1 0 R /Info 5 0 R >>'."\nstartxref\n".$xref."\n%%EOF\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* Gliederung (Lesezeichen): Ebene 1 unter der Wurzel, Ebene 2 unter dem vorangehenden Eintrag der Ebene 1.
|
||||
*
|
||||
* @param array<int, int> $numbers Objektnummer je Eintrag
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function outlineObjects(int $root, array $numbers, int $pageCount): array
|
||||
{
|
||||
$parentOf = [];
|
||||
$childrenOf = [];
|
||||
$lastTop = null;
|
||||
|
||||
foreach ($this->outline as $index => $item) {
|
||||
if ($item['level'] === 1 || $lastTop === null) {
|
||||
$parentOf[$index] = null;
|
||||
$lastTop = $index;
|
||||
} else {
|
||||
$parentOf[$index] = $lastTop;
|
||||
}
|
||||
|
||||
$childrenOf[$parentOf[$index] ?? -1][] = $index;
|
||||
}
|
||||
|
||||
$top = $childrenOf[-1];
|
||||
$objects = [$root => '<< /Type /Outlines /First '.$numbers[$top[0]].' 0 R /Last '.$numbers[$top[array_key_last($top)]].' 0 R /Count '.count($this->outline).' >>'];
|
||||
|
||||
foreach ($this->outline as $index => $item) {
|
||||
$siblings = $childrenOf[$parentOf[$index] ?? -1];
|
||||
$position = (int) array_search($index, $siblings, true);
|
||||
$kids = $childrenOf[$index] ?? [];
|
||||
$objects[$numbers[$index]] = '<< /Title ('.self::escape($item['title']).') /Parent '.($parentOf[$index] === null ? $root : $numbers[$parentOf[$index]]).' 0 R'
|
||||
.($position > 0 ? ' /Prev '.$numbers[$siblings[$position - 1]].' 0 R' : '')
|
||||
.($position < count($siblings) - 1 ? ' /Next '.$numbers[$siblings[$position + 1]].' 0 R' : '')
|
||||
.($kids === [] ? '' : ' /First '.$numbers[$kids[0]].' 0 R /Last '.$numbers[$kids[array_key_last($kids)]].' 0 R /Count '.count($kids))
|
||||
.' /Dest ['.(6 + 2 * min($item['page'], $pageCount - 1)).' 0 R /XYZ 0 '.$this->n($item['top']).' null] >>';
|
||||
}
|
||||
|
||||
return $objects;
|
||||
}
|
||||
|
||||
private function append(string $operators): void
|
||||
{
|
||||
if ($this->pages === []) {
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Media;
|
||||
|
||||
/**
|
||||
* Bereitet ein Bild für das PDF auf: Es wird mit GD gelesen, auf eine druckbare Größe verkleinert, auf Weiß gesetzt
|
||||
* (Transparenz gibt es im PDF-Schreiber nicht) und als JPEG neu kodiert. So braucht das PDF keine Bildbibliothek und
|
||||
* keine Rücksicht auf das Ausgangsformat. Was GD nicht lesen kann (zum Beispiel WebP in einem Image ohne WebP-Unterstützung),
|
||||
* liefert null; die Ausgabe zeigt dann einen Hinweis statt des Bildes.
|
||||
*/
|
||||
final class PdfImage
|
||||
{
|
||||
/** Längste Kante in Pixel; 1400 Pixel genügen für die Spaltenbreite einer A4-Seite bei guter Druckqualität. */
|
||||
public const MAX_EDGE = 1400;
|
||||
|
||||
/**
|
||||
* @return array{jpeg: string, width: int, height: int}|null
|
||||
*/
|
||||
public static function fromBytes(string $raw): ?array
|
||||
{
|
||||
if ($raw === '' || ! function_exists('imagecreatefromstring')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$source = @imagecreatefromstring($raw);
|
||||
|
||||
if ($source === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$width = imagesx($source);
|
||||
$height = imagesy($source);
|
||||
|
||||
if ($width < 1 || $height < 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$scale = min(1.0, self::MAX_EDGE / max($width, $height));
|
||||
$targetWidth = max(1, (int) round($width * $scale));
|
||||
$targetHeight = max(1, (int) round($height * $scale));
|
||||
$canvas = imagecreatetruecolor($targetWidth, $targetHeight);
|
||||
|
||||
if ($canvas === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
imagefill($canvas, 0, 0, (int) imagecolorallocate($canvas, 255, 255, 255));
|
||||
imagecopyresampled($canvas, $source, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height);
|
||||
|
||||
ob_start();
|
||||
$written = imagejpeg($canvas, null, 82);
|
||||
$jpeg = (string) ob_get_clean();
|
||||
|
||||
return $written && $jpeg !== '' ? ['jpeg' => $jpeg, 'width' => $targetWidth, 'height' => $targetHeight] : null;
|
||||
}
|
||||
}
|
||||
@@ -401,6 +401,16 @@ protected function richFelder(): array
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Texte dürfen Bilder aus dem Medienbestand enthalten (gemeinsamer Picker); Kurzangaben nicht.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
protected function richBilder(): array
|
||||
{
|
||||
return ['partBody', 'newTextBody'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
use App\Domain\Catalog\ContentService;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\EditorialVocabulary;
|
||||
use App\Domain\Catalog\EmbeddedImages;
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Domain\Catalog\IdentityDimension;
|
||||
use App\Domain\Catalog\IdentityDimensionValue;
|
||||
@@ -195,7 +196,7 @@ protected function mutateFormDataBeforeFill(array $data): array
|
||||
return [
|
||||
'working_title' => $this->getRecord()->working_title,
|
||||
'thumbnail_alt' => $this->getRecord()->thumbnail_alt,
|
||||
'body' => FormattedText::html($this->getRecord()->versions()->orderByDesc('number')->first()?->body),
|
||||
'body' => EmbeddedImages::forEditor($this->getRecord()->versions()->orderByDesc('number')->first()?->body),
|
||||
'display_title' => $this->getRecord()->display_title,
|
||||
'description' => FormattedText::html($this->getRecord()->description),
|
||||
'usage_note' => $this->getRecord()->usage_note,
|
||||
|
||||
@@ -791,6 +791,14 @@ protected function richFelder(): array
|
||||
return ['summary' => 'Kurzbeschreibung', 'descriptionText' => 'Ausführliche Beschreibung', 'bodyDraft' => 'Text der Fassung'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
protected function richBilder(): array
|
||||
{
|
||||
return ['bodyDraft'];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
|
||||
@@ -106,13 +106,15 @@ public function pickerResult(): array
|
||||
return ['items' => [], 'more' => false];
|
||||
}
|
||||
|
||||
if ($this->pickerPurpose === 'aufbau') {
|
||||
if (in_array($this->pickerPurpose, ['aufbau', 'textbild'], true)) {
|
||||
$image = $this->pickerPurpose === 'textbild';
|
||||
|
||||
return $this->filterByMaterialart(app(EditorialCatalog::class)->browse(
|
||||
$this->pickerQuery,
|
||||
$this->pickerKind,
|
||||
$image ? 'bild' : $this->pickerKind,
|
||||
$this->pickerDimension,
|
||||
$this->pickerExceptId(),
|
||||
false,
|
||||
$image,
|
||||
ctype_digit($this->pickerSaeule) ? (int) $this->pickerSaeule : 0,
|
||||
));
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
use App\Domain\Catalog\ContentElementVersion;
|
||||
use App\Domain\Catalog\ContentService;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\EmbeddedImages;
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Filament\Resources\ContentElements\Pages\EditContentElement;
|
||||
use Filament\Forms\Components\Component;
|
||||
@@ -71,7 +72,7 @@ public static function fields(ContentElement $element): array
|
||||
$latest = $element->versions()->orderByDesc('number')->first();
|
||||
|
||||
return [
|
||||
RichField::make('body', 'Text', live: false)->default(FormattedText::html($latest?->body)),
|
||||
RichField::make('body', 'Text', live: false)->default(EmbeddedImages::forEditor($latest?->body)),
|
||||
EditContentElement::uploadField(),
|
||||
Toggle::make('drop_file')
|
||||
->label('Datei in der neuen Fassung nicht mehr verwenden')
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
use App\Domain\Media\WebsiteRelease;
|
||||
use App\Filament\Resources\ContentElements\ContentElementResource;
|
||||
use App\Models\User;
|
||||
use Filament\Forms\Components\RichEditor\EditorCommand;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Livewire\Attributes\Url;
|
||||
|
||||
@@ -66,6 +67,12 @@ trait ManagesEditorialSurface
|
||||
|
||||
public bool $ausgabeOpen = false;
|
||||
|
||||
/** Der Editor, in den das gewählte Bild eingefügt wird (Eigenschaft der Seite), und seine Cursorstelle. */
|
||||
public string $textImageField = '';
|
||||
|
||||
/** @var array<string, mixed> */
|
||||
public array $textImageSelection = [];
|
||||
|
||||
/** @var array{aktion: string, argument: int|string|null, titel: string, text: string, label: string, gefahr: bool}|null */
|
||||
public ?array $bestaetigung = null;
|
||||
|
||||
@@ -596,6 +603,57 @@ public function closePicker(): void
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Öffnet den gemeinsamen Picker für ein Bild im Text. Der Editor ruft das mit seinem Namen und der Cursorstelle auf
|
||||
* ({@see RichField}). Gewählt wird eine freigegebene Bildfassung des Medienbestands; eine Adresse speichert der Text nie.
|
||||
*
|
||||
* @param array<string, mixed> $selection
|
||||
*/
|
||||
public function openTextImagePicker(string $field, array $selection = []): void
|
||||
{
|
||||
if (! method_exists($this, 'richKomponente') || $this->richKomponente($field) === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->textImageField = $field;
|
||||
$this->textImageSelection = $selection;
|
||||
$this->resetPicker('textbild');
|
||||
$this->pickerKind = 'bild';
|
||||
}
|
||||
|
||||
/**
|
||||
* Fügt die gewählte Bildfassung an der Cursorstelle ein. Nur freigegebene Fassungen: Der Text verweist auf genau
|
||||
* diese Fassung, und eine Dokumentfassung kann später nur freigegebene Bilder festschreiben.
|
||||
*/
|
||||
protected function insertTextImage(string $target): void
|
||||
{
|
||||
$component = method_exists($this, 'richKomponente') ? $this->richKomponente($this->textImageField) : null;
|
||||
$version = preg_match('/^element:(\d+)$/', $target, $match) === 1
|
||||
? ContentElementVersion::query()->with('element')->find($match[1])
|
||||
: null;
|
||||
|
||||
if ($component === null || ! $version instanceof ContentElementVersion || $version->element === null || $version->element->output_class !== 'bild') {
|
||||
$this->feedback('Dieses Bild lässt sich nicht einfügen.', true);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($version->status !== ContentVersionStatus::Bereit) {
|
||||
$this->feedback('„'.($version->element->display_title ?: $version->element->working_title).'“ ist noch nicht freigegeben. Gib das Bild im Medienbestand frei, dann lässt es sich einfügen.', true);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$alt = trim((string) ($version->element->website_alt ?: $version->element->display_title ?: $version->element->working_title));
|
||||
$component->runCommands([
|
||||
EditorCommand::make('insertContent', arguments: [[
|
||||
'type' => 'image',
|
||||
'attrs' => ['alt' => $alt, 'id' => (string) $version->id, 'src' => route('content.file', ['version' => $version->id], false)],
|
||||
]]),
|
||||
], editorSelection: $this->textImageSelection === [] ? null : $this->textImageSelection);
|
||||
$this->feedback('„'.($version->element->display_title ?: $version->element->working_title).'“ ist im Text eingefügt. Gespeichert wird mit dem Text.');
|
||||
}
|
||||
|
||||
public function pickerAllowsMany(): bool
|
||||
{
|
||||
return $this->pickerPurpose === 'praesentation' && $this->roleAllowsMany($this->presentationRole);
|
||||
@@ -625,6 +683,14 @@ public function confirmPicker(): void
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->pickerPurpose === 'textbild') {
|
||||
$target = $marked[0];
|
||||
$this->closePicker();
|
||||
$this->insertTextImage($target);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->guardEditorial();
|
||||
|
||||
if ($this->pickerPurpose === 'austausch' || ($this->pickerPurpose === 'praesentation' && $this->replacingKey !== null)) {
|
||||
@@ -684,7 +750,7 @@ public function assignFromPicker(string $target): void
|
||||
*/
|
||||
public function pickerKinds(): array
|
||||
{
|
||||
if ($this->pickerPurpose === 'vorschaubild') {
|
||||
if (in_array($this->pickerPurpose, ['vorschaubild', 'textbild'], true)) {
|
||||
return ['bild' => 'Bilder'];
|
||||
}
|
||||
|
||||
@@ -709,6 +775,7 @@ public function pickerTitle(): string
|
||||
'aufbau' => 'Bestandteil auswählen',
|
||||
'austausch' => 'Medium austauschen',
|
||||
'vorschaubild' => 'Vorschaubild aus dem Bestand',
|
||||
'textbild' => 'Bild in den Text einfügen',
|
||||
default => 'Medien auswählen',
|
||||
};
|
||||
}
|
||||
@@ -725,6 +792,7 @@ public function pickerConfirmLabel(): string
|
||||
'aufbau' => 'In den Aufbau übernehmen',
|
||||
'austausch' => 'Austauschen',
|
||||
'vorschaubild' => 'Als Vorschaubild übernehmen',
|
||||
'textbild' => 'Bild einfügen',
|
||||
default => $count === 1 ? '1 Medium übernehmen' : ($count === 0 ? 'Medien übernehmen' : $count.' Medien übernehmen'),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Support;
|
||||
|
||||
use App\Domain\Catalog\EmbeddedImages;
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use Filament\Forms\Components\RichEditor;
|
||||
use Filament\Schemas\Components\Component;
|
||||
@@ -41,6 +42,16 @@ protected function richFelder(): array
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Eigenschaften, deren Editor Bilder aus dem Medienbestand einfügen darf (Textinhalte, nicht Kurzangaben).
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
protected function richBilder(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
protected function richNamen(): array
|
||||
{
|
||||
@@ -51,7 +62,7 @@ public function richTextSchema(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->statePath('rich')
|
||||
->components(array_map(fn (string $name, string $label): RichEditor => RichField::make($name, $label, hideLabel: true), $this->richNamen(), $this->richFelder()));
|
||||
->components(array_map(fn (string $name, string $label): RichEditor => RichField::make($name, $label, hideLabel: true, images: in_array($name, $this->richBilder(), true) && method_exists($this, 'openTextImagePicker')), $this->richNamen(), $this->richFelder()));
|
||||
}
|
||||
|
||||
public function richKomponente(string $name): ?Component
|
||||
@@ -93,7 +104,7 @@ protected function richPush(string $name): void
|
||||
}
|
||||
|
||||
$canonical = FormattedText::canonical((string) $this->{$name});
|
||||
$component->state($canonical === '' ? null : $canonical);
|
||||
$component->state($canonical === '' ? null : FormattedText::forEditor($canonical, fn (int $id): string => EmbeddedImages::staffSource($id)));
|
||||
$this->richSeen[$name] = md5($canonical);
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
use App\Domain\Catalog\ContentService;
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Catalog\EditorialVocabulary;
|
||||
use App\Domain\Catalog\EmbeddedImages;
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use App\Domain\Catalog\IdentityProfile;
|
||||
use App\Domain\Media\PresentationFile;
|
||||
@@ -221,7 +222,7 @@ public static function fill(ContentElement $element): array
|
||||
'usage_note' => $element->usage_note,
|
||||
'license_note' => $element->license_note,
|
||||
'thumbnail_alt' => $element->thumbnail_alt,
|
||||
'body' => FormattedText::html($latest?->body),
|
||||
'body' => EmbeddedImages::forEditor($latest?->body),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
|
||||
use App\Domain\Catalog\FormattedText;
|
||||
use Filament\Forms\Components\RichEditor;
|
||||
use Filament\Forms\Components\RichEditor\RichEditorTool;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Illuminate\Support\Js;
|
||||
|
||||
/**
|
||||
* Der eine Editor für formatierte Texte (ADR-50): immer dieselbe Symbolleiste, dasselbe Ergebnis (bereinigtes HTML).
|
||||
@@ -15,10 +18,27 @@ final class RichField
|
||||
* @param ?string $label Bezeichnung des Felds; sie ist auch der Name für Hilfstechnik
|
||||
* @param bool $live Arbeitsplätze gleichen beim Verlassen des Felds ab ({@see ManagesRichFields}); Dialoge nicht
|
||||
* @param bool $hideLabel Die Bezeichnung zeigt der Arbeitsplatz selbst
|
||||
* @param bool $images Bilder aus dem Medienbestand einfügen; nur auf Seiten mit dem gemeinsamen Picker
|
||||
* ({@see ManagesEditorialSurface::openTextImagePicker()})
|
||||
*/
|
||||
public static function make(string $name, ?string $label = null, bool $live = true, bool $hideLabel = false): RichEditor
|
||||
public static function make(string $name, ?string $label = null, bool $live = true, bool $hideLabel = false, bool $images = false): RichEditor
|
||||
{
|
||||
$field = RichEditor::make($name)->toolbarButtons(FormattedText::TOOLBAR);
|
||||
$toolbar = FormattedText::TOOLBAR;
|
||||
|
||||
if ($images) {
|
||||
array_splice($toolbar, count($toolbar) - 1, 0, [['bild']]);
|
||||
}
|
||||
|
||||
$field = RichEditor::make($name)->toolbarButtons($toolbar);
|
||||
|
||||
if ($images) {
|
||||
$field->tools([
|
||||
RichEditorTool::make('bild')
|
||||
->label('Bild aus dem Medienbestand einfügen')
|
||||
->icon(Heroicon::Photo)
|
||||
->jsHandler('$wire.openTextImagePicker('.Js::from($name).', editorSelection)'),
|
||||
]);
|
||||
}
|
||||
|
||||
if ($live) {
|
||||
$field->live(onBlur: true);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Domain\Catalog\ArticleRelease;
|
||||
use App\Domain\Catalog\CompositionVersion;
|
||||
use App\Domain\Catalog\EmbeddedImages;
|
||||
use App\Domain\Catalog\ExerciseGuide;
|
||||
use App\Domain\Catalog\ExercisePdf;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
@@ -76,6 +77,7 @@ public function pdf(Request $request, LicenseArticle $article, ArticleRelease $r
|
||||
|
||||
$copy = DeliveryLog::newCopyId();
|
||||
$variant = collect($guide['variants'])->firstWhere('key', $guide['chosen']);
|
||||
$images = app(EmbeddedImages::class)->forPdf($request->user(), $article, $release);
|
||||
$content = $pdf->render(
|
||||
$guide,
|
||||
$sections,
|
||||
@@ -83,6 +85,7 @@ public function pdf(Request $request, LicenseArticle $article, ArticleRelease $r
|
||||
$copy,
|
||||
(string) ($variant['name'] ?? ''),
|
||||
route('member.exercise', ['article' => $article, 'release' => $release, 'path' => $path, 'variante' => $guide['chosen']]),
|
||||
$images,
|
||||
);
|
||||
$checksum = hash('sha256', $content);
|
||||
|
||||
@@ -94,6 +97,11 @@ public function pdf(Request $request, LicenseArticle $article, ArticleRelease $r
|
||||
}
|
||||
}
|
||||
|
||||
// Bilder im Text sind eigene Fassungen: Auch sie stehen im Ausgabenachweis dieses PDF.
|
||||
foreach ($images->used() as $image) {
|
||||
app(DeliveryLog::class)->write($image['grant'], $article, $release, $image['version'], 'laden', 'pdf', $checksum, 'k2', $copy, $located['version']->id);
|
||||
}
|
||||
|
||||
$name = str($guide['title'])->slug()->value() ?: 'uebung';
|
||||
|
||||
return response($content, 200, [
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
use App\Domain\Catalog\ContentElementVersion;
|
||||
use App\Domain\Catalog\ContentVersionStatus;
|
||||
use App\Domain\Catalog\EditorialVocabulary;
|
||||
use App\Domain\Catalog\EmbeddedImages;
|
||||
use App\Domain\Catalog\IdentityDimension;
|
||||
use App\Domain\Catalog\LicenseArticle;
|
||||
use App\Domain\Catalog\Pillar;
|
||||
@@ -278,6 +279,7 @@ public function show(Request $request, LicenseArticle $article): View
|
||||
'entries' => $entries,
|
||||
'title' => app(CourseOutline::class)->title($article),
|
||||
'kind' => app(CourseOutline::class)->kindLabel($article),
|
||||
'images' => $release === null ? null : app(EmbeddedImages::class)->forView($request->user(), $article, $release),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -319,6 +321,7 @@ public function media(
|
||||
'article' => $article,
|
||||
'version' => $version,
|
||||
'license' => $decision->grant->rights_snapshot['purpose'] ?? null,
|
||||
'images' => app(EmbeddedImages::class)->forView($request->user(), $article, $release),
|
||||
'reader' => $request->user()->name,
|
||||
'copy' => $delivery->copy_id,
|
||||
]);
|
||||
|
||||
Reference in new issue
Block a user