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];
}
}
@@ -39,7 +39,7 @@
class PublicMaterialReader
{
/** Inhaltsarten, die nie öffentlich auf einer Karte erscheinen: Anleitungen für Trainer und die Textabschnitte der Übungen. */
public const CONFIDENTIAL_KINDS = ['traineranleitung', 'uebungsabschnitt'];
public const CONFIDENTIAL_KINDS = ['traineranleitung', 'uebungsabschnitt', 'dokumentkapitel'];
/** @var array<int, array{id: int, title: string}>|null Element-ID => erstes öffentliches Programm */
private ?array $publicIndex = null;
@@ -27,6 +27,7 @@
use App\Filament\Resources\ContentElements\ContentElementResource;
use App\Filament\Support\AssignsPillars;
use App\Filament\Support\EditorialCatalog;
use App\Filament\Support\ManagesDocumentChapters;
use App\Filament\Support\ManagesEditorialSurface;
use App\Filament\Support\ManagesRichFields;
use App\Filament\Support\MediumForm;
@@ -50,6 +51,7 @@
abstract class EditComposition extends EditRecord
{
use AssignsPillars;
use ManagesDocumentChapters;
use ManagesEditorialSurface;
use ManagesRichFields;
use WithFileUploads;
@@ -278,6 +280,10 @@ public function previewUrl(): ?string
/** @var Composition $composition */
$composition = $this->getRecord();
if ($this->isDocument()) {
return $this->currentReadyVersion() === null && ! is_array($composition->working_draft) ? null : route('editorial.document-preview', ['composition' => $composition]);
}
if (is_array($composition->working_draft) && $composition->working_draft !== []) {
return route('editorial.draft-preview', ['composition' => $composition]);
}
@@ -371,8 +377,18 @@ public function redaktionKopf(): array
return [
'art' => $this->hostLabel(),
'fuer' => $program ? 'das Programm' : 'das Modul',
'liste' => $program ? 'Programme' : 'Module',
'fuer' => match (true) {
$program => 'das Programm',
$this->isDocument() => 'das Dokument',
$this->isExercise() => 'die Übung',
default => 'das Modul',
},
'liste' => match (true) {
$program => 'Programme',
$this->isDocument() => 'Dokumente',
$this->isExercise() => 'Übungen',
default => 'Module',
},
'zurueck' => 'Zurück zum Aufbau',
'typ' => null,
'umfang' => '„Redaktion speichern“ sichert Name, Texte, Präsentationsmedien und Einordnung. Aufbau, Lernziel, Zeit und Fassungen bleiben unverändert; offene Änderungen am Aufbau bleiben offen.',
@@ -705,10 +721,16 @@ public function saveDraft(): void
return;
}
if (! $this->persistChapterEdits()) {
return;
}
/** @var Composition $record */
$record = $this->getRecord();
app(EditorialWorkingDraft::class)->write($record, $this->payload());
$this->feedback = 'Der Entwurf ist gespeichert. Es entsteht keine neue Fassung.';
$this->feedback = $this->isDocument()
? 'Der Entwurf ist gespeichert, auch die Texte der Kapitel. Es entsteht keine neue Dokumentfassung.'
: 'Der Entwurf ist gespeichert. Es entsteht keine neue Fassung.';
}
public function armRelease(): void
@@ -722,6 +744,12 @@ public function armRelease(): void
$this->commitRoleDraft();
if (! $this->persistChapterEdits()) {
$this->releaseArmed = false;
return;
}
if ($this->members === []) {
$this->releaseArmed = false;
$this->feedback = 'Eine Fassung braucht mindestens einen Bestandteil. Anzeige und Entwurf kannst du schon speichern.';
@@ -807,6 +835,7 @@ public function discardDraft(): void
$record = $this->getRecord();
app(EditorialWorkingDraft::class)->clear($record);
$this->releaseArmed = false;
$this->chapterEdits = [];
$this->loadAufbau();
$this->selected = null;
$this->selectFirstPart();
@@ -852,6 +881,12 @@ public function includeNeedsRelease(): bool
public function moveTo(int $from, int $to): void
{
if ($this->isDocument()) {
$this->moveChapterTo($from, $to);
return;
}
$this->commitRoleDraft();
$count = count($this->members);
@@ -1184,6 +1219,11 @@ public function removePart(int $index): void
}
$title = (string) ($this->members[$index]['title'] ?? 'Der Bestandteil');
if ($this->isDocument()) {
$this->forgetChapter($index);
}
unset($this->members[$index]);
$this->members = array_values($this->members);
$this->selected = $this->members === [] ? null : min($index, count($this->members) - 1);
@@ -1206,7 +1246,9 @@ protected function extraConfirmation(string $aktion, int|string|null $argument):
'aktion' => $aktion,
'argument' => (int) $argument,
'titel' => '„'.$title.'“ aus diesem Aufbau entfernen?',
'text' => 'Nur diese Verwendung wird entfernt. Das Medium oder Modul bleibt im Bestand und in anderen Aufbauten. Gespeichert wird das mit „Entwurf speichern“.',
'text' => $this->isDocument()
? 'Nur dieses Kapitel wird aus dem Dokument genommen; seine Unterkapitel bleiben und gehören dann zum Kapitel davor. Der Text bleibt im Medienbestand, ungespeicherte Eingaben zu diesem Kapitel entfallen. Gespeichert wird das mit „Entwurf speichern“.'
: 'Nur diese Verwendung wird entfernt. Das Medium oder Modul bleibt im Bestand und in anderen Aufbauten. Gespeichert wird das mit „Entwurf speichern“.',
'label' => 'Aus dem Aufbau entfernen',
'gefahr' => true,
];
@@ -1221,6 +1263,12 @@ protected function runExtraConfirmation(string $aktion, int|string|null $argumen
public function movePart(int $index, int $direction): void
{
if ($this->isDocument()) {
$this->moveChapter($index, $direction);
return;
}
$this->commitRoleDraft();
$target = $index + $direction;
@@ -1754,6 +1802,10 @@ public function publishRevision(): bool
$this->commitRoleDraft();
if (! $this->persistChapterEdits()) {
return false;
}
if ($this->members === []) {
$this->feedback = 'Eine Fassung braucht mindestens einen Bestandteil. Anzeige und Kurzbeschreibung kannst du schon speichern.';
@@ -1813,7 +1865,9 @@ public function publishRevision(): bool
$this->loadEditor();
$released = $this->currentReadyVersion();
$number = $released instanceof CompositionVersion ? $released->number : '';
$this->feedback = 'Fassung '.$number.' ist freigegeben. Der Entwurf ist geschlossen und die bisherige Fassung bleibt erhalten. Die Mitgliederbibliothek ändert sich dadurch nicht.';
$this->feedback = $this->isDocument()
? 'Dokumentfassung '.$number.' ist bereitgestellt. Der Entwurf ist geschlossen, frühere Fassungen bleiben erhalten. Ein Modul oder Programm bindet sie über „Hinzufügen“ ein; bestehende Stände ändern sich dadurch nicht.'
: 'Fassung '.$number.' ist freigegeben. Der Entwurf ist geschlossen und die bisherige Fassung bleibt erhalten. Die Mitgliederbibliothek ändert sich dadurch nicht.';
if ($this->returnAfterRelease) {
$this->returnAfterRelease = false;
@@ -1969,6 +2023,7 @@ protected function applyDraft(array $draft): void
}
$this->members = $rows;
$this->slimChapterMembers();
$this->variants = $this->normalizeVariants($draft['variants'] ?? []);
$this->durationMax = ($draft['duration_max'] ?? null) === null ? '' : (string) $draft['duration_max'];
$this->prerequisites = (string) ($draft['prerequisites'] ?? '');
@@ -1989,6 +2044,7 @@ protected function applyDraft(array $draft): void
protected function applyVersion(CompositionVersion $version): void
{
$this->members = app(EditorialCatalog::class)->rows($version, (int) $this->getRecord()->getKey());
$this->slimChapterMembers();
$this->variants = $this->normalizeVariants($version->variants->map(fn ($variant): array => [
'key' => $variant->key, 'name' => $variant->name, 'description' => (string) $variant->description, 'origin' => $variant->origin,
])->all());
@@ -2014,6 +2070,13 @@ protected function commitRoleDraft(?string $value = null): void
return;
}
if ($this->isDocument()) {
// Ein Kapitel hat keine freie Rolle: Die Ebene steht fest; offene Eingaben des Kapitels bleiben erhalten.
$this->stashChapter();
return;
}
$this->members[$this->selected]['role'] = trim($value ?? $this->roleDraft);
$this->members[$this->selected]['note'] = trim($this->noteDraft);
}
@@ -2023,6 +2086,13 @@ protected function syncRoleDraft(): void
$member = $this->selected !== null ? ($this->members[$this->selected] ?? null) : null;
$this->roleDraft = is_array($member) ? (string) ($member['role'] ?? '') : '';
$this->noteDraft = is_array($member) ? (string) ($member['note'] ?? '') : '';
if ($this->isDocument()) {
$this->loadChapterFields();
return;
}
$this->partTitle = is_array($member) ? (string) ($member['title'] ?? '') : '';
$this->partBody = is_array($member) ? (string) ($member['body'] ?? '') : '';
}
@@ -2340,6 +2410,8 @@ protected function payload(): array
'prerequisites' => $this->blank($this->prerequisites),
'variants' => $this->normalizeVariants($this->variants),
'revision_note' => $this->blank($this->revisionNote),
// Ungespeicherte Texte der Kapitel gelten als Änderung des Entwurfs; nach dem Speichern sind sie leer.
'chapters' => $this->chapterEditsNow(),
'members' => array_values(array_map(
fn (array $member): array => [
'role' => trim((string) ($member['role'] ?? '')),
@@ -2442,6 +2514,7 @@ protected function normalizePayload(array $payload): array
'prerequisites' => $payload['prerequisites'] ?? null,
'variants' => $this->normalizeVariants($payload['variants'] ?? []),
'revision_note' => $payload['revision_note'] ?? null,
'chapters' => is_array($payload['chapters'] ?? null) ? $payload['chapters'] : [],
'members' => $members,
];
}
@@ -34,12 +34,12 @@ protected function fixedKind(): ?CompositionKind
private function onDesk(): bool
{
return in_array($this->kind(), [CompositionKind::Kurs, CompositionKind::Uebung, CompositionKind::Exercise], true);
return in_array($this->kind(), [CompositionKind::Kurs, CompositionKind::Uebung, CompositionKind::Exercise, CompositionKind::Document], true);
}
public function getSubheading(): string|Htmlable|null
{
$desk = $this->onDesk() && $this->kind() !== CompositionKind::Exercise ? ' Programme und Module stehen gemeinsam auch auf dem Arbeitsplatz.' : '';
$desk = $this->onDesk() && ! in_array($this->kind(), [CompositionKind::Exercise, CompositionKind::Document], true) ? ' Programme und Module stehen gemeinsam auch auf dem Arbeitsplatz.' : '';
return $this->kind()->deskExplanation().$desk;
}
@@ -0,0 +1,38 @@
<?php
namespace App\Filament\Resources\Documents;
use App\Domain\Catalog\CompositionKind;
use App\Filament\Resources\Compositions\CompositionKindResource;
use App\Filament\Resources\Documents\Pages\EditDocument;
use App\Filament\Resources\Documents\Pages\ListDocuments;
/**
* Dokumente unter „Inhalte“: zusammenhängende Texte aus Kapiteln, der erste Fall ist das Trainerhandbuch (ADR-51).
* Wie Übungen sind es Kompositionen mit eigener Art; Fassung, Einbindung und Stand arbeiten mit denselben Bausteinen.
*/
class DocumentResource extends CompositionKindResource
{
protected static ?string $slug = 'dokumente';
protected static ?string $navigationLabel = 'Dokumente';
protected static ?string $modelLabel = 'Dokument';
protected static ?string $pluralModelLabel = 'Dokumente';
protected static ?int $navigationSort = 4;
public static function kind(): CompositionKind
{
return CompositionKind::Document;
}
public static function getPages(): array
{
return [
'index' => ListDocuments::route('/'),
'edit' => EditDocument::route('/{record}'),
];
}
}
@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\Documents\Pages;
use App\Filament\Resources\Compositions\Pages\EditComposition;
use App\Filament\Resources\Documents\DocumentResource;
class EditDocument extends EditComposition
{
protected static string $resource = DocumentResource::class;
}
@@ -0,0 +1,17 @@
<?php
namespace App\Filament\Resources\Documents\Pages;
use App\Domain\Catalog\CompositionKind;
use App\Filament\Resources\Compositions\Pages\ListCompositionKind;
use App\Filament\Resources\Documents\DocumentResource;
class ListDocuments extends ListCompositionKind
{
protected static string $resource = DocumentResource::class;
protected function kind(): CompositionKind
{
return CompositionKind::Document;
}
}
+11 -2
View File
@@ -21,6 +21,7 @@
use App\Filament\Resources\Combinations\CombinationResource;
use App\Filament\Resources\ContentElements\ContentElementResource;
use App\Filament\Resources\Courses\CourseResource;
use App\Filament\Resources\Documents\DocumentResource;
use App\Filament\Resources\Exercises\ExerciseResource;
use App\Filament\Resources\Practices\PracticeResource;
use Illuminate\Database\Eloquent\Builder;
@@ -297,7 +298,7 @@ public function browse(string $query, string $kind, string $dimension, int $exce
$rows = [];
$dimensionId = ctype_digit($dimension) ? (int) $dimension : 0;
if ($kind !== 'modul') {
if (! in_array($kind, ['modul', 'dokumentfassung'], true)) {
$latestElements = ContentElementVersion::query()
->selectRaw('MAX(id)')
->whereIn('status', [ContentVersionStatus::Bereit, ContentVersionStatus::Entwurf])
@@ -321,7 +322,7 @@ public function browse(string $query, string $kind, string $dimension, int $exce
}
}
if (! $elementsOnly && in_array($kind, ['alle', 'modul'], true)) {
if (! $elementsOnly && in_array($kind, ['alle', 'modul', 'dokumentfassung'], true)) {
$latestCompositions = CompositionVersion::query()
->selectRaw('MAX(id)')
->where('status', ContentVersionStatus::Bereit)
@@ -331,6 +332,10 @@ public function browse(string $query, string $kind, string $dimension, int $exce
$builder->whereIn('kind', [CompositionKind::Uebung, CompositionKind::Exercise]);
}
if ($kind === 'dokumentfassung') {
$builder->where('kind', CompositionKind::Document);
}
if ($dimensionId > 0) {
$builder->whereIn('id', $this->dimensionSubjectIds(Composition::class, $dimensionId));
}
@@ -370,6 +375,8 @@ public function browse(string $query, string $kind, string $dimension, int $exce
$unreleased = Composition::query()
->where('id', '!=', $exceptCompositionId)
->whereNotNull('working_draft')
// Ein Dokument bindet man nur als bereitgestellte Fassung ein, nie als Entwurf.
->where('kind', '!=', CompositionKind::Document->value)
->whereDoesntHave('versions', function ($builder): void {
$builder->where('status', ContentVersionStatus::Bereit);
})
@@ -1085,6 +1092,7 @@ public function create(string $designation, CompositionKind $kind): Composition
CompositionKind::Kurs => 'programm',
CompositionKind::Uebung => 'modul',
CompositionKind::Exercise => 'uebung',
CompositionKind::Document => 'dokument',
default => null,
};
$editorial = $slug === null ? null : EditorialContentKind::query()->where('slug', $slug)->first();
@@ -1107,6 +1115,7 @@ public static function editUrl(Composition $composition): string
CompositionKind::Kombination => CombinationResource::class,
CompositionKind::Uebung => ExerciseResource::class,
CompositionKind::Exercise => PracticeResource::class,
CompositionKind::Document => DocumentResource::class,
};
return $resource::getUrl('edit', ['record' => $composition]);
@@ -78,6 +78,7 @@ public function bestand(): array
CompositionKind::Kurs => ['Programm', 'Programme'],
CompositionKind::Uebung => ['Modul', 'Module'],
CompositionKind::Exercise => ['Übung', 'Übungen'],
CompositionKind::Document => ['Dokument', 'Dokumente'],
CompositionKind::Kombination => ['Fachliche Kombination', 'Fachliche Kombinationen'],
default => ['Programm oder Modul', 'Programme und Module'],
};
@@ -118,6 +119,8 @@ public function bestand(): array
'text' => 'Mit „'.match ($fixed) {
CompositionKind::Kurs => 'Programm anlegen',
CompositionKind::Kombination => CompositionKind::Kombination->createLabel(),
CompositionKind::Exercise => 'Übung anlegen',
CompositionKind::Document => 'Dokument anlegen',
default => 'Modul anlegen',
}.'“ oben entsteht der erste Eintrag. Der Name genügt.',
],
@@ -247,12 +250,14 @@ protected function createCompositionAction(CompositionKind $kind): Action
$label = match ($kind) {
CompositionKind::Kurs => 'Programm',
CompositionKind::Exercise => 'Übung',
CompositionKind::Document => 'Dokument',
default => 'Modul',
};
return Action::make(match ($kind) {
CompositionKind::Kurs => 'createProgram',
CompositionKind::Exercise => 'createExercise',
CompositionKind::Document => 'createDocument',
default => 'createModule',
})
->label($label.' anlegen')
@@ -0,0 +1,506 @@
<?php
namespace App\Filament\Support;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionKind;
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\DocumentChapters;
use App\Domain\Catalog\DocumentOutline;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\FormattedText;
use App\Filament\Resources\Compositions\Pages\EditComposition;
/**
* Kapitelarbeitsplatz eines Dokuments im Aufbaueditor (ADR-51). Der Arbeitsplatz hält die Kapitel wie jeden Aufbau als
* Mitglieder in `$members`; die Ebene steht in der Rolle („Kapitel“, „Unterkapitel“). Das Kapitel, das gerade offen ist,
* liegt in `$partTitle` und `$partBody` (derselbe Editor wie bei jedem Text).
*
* Offene Eingaben bleiben beim Wechsel des Kapitels erhalten: Der Wechsel legt Titel und Text des verlassenen Kapitels in
* `$chapterEdits` ab, und das Öffnen eines Kapitels liest zuerst dort. Geschrieben wird erst mit „Entwurf speichern“
* ({@see self::persistChapterEdits()}), und zwar als Entwurfsfassung des Kapitels; bereitgestellt wird erst mit der
* Dokumentfassung. Die Reihenfolge ändert immer den ganzen Block aus Kapitel und seinen Unterkapiteln.
*
* Die Seite stellt `members`, `selected`, `partTitle`, `partBody`, `feedback` und `memberExtras()` bereit
* ({@see EditComposition}).
*/
trait ManagesDocumentChapters
{
/** @var array<string, array{title: string, body: string}> Ungespeicherte Änderungen je Kapitel (Ziel => Titel und Text) */
public array $chapterEdits = [];
/** @var array<string, string> Gespeicherter Text je Ziel, nur für den Vergleich innerhalb einer Anfrage */
private array $chapterBase = [];
public function isDocument(): bool
{
return $this->hostKind() === CompositionKind::Document;
}
/**
* Die Kapitelübersicht: Nummer, Ebene, Titel (auch ein noch nicht gespeicherter) und Stand je Kapitel.
*
* @return list<array{index: int, number: string, level: int, anchor: string, title: string, changed: bool, draft: bool, selected: bool, first: bool, last: bool}>
*/
public function chapterRows(): array
{
$numbering = DocumentOutline::numbering(array_map(fn (array $member): string => (string) ($member['role'] ?? ''), $this->members));
$open = $this->openChapterEdit();
$rows = [];
foreach ($this->members as $index => $member) {
$target = (string) ($member['target'] ?? '');
$edit = $this->chapterEdits[$target] ?? null;
$title = $this->selected === $index && $open !== null ? $open['title'] : ($edit['title'] ?? (string) ($member['title'] ?? ''));
$rows[] = $numbering[$index] + [
'index' => $index,
'title' => trim($title) === '' ? 'Ohne Titel' : $title,
'changed' => $edit !== null || ($this->selected === $index && $open !== null),
'draft' => ($member['version_label'] ?? '') === 'Entwurf',
'selected' => $this->selected === $index,
'first' => $index === 0,
'last' => $index === count($this->members) - 1,
];
}
return $rows;
}
public function chapterCount(): int
{
return count($this->members);
}
/** Anzahl der Kapitel mit offenen Änderungen (gespeichert wird mit „Entwurf speichern“). */
public function chapterEditCount(): int
{
return count($this->chapterEditsNow());
}
/**
* Wechselt das Kapitel. Das verlassene bleibt mit seinen offenen Eingaben erhalten.
*/
public function selectChapter(int $index): void
{
if (! isset($this->members[$index])) {
return;
}
$this->commitRoleDraft();
$this->selected = $index;
$this->panel = 'bestandteil';
$this->aufbauTab = 'aufbau';
$this->syncRoleDraft();
}
/** Legt das offene Kapitel in den Arbeitsstand, wenn es vom gespeicherten abweicht. */
protected function stashChapter(): void
{
$open = $this->openChapterEdit();
$target = $this->selectedChapterTarget();
if ($target === null) {
return;
}
if ($open === null) {
unset($this->chapterEdits[$target]);
return;
}
$this->chapterEdits[$target] = $open;
}
/**
* Das offene Kapitel, falls Titel oder Text vom gespeicherten Stand abweichen.
*
* @return array{title: string, body: string}|null
*/
protected function openChapterEdit(): ?array
{
$target = $this->selectedChapterTarget();
if ($target === null) {
return null;
}
$title = trim($this->partTitle);
$body = FormattedText::canonical($this->partBody);
$storedTitle = trim((string) ($this->members[$this->selected]['title'] ?? ''));
if ($title === $storedTitle && FormattedText::same($body, $this->storedChapterBody($target))) {
return null;
}
return ['title' => $title, 'body' => $body];
}
/**
* Alle Änderungen, auch die des gerade offenen Kapitels.
*
* @return array<string, array{title: string, body: string}>
*/
public function chapterEditsNow(): array
{
$edits = $this->chapterEdits;
$target = $this->selectedChapterTarget();
if ($target !== null) {
$open = $this->openChapterEdit();
if ($open === null) {
unset($edits[$target]);
} else {
$edits[$target] = $open;
}
}
ksort($edits);
return $edits;
}
private function selectedChapterTarget(): ?string
{
if (! $this->isDocument() || $this->selected === null || ! isset($this->members[$this->selected])) {
return null;
}
$target = (string) ($this->members[$this->selected]['target'] ?? '');
return preg_match('/^element:\d+$/', $target) === 1 ? $target : null;
}
private function storedChapterBody(string $target): string
{
if (! array_key_exists($target, $this->chapterBase)) {
$version = ContentElementVersion::query()->find((int) substr($target, 8));
$this->chapterBase[$target] = $version instanceof ContentElementVersion ? (string) $version->body : '';
}
return $this->chapterBase[$target];
}
/**
* Titel und Text des gewählten Kapitels in die Eingabefelder laden: zuerst die offenen Eingaben, sonst den gespeicherten Stand.
*/
protected function loadChapterFields(): void
{
$target = $this->selectedChapterTarget();
if ($target === null) {
$this->partTitle = '';
$this->partBody = '';
return;
}
$edit = $this->chapterEdits[$target] ?? null;
$this->partTitle = $edit['title'] ?? (string) ($this->members[$this->selected]['title'] ?? '');
$this->partBody = $edit['body'] ?? FormattedText::canonical($this->storedChapterBody($target));
}
/**
* Schreibt die offenen Kapitel als Entwurfsfassungen und übernimmt sie in den Aufbau. Eine festgeschriebene Fassung
* bleibt unverändert; es entsteht eine neue Entwurfsfassung, die erst mit der Dokumentfassung bereitgestellt wird.
*/
protected function persistChapterEdits(): bool
{
if (! $this->isDocument()) {
return true;
}
$this->stashChapter();
foreach ($this->chapterEdits as $target => $edit) {
if (trim($edit['title']) === '') {
$this->feedback = 'Jedes Kapitel braucht einen Titel.';
$this->selectTarget($target);
return false;
}
}
$service = app(ContentService::class);
foreach ($this->chapterEdits as $target => $edit) {
$index = $this->memberIndex($target);
$version = $index === null ? null : ContentElementVersion::query()->with('element')->find((int) substr($target, 8));
if ($index === null || ! $version instanceof ContentElementVersion || $version->element === null) {
continue;
}
try {
$service->describe($version->element, trim($edit['title']), $version->element->description);
$updated = $service->reviseElementDraft($version, $edit['body'] === '' ? '<p></p>' : $edit['body']);
} catch (DomainRuleException $exception) {
$this->feedback = $exception->getMessage();
return false;
}
if ($updated->id !== $version->id) {
$row = app(EditorialCatalog::class)->rowForTarget('element:'.$updated->id, (int) $this->getRecord()->getKey(), allowSelf: true, allowDraft: true);
if ($row === null) {
$this->feedback = 'Die neue Fassung des Kapitels ließ sich nicht übernehmen.';
return false;
}
$this->members[$index] = [...$row, 'role' => (string) $this->members[$index]['role'], 'note' => (string) ($this->members[$index]['note'] ?? ''), ...$this->memberExtras($this->members[$index])];
} else {
$this->members[$index]['title'] = trim($edit['title']);
}
}
$this->chapterEdits = [];
$this->chapterBase = [];
$this->slimChapterMembers();
$this->syncRoleDraft();
return true;
}
/**
* Ein Kapitelmitglied trägt nur, was die Übersicht braucht. Der Text eines Kapitels liegt in der Datenbank und wird beim
* Öffnen gelesen; so bleibt der Zustand der Seite klein, auch bei einem Handbuch mit vielen Kapiteln (jede Anfrage sendet ihn).
*/
protected function slimChapterMembers(): void
{
if (! $this->isDocument()) {
return;
}
foreach ($this->members as $index => $member) {
unset($this->members[$index]['body'], $this->members[$index]['summary'], $this->members[$index]['medium_description'], $this->members[$index]['usage_note'], $this->members[$index]['license_note']);
}
}
private function memberIndex(string $target): ?int
{
foreach ($this->members as $index => $member) {
if (($member['target'] ?? '') === $target) {
return $index;
}
}
return null;
}
private function selectTarget(string $target): void
{
$index = $this->memberIndex($target);
if ($index !== null) {
$this->selected = $index;
$this->syncRoleDraft();
}
}
/**
* Legt ein neues Kapitel (Ebene 1) oder Unterkapitel (Ebene 2) an. Es steht hinter dem gewählten Kapitel samt dessen
* Unterkapiteln beziehungsweise hinter dem gewählten Unterkapitel und ist sofort zum Schreiben geöffnet.
*/
public function addChapter(int $level = 1): void
{
abort_unless($this->canEditEditorial(), 403);
if (($reason = $this->schreibschutz()) !== null) {
$this->feedback = $reason;
return;
}
$this->commitRoleDraft();
$level = $level >= 2 && $this->members !== [] ? 2 : 1;
$title = $level === 2 ? 'Neues Unterkapitel' : 'Neues Kapitel';
try {
$service = app(ContentService::class);
$element = $service->createElement('text', 'text', $title);
$version = $service->draftElementVersion($element, '<p></p>');
/** @var Composition $document */
$document = $this->getRecord();
app(DocumentChapters::class)->mark($element, $document);
} catch (DomainRuleException $exception) {
$this->feedback = $exception->getMessage();
return;
}
$row = app(EditorialCatalog::class)->rowForTarget('element:'.$version->id, (int) $this->getRecord()->getKey(), allowSelf: true, allowDraft: true);
if ($row === null) {
$this->feedback = 'Das Kapitel ließ sich nicht anlegen.';
return;
}
$row['role'] = DocumentOutline::role($level);
$row['note'] = '';
$row = [...$row, ...$this->memberExtras([])];
unset($row['body'], $row['summary'], $row['medium_description'], $row['usage_note'], $row['license_note']);
$roles = array_map(fn (array $member): string => (string) ($member['role'] ?? ''), $this->members);
$at = count($this->members);
if ($this->selected !== null && isset($this->members[$this->selected])) {
$base = $this->selected;
$levels = array_column(DocumentOutline::numbering($roles), 'level');
// Ein neues Kapitel steht hinter dem ganzen gewählten Kapitel, ein Unterkapitel hinter dem gewählten Eintrag.
while ($level === 1 && $levels[$base] === 2 && $base > 0) {
$base--;
}
$at = DocumentOutline::blockEnd($roles, $base) + 1;
}
array_splice($this->members, $at, 0, [$row]);
$this->members = array_values($this->members);
$this->selected = $at;
$this->panel = 'bestandteil';
$this->syncRoleDraft();
$this->feedback = '„'.$title.'“ steht jetzt an Stelle '.($at + 1).'. Gib dem Kapitel einen Titel und schreibe den Text; gespeichert wird mit „Entwurf speichern“.';
}
/** Ändert die Ebene: Kapitel oder Unterkapitel. Das erste Kapitel bleibt immer ein Kapitel. */
public function setChapterLevel(int $index, int $level): void
{
if (! isset($this->members[$index])) {
return;
}
$this->commitRoleDraft();
if ($index === 0 && $level >= 2) {
$this->feedback = 'Das erste Kapitel bleibt ein Kapitel: Ein Unterkapitel braucht ein Kapitel davor.';
return;
}
$this->members[$index]['role'] = DocumentOutline::role($level);
$this->syncRoleDraft();
$this->feedback = '„'.$this->members[$index]['title'].'“ ist jetzt ein '.DocumentOutline::role($level).'. Die Nummern folgen der Reihenfolge. Gespeichert ist das erst mit „Entwurf speichern“.';
}
/** Verschiebt ein Kapitel mit seinen Unterkapiteln um eine Stelle; ein Unterkapitel wandert auch in das Nachbarkapitel. */
public function moveChapter(int $index, int $direction): void
{
$this->commitRoleDraft();
if (! isset($this->members[$index]) || ! in_array($direction, [-1, 1], true)) {
return;
}
$roles = array_map(fn (array $member): string => (string) ($member['role'] ?? ''), $this->members);
$levels = array_column(DocumentOutline::numbering($roles), 'level');
$end = DocumentOutline::blockEnd($roles, $index);
$after = null;
if ($levels[$index] === 1) {
if ($direction < 0) {
$previous = null;
for ($i = $index - 1; $i >= 0; $i--) {
if ($levels[$i] === 1) {
$previous = $i;
break;
}
}
$after = $previous === null ? null : $previous - 1;
} elseif (isset($this->members[$end + 1])) {
$after = DocumentOutline::blockEnd($roles, $end + 1);
}
} elseif ($direction < 0) {
if ($index > 0 && $levels[$index - 1] === 2) {
$after = $index - 2;
} elseif ($index - 1 > 0) {
// Das erste Unterkapitel wandert ans Ende des vorigen Kapitels.
$after = $index - 2;
}
} elseif (isset($levels[$index + 1])) {
// Hinter das nächste Unterkapitel, beziehungsweise als erstes Unterkapitel in das nächste Kapitel.
$after = $index + 1;
}
if ($after === null) {
$this->feedback = 'Weiter lässt sich dieses Kapitel nicht verschieben.';
return;
}
$this->relocate($index, $end, $after);
}
/** Ablegen per Ziehen: Der Block des gezogenen Kapitels wandert an die Stelle des Ziels. */
protected function moveChapterTo(int $from, int $to): void
{
$this->commitRoleDraft();
if (! isset($this->members[$from], $this->members[$to]) || $from === $to) {
return;
}
$roles = array_map(fn (array $member): string => (string) ($member['role'] ?? ''), $this->members);
$levels = array_column(DocumentOutline::numbering($roles), 'level');
$end = DocumentOutline::blockEnd($roles, $from);
if ($to >= $from && $to <= $end) {
return;
}
if ($levels[$from] === 1) {
// Ein Kapitel zieht man auf ein Kapitel; ein Unterkapitel als Ziel zählt als sein Kapitel.
while ($levels[$to] === 2 && $to > 0) {
$to--;
}
$after = $to < $from ? $to - 1 : DocumentOutline::blockEnd($roles, $to);
} else {
$after = $to < $from ? $to - 1 : $to;
}
$this->relocate($from, $end, $after);
}
/**
* Setzt den Block `$start..$end` hinter den Eintrag mit dem ursprünglichen Index `$after` (−1 = an den Anfang).
*/
private function relocate(int $start, int $end, int $after): void
{
$selectedTarget = $this->selected !== null ? ($this->members[$this->selected]['target'] ?? null) : null;
$block = array_slice($this->members, $start, $end - $start + 1);
$position = 0;
foreach (array_keys($this->members) as $i) {
if ($i <= $after && ($i < $start || $i > $end)) {
$position++;
}
}
$rest = array_values(array_filter($this->members, fn (int $i): bool => $i < $start || $i > $end, ARRAY_FILTER_USE_KEY));
array_splice($rest, $position, 0, $block);
$this->members = $rest;
// Ein Unterkapitel am Anfang hätte kein Kapitel davor.
if (DocumentOutline::level((string) ($this->members[0]['role'] ?? '')) === 2) {
$this->members[0]['role'] = DocumentOutline::CHAPTER;
}
$this->selected = $this->memberIndex((string) $selectedTarget) ?? $this->selected;
$this->syncRoleDraft();
$this->feedback = 'Die Reihenfolge ist geändert. Die Nummern folgen ihr. Gespeichert ist das erst mit „Entwurf speichern“.';
}
/** Entfernt ein Kapitel aus dem Dokument; seine offenen Eingaben entfallen, der Text bleibt im Medienbestand. */
protected function forgetChapter(int $index): void
{
$target = (string) ($this->members[$index]['target'] ?? '');
unset($this->chapterEdits[$target]);
}
}
@@ -755,7 +755,7 @@ public function pickerKinds(): array
}
if ($this->pickerPurpose === 'aufbau') {
return ['alle' => 'Alle Inhalte', 'film' => 'Filme', 'bild' => 'Bilder', 'audio' => 'Hörstücke', 'dokument' => 'Dokumente', 'text' => 'Texte', 'modul' => 'Module'];
return ['alle' => 'Alle Inhalte', 'film' => 'Filme', 'bild' => 'Bilder', 'audio' => 'Hörstücke', 'dokument' => 'Dokumente', 'text' => 'Texte', 'modul' => 'Module', 'dokumentfassung' => 'Dokumente (Fassungen)'];
}
return ['alle' => 'Alle Medien', 'bild' => 'Bilder', 'film' => 'Filme', 'audio' => 'Hörstücke', 'dokument' => 'Dokumente'];
@@ -0,0 +1,86 @@
<?php
namespace App\Http\Controllers;
use App\Domain\Catalog\Composition;
use App\Domain\Catalog\CompositionKind;
use App\Domain\Catalog\DocumentGuide;
use App\Domain\Catalog\DocumentPdf;
use App\Domain\Catalog\DocumentReader;
use App\Domain\Catalog\EmbeddedImages;
use App\Domain\Catalog\FormattedText;
use App\Domain\Identity\StaffRole;
use App\Filament\Support\EditorialCatalog;
use App\Models\User;
use Illuminate\Http\Response;
use Illuminate\View\View;
/**
* Vorschau eines Dokuments für die Redaktion: der gespeicherte Entwurf, sonst die letzte bereitgestellte Fassung, so wie ein
* Mitglied sie als Seite und als PDF sieht (ohne Rechteprüfung und ohne Ausgabenachweis). Ungespeicherte Eingaben im Editor
* erscheinen hier erst nach „Entwurf speichern“.
*/
class DocumentPreviewController extends Controller
{
public function show(Composition $composition): View
{
$this->authorizeStaff($composition);
$guide = $this->guide($composition);
$images = EmbeddedImages::staff();
foreach ($guide['chapters'] as $index => $chapter) {
$guide['chapters'][$index]['html'] = DocumentGuide::shiftHeadings(FormattedText::html($chapter['version']->body, $images));
}
return view('document.preview', ['guide' => $guide, 'composition' => $composition, 'pdfUrl' => route('editorial.document-preview.pdf', $composition)]);
}
public function pdf(Composition $composition): Response
{
$this->authorizeStaff($composition);
$content = app(DocumentPdf::class)->render($this->guide($composition), 'Vorschau der Redaktion', 'vorschau', EmbeddedImages::forStaffPdf());
return response($content, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="vorschau.pdf"',
'Cache-Control' => 'private, no-store',
]);
}
/**
* @return array<string, mixed>
*/
private function guide(Composition $composition): array
{
$chapters = app(DocumentReader::class)->forStaff($composition);
abort_if($chapters === null, 404);
foreach ($chapters as $index => $chapter) {
$chapters[$index] += [
'allowed' => true,
'grant' => null,
'may_download' => true,
'download_grant' => null,
'state' => 'ok',
'html' => null,
'blocks' => FormattedText::blocks($chapter['version']->body),
];
}
return [
'title' => app(EditorialCatalog::class)->compositionTitle($composition),
'summary_html' => FormattedText::html($composition->summary),
'chapters' => $chapters,
];
}
private function authorizeStaff(Composition $composition): void
{
$user = auth('staff')->user();
abort_unless(
$user instanceof User && ($user->hasStaffRole(StaffRole::Redakteur) || $user->hasStaffRole(StaffRole::Katalogverwalter)),
403,
);
abort_unless($composition->kind === CompositionKind::Document, 404);
}
}
@@ -0,0 +1,97 @@
<?php
namespace App\Http\Controllers\Member;
use App\Domain\Catalog\ArticleRelease;
use App\Domain\Catalog\CompositionKind;
use App\Domain\Catalog\CompositionVersion;
use App\Domain\Catalog\DocumentGuide;
use App\Domain\Catalog\DocumentPdf;
use App\Domain\Catalog\EmbeddedImages;
use App\Domain\Catalog\ExerciseGuide;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Media\DeliveryLog;
use App\Http\Controllers\Controller;
use App\Http\SignedLink;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
* Das Dokument innerhalb des erworbenen Moduls oder Programms: als zusammenhängende Seite mit anklickbarem
* Inhaltsverzeichnis und als PDF. Beide zeigen die im Artikel-Stand gebundene Dokumentfassung (ADR-51); über jedes Kapitel
* und jedes Bild entscheidet `DecideAccess`, auch die direkte PDF-Adresse wird bei jedem Abruf neu entschieden.
*/
class DocumentController extends Controller
{
public function show(Request $request, LicenseArticle $article, ArticleRelease $release, string $path): View
{
[$guide, $located] = $this->load($request, $article, $release, $path);
$copy = DeliveryLog::newCopyId();
$shown = false;
foreach ($guide['chapters'] as $chapter) {
if ($chapter['allowed'] && $chapter['grant'] !== null) {
app(DeliveryLog::class)->write($chapter['grant'], $article, $release, $chapter['version'], 'ansehen', 'text', hash('sha256', (string) $chapter['version']->body), 'k2', $copy, $located['version']->id);
$shown = true;
}
}
return view('member.document', [
'guide' => $guide,
'reader' => $request->user()->name,
'copy' => $shown ? $copy : null,
'pdfUrl' => app(DocumentGuide::class)->pdfAllowed($guide) ? SignedLink::temporary('member.document.pdf', now()->addMinutes(10), [
'article' => $article->id,
'release' => $release->id,
'path' => $path,
'reader' => $request->user()->id,
]) : null,
]);
}
public function pdf(Request $request, LicenseArticle $article, ArticleRelease $release, string $path): Response
{
abort_unless((int) $request->query('reader') === $request->user()->id, 403);
[$guide, $located] = $this->load($request, $article, $release, $path);
abort_unless(app(DocumentGuide::class)->pdfAllowed($guide), 403, 'Für dieses PDF fehlt die Berechtigung für ein Kapitel.');
$copy = DeliveryLog::newCopyId();
$images = app(EmbeddedImages::class)->forPdf($request->user(), $article, $release);
$content = app(DocumentPdf::class)->render($guide, $request->user()->name, $copy, $images);
$checksum = hash('sha256', $content);
foreach ($guide['chapters'] as $chapter) {
$grant = $chapter['download_grant'] ?? $chapter['grant'];
if ($grant !== null) {
app(DeliveryLog::class)->write($grant, $article, $release, $chapter['version'], 'laden', 'pdf', $checksum, 'k2', $copy, $located['version']->id);
}
}
foreach ($images->used() as $image) {
app(DeliveryLog::class)->write($image['grant'], $article, $release, $image['version'], 'laden', 'pdf', $checksum, 'k2', $copy, $located['version']->id);
}
return response($content, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="'.(str($guide['title'])->slug()->value() ?: 'dokument').'.pdf"',
'X-License-Copy' => $copy,
'Cache-Control' => 'private, no-store',
]);
}
/**
* @return array{0: array<string, mixed>, 1: array{version: CompositionVersion, selection: list<string>|null}}
*/
private function load(Request $request, LicenseArticle $article, ArticleRelease $release, string $path): array
{
$guides = app(ExerciseGuide::class);
abort_unless($guides->mayOpen($request->user(), $article, $release), 403);
$located = $guides->locate($release, $path, CompositionKind::Document);
abort_if($located === null, 404);
return [app(DocumentGuide::class)->build($request->user(), $article, $release, $located['version']), $located];
}
}
+16 -5
View File
@@ -380,6 +380,8 @@ private function present(User $user, StructureNode $node, bool $full, int $rootI
}
}
$document = $this->isDocument($node);
$documentUrl = $document ? $this->exerciseUrl($user, $rootId, $node) : null;
$title = $node->title;
if ($element !== null) {
@@ -396,10 +398,11 @@ private function present(User $user, StructureNode $node, bool $full, int $rootI
'kind' => $node->editorialKindLabel ?? $this->outputLabel($node->technicalKindLabel) ?? $node->technicalKindLabel,
'output_class' => $node->outputClass,
'playback' => $playback,
'view_url' => $view,
'view_url' => $view ?? $documentUrl,
'poster_url' => $poster,
'download_url' => $download,
'program_url' => $this->exerciseUrl($user, $rootId, $node) ?? $this->programUrl($node),
'program_url' => $documentUrl ?? $this->exerciseUrl($user, $rootId, $node) ?? $this->programUrl($node),
'document' => $document,
'composition_id' => $node->compositionId,
'element_id' => $node->contentElementId,
'version_id' => $node->contentElementVersionId,
@@ -407,13 +410,20 @@ private function present(User $user, StructureNode $node, bool $full, int $rootI
'composition' => $rootId,
'version' => $node->contentElementVersionId,
]),
'children' => array_map(
// Ein Dokument steht als ein Eintrag da; seine Kapitel lesen Mitglieder im Dokument selbst.
'children' => $document ? [] : array_map(
fn (StructureNode $child): array => $this->present($user, $child, $full, $rootId),
$node->children,
),
];
}
private function isDocument(StructureNode $node): bool
{
return $node->compositionId !== null
&& Composition::query()->whereKey($node->compositionId)->where('kind', CompositionKind::Document->value)->exists();
}
/**
* @param list<array<string, mixed>> $nodes
* @param list<array<string, mixed>> $parents
@@ -513,8 +523,9 @@ private function exerciseUrl(User $user, int $rootId, StructureNode $node): ?str
}
$nested = CompositionVersion::query()->with('composition')->find($node->compositionVersionId);
$kind = $nested?->composition?->kind;
if ($nested?->composition?->kind !== CompositionKind::Exercise) {
if (! in_array($kind, [CompositionKind::Exercise, CompositionKind::Document], true)) {
return null;
}
@@ -533,7 +544,7 @@ private function exerciseUrl(User $user, int $rootId, StructureNode $node): ?str
$path = $guide->pathTo($release->rootCompositionVersion, $nested->id);
if ($path !== null) {
return route('member.exercise', ['article' => $grant->license_article_id, 'release' => $release->id, 'path' => $path]);
return route($kind === CompositionKind::Document ? 'member.document' : 'member.exercise', ['article' => $grant->license_article_id, 'release' => $release->id, 'path' => $path]);
}
}
}