Zwei Werkzeuge im Texteditor (Symbol vor dem Absatz, Listenstil); gespeichert werden nur Schlüssel, Bild und Farbe setzt die Ausgabe ein. Kreisfarben aus der Palette, Verwendung wird mitgezählt. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
826 lines
32 KiB
PHP
826 lines
32 KiB
PHP
<?php
|
||
|
||
namespace App\Domain\Catalog;
|
||
|
||
use App\Domain\Cms\Widgets\Support\TextMarkers;
|
||
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, ADR-51).
|
||
*
|
||
* Gespeichert wird bereinigtes HTML aus einer festen Auswahl: Absatz, Zwischenüberschriften (h3 bis h6), fett, kursiv, Aufzählung,
|
||
* 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
|
||
* 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', 'h4', 'h5', 'h6', 'ul', 'ol', 'blockquote', 'table', 'img'];
|
||
|
||
/** Angaben der Redaktion, die formatiert gespeichert werden. Suchbegriffe, Titel und Teaser bleiben Klartext. */
|
||
public const FIELDS = ['summary', 'description'];
|
||
|
||
/** Schriftgrößen der Website (Schlüssel => Bezeichnung); nur im Profil `$site`. Die Werte stehen in `widgets.css`. */
|
||
public const SITE_SIZES = ['small' => 'Klein', 'large' => 'Groß', 'xlarge' => 'Sehr groß'];
|
||
|
||
/** Schriftfarben der Website (Schlüssel => Bezeichnung); nur im Profil `$site`. Die Farbwerte stehen in `widgets.css`. */
|
||
public const SITE_COLORS = ['marine' => 'Marine', 'gruen' => 'Grün', 'rot' => 'Rot', 'grau' => 'Grau'];
|
||
|
||
/** Ausrichtungen der Website außer der Vorgabe „linksbündig“ (so schreibt der Editor sie: `end` heißt rechtsbündig). */
|
||
private const SITE_ALIGNMENTS = ['center', 'end'];
|
||
|
||
/** @var array<string, HtmlSanitizer> je Profil eine Bereinigung (siehe sanitizer()) */
|
||
private static array $sanitizers = [];
|
||
|
||
/** Symbolleiste der Editoren; muss zur Auswahl oben passen. */
|
||
public const TOOLBAR = [
|
||
['bold', 'italic', 'link'],
|
||
['h3', 'h4', 'h5', 'h6'],
|
||
['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.
|
||
*
|
||
* `$site` ist das Profil der Website (CMS): Links auf Seiten der eigenen Website (`/materialien`, `#anker`) bleiben
|
||
* erhalten, dazu Ausrichtung (zentriert, rechtsbündig), Schriftgröße und Schriftfarbe aus festen Werten
|
||
* ({@see self::SITE_SIZES}, {@see self::SITE_COLORS}). Verwaltung und PDF kennen nur ausdrückliche Adressen
|
||
* (http, https, mailto) und keine dieser Auszeichnungen; sie fallen dort beim Speichern weg. Das Profil gehört zum Text:
|
||
* Wer mit `true` speichert, liest auch mit `true`.
|
||
*/
|
||
public static function canonical(?string $value, bool $site = false): string
|
||
{
|
||
$value = trim((string) $value);
|
||
|
||
if ($value === '') {
|
||
return '';
|
||
}
|
||
|
||
return self::normalize(self::isHtml($value) ? $value : self::legacyToHtml($value), $site);
|
||
}
|
||
|
||
/**
|
||
* 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, bool $site = false): string
|
||
{
|
||
$html = trim((string) $html);
|
||
|
||
return $html === '' ? '' : self::normalize($html, $site);
|
||
}
|
||
|
||
/**
|
||
* 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, bool $site = false): string
|
||
{
|
||
return self::renderImages(self::canonical($value, $site), $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<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;
|
||
}
|
||
|
||
/**
|
||
* Versieht die Zwischenüberschriften (h3 bis h6, auf oberster Ebene des Texts) mit Sprungmarken `<Präfix>-u<n>` und
|
||
* verschiebt ihre Stufe um `$shift` (höchstens h6). Die Marken zählen die nicht leeren Überschriften in ihrer Reihenfolge;
|
||
* {@see self::blocks()} zählt dieselben.
|
||
*
|
||
* @return array{html: string, headings: list<array{level: int, text: string, anchor: string}>}
|
||
*/
|
||
public static function anchorHeadings(string $html, string $prefix, int $shift = 0): array
|
||
{
|
||
if (preg_match('/<h[3-6][\s>]/i', $html) !== 1) {
|
||
return ['html' => $html, 'headings' => []];
|
||
}
|
||
|
||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||
$headings = [];
|
||
|
||
foreach (iterator_to_array($document->body->childNodes) as $node) {
|
||
if ($node->nodeType !== XML_ELEMENT_NODE || preg_match('/^h([3-6])$/', strtolower($node->nodeName), $match) !== 1) {
|
||
continue;
|
||
}
|
||
|
||
$text = trim((string) preg_replace('/\s+/u', ' ', (string) $node->textContent));
|
||
|
||
if ($text === '') {
|
||
continue;
|
||
}
|
||
|
||
$level = min(6, (int) $match[1] + $shift);
|
||
$anchor = $prefix.'-u'.(count($headings) + 1);
|
||
$replacement = $document->createElement('h'.$level);
|
||
$replacement->setAttribute('id', $anchor);
|
||
|
||
while ($node->firstChild !== null) {
|
||
$replacement->appendChild($node->firstChild);
|
||
}
|
||
|
||
$node->replaceWith($replacement);
|
||
$headings[] = ['level' => $level, 'text' => $text, 'anchor' => $anchor];
|
||
}
|
||
|
||
return ['html' => trim($document->body->innerHTML), 'headings' => $headings];
|
||
}
|
||
|
||
/**
|
||
* 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
|
||
{
|
||
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<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
|
||
{
|
||
$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<array<string, mixed>>
|
||
*/
|
||
public static function blocks(?string $value): array
|
||
{
|
||
$html = self::canonical($value);
|
||
|
||
if ($html === '') {
|
||
return [];
|
||
}
|
||
|
||
$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 ($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;
|
||
}
|
||
|
||
$level = preg_match('/^h([3-6])$/', $name, $heading) === 1 ? (int) $heading[1] : 0;
|
||
$type = match (true) {
|
||
$level > 0 => 'heading',
|
||
$name === 'blockquote' => 'quote',
|
||
default => 'paragraph',
|
||
};
|
||
|
||
// Ein Bild mitten im Absatz (so setzt der Editor es) teilt den Absatz: Text davor, Bild, Text danach.
|
||
$images = $node->querySelectorAll('img');
|
||
|
||
if (count($images) === 0) {
|
||
$blocks[] = self::textBlock($type, $level, self::runs($node));
|
||
|
||
continue;
|
||
}
|
||
|
||
$pending = [];
|
||
|
||
foreach ($node->childNodes as $child) {
|
||
if ($child->nodeType === XML_ELEMENT_NODE && strtolower($child->nodeName) === 'img') {
|
||
if (trim(self::runsText($pending)) !== '') {
|
||
$blocks[] = self::textBlock($type, $level, $pending);
|
||
}
|
||
|
||
$pending = [];
|
||
$blocks[] = ['type' => 'image', 'id' => (int) $child->getAttribute('data-id'), 'alt' => (string) $child->getAttribute('alt')];
|
||
|
||
continue;
|
||
}
|
||
|
||
$holder = $node->ownerDocument->createElement('span');
|
||
$holder->appendChild($child->cloneNode(true));
|
||
$pending = [...$pending, ...self::runs($holder)];
|
||
}
|
||
|
||
if (trim(self::runsText($pending)) !== '') {
|
||
$blocks[] = self::textBlock($type, $level, $pending);
|
||
}
|
||
}
|
||
|
||
return $blocks;
|
||
}
|
||
|
||
/**
|
||
* Ein Textblock; eine Überschrift trägt zusätzlich ihre Stufe (3 bis 6) und ihren Text ohne Auszeichnung.
|
||
*
|
||
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
|
||
* @return array<string, mixed>
|
||
*/
|
||
private static function textBlock(string $type, int $level, array $runs): array
|
||
{
|
||
return $type === 'heading'
|
||
? ['type' => $type, 'level' => $level, 'text' => self::runsText($runs), 'runs' => $runs]
|
||
: ['type' => $type, 'runs' => $runs];
|
||
}
|
||
|
||
/**
|
||
* 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, bool $site = false): string
|
||
{
|
||
$html = self::mapLegacyTags($html);
|
||
$html = trim(self::sanitizer($site)->sanitize($html));
|
||
|
||
if ($html === '') {
|
||
return '';
|
||
}
|
||
|
||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||
$body = $document->body;
|
||
|
||
if ($site) {
|
||
self::siteMarks($document);
|
||
}
|
||
|
||
// Ein Bild steht zwischen den Absätzen, in einem Absatz (so setzt der Editor es) oder in einer Tabellenzelle und braucht
|
||
// seine Bildfassung. Anderswo (Liste, Zitat, Überschrift) entfällt es.
|
||
foreach (iterator_to_array($document->querySelectorAll('img')) as $image) {
|
||
if (! self::mayHoldImage($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(['<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) || str_contains($out, '<img') ? $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 ($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 = '';
|
||
|
||
foreach ($node->childNodes as $child) {
|
||
if ($child->nodeType !== XML_ELEMENT_NODE || strtolower($child->nodeName) !== 'li') {
|
||
continue;
|
||
}
|
||
|
||
$inner = self::inner($child);
|
||
|
||
if (preg_match('/<p[\s>]/', $inner) !== 1) {
|
||
$inner = '<p>'.$inner.'</p>';
|
||
}
|
||
|
||
if (self::hasText($inner)) {
|
||
$items .= '<li>'.$inner.'</li>';
|
||
}
|
||
}
|
||
|
||
// Zeichen der Liste (Nummern im Kreis, Symbol): nur Schlüssel, die TextMarkers kennt; im Profil der
|
||
// Verwaltung hat die Bereinigung sie schon entfernt.
|
||
return $items === '' ? '' : '<'.$name.TextMarkers::attributes($name, $node).'>'.$items.'</'.$name.'>';
|
||
}
|
||
|
||
$inner = self::inner($node);
|
||
|
||
if ($name === 'blockquote' && preg_match('/<p[\s>]/', $inner) !== 1) {
|
||
$inner = '<p>'.$inner.'</p>';
|
||
}
|
||
|
||
// Die Ausrichtung ist im Webprofil schon auf `text-align: center|end` zurückgeführt (siehe siteMarks()).
|
||
$align = $name !== 'blockquote' && preg_match('/^text-align: (?:'.implode('|', self::SITE_ALIGNMENTS).')$/', (string) $node->getAttribute('style')) === 1
|
||
? ' style="'.$node->getAttribute('style').'"'
|
||
: '';
|
||
|
||
// Symbol vor dem Absatz (nur Absätze auf der obersten Ebene, siehe TextMarkers::attributes()).
|
||
$symbol = $name === 'p' ? TextMarkers::attributes('p', $node) : '';
|
||
|
||
return self::hasContent($inner) ? '<'.$name.$align.$symbol.'>'.$inner.'</'.$name.'>' : '';
|
||
}
|
||
|
||
/**
|
||
* Webprofil: Ausrichtung, Größe und Farbe auf feste Werte zurückführen. Stil und Klassen aus dem Editor oder von Hand
|
||
* sind nie maßgeblich: Ein Span trägt nur noch `class="color" data-color` (bekannter Schlüssel) und/oder `data-size`
|
||
* (bekannter Schlüssel), sonst entfällt er; Absatz und Zwischenüberschrift nur `style="text-align: center|end"`. So
|
||
* liest der Editor den Wert beim Öffnen wieder, und ein beliebiger Stil kommt nie auf die Seite.
|
||
*/
|
||
private static function siteMarks(HTMLDocument $document): void
|
||
{
|
||
foreach (iterator_to_array($document->querySelectorAll('span')) as $span) {
|
||
$color = (string) $span->getAttribute('data-color');
|
||
$size = (string) $span->getAttribute('data-size');
|
||
$color = array_key_exists($color, self::SITE_COLORS) ? $color : '';
|
||
$size = array_key_exists($size, self::SITE_SIZES) ? $size : '';
|
||
|
||
if ($color === '' && $size === '') {
|
||
while ($span->firstChild !== null) {
|
||
$span->parentNode->insertBefore($span->firstChild, $span);
|
||
}
|
||
|
||
$span->remove();
|
||
|
||
continue;
|
||
}
|
||
|
||
foreach (iterator_to_array($span->attributes) as $attribute) {
|
||
$span->removeAttribute($attribute->name);
|
||
}
|
||
|
||
if ($color !== '') {
|
||
$span->setAttribute('class', 'color');
|
||
$span->setAttribute('data-color', $color);
|
||
}
|
||
|
||
if ($size !== '') {
|
||
$span->setAttribute('data-size', $size);
|
||
}
|
||
}
|
||
|
||
foreach ($document->querySelectorAll('p, h3, h4, h5, h6') as $block) {
|
||
$align = preg_match('/(?:^|;)\s*text-align\s*:\s*(center|end|right)\s*(?:;|$)/i', (string) $block->getAttribute('style'), $match) === 1
|
||
? (strtolower($match[1]) === 'center' ? 'center' : 'end')
|
||
: null;
|
||
|
||
$block->removeAttribute('style');
|
||
|
||
if ($align !== null) {
|
||
$block->setAttribute('style', 'text-align: '.$align);
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 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|h[3-6]|img)[\s>]/', $inner) === 1 ? $inner : '<p>'.$inner.'</p>')).'</'.$name.'>';
|
||
}
|
||
|
||
if ($cells !== '') {
|
||
$rows .= '<tr>'.$cells.'</tr>';
|
||
}
|
||
}
|
||
|
||
return $rows !== '' && (self::hasText($rows) || str_contains($rows, '<img')) ? '<table><tbody>'.$rows.'</tbody></table>' : '';
|
||
}
|
||
|
||
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', 'img'], true)) {
|
||
$html .= self::block($child);
|
||
|
||
continue;
|
||
}
|
||
|
||
$html .= $node->ownerDocument->saveHtml($child);
|
||
}
|
||
|
||
return trim($html);
|
||
}
|
||
|
||
/** Wo darf ein Bild stehen: im Text, in einer Tabellenzelle oder in einem Absatz dort. */
|
||
private static function mayHoldImage(?Node $parent, Node $body): bool
|
||
{
|
||
if ($parent === null) {
|
||
return false;
|
||
}
|
||
|
||
$name = strtolower($parent->nodeName);
|
||
|
||
if ($parent === $body || in_array($name, ['td', 'th'], true)) {
|
||
return true;
|
||
}
|
||
|
||
return $name === 'p' && $parent->parentNode !== null && ($parent->parentNode === $body || in_array(strtolower($parent->parentNode->nodeName), ['td', 'th'], true));
|
||
}
|
||
|
||
/** Hat der Ausschnitt einen Inhalt: Text oder ein Bild? */
|
||
private static function hasContent(string $html): bool
|
||
{
|
||
return self::hasText($html) || str_contains($html, '<img');
|
||
}
|
||
|
||
private static function hasText(string $html): bool
|
||
{
|
||
return trim(html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8')) !== '';
|
||
}
|
||
|
||
/** b, i und die Überschriftsstufen 1 und 2 der Quelle werden auf die feste Auswahl abgebildet (h1 und h2 gehören dem Dokument und dem Kapitel); 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[12](?=[\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(bool $site = false): HtmlSanitizer
|
||
{
|
||
if (isset(self::$sanitizers[$site ? 'site' : 'catalog'])) {
|
||
return self::$sanitizers[$site ? 'site' : 'catalog'];
|
||
}
|
||
|
||
// Das Webprofil lässt zusätzlich Spans (Größe, Farbe) und den Stil an Absätzen und Überschriften zu; siteMarks()
|
||
// führt beides danach auf feste Werte zurück. Verwaltung und PDF kennen weder Spans noch Stile.
|
||
$text = $site ? ['style'] : [];
|
||
$paragraph = $site ? [...$text, ...TextMarkers::PARAGRAPH_ATTRIBUTES] : [];
|
||
$list = $site ? TextMarkers::LIST_ATTRIBUTES : [];
|
||
$config = (new HtmlSanitizerConfig)
|
||
->allowElement('p', $paragraph)
|
||
->allowElement('h3', $text)
|
||
->allowElement('h4', $text)
|
||
->allowElement('h5', $text)
|
||
->allowElement('h6', $text);
|
||
|
||
if ($site) {
|
||
$config = $config->allowElement('span', ['class', 'data-color', 'data-size']);
|
||
}
|
||
|
||
return self::$sanitizers[$site ? 'site' : 'catalog'] = new HtmlSanitizer(
|
||
$config
|
||
->allowElement('br')
|
||
->allowElement('strong')
|
||
->allowElement('em')
|
||
->allowElement('ul', $list)
|
||
->allowElement('ol', $list)
|
||
->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($site)
|
||
->forceAttribute('a', 'rel', 'noopener noreferrer')
|
||
->withMaxInputLength(100000),
|
||
);
|
||
}
|
||
}
|