Führe Dokumente mit Kapiteln, Fassung, Seite und PDF mit Inhaltsverzeichnis ein (ADR-51)

Ein Dokument ist eine Komposition der Art document, ein Kapitel ein Text mit der
automatischen Materialart Dokumentkapitel; die Ebene steht in der Rolle. Der
Aufbaueditor bekommt den Kapitelarbeitsplatz (Übersicht, Ordnen als Block,
offene Eingaben bleiben beim Wechsel erhalten, Speichern als Entwurf,
Bereitstellen als Dokumentfassung). Module und Programme binden eine Fassung
über den gemeinsamen Picker ein. Mitglieder lesen sie mit anklickbarem
Inhaltsverzeichnis und laden ein PDF mit Inhaltsverzeichnis, Seitenzahlen,
Tabellen und Bildern. Ein älterer Stand liefert die gebundene Fassung weiter.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Sonnet 5.5 committed 2026-11-24 12:23:18 +01:00
1 parent c57a506f85
commit 3e2fd872c2
43 files changed
+2827 -64

No files matched your search

+8 -1
View File
@@ -9,6 +9,8 @@ enum CompositionKind: string
case Kurs = 'kurs';
/** Seit der Übungsverwaltung: die fachliche Übung. Der ältere Wert `uebung` bezeichnet in der Verwaltung das Modul. */
case Exercise = 'exercise';
/** Ein zusammenhängendes Dokument aus Kapiteln, zum Beispiel ein Trainerhandbuch (ADR-51). */
case Document = 'document';
/**
* @return list<string>
@@ -25,6 +27,7 @@ public function label(): string
self::Uebung => 'Modul',
self::Kurs => 'Kurs',
self::Exercise => 'Übung',
self::Document => 'Dokument',
};
}
@@ -35,6 +38,7 @@ public function plural(): string
self::Uebung => 'Module',
self::Kurs => 'Kurse',
self::Exercise => 'Übungen',
self::Document => 'Dokumente',
};
}
@@ -45,6 +49,7 @@ public function createLabel(): string
self::Uebung => 'Modul anlegen',
self::Kurs => 'Kurs anlegen',
self::Exercise => 'Übung anlegen',
self::Document => 'Dokument anlegen',
};
}
@@ -55,6 +60,7 @@ public function explanation(): string
self::Uebung => 'Eine konkrete Lernsituation, zum Beispiel aus Film und Merkblatt. Dieselben Medien können in mehreren Übungen stecken.',
self::Kurs => 'Ein Ablauf für den Kursbetrieb aus Übungen, Kombinationen und Medien. Ein Kurs ist keine Übung.',
self::Exercise => 'Eine Übung mit Lernziel, Vorbereitung, Durchführung und Varianten, mit Texten und Medien in fester Abfolge. Sie wird in Module und Programme aufgenommen.',
self::Document => 'Ein zusammenhängendes Dokument, zum Beispiel ein Trainerhandbuch, aus Kapiteln und Unterkapiteln. Eine Fassung schreibt Reihenfolge und Texte fest; sie wird in Module und Programme aufgenommen und erscheint für Mitglieder mit Inhaltsverzeichnis und als PDF.',
};
}
@@ -65,6 +71,7 @@ public function deskLabel(): string
self::Uebung => 'Modul',
self::Kurs => 'Programm',
self::Exercise => 'Übung',
self::Document => 'Dokument',
};
}
@@ -74,7 +81,7 @@ public function deskExplanation(): string
self::Kombination => $this->explanation(),
self::Uebung => 'Ein Modul mit Lernziel, Zeit, Material und geordneten Bestandteilen. Dieselben Medien können in mehreren Modulen stecken.',
self::Kurs => 'Ein Programm aus Modulen und weiteren Inhalten.',
self::Exercise => $this->explanation(),
self::Exercise, self::Document => $this->explanation(),
};
}
+36
View File
@@ -164,6 +164,42 @@ public function reviseElementContent(ContentElementVersion $version, string $bod
return $version->refresh();
}
/**
* Ändert den Text einer Fassung nur als Entwurf. Ist die Fassung schon festgeschrieben (in einer bereitgestellten
* Komposition oder einem Stand), entsteht eine neue Entwurfsfassung und die festgeschriebene bleibt unverändert.
* Anders als {@see self::reviseElementContent()} wird nichts bereitgestellt: Das geschieht erst mit der Fassung des
* Dokuments.
*/
public function reviseElementDraft(ContentElementVersion $version, string $body): ContentElementVersion
{
$body = trim($body);
if ($body === '') {
throw new DomainRuleException('Der Text braucht einen Inhalt.');
}
$version->loadMissing('element');
if ($version->status === ContentVersionStatus::Gesperrt) {
throw new DomainRuleException('Eine deaktivierte Fassung lässt sich nicht ändern.');
}
if (trim((string) $version->body) === $body) {
return $version;
}
if ($version->status === ContentVersionStatus::Entwurf) {
return $this->reviseElementContent($version, $body);
}
// Eine bereitgestellte Fassung, die nirgends festgeschrieben ist, wird weiterhin an Ort und Stelle geändert.
if (! $this->isCommitted($version)) {
return $this->reviseElementContent($version, $body);
}
return $this->draftElementVersion($version->element, $body);
}
public function elementReleaseProblem(ContentElementVersion $version): ?string
{
$version->loadMissing('element');
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Domain\Catalog;
/**
* Kapitel eines Dokuments: Textabschnitte im gemeinsamen Medienbestand mit der automatischen Materialart „Dokumentkapitel“
* und dem Verweis auf ihr Dokument (`origin_composition_id`), wie die Übungsabschnitte ({@see ExerciseSections}).
*/
final class DocumentChapters
{
public function kindId(): ?int
{
$id = EditorialContentKind::query()->where('slug', EditorialContentKind::DOCUMENT_CHAPTER_SLUG)->value('id');
return $id === null ? null : (int) $id;
}
public function mark(ContentElement $element, Composition $document): void
{
$element->origin_composition_id = $document->getKey();
if ($element->editorial_content_kind_id === null) {
$element->editorial_content_kind_id = $this->kindId();
}
$element->save();
}
}
+91
View File
@@ -0,0 +1,91 @@
<?php
namespace App\Domain\Catalog;
use App\Domain\Entitlement\DecideAccess;
use App\Http\LibraryCatalog;
use App\Models\User;
/**
* Das Dokument, wie ein Stand es festschreibt: die im Stand gebundene Dokumentfassung mit ihren Kapiteln und je Kapitel die
* Entscheidung der zentralen Rechteprüfung (`DecideAccess`). Ansicht und PDF lesen dieses Ergebnis; beide zeigen dieselbe
* Kapitelreihenfolge und dieselben gebundenen Textfassungen. Eine spätere Bearbeitung des Dokuments ändert einen älteren Stand
* nicht: Der Stand verweist auf die Fassung, die er festgeschrieben hat.
*/
class DocumentGuide
{
public function __construct(
private readonly DecideAccess $access,
private readonly DocumentReader $reader,
) {}
/**
* @return array<string, mixed>
*/
public function build(User $user, LicenseArticle $article, ArticleRelease $release, CompositionVersion $document): array
{
$document->loadMissing('composition');
$library = app(LibraryCatalog::class);
$images = app(EmbeddedImages::class)->forView($user, $article, $release);
$chapters = [];
foreach ($this->reader->fromVersion($document) as $chapter) {
$version = $chapter['version'];
$view = ($this->access)($user, $article, $release, $version, 'ansehen');
$download = ($this->access)($user, $article, $release, $version, 'laden');
$chapters[] = [
'number' => $chapter['number'],
'level' => $chapter['level'],
'anchor' => $chapter['anchor'],
'title' => $chapter['title'],
'version' => $version,
'allowed' => $view->allowed,
'grant' => $view->grant,
'may_download' => $download->allowed,
'download_grant' => $download->grant,
'state' => $view->allowed ? 'ok' : ($version->status === ContentVersionStatus::Gesperrt ? 'gesperrt' : 'nicht_lizenziert'),
'html' => $view->allowed ? $this->shiftHeadings(FormattedText::html($version->body, $images)) : null,
'blocks' => $view->allowed ? FormattedText::blocks($version->body) : null,
];
}
$text = $library->text($document->composition);
return [
'document' => $document,
'title' => $text['title'],
'summary_html' => $text['summary_html'],
'chapters' => $chapters,
];
}
/**
* Zwischenüberschriften im Kapiteltext stehen eine Ebene unter dem Kapiteltitel (h3 wird h4), damit die
* Überschriftenfolge der Seite stimmt: Dokument h1, Kapitel h2, Unterkapitel h3, Zwischenüberschrift h4.
*/
public static function shiftHeadings(string $html): string
{
return (string) preg_replace('/<(\/?)h3(?=[\s>])/i', '<$1h4', $html);
}
/**
* Darf das PDF entstehen? Jedes Kapitel muss für `laden` zulässig sein; sonst fehlte ein Teil des Handbuchs.
*
* @param array<string, mixed> $guide
*/
public function pdfAllowed(array $guide): bool
{
if ($guide['chapters'] === []) {
return false;
}
foreach ($guide['chapters'] as $chapter) {
if (! $chapter['allowed'] || ! $chapter['may_download']) {
return false;
}
}
return true;
}
}
+83
View File
@@ -0,0 +1,83 @@
<?php
namespace App\Domain\Catalog;
/**
* Gliederung eines Dokuments (ADR-51). Ein Dokument ist eine flache Folge von Kapiteln; die Ebene steht in der Rolle des
* Mitglieds: „Kapitel“ (Ebene 1) oder „Unterkapitel“ (Ebene 2). Ein Unterkapitel gehört zum Kapitel davor. Die Nummern
* („3“, „3.2“) entstehen aus der Reihenfolge und werden nirgends gespeichert; Editor, Ansicht und PDF zählen gleich.
*/
final class DocumentOutline
{
public const CHAPTER = 'Kapitel';
public const SUBCHAPTER = 'Unterkapitel';
public static function level(?string $role): int
{
return trim((string) $role) === self::SUBCHAPTER ? 2 : 1;
}
public static function role(int $level): string
{
return $level >= 2 ? self::SUBCHAPTER : self::CHAPTER;
}
/**
* Ebene und Nummer je Eintrag. Ein Unterkapitel ohne Kapitel davor zählt als Kapitel.
*
* @param list<string> $roles
* @return list<array{level: int, number: string, anchor: string}>
*/
public static function numbering(array $roles): array
{
$chapter = 0;
$sub = 0;
$out = [];
foreach ($roles as $role) {
$level = self::level($role);
if ($level === 2 && $chapter === 0) {
$level = 1;
}
if ($level === 1) {
$chapter++;
$sub = 0;
$number = (string) $chapter;
} else {
$sub++;
$number = $chapter.'.'.$sub;
}
$out[] = ['level' => $level, 'number' => $number, 'anchor' => 'kapitel-'.str_replace('.', '-', $number)];
}
return $out;
}
/**
* Letzter Index des Blocks, den der Eintrag bei `$index` mit seinen Unterkapiteln bildet.
*
* @param list<string> $roles
*/
public static function blockEnd(array $roles, int $index): int
{
if (self::numbering($roles)[$index]['level'] === 2) {
return $index;
}
$end = $index;
for ($i = $index + 1; $i < count($roles); $i++) {
if (self::level($roles[$i]) !== 2) {
break;
}
$end = $i;
}
return $end;
}
}
+196
View File
@@ -0,0 +1,196 @@
<?php
namespace App\Domain\Catalog;
use App\Domain\Commerce\Receipt\PdfDocument;
use Closure;
use Transliterator;
/**
* Druckbare Ausgabe eines Dokuments (DIN A4) aus demselben Ergebnis wie die Ansicht ({@see DocumentGuide}): Titelseite mit
* anklickbarem Inhaltsverzeichnis samt Seitenzahlen, jedes Kapitel der ersten Ebene beginnt auf einer neuen Seite,
* Lesezeichen für die Gliederung des PDF-Betrachters. Fußzeile mit Lizenznehmer, Lizenzkopie und „Seite n von m“ auf jeder
* Seite (K2), die Kennung in den Metadaten (K1). Die Datei wird bei jedem Abruf neu erzeugt und nie abgelegt.
*
* Seitenzahlen stehen erst nach dem Satz fest. Der Satz läuft deshalb so oft, bis Inhaltsverzeichnis, Kapitelanfänge und
* Seitenzahl sich nicht mehr ändern (in der Regel zweimal).
*/
class DocumentPdf
{
private const LEFT = 56.0;
private const RIGHT = 539.0;
private const TOP = 790.0;
private const BOTTOM = 72.0;
private PdfDocument $pdf;
private PdfFlow $flow;
private int $page = 0;
private string $footer = '';
private int $total = 0;
/** @var array<string, array{page: int, top: float}> */
private array $starts = [];
/**
* @param array<string, mixed> $guide Ergebnis von {@see DocumentGuide::build}
*/
public function render(array $guide, string $licensee, string $copyId, ?PdfImages $images = null): string
{
$starts = [];
$total = 0;
$bytes = '';
for ($pass = 0; $pass < 5; $pass++) {
$bytes = $this->pass($guide, $licensee, $copyId, $images, $starts, $total);
if ($this->starts === $starts && $this->total === $total) {
break;
}
$starts = $this->starts;
$total = $this->total;
}
return $bytes;
}
/**
* @param array<string, mixed> $guide
* @param array<string, array{page: int, top: float}> $known Kapitelanfänge aus dem vorigen Durchgang
*/
private function pass(array $guide, string $licensee, string $copyId, ?PdfImages $images, array $known, int $total): string
{
$this->pdf = new PdfDocument;
$this->page = 0;
$this->total = 0;
$this->starts = [];
$this->footer = PdfFlow::printable('Lizenziert für '.$licensee.' · Lizenzkopie '.$copyId);
$this->flow = new PdfFlow($this->pdf, self::LEFT, self::RIGHT, self::TOP, self::BOTTOM, function (): void {
$this->closePage();
$this->newPage();
}, $images === null ? null : Closure::fromCallable($images));
$knownTotal = $total;
$this->total = $knownTotal;
$this->newPage();
$this->flow->write(PdfFlow::printable((string) $guide['title']), 24, true, 10);
$this->flow->write('Inhaltsverzeichnis', 14, true, 8, keep: 40);
foreach ($guide['chapters'] as $chapter) {
$this->contentsLine($chapter, $known[$chapter['anchor']] ?? ['page' => 1, 'top' => self::TOP]);
}
foreach ($guide['chapters'] as $chapter) {
$this->chapter($chapter);
}
$this->closePage();
$total = $this->page;
$starts = $this->starts;
$bytes = $this->pdf->output($this->asciiTitle((string) $guide['title']), 'Lizenzkopie '.$copyId);
$this->total = $total;
$this->starts = $starts;
return $bytes;
}
/**
* Eine Zeile des Inhaltsverzeichnisses: Nummer und Titel, Punktlinie, Seitenzahl; die ganze Zeile springt zum Kapitel.
*
* @param array<string, mixed> $chapter
* @param array{page: int, top: float} $target
*/
private function contentsLine(array $chapter, array $target): void
{
$level = $chapter['level'];
$size = $level === 1 ? 11.0 : 10.0;
$indent = $level === 1 ? 0.0 : 18.0;
$label = PdfFlow::printable($chapter['number'].' '.$chapter['title']);
$pageText = (string) $target['page'];
$numberWidth = PdfDocument::exactWidth($pageText, $size, false);
$lines = PdfDocument::wrap($label, self::RIGHT - self::LEFT - $indent - $numberWidth - 14, $size, $level === 1);
$x = self::LEFT + $indent;
$this->flow->room(count($lines) * ($size + 4) + 2);
$top = $this->flow->y;
foreach ($lines as $index => $line) {
$this->pdf->text($x, $this->flow->y, $line, $size, $level === 1);
if ($index === count($lines) - 1) {
$used = PdfDocument::exactWidth($line, $size, $level === 1) + 4;
$room = self::RIGHT - $numberWidth - 4 - ($x + $used);
$dots = (int) floor($room / PdfDocument::exactWidth('.', 8, false));
if ($dots > 2) {
$this->pdf->text($x + $used, $this->flow->y, str_repeat('.', $dots), 8);
}
$this->pdf->textRight(self::RIGHT, $this->flow->y, $pageText, $size);
}
$this->flow->y -= $size + 4;
}
$this->pdf->link(self::LEFT, $this->flow->y + 2, self::RIGHT - self::LEFT, $top - $this->flow->y, max(0, $target['page'] - 1), $target['top']);
$this->flow->y -= 2;
}
/**
* @param array<string, mixed> $chapter
*/
private function chapter(array $chapter): void
{
$level = $chapter['level'];
if ($level === 1) {
$this->closePage();
$this->newPage();
}
$size = $level === 1 ? 18.0 : 13.5;
$title = PdfFlow::printable($chapter['number'].' '.$chapter['title']);
$this->flow->room(($size + 4) + 60);
$top = $this->flow->y + $size;
$this->starts[$chapter['anchor']] = ['page' => $this->page, 'top' => $top];
$this->pdf->bookmark($chapter['number'].' '.$chapter['title'], $this->page - 1, $top, $level);
$this->flow->y -= $level === 1 ? 0 : 6;
$this->flow->write($title, $size, true, $level === 1 ? 10 : 5, keep: 40);
if (! $chapter['allowed']) {
$this->flow->write('Dieses Kapitel ist derzeit nicht verfügbar.', 10.5, false, 6);
return;
}
$this->flow->formatted($chapter['blocks'] ?? []);
$this->flow->y -= 4;
}
private function newPage(): void
{
$this->pdf->addPage();
$this->page++;
$this->flow->restart();
}
private function closePage(): void
{
$this->pdf->line(self::LEFT, 54, self::RIGHT, 54, 0.4);
$this->pdf->text(self::LEFT, 40, $this->footer, 8);
$this->pdf->textRight(self::RIGHT, 40, 'Seite '.$this->page.($this->total > 0 ? ' von '.$this->total : ''), 8);
}
private function asciiTitle(string $title): string
{
$ascii = Transliterator::create('Any-Latin; Latin-ASCII');
return $ascii?->transliterate($title) ?: 'Dokument';
}
}
+82
View File
@@ -0,0 +1,82 @@
<?php
namespace App\Domain\Catalog;
/**
* Liest die Kapitel eines Dokuments in ihrer Reihenfolge: aus einer Fassung (gebundene Textfassungen) oder aus dem
* gespeicherten Entwurf (jeweils verwiesene Fassung). Ansicht, PDF und Vorschau zählen dadurch dieselben Kapitel und
* Nummern ({@see DocumentOutline}).
*/
final class DocumentReader
{
/**
* @return list<array{number: string, level: int, anchor: string, role: string, title: string, version: ContentElementVersion}>
*/
public function fromVersion(CompositionVersion $document): array
{
$document->loadMissing('members.contentElementVersion.element');
$items = [];
foreach ($document->members as $member) {
if ($member->contentElementVersion !== null) {
$items[] = ['role' => (string) $member->role, 'version' => $member->contentElementVersion];
}
}
return $this->number($items);
}
/**
* Der gespeicherte Entwurf; ohne Entwurf die letzte bereitgestellte Fassung. Null, wenn beides fehlt.
*
* @return list<array{number: string, level: int, anchor: string, role: string, title: string, version: ContentElementVersion}>|null
*/
public function forStaff(Composition $document): ?array
{
$draft = app(EditorialWorkingDraft::class)->read($document);
if ($draft === null) {
$ready = $document->versions()->where('status', ContentVersionStatus::Bereit)->orderByDesc('number')->first();
return $ready instanceof CompositionVersion ? $this->fromVersion($ready) : null;
}
$items = [];
foreach (is_array($draft['members'] ?? null) ? $draft['members'] : [] as $member) {
if (! is_array($member) || preg_match('/^element:(\d+)$/', (string) ($member['target'] ?? ''), $match) !== 1) {
continue;
}
$version = ContentElementVersion::query()->with('element')->find($match[1]);
if ($version instanceof ContentElementVersion && $version->element !== null) {
$items[] = ['role' => (string) ($member['role'] ?? ''), 'version' => $version];
}
}
return $this->number($items);
}
public static function title(ContentElementVersion $version): string
{
$element = $version->element;
return $element === null ? 'Kapitel' : (filled($element->display_title) ? (string) $element->display_title : (string) $element->working_title);
}
/**
* @param list<array{role: string, version: ContentElementVersion}> $items
* @return list<array{number: string, level: int, anchor: string, role: string, title: string, version: ContentElementVersion}>
*/
private function number(array $items): array
{
$numbering = DocumentOutline::numbering(array_column($items, 'role'));
return array_map(fn (array $item, array $number): array => $number + [
'role' => DocumentOutline::role($number['level']),
'title' => self::title($item['version']),
'version' => $item['version'],
], $items, $numbering);
}
}
+6 -2
View File
@@ -18,6 +18,7 @@ class EditorialContentKind extends Model
'medium' => 'Medium',
'modul' => 'Modul',
'uebung' => 'Übung',
'dokument' => 'Dokument',
'programm' => 'Programm',
'lizenzartikel' => 'Lizenzartikel',
];
@@ -27,7 +28,7 @@ class EditorialContentKind extends Model
* Modulen (programm, modul), Vertraulichkeit von Traineranleitungen (traineranleitung). Ihre Bezeichnung bleibt
* pflegbar; deaktivieren, Kontexte ändern und löschen sind gesperrt.
*/
public const SYSTEM_SLUGS = ['programm', 'modul', 'uebung', 'traineranleitung', self::EXERCISE_SECTION_SLUG];
public const SYSTEM_SLUGS = ['programm', 'modul', 'uebung', 'dokument', 'traineranleitung', self::EXERCISE_SECTION_SLUG, self::DOCUMENT_CHAPTER_SLUG];
/**
* Textabschnitte einer Übung. Die Materialart wird nur automatisch gesetzt (ExerciseSections) und hat deshalb
@@ -35,6 +36,9 @@ class EditorialContentKind extends Model
*/
public const EXERCISE_SECTION_SLUG = 'uebungsabschnitt';
/** Kapitel eines Dokuments: wie Übungsabschnitte nur automatisch gesetzt, nie öffentlich (ADR-51). */
public const DOCUMENT_CHAPTER_SLUG = 'dokumentkapitel';
protected $fillable = [
'slug',
'label',
@@ -83,7 +87,7 @@ public function allows(string $context): bool
/** Wird nie von Hand gewählt, sondern von der Übungsverwaltung gesetzt. */
public function isAutomatic(): bool
{
return $this->slug === self::EXERCISE_SECTION_SLUG;
return in_array($this->slug, [self::EXERCISE_SECTION_SLUG, self::DOCUMENT_CHAPTER_SLUG], true);
}
public function isSystem(): bool
@@ -47,6 +47,7 @@ public static function compositionContext(?CompositionKind $kind): ?string
CompositionKind::Kurs => 'programm',
CompositionKind::Uebung => 'modul',
CompositionKind::Exercise => 'uebung',
CompositionKind::Document => 'dokument',
default => null,
};
}
@@ -181,6 +182,7 @@ private function usedKindIds(string $context): array
'programm' => DB::table('compositions')->where('kind', CompositionKind::Kurs->value),
'modul' => DB::table('compositions')->where('kind', CompositionKind::Uebung->value),
'uebung' => DB::table('compositions')->where('kind', CompositionKind::Exercise->value),
'dokument' => DB::table('compositions')->where('kind', CompositionKind::Document->value),
default => null,
};
+34 -5
View File
@@ -91,11 +91,7 @@ public function forPdf(User $user, LicenseArticle $article, ArticleRelease $rele
return ['note' => 'Bild nicht verfügbar', 'grant' => null, 'version' => null];
}
$file = $decision['version']->metadata['file'] ?? null;
$disk = Storage::disk('media_derived');
$prepared = is_string($file) && $file !== '' && ! str_contains($file, '..') && $disk->exists($file)
? PdfImage::fromBytes((string) $disk->get($file))
: null;
$prepared = self::prepared($decision['version']);
if ($prepared === null) {
return ['note' => 'Bild kann nicht gedruckt werden', 'grant' => null, 'version' => null];
@@ -105,6 +101,39 @@ public function forPdf(User $user, LicenseArticle $article, ArticleRelease $rele
});
}
/**
* Auflösung für die PDF-Vorschau der Redaktion: ohne Rechteprüfung, ohne Ausgabenachweis.
*/
public static function forStaffPdf(): PdfImages
{
return new PdfImages(function (int $id): ?array {
$version = ContentElementVersion::query()->with('element')->find($id);
if (! $version instanceof ContentElementVersion || $version->element === null || $version->element->output_class !== 'bild') {
return ['note' => 'Bild nicht mehr vorhanden', 'grant' => null, 'version' => null];
}
$prepared = self::prepared($version);
return $prepared === null ? ['note' => 'Bild kann nicht gedruckt werden', 'grant' => null, 'version' => null] : $prepared + ['grant' => null, 'version' => null];
});
}
/**
* Die Bilddatei aus dem abgeleiteten Bestand (der Web-Prozess liest nur dort), für das PDF aufbereitet.
*
* @return array{jpeg: string, width: int, height: int}|null
*/
private static function prepared(ContentElementVersion $version): ?array
{
$file = $version->metadata['file'] ?? null;
$disk = Storage::disk('media_derived');
return is_string($file) && $file !== '' && ! str_contains($file, '..') && $disk->exists($file)
? PdfImage::fromBytes((string) $disk->get($file))
: null;
}
/**
* @return array{allowed: bool, version: ContentElementVersion, grant: ?Grant}|null
*/
+2 -2
View File
@@ -45,7 +45,7 @@ public function mayOpen(User $user, LicenseArticle $article, ArticleRelease $rel
*
* @return array{version: CompositionVersion, selection: list<string>|null}|null
*/
public function locate(ArticleRelease $release, string $path): ?array
public function locate(ArticleRelease $release, string $path, CompositionKind $kind = CompositionKind::Exercise): ?array
{
if (preg_match('/^\d+(-\d+)*$/', $path) !== 1) {
return null;
@@ -71,7 +71,7 @@ public function locate(ArticleRelease $release, string $path): ?array
$version?->loadMissing('composition');
if ($version === null || $version->composition === null || $version->composition->kind !== CompositionKind::Exercise) {
if ($version === null || $version->composition === null || $version->composition->kind !== $kind) {
return null;
}
+66 -14
View File
@@ -335,14 +335,43 @@ private static function extractBlocks(Node $parent): array
continue;
}
$blocks[] = [
'type' => match ($name) {
'h3' => 'heading',
'blockquote' => 'quote',
default => 'paragraph',
},
'runs' => self::runs($node),
];
$type = match ($name) {
'h3' => 'heading',
'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[] = ['type' => $type, 'runs' => 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[] = ['type' => $type, 'runs' => $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[] = ['type' => $type, 'runs' => $pending];
}
}
return $blocks;
@@ -380,9 +409,10 @@ 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.
// 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 ($image->parentNode !== $body || (int) $image->getAttribute('data-id') < 1) {
if (! self::mayHoldImage($image->parentNode, $body) || (int) $image->getAttribute('data-id') < 1) {
$image->remove();
}
}
@@ -459,7 +489,7 @@ private static function block(Node $node): string
$inner = '<p>'.$inner.'</p>';
}
return self::hasText($inner) ? '<'.$name.'>'.$inner.'</'.$name.'>' : '';
return self::hasContent($inner) ? '<'.$name.'>'.$inner.'</'.$name.'>' : '';
}
/**
@@ -490,7 +520,7 @@ private static function table(Node $table): string
}
$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.'>';
$cells .= '<'.$name.$attributes.'>'.($inner === '' ? '<p></p>' : (preg_match('/^<(?:p|ul|ol|blockquote|h3|img)[\s>]/', $inner) === 1 ? $inner : '<p>'.$inner.'</p>')).'</'.$name.'>';
}
if ($cells !== '') {
@@ -498,7 +528,7 @@ private static function table(Node $table): string
}
}
return $rows !== '' && self::hasText($rows) ? '<table><tbody>'.$rows.'</tbody></table>' : '';
return $rows !== '' && (self::hasText($rows) || str_contains($rows, '<img')) ? '<table><tbody>'.$rows.'</tbody></table>' : '';
}
private static function inner(Node $node): string
@@ -506,7 +536,7 @@ 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)) {
if ($child->nodeType === XML_ELEMENT_NODE && in_array(strtolower($child->nodeName), ['ul', 'ol', 'p', 'blockquote', 'img'], true)) {
$html .= self::block($child);
continue;
@@ -518,6 +548,28 @@ private static function inner(Node $node): string
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')) !== '';
+47 -12
View File
@@ -279,9 +279,9 @@ private function image(array $block, float $x): void
$width = max(1.0, $found['width'] * $scale);
$height = max(1.0, $found['height'] * $scale);
$this->room($height + 8);
$this->pdf->image($x, $this->y - $height, $width, $height, $found['jpeg'], $found['width'], $found['height']);
$this->y -= $height + 8;
$this->room($height + 16);
$this->pdf->image($x, $this->y + 4 - $height, $width, $height, $found['jpeg'], $found['width'], $found['height']);
$this->y -= $height + 16;
}
/**
@@ -330,7 +330,7 @@ private function table(array $rows, float $x): void
$this->depth++;
$cell['lines'] = $this->cellLines($cell['blocks'], max(10.0, $inner), $size, $cell['header']);
$this->depth--;
$cell['height'] = max(1, count($cell['lines'])) * $lineHeight + 2 * $pad;
$cell['height'] = max($lineHeight, array_sum(array_column($cell['lines'], 'height'))) + 2 * $pad;
$prepared[] = $cell;
}
@@ -363,7 +363,7 @@ private function table(array $rows, float $x): void
return;
}
$drawRows = function (int $from, int $to) use ($prepared, $widths, $heights, $x, $size, $pad, $lineHeight): void {
$drawRows = function (int $from, int $to) use ($prepared, $widths, $heights, $x, $size, $pad): void {
$y = $this->y;
for ($r = $from; $r <= $to; $r++) {
@@ -379,6 +379,13 @@ private function table(array $rows, float $x): void
$textY = $y - $pad - $size;
foreach ($cell['lines'] as $line) {
if (isset($line['image'])) {
$this->pdf->image($cellLeft + $pad, $textY + $size - $line['image']['height'], $line['image']['width'], $line['image']['height'], $line['image']['jpeg'], $line['image']['pixelWidth'], $line['image']['pixelHeight']);
$textY -= $line['height'];
continue;
}
if ($line['marker'] !== null) {
$this->pdf->text($cellLeft + $pad + $line['indent'] - 12, $textY, $line['marker'], $size, $cell['header']);
}
@@ -390,7 +397,7 @@ private function table(array $rows, float $x): void
$cursor += PdfDocument::exactWidth($text, $size, $isBold || $cell['header']);
}
$textY -= $lineHeight;
$textY -= $line['height'];
}
}
@@ -528,10 +535,21 @@ private function columnWidths(array $cells, int $columns, float $available, floa
return array_map(fn (float $w): float => $w + $extra, $want);
}
// Der Platz über dem Mindestmaß wird gleichmäßig verteilt, aber keine Spalte bekommt mehr, als sie sich wünscht:
// Schmale Spalten behalten ihren Text in einer Zeile, die breite nimmt den Rest.
$widths = $min;
$room = $available - array_sum($min);
$wishes = array_sum($want) - array_sum($min);
$open = array_keys($min);
usort($open, fn (int $a, int $b): int => ($want[$a] - $min[$a]) <=> ($want[$b] - $min[$b]));
return array_map(fn (float $m, float $w): float => $m + $room * (($w - $m) / max(1.0, $wishes)), $min, $want);
foreach ($open as $position => $c) {
$share = $room / (count($open) - $position);
$give = min($want[$c] - $min[$c], $share);
$widths[$c] += $give;
$room -= $give;
}
return $widths;
}
/**
@@ -553,32 +571,49 @@ private function cellText(array $blocks): string
}
/**
* Zeilen einer Tabellenzelle: Absätze, Aufzählungen und Zwischenüberschriften; ein Bild in der Zelle entfällt.
* Zeilen einer Tabellenzelle: Absätze, Aufzählungen, Zwischenüberschriften und Bilder (höchstens 110 Punkt hoch, in
* Breite der Zelle). Jeder Eintrag trägt seine Höhe.
*
* @param list<array<string, mixed>> $blocks
* @return list<array{segments: list<array{0: string, 1: bool, 2: bool}>, indent: float, marker: ?string}>
* @return list<array<string, mixed>>
*/
private function cellLines(array $blocks, float $width, float $size, bool $header): array
{
$out = [];
$lineHeight = $size + 3;
foreach ($blocks as $block) {
if (in_array($block['type'], ['bullets', 'numbered'], true)) {
foreach ($block['items'] as $index => $item) {
foreach ($this->lines($item, $width - 12, $size, $header) as $i => $segments) {
$out[] = ['segments' => $segments, 'indent' => 12.0, 'marker' => $i === 0 ? ($block['type'] === 'bullets' ? '•' : ($index + 1).'.') : null];
$out[] = ['segments' => $segments, 'indent' => 12.0, 'marker' => $i === 0 ? ($block['type'] === 'bullets' ? '•' : ($index + 1).'.') : null, 'height' => $lineHeight];
}
}
continue;
}
if ($block['type'] === 'image') {
$found = $this->images === null ? null : ($this->images)((int) $block['id']);
if ($found !== null && isset($found['jpeg'])) {
$scale = min(1.0, $width / max(1, $found['width']), 110.0 / max(1, $found['height']));
$w = max(1.0, $found['width'] * $scale);
$h = max(1.0, $found['height'] * $scale);
$out[] = ['image' => ['jpeg' => $found['jpeg'], 'width' => $w, 'height' => $h, 'pixelWidth' => $found['width'], 'pixelHeight' => $found['height']], 'height' => $h + 4];
} elseif ($found !== null) {
$out[] = ['segments' => [['['.($found['note'] ?? 'Bild nicht verfügbar').']', false, true]], 'indent' => 0.0, 'marker' => null, 'height' => $lineHeight];
}
continue;
}
if (! isset($block['runs'])) {
continue;
}
foreach ($this->lines($block['runs'], $width, $size, $header || $block['type'] === 'heading', $block['type'] === 'quote') as $segments) {
$out[] = ['segments' => $segments, 'indent' => 0.0, 'marker' => null];
$out[] = ['segments' => $segments, 'indent' => 0.0, 'marker' => null, 'height' => $lineHeight];
}
}