Speichere formatierte Texte als bereinigtes HTML mit einem Editor (ADR-50)
Ein Baustein (FormattedText) bereinigt, bringt Werte in die kanonische Form und wandelt Klartext des Altbestands; RichField ist der eine Editor, ManagesRichFields verbindet ihn mit den Arbeitsplätzen. Formatiert sind Texte der Übungen und Textbausteine, Kurzbeschreibung und Beschreibung, Lernziel und Ausstattung. Mitgliederansicht und PDF zeigen fett, kursiv, Listen, Überschrift, Zitat und Link (PDF: schräge Schnitte, nur wenn gebraucht). Das Livewire-Limit für verschachtelte Pfade steigt auf 30, weil Aufzählungen sonst abgelehnt werden. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
be24f3bf64
commit
9fbd933e1e
50 files changed
+1461
-181
No files matched your search
@@ -27,11 +27,34 @@ public function text(string $field): ResolvedText
|
||||
return $this->texts[$field] ?? new ResolvedText(null, 'leer', null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Text einer Angabe. Formatierte Angaben (Kurzbeschreibung, Beschreibung) kommen hier als Klartext, damit nirgends
|
||||
* Auszeichnung in Karten, Listen, Suchergebnisse oder Meta-Angaben gelangt; wer die Formatierung zeigt, nutzt
|
||||
* {@see self::html()}.
|
||||
*/
|
||||
public function value(string $field): ?string
|
||||
{
|
||||
$value = $this->text($field)->value;
|
||||
|
||||
if ($value !== null && in_array($field, FormattedText::FIELDS, true)) {
|
||||
return FormattedText::plain($value) ?: null;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/** Gespeicherter Wert unverändert (HTML oder Klartext des Altbestands), für Bearbeitung und Vergleich. */
|
||||
public function raw(string $field): ?string
|
||||
{
|
||||
return $this->text($field)->value;
|
||||
}
|
||||
|
||||
/** Sicheres HTML einer formatierten Angabe; leer, wenn nichts da ist. */
|
||||
public function html(string $field): string
|
||||
{
|
||||
return FormattedText::html($this->text($field)->value);
|
||||
}
|
||||
|
||||
public function origin(string $field): string
|
||||
{
|
||||
return $this->text($field)->origin;
|
||||
|
||||
@@ -145,7 +145,8 @@ public function build(User $user, LicenseArticle $article, ArticleRelease $relea
|
||||
'grant' => $decision->grant,
|
||||
'download_grant' => $download?->grant,
|
||||
'state' => $decision->allowed ? 'ok' : ($version->status === ContentVersionStatus::Gesperrt ? 'gesperrt' : 'nicht_lizenziert'),
|
||||
'blocks' => $decision->allowed && $class === 'text' ? GuideText::blocks($version->body) : null,
|
||||
'blocks' => $decision->allowed && $class === 'text' ? FormattedText::blocks($version->body) : null,
|
||||
'html' => $decision->allowed && $class === 'text' ? FormattedText::html($version->body) : null,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -169,6 +170,7 @@ public function build(User $user, LicenseArticle $article, ArticleRelease $relea
|
||||
'exercise' => $exercise,
|
||||
'title' => $library->text($exercise->composition)['title'],
|
||||
'summary' => $library->text($exercise->composition)['summary'],
|
||||
'summary_html' => $library->text($exercise->composition)['summary_html'],
|
||||
'learning_goal' => $exercise->learning_goal,
|
||||
'duration_minutes' => $exercise->duration_minutes,
|
||||
'duration_max' => $exercise->duration_max,
|
||||
|
||||
@@ -77,17 +77,18 @@ public function render(array $guide, array $sections, string $licensee, string $
|
||||
$this->write(self::printable('Variante: '.$variantName), 11, true, 6);
|
||||
}
|
||||
|
||||
$facts = array_filter([
|
||||
filled($guide['learning_goal']) ? 'Lernziel: '.$guide['learning_goal'] : null,
|
||||
$guide['duration_minutes'] !== null ? 'Dauer: '.$guide['duration_minutes'].($guide['duration_max'] !== null ? ' bis '.$guide['duration_max'] : '').' Minuten' : null,
|
||||
filled($guide['prerequisites']) ? 'Voraussetzungen: '.$guide['prerequisites'] : null,
|
||||
filled($guide['material_note']) ? 'Ausstattung: '.$guide['material_note'] : null,
|
||||
]);
|
||||
$this->fact('Lernziel', $guide['learning_goal']);
|
||||
|
||||
foreach ($facts as $fact) {
|
||||
$this->write(self::printable($fact), 10.5, false, 4);
|
||||
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);
|
||||
}
|
||||
|
||||
if (filled($guide['prerequisites'])) {
|
||||
$this->write(self::printable('Voraussetzungen: '.$guide['prerequisites']), 10.5, false, 4);
|
||||
}
|
||||
|
||||
$this->fact('Ausstattung', $guide['material_note']);
|
||||
|
||||
$this->y -= 6;
|
||||
|
||||
foreach ($sections as $section) {
|
||||
@@ -137,41 +138,168 @@ private function section(array $section, string $guideUrl): void
|
||||
|
||||
$this->write($title, 12.5, true, 5);
|
||||
|
||||
foreach ($section['blocks'] ?? [] as $block) {
|
||||
match ($block['type']) {
|
||||
'heading' => $this->write(self::printable($block['text']), 11, true, 4),
|
||||
'paragraph' => $this->write(self::printable($block['text']), 10.5, false, 5),
|
||||
'bullets' => $this->items($block['items'], fn (int $n): string => '•'),
|
||||
'numbered' => $this->items($block['items'], fn (int $n): string => $n.'.'),
|
||||
};
|
||||
}
|
||||
$this->formatted($section['blocks'] ?? []);
|
||||
|
||||
$this->y -= 4;
|
||||
}
|
||||
|
||||
/** Angabe mit Bezeichnung; formatierte Angaben stehen unter der Bezeichnung, einfache dahinter. */
|
||||
private function fact(string $label, ?string $value): void
|
||||
{
|
||||
$blocks = FormattedText::blocks($value);
|
||||
|
||||
if ($blocks === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->write(self::printable($label.':'), 10.5, true, 2);
|
||||
$this->formatted($blocks);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $items
|
||||
* Blöcke aus {@see FormattedText::blocks()}: Absatz, Zwischenüberschrift, Zitat und Listen mit fett und kursiv.
|
||||
*
|
||||
* @param list<array<string, mixed>> $blocks
|
||||
*/
|
||||
private function items(array $items, callable $marker): void
|
||||
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) {
|
||||
$lines = PdfDocument::wrap(self::printable($item), self::RIGHT - self::LEFT - 18, 10.5);
|
||||
|
||||
foreach ($lines as $line => $text) {
|
||||
$this->room(14);
|
||||
|
||||
if ($line === 0) {
|
||||
$this->pdf->text(self::LEFT + 4, $this->y, $marker($index + 1), 10.5);
|
||||
}
|
||||
|
||||
$this->pdf->text(self::LEFT + 18, $this->y, $text, 10.5);
|
||||
$this->y -= 14;
|
||||
}
|
||||
$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) {
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Catalog;
|
||||
|
||||
use Dom\HTMLDocument;
|
||||
use Dom\Node;
|
||||
use Symfony\Component\HtmlSanitizer\HtmlSanitizer;
|
||||
use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig;
|
||||
|
||||
/**
|
||||
* Formatierter Text in der Verwaltung und im Mitgliederbereich (ADR-50).
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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
|
||||
* Text beginnt (nach Leerraum) mit einem der Blockelemente dieser Auswahl. Gespeichertes HTML ist kanonisch und beginnt
|
||||
* deshalb immer so; Klartext beginnt nie mit einem solchen Tag, wenn er nicht von Hand so geschrieben wurde.
|
||||
*
|
||||
* Verglichen und gehasht wird immer nur die kanonische Form ({@see self::canonical()}), damit das Öffnen im Editor oder
|
||||
* eine andere Schreibweise desselben Inhalts keine neue Fassung und keinen Scheinkonflikt erzeugt.
|
||||
*/
|
||||
final class FormattedText
|
||||
{
|
||||
/** Blockelemente, mit denen gespeichertes HTML beginnt. */
|
||||
private const BLOCKS = ['p', 'h3', 'ul', 'ol', 'blockquote'];
|
||||
|
||||
/** Angaben der Redaktion, die formatiert gespeichert werden. Suchbegriffe, Titel und Teaser bleiben Klartext. */
|
||||
public const FIELDS = ['summary', 'description'];
|
||||
|
||||
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']];
|
||||
|
||||
/** Wird der Wert als HTML gelesen (sonst als Klartext des Altbestands)? */
|
||||
public static function isHtml(?string $value): bool
|
||||
{
|
||||
return preg_match('/^\s*<(?:'.implode('|', self::BLOCKS).')[\s>\/]/i', (string) $value) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Kanonische Form eines gespeicherten oder eingegebenen Werts (HTML oder Klartext). Leer, wenn kein Text übrig ist.
|
||||
*/
|
||||
public static function canonical(?string $value): string
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
|
||||
if ($value === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
return self::normalize(self::isHtml($value) ? $value : self::legacyToHtml($value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Kanonische Form eines Werts, der sicher HTML ist (zum Beispiel aus der Quelle Shinkan), auch wenn er nicht mit
|
||||
* einem Blockelement beginnt.
|
||||
*/
|
||||
public static function canonicalHtml(?string $html): string
|
||||
{
|
||||
$html = trim((string) $html);
|
||||
|
||||
return $html === '' ? '' : self::normalize($html);
|
||||
}
|
||||
|
||||
/** Sicheres HTML zur Ausgabe (für `{!! !!}`); Klartext des Altbestands wird dabei umgewandelt. */
|
||||
public static function html(?string $value): string
|
||||
{
|
||||
return self::canonical($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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).
|
||||
*/
|
||||
public static function display(?string $value): string
|
||||
{
|
||||
$value = (string) $value;
|
||||
|
||||
return self::isHtml($value) ? self::canonical($value) : nl2br(e($value));
|
||||
}
|
||||
|
||||
public static function isBlank(?string $value): bool
|
||||
{
|
||||
return self::canonical($value) === '';
|
||||
}
|
||||
|
||||
/** Sind beide Werte inhaltlich gleich (unabhängig von Klartext oder Schreibweise des HTML)? */
|
||||
public static function same(?string $a, ?string $b): bool
|
||||
{
|
||||
return self::canonical($a) === self::canonical($b);
|
||||
}
|
||||
|
||||
/**
|
||||
* Text ohne Auszeichnung für Orte, die kein HTML vertragen (Zahlungsdienst, Meta-Beschreibung, Listen). Absätze sind
|
||||
* durch Leerzeilen getrennt, Listenpunkte beginnen mit „- “ beziehungsweise „1. “.
|
||||
*/
|
||||
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']),
|
||||
};
|
||||
}
|
||||
|
||||
return trim(implode("\n\n", $out));
|
||||
}
|
||||
|
||||
/** Kurzer Text für Listen und Karten. */
|
||||
public static function excerpt(?string $value, int $length = 120): string
|
||||
{
|
||||
$text = trim((string) preg_replace('/\s+/u', ' ', self::plain($value)));
|
||||
|
||||
return mb_strlen($text) > $length ? rtrim(mb_substr($text, 0, $length - 1)).'…' : $text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zerlegung in Blöcke mit Textabschnitten für das PDF. Ein Textabschnitt (Run) trägt `text`, `bold`, `italic` und
|
||||
* `href`.
|
||||
*
|
||||
* @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}>>}>
|
||||
*/
|
||||
public static function blocks(?string $value): array
|
||||
{
|
||||
$html = self::canonical($value);
|
||||
|
||||
if ($html === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
$blocks = [];
|
||||
|
||||
foreach ($document->body->childNodes as $node) {
|
||||
if ($node->nodeType !== XML_ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = strtolower($node->nodeName);
|
||||
|
||||
if (in_array($name, ['ul', 'ol'], true)) {
|
||||
$items = [];
|
||||
|
||||
foreach ($node->childNodes as $item) {
|
||||
if ($item->nodeType === XML_ELEMENT_NODE && strtolower($item->nodeName) === 'li') {
|
||||
$items[] = self::runs($item);
|
||||
}
|
||||
}
|
||||
|
||||
$blocks[] = ['type' => $name === 'ul' ? 'bullets' : 'numbered', 'items' => $items];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$blocks[] = [
|
||||
'type' => match ($name) {
|
||||
'h3' => 'heading',
|
||||
'blockquote' => 'quote',
|
||||
default => 'paragraph',
|
||||
},
|
||||
'runs' => self::runs($node),
|
||||
];
|
||||
}
|
||||
|
||||
return $blocks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Klartext des Altbestands als HTML: Absätze an Leerzeilen, Listen mit „- “, „• “ oder „1. “, Zwischenüberschriften
|
||||
* mit „## “. Dieselben Konventionen wie {@see GuideText}.
|
||||
*/
|
||||
public static function legacyToHtml(?string $text): string
|
||||
{
|
||||
$html = '';
|
||||
|
||||
foreach (GuideText::blocks($text) as $block) {
|
||||
$html .= match ($block['type']) {
|
||||
'heading' => '<h3>'.e($block['text']).'</h3>',
|
||||
'bullets' => '<ul>'.implode('', array_map(fn (string $item): string => '<li><p>'.e($item).'</p></li>', $block['items'])).'</ul>',
|
||||
'numbered' => '<ol>'.implode('', array_map(fn (string $item): string => '<li><p>'.e($item).'</p></li>', $block['items'])).'</ol>',
|
||||
default => '<p>'.e($block['text']).'</p>',
|
||||
};
|
||||
}
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
private static function normalize(string $html): string
|
||||
{
|
||||
$html = self::mapLegacyTags($html);
|
||||
$html = trim(self::sanitizer()->sanitize($html));
|
||||
|
||||
if ($html === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
$body = $document->body;
|
||||
$out = '';
|
||||
$loose = '';
|
||||
|
||||
$flush = function () use (&$out, &$loose): void {
|
||||
$loose = trim($loose);
|
||||
|
||||
if ($loose !== '' && trim(strip_tags(str_replace(['<br>', '<br/>', '<br />'], '', $loose))) !== '') {
|
||||
$out .= '<p>'.$loose.'</p>';
|
||||
}
|
||||
|
||||
$loose = '';
|
||||
};
|
||||
|
||||
foreach ($body->childNodes as $node) {
|
||||
if ($node->nodeType === XML_ELEMENT_NODE && in_array(strtolower($node->nodeName), self::BLOCKS, true)) {
|
||||
$flush();
|
||||
$out .= self::block($node);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$loose .= $document->saveHtml($node);
|
||||
}
|
||||
|
||||
$flush();
|
||||
|
||||
return self::hasText($out) ? $out : '';
|
||||
}
|
||||
|
||||
/** Ein Blockelement ohne Leerraum zwischen den Kindern; Listenpunkte tragen ihren Text immer in einem Absatz. */
|
||||
private static function block(Node $node): string
|
||||
{
|
||||
$name = strtolower($node->nodeName);
|
||||
|
||||
if (in_array($name, ['ul', 'ol'], true)) {
|
||||
$items = '';
|
||||
|
||||
foreach ($node->childNodes as $child) {
|
||||
if ($child->nodeType !== XML_ELEMENT_NODE || strtolower($child->nodeName) !== 'li') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$inner = self::inner($child);
|
||||
|
||||
if (! str_contains($inner, '<p>')) {
|
||||
$inner = '<p>'.$inner.'</p>';
|
||||
}
|
||||
|
||||
if (self::hasText($inner)) {
|
||||
$items .= '<li>'.$inner.'</li>';
|
||||
}
|
||||
}
|
||||
|
||||
return $items === '' ? '' : '<'.$name.'>'.$items.'</'.$name.'>';
|
||||
}
|
||||
|
||||
$inner = self::inner($node);
|
||||
|
||||
if ($name === 'blockquote' && ! str_contains($inner, '<p>')) {
|
||||
$inner = '<p>'.$inner.'</p>';
|
||||
}
|
||||
|
||||
return self::hasText($inner) ? '<'.$name.'>'.$inner.'</'.$name.'>' : '';
|
||||
}
|
||||
|
||||
private static function inner(Node $node): string
|
||||
{
|
||||
$html = '';
|
||||
|
||||
foreach ($node->childNodes as $child) {
|
||||
if ($child->nodeType === XML_ELEMENT_NODE && in_array(strtolower($child->nodeName), ['ul', 'ol', 'p', 'blockquote'], true)) {
|
||||
$html .= self::block($child);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$html .= $node->ownerDocument->saveHtml($child);
|
||||
}
|
||||
|
||||
return trim($html);
|
||||
}
|
||||
|
||||
private static function hasText(string $html): bool
|
||||
{
|
||||
return trim(html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8')) !== '';
|
||||
}
|
||||
|
||||
/** b, i und andere Überschriftsstufen der Quelle werden auf die feste Auswahl abgebildet; der Rest fällt in der Bereinigung weg. */
|
||||
private static function mapLegacyTags(string $html): string
|
||||
{
|
||||
$html = (string) preg_replace('/<(\/?)b(?=[\s>\/])/i', '<$1strong', $html);
|
||||
$html = (string) preg_replace('/<(\/?)i(?=[\s>\/])/i', '<$1em', $html);
|
||||
$html = (string) preg_replace('/<(\/?)h[1-6](?=[\s>\/])/i', '<$1h3', $html);
|
||||
|
||||
return (string) preg_replace('/<(\/?)div(?=[\s>\/])/i', '<$1p', $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{text: string, bold: bool, italic: bool, href: ?string}>
|
||||
*/
|
||||
private static function runs(Node $node, bool $bold = false, bool $italic = false, ?string $href = null): array
|
||||
{
|
||||
$runs = [];
|
||||
|
||||
foreach ($node->childNodes as $child) {
|
||||
if ($child->nodeType === XML_TEXT_NODE) {
|
||||
$runs[] = ['text' => (string) $child->textContent, 'bold' => $bold, 'italic' => $italic, 'href' => $href];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($child->nodeType !== XML_ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = strtolower($child->nodeName);
|
||||
|
||||
if ($name === 'br') {
|
||||
$runs[] = ['text' => "\n", 'bold' => $bold, 'italic' => $italic, 'href' => $href];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_array($name, ['p', 'ul', 'ol', 'blockquote'], true)) {
|
||||
// Verschachtelte Blöcke (Absatz im Listenpunkt) werden zu Fließtext.
|
||||
$runs = [...$runs, ...self::runs($child, $bold, $italic, $href)];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$runs = [...$runs, ...self::runs(
|
||||
$child,
|
||||
$bold || $name === 'strong',
|
||||
$italic || $name === 'em',
|
||||
$name === 'a' ? ((string) $child->getAttribute('href') ?: $href) : $href,
|
||||
)];
|
||||
}
|
||||
|
||||
return $runs;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
|
||||
*/
|
||||
private static function runsText(array $runs): string
|
||||
{
|
||||
return trim(implode('', array_map(fn (array $run): string => $run['text'], $runs)));
|
||||
}
|
||||
|
||||
private static function sanitizer(): HtmlSanitizer
|
||||
{
|
||||
return self::$sanitizer ??= new HtmlSanitizer(
|
||||
(new HtmlSanitizerConfig)
|
||||
->allowElement('p')
|
||||
->allowElement('br')
|
||||
->allowElement('h3')
|
||||
->allowElement('strong')
|
||||
->allowElement('em')
|
||||
->allowElement('ul')
|
||||
->allowElement('ol')
|
||||
->allowElement('li')
|
||||
->allowElement('blockquote')
|
||||
->allowElement('a', ['href'])
|
||||
->allowLinkSchemes(['http', 'https', 'mailto'])
|
||||
->allowRelativeLinks(false)
|
||||
->forceAttribute('a', 'rel', 'noopener noreferrer')
|
||||
->withMaxInputLength(100000),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -17,14 +17,44 @@ final class PdfDocument
|
||||
/** @var list<string> */
|
||||
private array $pages = [];
|
||||
|
||||
/** Schräge Schnitte werden nur eingebunden, wenn das Dokument sie braucht (Belege bleiben unverändert). */
|
||||
private bool $usesItalic = false;
|
||||
|
||||
/** 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];
|
||||
|
||||
/** Breiten der Helvetica-Bold für Zeichen 32 bis 126; schräg wie aufrecht. */
|
||||
private const BOLD = [278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584];
|
||||
|
||||
public function addPage(): void
|
||||
{
|
||||
$this->pages[] = '';
|
||||
}
|
||||
|
||||
public function text(float $x, float $y, string $text, float $size = 10, bool $bold = false): void
|
||||
public function text(float $x, float $y, string $text, float $size = 10, bool $bold = false, bool $italic = false): void
|
||||
{
|
||||
$this->append(sprintf("BT /%s %s Tf %s %s Td (%s) Tj ET\n", $bold ? 'F2' : 'F1', $this->n($size), $this->n($x), $this->n($y), self::escape($text)));
|
||||
$font = $italic ? ($bold ? 'F4' : 'F3') : ($bold ? 'F2' : 'F1');
|
||||
$this->usesItalic = $this->usesItalic || $italic;
|
||||
$this->append(sprintf("BT /%s %s Tf %s %s Td (%s) Tj ET\n", $font, $this->n($size), $this->n($x), $this->n($y), self::escape($text)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Genaue Breite in Punkt nach den Schriftbreiten der Helvetica, damit Textabschnitte mit verschiedenen Schnitten in
|
||||
* einer Zeile ohne Lücken aneinanderstoßen. Umlaute zählen wie ihr Grundbuchstabe, das ß wie ein kleines b, jedes
|
||||
* andere Zeichen außerhalb von ASCII wie eine Ziffer.
|
||||
*/
|
||||
public static function exactWidth(string $text, float $size = 10, bool $bold = false): float
|
||||
{
|
||||
$table = $bold ? self::BOLD : self::REGULAR;
|
||||
$units = 0;
|
||||
$text = strtr($text, ['ä' => 'a', 'ö' => 'o', 'ü' => 'u', 'Ä' => 'A', 'Ö' => 'O', 'Ü' => 'U', 'ß' => 'b', "\u{2019}" => "'", "\u{2026}" => '...', "\u{00A0}" => ' ']);
|
||||
|
||||
foreach (mb_str_split($text) as $char) {
|
||||
$code = strlen($char) === 1 ? ord($char) : 0;
|
||||
$units += $code >= 32 && $code <= 126 ? $table[$code - 32] : 556;
|
||||
}
|
||||
|
||||
return $units / 1000 * $size;
|
||||
}
|
||||
|
||||
public function textRight(float $xRight, float $y, string $text, float $size = 10, bool $bold = false): void
|
||||
@@ -117,11 +147,20 @@ public function output(string $title, ?string $keywords = null): string
|
||||
|
||||
foreach ($pages as $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 >> >> /Contents '.($next + 1).' 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 >>';
|
||||
$objects[$next + 1] = '<< /Length '.strlen($stream)." >>\nstream\n".$stream.'endstream';
|
||||
$next += 2;
|
||||
}
|
||||
|
||||
if ($this->usesItalic) {
|
||||
$objects[$next] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Oblique /Encoding /WinAnsiEncoding >>';
|
||||
$objects[$next + 1] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-BoldOblique /Encoding /WinAnsiEncoding >>';
|
||||
|
||||
foreach ($objects as $number => $body) {
|
||||
$objects[$number] = str_replace(['%ITALIC%', '%BOLDITALIC%'], [(string) $next, (string) ($next + 1)], $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 >>';
|
||||
|
||||
Reference in new issue
Block a user