`). * 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 * 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', 'table', 'img']; /** 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'], ['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 { 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. * * 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::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, ?callable $images = null): string { $value = (string) $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 */ public static function imageIds(?string $value): array { $html = self::canonical($value); if ($html === '' || ! str_contains($html, ''.$html.'', 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, ''.$html.'', 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, ''.$html.'', 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 { 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) { $text = self::plainBlock($block); if ($text !== '') { $out[] = $text; } } return trim(implode("\n\n", $out)); } /** * @param array $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 { $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`. 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> */ public static function blocks(?string $value): array { $html = self::canonical($value); if ($html === '') { return []; } $document = HTMLDocument::createFromString(''.$html.'', LIBXML_NOERROR); return self::extractBlocks($document->body); } /** * @return list> */ private static function extractBlocks(Node $parent): array { $blocks = []; foreach ($parent->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; } 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', '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' => '

'.e($block['text']).'

', 'bullets' => '
    '.implode('', array_map(fn (string $item): string => '
  • '.e($item).'

  • ', $block['items'])).'
', 'numbered' => '
    '.implode('', array_map(fn (string $item): string => '
  1. '.e($item).'

  2. ', $block['items'])).'
', default => '

'.e($block['text']).'

', }; } 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(''.$html.'', 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 = ''; $flush = function () use (&$out, &$loose): void { $loose = trim($loose); if ($loose !== '' && trim(strip_tags(str_replace(['
', '
', '
'], '', $loose))) !== '') { $out .= '

'.$loose.'

'; } $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) || str_contains($out, 'nodeName); if ($name === 'img') { $id = (int) $node->getAttribute('data-id'); return $id > 0 ? ''.e(trim((string) $node->getAttribute('alt'))).'' : ''; } if ($name === 'table') { return self::table($node); } 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, '

')) { $inner = '

'.$inner.'

'; } if (self::hasText($inner)) { $items .= '
  • '.$inner.'
  • '; } } return $items === '' ? '' : '<'.$name.'>'.$items.''; } $inner = self::inner($node); if ($name === 'blockquote' && ! str_contains($inner, '

    ')) { $inner = '

    '.$inner.'

    '; } return self::hasText($inner) ? '<'.$name.'>'.$inner.'' : ''; } /** * 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 === '' ? '

    ' : (preg_match('/^<(?:p|ul|ol|blockquote|h3)[\s>]/', $inner) === 1 ? $inner : '

    '.$inner.'

    ')).''; } if ($cells !== '') { $rows .= ''.$cells.''; } } return $rows !== '' && self::hasText($rows) ? ''.$rows.'
    ' : ''; } 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 */ 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 $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('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) ->forceAttribute('a', 'rel', 'noopener noreferrer') ->withMaxInputLength(100000), ); } }