Führe Übungen als Fassungen mit Varianten, Verwendung und Mitgliederausgabe ein
CI Feature / test (push) Successful in 3m32s

Neuer kind 'exercise', Varianten je Fassung, Verwendung (erforderlich/ergänzend) und Variantenauswahl am einbindenden
Mitglied; der Stand schreibt nur gewählte Varianten fest. Änderungsnachweis über structure_hash. Formatierte Anleitung
im Mitgliederbereich und PDF (Fußzeile, Metadaten, Ausgabenachweis, keine gespeicherten Kopien); Sperre trifft nur das
Medium.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Sonnet 5.5 committed 2026-11-23 16:52:01 +01:00
1 parent ef56befc0e
commit d1f97a351a
26 files changed
+1628 -15

No files matched your search

+2
View File
@@ -57,6 +57,8 @@ public function publishRelease(
'content_element_version_id' => $row['version_id'],
'role' => $row['role'] !== '' ? $row['role'] : $row['path'],
'path' => $row['path'],
'requirement' => $row['requirement'] ?? null,
'variant_key' => $row['variant'] ?? null,
]);
}
@@ -13,6 +13,7 @@ class CompatibilityAttestation extends Model
protected $fillable = [
'composition_version_id',
'resolved_hash',
'structure_hash',
'confirmed_by',
'confirmed_at',
'note',
+11 -3
View File
@@ -7,6 +7,8 @@ enum CompositionKind: string
case Kombination = 'kombination';
case Uebung = 'uebung';
case Kurs = 'kurs';
/** Seit der Übungsverwaltung: die fachliche Übung. Der ältere Wert `uebung` bezeichnet in der Verwaltung das Modul. */
case Exercise = 'exercise';
/**
* @return list<string>
@@ -20,8 +22,9 @@ public function label(): string
{
return match ($this) {
self::Kombination => 'Fachliche Kombination',
self::Uebung => 'Übung',
self::Uebung => 'Modul',
self::Kurs => 'Kurs',
self::Exercise => 'Übung',
};
}
@@ -29,8 +32,9 @@ public function plural(): string
{
return match ($this) {
self::Kombination => 'Fachliche Kombinationen',
self::Uebung => 'Übungen',
self::Uebung => 'Module',
self::Kurs => 'Kurse',
self::Exercise => 'Übungen',
};
}
@@ -38,8 +42,9 @@ public function createLabel(): string
{
return match ($this) {
self::Kombination => 'Kombination anlegen',
self::Uebung => 'Übung anlegen',
self::Uebung => 'Modul anlegen',
self::Kurs => 'Kurs anlegen',
self::Exercise => 'Übung anlegen',
};
}
@@ -49,6 +54,7 @@ public function explanation(): string
self::Kombination => 'Didaktische oder thematische Zusammenstellung, zum Beispiel ein Materialsatz. Sie wird in Übungen und Kursen wiederverwendet und ist selbst kein Kurs.',
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.',
};
}
@@ -58,6 +64,7 @@ public function deskLabel(): string
self::Kombination => 'Fachliche Kombination',
self::Uebung => 'Modul',
self::Kurs => 'Programm',
self::Exercise => 'Übung',
};
}
@@ -67,6 +74,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(),
};
}
+17
View File
@@ -14,8 +14,20 @@ class CompositionMember extends Model
'placement_note',
'content_element_version_id',
'nested_composition_version_id',
'variant_id',
'requirement',
'variant_selection',
];
public const REQUIRED = 'erforderlich';
public const SUPPLEMENTARY = 'ergaenzend';
protected function casts(): array
{
return ['variant_selection' => 'array'];
}
protected static function booted(): void
{
static::creating(function (CompositionMember $member): void {
@@ -41,6 +53,11 @@ public function contentElementVersion(): BelongsTo
return $this->belongsTo(ContentElementVersion::class);
}
public function variant(): BelongsTo
{
return $this->belongsTo(CompositionVersionVariant::class, 'variant_id');
}
public function nestedCompositionVersion(): BelongsTo
{
return $this->belongsTo(CompositionVersion::class, 'nested_composition_version_id');
@@ -17,6 +17,9 @@ class CompositionVersion extends Model
'learning_goal',
'duration_minutes',
'material_note',
'duration_max',
'prerequisites',
'structure_hash',
];
protected function casts(): array
@@ -60,6 +63,11 @@ public function members(): HasMany
return $this->hasMany(CompositionMember::class)->orderBy('position');
}
public function variants(): HasMany
{
return $this->hasMany(CompositionVersionVariant::class)->orderBy('position');
}
public function attestations(): HasMany
{
return $this->hasMany(CompatibilityAttestation::class);
@@ -0,0 +1,36 @@
<?php
namespace App\Domain\Catalog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Durchführungsvariante einer Übungsfassung. Der Schlüssel ist je Fassung eindeutig und bleibt über Fassungen hinweg
* gleich, damit eine Auswahl im Modul oder Programm und der Abgleich mit einer Quelle dieselbe Variante meinen.
* Wie die Mitglieder ist sie nur im Entwurf der Fassung schreibbar.
*/
class CompositionVersionVariant extends Model
{
protected $fillable = ['composition_version_id', 'key', 'position', 'name', 'description'];
protected static function booted(): void
{
static::creating(function (CompositionVersionVariant $variant): void {
$status = CompositionVersion::query()->whereKey($variant->composition_version_id)->value('status');
if (StatusValue::of($status) === ContentVersionStatus::Bereit->value) {
throw new DomainRuleException('Eine bestätigte Kompositionsfassung nimmt keine weiteren Varianten auf.');
}
});
static::updating(function (): void {
throw new DomainRuleException('Varianten einer Komposition werden nicht verändert, sondern durch eine neue Fassung ersetzt.');
});
}
public function compositionVersion(): BelongsTo
{
return $this->belongsTo(CompositionVersion::class);
}
}
+24 -4
View File
@@ -5,9 +5,14 @@
class ContentResolver
{
/**
* @return list<array{version_id: int, role: string, path: string}>
* Löst eine Wurzel zu den enthaltenen Medienfassungen auf. Eine Übung wird nur mit ihren gemeinsamen Mitgliedern und
* den ausgewählten Varianten aufgelöst: Das Mitglied, das die Übungsfassung einbindet, trägt die Auswahl
* (`variant_selection`, Liste von Variantenschlüsseln; leer gelassen bedeutet alle Varianten).
*
* @param list<string>|null $selection Variantenschlüssel, die für diese Fassung gelten; null = alle
* @return list<array{version_id: int, role: string, path: string, requirement: string, variant: string|null}>
*/
public function expand(ContentElementVersion|CompositionVersion $node, string $path = '', array $stack = []): array
public function expand(ContentElementVersion|CompositionVersion $node, string $path = '', array $stack = [], ?array $selection = null): array
{
if ($node instanceof ContentElementVersion) {
$node->loadMissing('element');
@@ -16,6 +21,8 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
'version_id' => $node->id,
'role' => $path,
'path' => $path !== '' ? $path : $node->element->working_title,
'requirement' => CompositionMember::REQUIRED,
'variant' => null,
]];
}
@@ -26,7 +33,13 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
$stack[] = $node->composition_id;
$rows = [];
foreach ($node->members()->orderBy('position')->get() as $member) {
foreach ($node->members()->with('variant')->orderBy('position')->get() as $member) {
$variantKey = $member->variant?->key;
if ($variantKey !== null && $selection !== null && ! in_array($variantKey, $selection, true)) {
continue;
}
$segment = $path === '' ? $member->role : $path.' / '.$member->role;
if ($member->content_element_version_id !== null) {
@@ -34,6 +47,8 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
'version_id' => $member->content_element_version_id,
'role' => $member->role,
'path' => $segment,
'requirement' => $member->requirement ?: CompositionMember::REQUIRED,
'variant' => $variantKey,
];
continue;
@@ -53,7 +68,12 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p
continue;
}
$rows = array_merge($rows, $this->expand($nested, $segment, $stack));
$rows = array_merge($rows, $this->expand(
$nested,
$segment,
$stack,
is_array($member->variant_selection) ? array_values(array_map('strval', $member->variant_selection)) : null,
));
}
return $rows;
+126 -2
View File
@@ -225,7 +225,9 @@ public function releaseElementVersion(ContentElementVersion $version): ContentEl
}
/**
* @param list<array{role: string, target: ContentElementVersion|CompositionVersion}> $members
* @param list<array{role: string, target: ContentElementVersion|CompositionVersion, note?: string|null, variant?: string|null, requirement?: string|null, selection?: list<string>|null}> $members
* @param array{learning_goal?: mixed, duration_minutes?: mixed, duration_max?: mixed, material_note?: mixed, prerequisites?: mixed} $didactic
* @param list<array{key: string, name: string, description?: string|null}> $variants Durchführungsvarianten einer Übung
*/
public function publishComposition(
Composition $composition,
@@ -233,18 +235,21 @@ public function publishComposition(
?User $confirmedBy = null,
?string $note = null,
array $didactic = [],
array $variants = [],
): CompositionVersion {
if ($members === []) {
throw new DomainRuleException('Eine Komposition braucht mindestens ein Mitglied.');
}
$variants = $this->checkedVariants($variants);
$this->assertAcyclic($composition->id, $members);
foreach ($members as $member) {
$this->assertReadyMember($member['target']);
$this->assertMemberPlacement($member, $variants);
}
return DB::transaction(function () use ($composition, $members, $confirmedBy, $note, $didactic): CompositionVersion {
return DB::transaction(function () use ($composition, $members, $confirmedBy, $note, $didactic, $variants): CompositionVersion {
$number = ((int) $composition->versions()->max('number')) + 1;
$version = $composition->versions()->create([
'number' => $number,
@@ -253,28 +258,49 @@ public function publishComposition(
'resolved_hash' => 'pending',
'learning_goal' => $this->optionalText($didactic['learning_goal'] ?? null),
'duration_minutes' => isset($didactic['duration_minutes']) ? (int) $didactic['duration_minutes'] : null,
'duration_max' => isset($didactic['duration_max']) ? (int) $didactic['duration_max'] : null,
'material_note' => $this->optionalText($didactic['material_note'] ?? null),
'prerequisites' => $this->optionalText($didactic['prerequisites'] ?? null),
]);
$variantIds = [];
foreach ($variants as $index => $variant) {
$variantIds[$variant['key']] = $version->variants()->create([
'key' => $variant['key'],
'position' => $index + 1,
'name' => $variant['name'],
'description' => $variant['description'],
])->id;
}
foreach (array_values($members) as $index => $member) {
$target = $member['target'];
$selection = $target instanceof CompositionVersion ? ($member['selection'] ?? null) : null;
$version->members()->create([
'position' => $index + 1,
'role' => $this->required($member['role'], 'Die Rolle eines Mitglieds fehlt.'),
'placement_note' => $this->optionalText($member['note'] ?? null),
'content_element_version_id' => $target instanceof ContentElementVersion ? $target->id : null,
'nested_composition_version_id' => $target instanceof CompositionVersion ? $target->id : null,
'variant_id' => isset($member['variant']) ? $variantIds[$member['variant']] : null,
'requirement' => $member['requirement'] ?? CompositionMember::REQUIRED,
'variant_selection' => $selection === null ? null : array_values($selection),
]);
}
$version->load('members.variant', 'variants');
$resolvedHash = $this->resolver->resolvedHash($version);
$structureHash = $this->structureHash($version);
$version->attestations()->create([
'resolved_hash' => $resolvedHash,
'structure_hash' => $structureHash,
'confirmed_by' => $confirmedBy?->id,
'confirmed_at' => now(),
'note' => $note,
]);
$version->resolved_hash = $resolvedHash;
$version->structure_hash = $structureHash;
$version->status = ContentVersionStatus::Bereit;
$version->save();
@@ -282,6 +308,101 @@ public function publishComposition(
});
}
/**
* Änderungsnachweis einer Fassung: Felder, Varianten und die Verwendung jedes Mitglieds. Anders als der
* `resolved_hash` (nur die Menge der enthaltenen Medienfassungen) ändert er sich auch dann, wenn Variante,
* Verwendung, Reihenfolge oder Variantenauswahl wechseln und die Medien gleich bleiben.
*/
public function structureHash(CompositionVersion $version): string
{
$version->loadMissing('members.variant', 'variants');
return hash('sha256', json_encode([
'fields' => [
$version->learning_goal,
$version->duration_minutes,
$version->duration_max,
$version->material_note,
$version->prerequisites,
],
'variants' => $version->variants->map(fn (CompositionVersionVariant $variant): array => [
$variant->key, $variant->position, $variant->name, $variant->description,
])->all(),
'members' => $version->members->map(fn (CompositionMember $member): array => [
$member->position,
$member->role,
$member->placement_note,
$member->content_element_version_id,
$member->nested_composition_version_id,
$member->variant?->key,
$member->requirement,
$member->variant_selection,
])->all(),
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
/**
* @param list<array{key?: string, name?: string, description?: string|null}> $variants
* @return list<array{key: string, name: string, description: string|null}>
*/
private function checkedVariants(array $variants): array
{
$checked = [];
$keys = [];
foreach (array_values($variants) as $variant) {
$key = trim((string) ($variant['key'] ?? ''));
if ($key === '' || in_array($key, $keys, true)) {
throw new DomainRuleException('Jede Variante braucht einen eigenen Schlüssel.');
}
$keys[] = $key;
$checked[] = [
'key' => $key,
'name' => $this->required((string) ($variant['name'] ?? ''), 'Jede Variante braucht einen Namen.'),
'description' => $this->optionalText($variant['description'] ?? null),
];
}
return $checked;
}
/**
* @param array{target: ContentElementVersion|CompositionVersion, variant?: string|null, requirement?: string|null, selection?: list<string>|null} $member
* @param list<array{key: string, name: string, description: string|null}> $variants
*/
private function assertMemberPlacement(array $member, array $variants): void
{
$variant = $member['variant'] ?? null;
if ($variant !== null && ! in_array($variant, array_column($variants, 'key'), true)) {
throw new DomainRuleException('Ein Mitglied verweist auf eine Variante, die es in dieser Fassung nicht gibt.');
}
$requirement = $member['requirement'] ?? CompositionMember::REQUIRED;
if (! in_array($requirement, [CompositionMember::REQUIRED, CompositionMember::SUPPLEMENTARY], true)) {
throw new DomainRuleException('Die Verwendung eines Mitglieds ist erforderlich oder ergänzend.');
}
$selection = $member['selection'] ?? null;
if ($selection === null) {
return;
}
if (! $member['target'] instanceof CompositionVersion) {
throw new DomainRuleException('Eine Variantenauswahl gibt es nur an einer eingebundenen Übungsfassung.');
}
$offered = $member['target']->variants()->pluck('key')->all();
if ($selection === [] || array_diff($selection, $offered) !== []) {
throw new DomainRuleException('Die Variantenauswahl nennt eine Variante, die die eingebundene Fassung nicht anbietet, oder keine.');
}
}
public function createComposition(string $designation, CompositionKind $kind = CompositionKind::Uebung): Composition
{
return Composition::query()->create([
@@ -369,6 +490,9 @@ private function membersHash(array $members): string
'note' => $this->optionalText($member['note'] ?? null),
'element_version_id' => $target instanceof ContentElementVersion ? $target->id : null,
'composition_version_id' => $target instanceof CompositionVersion ? $target->id : null,
'variant' => $member['variant'] ?? null,
'requirement' => $member['requirement'] ?? CompositionMember::REQUIRED,
'selection' => $member['selection'] ?? null,
];
}
+2 -1
View File
@@ -17,6 +17,7 @@ class EditorialContentKind extends Model
public const CONTEXTS = [
'medium' => 'Medium',
'modul' => 'Modul',
'uebung' => 'Übung',
'programm' => 'Programm',
'lizenzartikel' => 'Lizenzartikel',
];
@@ -26,7 +27,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', 'traineranleitung'];
public const SYSTEM_SLUGS = ['programm', 'modul', 'uebung', 'traineranleitung'];
protected $fillable = [
'slug',
@@ -46,6 +46,7 @@ public static function compositionContext(?CompositionKind $kind): ?string
return match ($kind) {
CompositionKind::Kurs => 'programm',
CompositionKind::Uebung => 'modul',
CompositionKind::Exercise => 'uebung',
default => null,
};
}
@@ -137,6 +138,7 @@ private function usedKindIds(string $context): array
'lizenzartikel' => DB::table('license_articles'),
'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),
default => null,
};
+183
View File
@@ -0,0 +1,183 @@
<?php
namespace App\Domain\Catalog;
use App\Domain\Entitlement\DecideAccess;
use App\Domain\Entitlement\Grant;
use App\Domain\Entitlement\GrantStatus;
use App\Http\LibraryCatalog;
use App\Models\User;
/**
* Die Anleitung einer Übung, wie ein Stand sie festschreibt: die im Stand gebundene Übungsfassung, die angebotenen
* Varianten und je Abschnitt oder Medium die Entscheidung der zentralen Rechteprüfung (`DecideAccess`). Ansicht und
* PDF lesen dieses Ergebnis und zeigen damit dieselbe Fassung.
*
* Eine Sperre oder fehlende Berechtigung betrifft nur den betroffenen Abschnitt oder das Medium. Anleitung und übrige
* Inhalte bleiben im selben Stand erreichbar. Fehlt in einer Variante ein erforderlicher Bestandteil, gilt die Variante
* als derzeit nicht vollständig durchführbar; ein ergänzender Bestandteil entfällt mit einem Hinweis.
*/
class ExerciseGuide
{
public function __construct(private readonly DecideAccess $access) {}
/**
* Darf dieses Konto den Stand überhaupt sehen? Aktive, nutzbare Berechtigung auf den Artikel und ein auslieferbarer
* Stand. Über die einzelnen Inhalte entscheidet danach `DecideAccess`.
*/
public function mayOpen(User $user, LicenseArticle $article, ArticleRelease $release): bool
{
if ($release->license_article_id !== $article->id
|| ! in_array($release->status, [ReleaseStatus::Veroeffentlicht, ReleaseStatus::AbgeloestVerfuegbar], true)) {
return false;
}
return Grant::query()
->where('license_article_id', $article->id)
->where('status', GrantStatus::Aktiv)
->usableBy($user)
->exists();
}
/**
* Die Übungsfassung an einer Stelle des Stands. Der Pfad nennt die Positionen der Mitglieder von der Wurzel des
* Stands abwärts („2“ oder „1-3“). So ist auch dieselbe Übung an zwei Stellen eines Produkts unterscheidbar.
*
* @return array{version: CompositionVersion, selection: list<string>|null}|null
*/
public function locate(ArticleRelease $release, string $path): ?array
{
if (preg_match('/^\d+(-\d+)*$/', $path) !== 1) {
return null;
}
$version = $release->rootCompositionVersion;
$selection = null;
foreach (array_map('intval', explode('-', $path)) as $position) {
if ($version === null) {
return null;
}
$member = $version->members()->where('position', $position)->first();
if ($member === null || $member->nested_composition_version_id === null) {
return null;
}
$selection = is_array($member->variant_selection) ? array_values(array_map('strval', $member->variant_selection)) : null;
$version = $member->nestedCompositionVersion;
}
$version?->loadMissing('composition');
if ($version === null || $version->composition === null || $version->composition->kind !== CompositionKind::Exercise) {
return null;
}
return ['version' => $version, 'selection' => $selection];
}
/**
* Pfad zur ersten Stelle, an der die Wurzel die Übungsfassung einbindet.
*/
public function pathTo(CompositionVersion $root, int $versionId, array $stack = []): ?string
{
if (in_array($root->id, $stack, true)) {
return null;
}
foreach ($root->members()->orderBy('position')->get() as $member) {
if ($member->nested_composition_version_id === null) {
continue;
}
if ($member->nested_composition_version_id === $versionId) {
return (string) $member->position;
}
$below = $this->pathTo($member->nestedCompositionVersion, $versionId, [...$stack, $root->id]);
if ($below !== null) {
return $member->position.'-'.$below;
}
}
return null;
}
/**
* @param list<string>|null $selection angebotene Variantenschlüssel; null = alle
* @return array<string, mixed>
*/
public function build(User $user, LicenseArticle $article, ArticleRelease $release, CompositionVersion $exercise, ?array $selection, ?string $variantKey = null): array
{
$exercise->loadMissing(['composition', 'variants', 'members.variant', 'members.contentElementVersion.element']);
$library = app(LibraryCatalog::class);
$offered = $exercise->variants->filter(fn (CompositionVersionVariant $variant): bool => $selection === null || in_array($variant->key, $selection, true))->values();
$chosen = $offered->firstWhere('key', $variantKey) ?? $offered->first();
$entries = [];
foreach ($exercise->members as $member) {
$version = $member->contentElementVersion;
if ($version === null) {
continue;
}
$key = $member->variant?->key;
$class = (string) $version->element->output_class;
$action = in_array($class, ['film', 'audio'], true) ? 'streamen' : 'ansehen';
$decision = ($this->access)($user, $article, $release, $version, $action);
$download = $action === 'ansehen' ? ($this->access)($user, $article, $release, $version, 'laden') : null;
$entries[] = [
'variant' => $key,
'role' => $member->role,
'note' => $member->placement_note,
'title' => $library->text($version->element)['title'] ?: $version->element->working_title,
'class' => $class,
'requirement' => $member->requirement ?: CompositionMember::REQUIRED,
'action' => $action,
'version' => $version,
'allowed' => $decision->allowed,
'may_download' => $download?->allowed ?? false,
'grant' => $decision->grant,
'download_grant' => $download?->grant,
'state' => $decision->allowed ? 'ok' : ($version->status === ContentVersionStatus::Gesperrt ? 'gesperrt' : 'nicht_lizenziert'),
'blocks' => $decision->allowed && $class === 'text' ? GuideText::blocks($version->body) : null,
];
}
$variants = $offered->map(function (CompositionVersionVariant $variant) use ($entries): array {
$missing = array_values(array_filter($entries, fn (array $entry): bool => ($entry['variant'] === null || $entry['variant'] === $variant->key)
&& $entry['requirement'] === CompositionMember::REQUIRED
&& ! $entry['allowed']));
return [
'key' => $variant->key,
'name' => $variant->name,
'description' => $variant->description,
'complete' => $missing === [],
'missing' => array_map(fn (array $entry): string => $entry['title'], $missing),
];
})->all();
$shown = array_values(array_filter($entries, fn (array $entry): bool => $entry['variant'] === null || $entry['variant'] === $chosen?->key));
return [
'exercise' => $exercise,
'title' => $library->text($exercise->composition)['title'],
'summary' => $library->text($exercise->composition)['summary'],
'learning_goal' => $exercise->learning_goal,
'duration_minutes' => $exercise->duration_minutes,
'duration_max' => $exercise->duration_max,
'prerequisites' => $exercise->prerequisites,
'material_note' => $exercise->material_note,
'variants' => $variants,
'chosen' => $chosen?->key,
'entries' => $shown,
'entry_total' => count($entries),
];
}
}
+207
View File
@@ -0,0 +1,207 @@
<?php
namespace App\Domain\Catalog;
use App\Domain\Commerce\Receipt\PdfDocument;
use Transliterator;
/**
* Druckbare Ausgabe einer Übung (DIN A4, mehrere Seiten) aus demselben Ergebnis wie die Ansicht ({@see ExerciseGuide}).
* Kennzeichnung: Fußzeile mit Lizenznehmer und Lizenzkopie auf jeder Seite (K2) und die Kennung in den Metadaten (K1).
* Das Dokument wird bei jedem Abruf neu erzeugt und nie abgelegt, damit eine spätere Sperre keine ältere Kopie
* ausliefern kann.
*/
class ExercisePdf
{
private const LEFT = 56.0;
private const RIGHT = 539.0;
private const TOP = 790.0;
private const BOTTOM = 72.0;
private PdfDocument $pdf;
private float $y = self::TOP;
private int $page = 0;
private string $footer = '';
/**
* Welche Abschnitte gehören ins PDF? Erforderliche Textabschnitte der Auswahl müssen für `laden` zulässig sein, sonst
* ist das PDF nicht erlaubt (null). Ergänzende ohne Berechtigung entfallen. Videos und Dokumente erscheinen nur als
* Hinweis.
*
* @param array<string, mixed> $guide Ergebnis von {@see ExerciseGuide::build}
* @return list<array<string, mixed>>|null
*/
public function sections(array $guide): ?array
{
$included = [];
foreach ($guide['entries'] as $entry) {
if ($entry['class'] === 'text') {
if ($entry['may_download'] && $entry['allowed']) {
$included[] = $entry;
} elseif ($entry['requirement'] === CompositionMember::REQUIRED) {
return null;
}
continue;
}
if ($entry['allowed']) {
$included[] = $entry;
}
}
return array_filter($included, fn (array $entry): bool => $entry['class'] === 'text') === [] ? null : $included;
}
/**
* @param array<string, mixed> $guide
* @param list<array<string, mixed>> $sections
*/
public function render(array $guide, array $sections, string $licensee, string $copyId, string $variantName, string $guideUrl): string
{
$this->pdf = new PdfDocument;
$this->page = 0;
$this->footer = self::printable('Lizenziert für '.$licensee.' · Lizenzkopie '.$copyId);
$this->newPage();
$this->write(self::printable((string) $guide['title']), 18, true, 8);
if ($variantName !== '') {
$this->write(self::printable('Variante: '.$variantName), 11, true, 6);
}
$facts = array_filter([
filled($guide['learning_goal']) ? 'Lernziel: '.$guide['learning_goal'] : null,
$guide['duration_minutes'] !== null ? 'Dauer: '.$guide['duration_minutes'].($guide['duration_max'] !== null ? ' bis '.$guide['duration_max'] : '').' Minuten' : null,
filled($guide['prerequisites']) ? 'Voraussetzungen: '.$guide['prerequisites'] : null,
filled($guide['material_note']) ? 'Ausstattung: '.$guide['material_note'] : null,
]);
foreach ($facts as $fact) {
$this->write(self::printable($fact), 10.5, false, 4);
}
$this->y -= 6;
foreach ($sections as $section) {
$this->section($section, $guideUrl);
}
$this->closePage();
$ascii = Transliterator::create('Any-Latin; Latin-ASCII');
return $this->pdf->output($ascii?->transliterate((string) $guide['title']) ?: 'Uebung', 'Lizenzkopie '.$copyId);
}
/**
* Zeichen außerhalb von Windows-1252 werden, wo möglich, lesbar ersetzt (Pfeil, Ungleichheitszeichen, andere
* lateinische Buchstaben); sonst bleibt „?“.
*/
public static function printable(string $text): string
{
$text = strtr($text, ['→' => '->', '←' => '<-', '≥' => '>=', '≤' => '<=', '✓' => '+', '✗' => 'x', '≠' => '!=', '≈' => '~']);
$latin = Transliterator::create('Any-Latin; Latin-ASCII');
$out = '';
foreach (mb_str_split($text) as $char) {
$encoded = mb_convert_encoding($char, 'Windows-1252', 'UTF-8');
$out .= $encoded === '?' && $char !== '?' ? ($latin?->transliterate($char) ?: '?') : $char;
}
return $out;
}
/**
* @param array<string, mixed> $section
*/
private function section(array $section, string $guideUrl): void
{
$title = self::printable((string) $section['title']);
if ($section['class'] !== 'text') {
$label = in_array($section['class'], ['film', 'audio'], true)
? 'Film: '.$title.' - online abrufbar im Mitgliederbereich (geschützte Wiedergabe): '.$guideUrl
: 'Material: '.$title.' - im Mitgliederbereich abrufbar: '.$guideUrl;
$this->write(self::printable($label), 10, false, 6);
return;
}
$this->write($title, 12.5, true, 5);
foreach ($section['blocks'] ?? [] as $block) {
match ($block['type']) {
'heading' => $this->write(self::printable($block['text']), 11, true, 4),
'paragraph' => $this->write(self::printable($block['text']), 10.5, false, 5),
'bullets' => $this->items($block['items'], fn (int $n): string => '•'),
'numbered' => $this->items($block['items'], fn (int $n): string => $n.'.'),
};
}
$this->y -= 4;
}
/**
* @param list<string> $items
*/
private function items(array $items, callable $marker): void
{
foreach ($items as $index => $item) {
$lines = PdfDocument::wrap(self::printable($item), self::RIGHT - self::LEFT - 18, 10.5);
foreach ($lines as $line => $text) {
$this->room(14);
if ($line === 0) {
$this->pdf->text(self::LEFT + 4, $this->y, $marker($index + 1), 10.5);
}
$this->pdf->text(self::LEFT + 18, $this->y, $text, 10.5);
$this->y -= 14;
}
}
$this->y -= 3;
}
private function write(string $text, float $size, bool $bold, float $after): void
{
foreach (PdfDocument::wrap($text, self::RIGHT - self::LEFT, $size, $bold) as $line) {
$this->room($size + 4);
$this->pdf->text(self::LEFT, $this->y, $line, $size, $bold);
$this->y -= $size + 4;
}
$this->y -= $after;
}
private function room(float $needed): void
{
if ($this->y - $needed < self::BOTTOM) {
$this->closePage();
$this->newPage();
}
}
private function newPage(): void
{
$this->pdf->addPage();
$this->page++;
$this->y = self::TOP;
}
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, 8);
}
}
+85
View File
@@ -0,0 +1,85 @@
<?php
namespace App\Domain\Catalog;
/**
* Anleitungstext als Klartext mit wenigen Konventionen: Absätze an Leerzeilen, Listen mit „- “ oder „• “ und
* nummerierte Listen mit „1. “, Zwischenüberschriften mit „## “. Ansicht und PDF lesen dieselben Blöcke und zeigen damit
* dieselbe Fassung. Es gibt kein freies HTML.
*/
final class GuideText
{
/**
* @return list<array{type: 'paragraph'|'bullets'|'numbered'|'heading', text?: string, items?: list<string>}>
*/
public static function blocks(?string $body): array
{
$blocks = [];
$paragraph = [];
$list = null;
$flushParagraph = function () use (&$blocks, &$paragraph): void {
if ($paragraph !== []) {
$blocks[] = ['type' => 'paragraph', 'text' => implode(' ', $paragraph)];
$paragraph = [];
}
};
$flushList = function () use (&$blocks, &$list): void {
if ($list !== null) {
$blocks[] = ['type' => $list['type'], 'items' => $list['items']];
$list = null;
}
};
foreach (preg_split('/\R/u', trim((string) $body)) ?: [] as $line) {
$line = rtrim($line);
if (trim($line) === '') {
$flushParagraph();
$flushList();
continue;
}
if (preg_match('/^##\s+(.+)$/u', $line, $match) === 1) {
$flushParagraph();
$flushList();
$blocks[] = ['type' => 'heading', 'text' => trim($match[1])];
continue;
}
if (preg_match('/^\s*(?:[-•*])\s+(.+)$/u', $line, $match) === 1) {
$flushParagraph();
if ($list === null || $list['type'] !== 'bullets') {
$flushList();
$list = ['type' => 'bullets', 'items' => []];
}
$list['items'][] = trim($match[1]);
continue;
}
if (preg_match('/^\s*\d+[.)]\s+(.+)$/u', $line, $match) === 1) {
$flushParagraph();
if ($list === null || $list['type'] !== 'numbered') {
$flushList();
$list = ['type' => 'numbered', 'items' => []];
}
$list['items'][] = trim($match[1]);
continue;
}
$flushList();
$paragraph[] = trim($line);
}
$flushParagraph();
$flushList();
return $blocks;
}
}
+2
View File
@@ -13,6 +13,8 @@ class ReleaseContent extends Model
'content_element_version_id',
'role',
'path',
'requirement',
'variant_key',
];
protected static function booted(): void
+3 -2
View File
@@ -107,7 +107,7 @@ public static function width(string $text, float $size = 10, bool $bold = false)
/**
* @param string $title Nur ASCII (Dokumenttitel)
*/
public function output(string $title): string
public function output(string $title, ?string $keywords = null): string
{
$pages = $this->pages === [] ? [''] : $this->pages;
$objects = [];
@@ -125,7 +125,8 @@ public function output(string $title): string
$objects[2] = '<< /Type /Pages /Kids ['.implode(' ', $kids).'] /Count '.count($pages).' >>';
$objects[3] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>';
$objects[4] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>';
$objects[5] = '<< /Title ('.preg_replace('/[^\x20-\x7E]/', '?', str_replace(['\\', '(', ')'], ['', '', ''], $title)).') /Producer (Lara und Felix) >>';
$ascii = fn (string $value): string => (string) preg_replace('/[^\x20-\x7E]/', '?', str_replace(['\\', '(', ')'], ['', '', ''], $value));
$objects[5] = '<< /Title ('.$ascii($title).')'.($keywords === null ? '' : ' /Keywords ('.$ascii($keywords).')').' /Producer (Lara und Felix) >>';
ksort($objects);
$pdf = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
+1
View File
@@ -16,6 +16,7 @@ class MediaDelivery extends Model
'copy_id',
'checksum',
'marking',
'composition_version_id',
'delivered_at',
];
+9 -1
View File
@@ -19,6 +19,8 @@ public function write(
string $format,
?string $checksum,
string $marking,
?string $copyId = null,
?int $compositionVersionId = null,
): MediaDelivery {
return MediaDelivery::query()->create([
'grant_id' => $grant->id,
@@ -27,10 +29,16 @@ public function write(
'content_element_version_id' => $version->id,
'action' => $action,
'format' => $format,
'copy_id' => 'LK-'.strtoupper(bin2hex(random_bytes(6))),
'copy_id' => $copyId ?? self::newCopyId(),
'composition_version_id' => $compositionVersionId,
'checksum' => $checksum,
'marking' => $marking,
'delivered_at' => now(),
]);
}
public static function newCopyId(): string
{
return 'LK-'.strtoupper(bin2hex(random_bytes(6)));
}
}
@@ -0,0 +1,124 @@
<?php
namespace App\Http\Controllers\Member;
use App\Domain\Catalog\ArticleRelease;
use App\Domain\Catalog\CompositionVersion;
use App\Domain\Catalog\ExerciseGuide;
use App\Domain\Catalog\ExercisePdf;
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;
/**
* Die Übung als formatierte Anleitung innerhalb des erworbenen Moduls oder Programms und ihre PDF-Ausgabe. Beide zeigen
* die im Artikel-Stand gebundene Übungsfassung und die dort angebotenen Varianten. Über jeden Abschnitt und jedes
* Medium entscheidet `DecideAccess`; auch die direkte PDF-Adresse wird bei jedem Abruf neu entschieden.
*/
class ExerciseController extends Controller
{
public function show(Request $request, LicenseArticle $article, ArticleRelease $release, string $path): View
{
[$guide, $located] = $this->load($request, $article, $release, $path);
$user = $request->user();
$copy = DeliveryLog::newCopyId();
$shown = false;
foreach ($guide['entries'] as $index => $entry) {
$link = fn (string $action) => SignedLink::temporary('member.media', now()->addMinutes(10), [
'article' => $article->id,
'release' => $release->id,
'version' => $entry['version']->id,
'action' => $action,
'reader' => $user->id,
]);
$guide['entries'][$index]['url'] = $entry['allowed'] && $entry['class'] !== 'text' ? $link($entry['action']) : null;
$guide['entries'][$index]['download_url'] = $entry['allowed'] && $entry['may_download'] && $entry['class'] !== 'text' ? $link('laden') : null;
if ($entry['allowed'] && $entry['class'] === 'text' && $entry['grant'] !== null) {
app(DeliveryLog::class)->write($entry['grant'], $article, $release, $entry['version'], 'ansehen', 'text', hash('sha256', (string) $entry['version']->body), 'k2', $copy, $located['version']->id);
$shown = true;
}
}
$pdfAllowed = app(ExercisePdf::class)->sections($guide) !== null;
return view('member.exercise', [
'guide' => $guide,
'article' => $article,
'release' => $release,
'path' => $path,
'reader' => $user->name,
'copy' => $shown ? $copy : null,
'pdfUrl' => $pdfAllowed ? SignedLink::temporary('member.exercise.pdf', now()->addMinutes(10), [
'article' => $article->id,
'release' => $release->id,
'path' => $path,
'variante' => $guide['chosen'],
'reader' => $user->id,
]) : null,
'variantUrl' => fn (string $key): string => route('member.exercise', ['article' => $article, 'release' => $release, 'path' => $path, 'variante' => $key]),
]);
}
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);
$pdf = app(ExercisePdf::class);
$sections = $pdf->sections($guide);
abort_if($sections === null, 403, 'Für dieses PDF fehlt die Berechtigung oder ein erforderlicher Bestandteil.');
$copy = DeliveryLog::newCopyId();
$variant = collect($guide['variants'])->firstWhere('key', $guide['chosen']);
$content = $pdf->render(
$guide,
$sections,
$request->user()->name,
$copy,
(string) ($variant['name'] ?? ''),
route('member.exercise', ['article' => $article, 'release' => $release, 'path' => $path, 'variante' => $guide['chosen']]),
);
$checksum = hash('sha256', $content);
foreach ($sections as $section) {
$grant = $section['download_grant'] ?? $section['grant'];
if ($grant !== null) {
app(DeliveryLog::class)->write($grant, $article, $release, $section['version'], 'laden', 'pdf', $checksum, 'k2', $copy, $located['version']->id);
}
}
$name = str($guide['title'])->slug()->value() ?: 'uebung';
return response($content, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="'.$name.'.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);
abort_if($located === null, 404);
$variant = $request->query('variante');
return [
$guides->build($request->user(), $article, $release, $located['version'], $located['selection'], is_string($variant) ? $variant : null),
$located,
];
}
}