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:
LarsandClaude Sonnet 5.5 committed 2026-11-24 11:31:03 +01:00
1 parent 219962daff
commit c57a506f85
27 files changed
+1729 -219

No files matched your search

+260 -19
View File
@@ -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, Ereignis­attribute
* 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,
* Ereignis­attribute 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)