\/]/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, items?: list>}> */ public static function blocks(?string $value): array { $html = self::canonical($value); if ($html === '') { return []; } $document = HTMLDocument::createFromString(''.$html.'', 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' => '

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

', 'bullets' => '', '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; $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) ? $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, '

')) { $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.'' : ''; } 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('a', ['href']) ->allowLinkSchemes(['http', 'https', 'mailto']) ->allowRelativeLinks(false) ->forceAttribute('a', 'rel', 'noopener noreferrer') ->withMaxInputLength(100000), ); } }