Phase 4: Seiten mit Pagebuilder, Redaktion und Freigaben
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m56s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m56s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 2m2s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 2m9s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 2m40s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 2m35s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 2m29s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 2m38s
CI / Build-Artefakte aktuell (pull_request) Successful in 55s

- Seiten-Plugin: Seitenbaum mit Adressen, Seitennavigation, Brotkrumen und
  optional Hauptnavigation; Sichtbarkeit vererbt sich auf Unterseiten
- Pagebuilder (Block-Registry im Kern, Plugins tragen Blöcke bei): Abschnitt,
  Spalten, Tabs, Akkordeon, Box, Überschrift, Text (TipTap), Zitat,
  Schaltflächen, Symbolliste, Tabelle, Trennlinie, Abstand, Bild, Galerie,
  Video (erst nach Klick), Titelbild, Ansprechpartner, Downloads, Unterseiten,
  Neuigkeiten, Termine; Sichtbarkeit je Block; Bereinigung beim Speichern
- Editor im Portal: Ziehen und Ablegen, Autospeichern als Entwurf,
  Rückgängig, Gerätevorschau, Versionen, Zeitsteuerung, Bearbeitungssperre,
  Freigabe anfordern
- Rechte „inkl. Unterseiten“ werden im Rechte-Cache aufgelöst
- Neuigkeiten: Schreiben im Portal, Freigabe-Workflow mit Benachrichtigungen
- Bereich „Redaktion“, Benachrichtigungen im Portal
- storage/.migrations-fingerprint nicht mehr ausliefern

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 08:52:19 +00:00
parent 6269d3302c
commit f3987e8386
328 changed files with 10618 additions and 389 deletions

View file

@ -0,0 +1,94 @@
<?php
namespace App\Pagebuilder;
use App\Models\User;
use Closure;
/**
* Eine Blockart des Pagebuilders.
*
* Container (Abschnitt, Spalten, Tabs, Akkordeon, Box) haben „items“: jeweils
* ein Bereich mit eigener Blockliste, bei Tabs und Akkordeon mit Titel.
*/
final class BlockType
{
/**
* @param list<Field> $fields
* @param array{min: int, max: int, titled: bool, label: string}|null $container
* @param (Closure(array<string, mixed>, User|null, array<string, mixed>): (array<string, mixed>|null))|null $resolve
* Daten für die Anzeige (z. B. Bild-URL, aktuelle Beiträge); null = Block ausblenden
*/
public function __construct(
public readonly string $key,
public readonly string $label,
public readonly string $icon,
public readonly string $group,
public readonly string $component,
public readonly array $fields = [],
public readonly ?array $container = null,
public readonly ?Closure $resolve = null,
public readonly string $description = '',
) {}
public static function make(string $key, string $label, string $icon, string $group, ?string $component = null): self
{
return new self($key, $label, $icon, $group, $component ?? str_replace(' ', '', ucwords(str_replace(['-', '_', '.'], ' ', $key))));
}
/**
* @param list<Field> $fields
*/
public function fields(array $fields): self
{
return new self($this->key, $this->label, $this->icon, $this->group, $this->component, $fields, $this->container, $this->resolve, $this->description);
}
public function container(int $min = 1, int $max = 1, bool $titled = false, string $label = 'Bereich'): self
{
return new self($this->key, $this->label, $this->icon, $this->group, $this->component, $this->fields, ['min' => $min, 'max' => $max, 'titled' => $titled, 'label' => $label], $this->resolve, $this->description);
}
public function resolveUsing(Closure $resolve): self
{
return new self($this->key, $this->label, $this->icon, $this->group, $this->component, $this->fields, $this->container, $resolve, $this->description);
}
public function description(string $description): self
{
return new self($this->key, $this->label, $this->icon, $this->group, $this->component, $this->fields, $this->container, $this->resolve, $description);
}
/**
* @return array<string, mixed>
*/
public function defaults(): array
{
$data = [];
foreach ($this->fields as $field) {
$data[$field->name] = $field->default();
}
return $data;
}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return [
'key' => $this->key,
'label' => $this->label,
'icon' => $this->icon,
'group' => $this->group,
'component' => $this->component,
'description' => $this->description,
'fields' => array_map(fn (Field $field) => $field->toArray(), $this->fields),
'container' => $this->container,
'defaults' => $this->defaults(),
'dynamic' => $this->resolve !== null,
];
}
}

239
app/Pagebuilder/Blocks.php Normal file
View file

@ -0,0 +1,239 @@
<?php
namespace App\Pagebuilder;
use App\Http\Resources\PersonResource;
use App\Models\User;
use App\Plugins\Hooks;
use Illuminate\Support\Facades\Storage;
/**
* Registry der Pagebuilder-Blöcke. Der Kern bringt Layout- und Inhaltsblöcke
* mit, Plugins tragen eigene ein (z. B. „Neueste Beiträge“):
*
* app(Blocks::class)->add(BlockType::make('news.latest', 'Neuigkeiten', 'newspaper', 'dynamic', 'news::LatestBlock')
* ->fields([...])->resolveUsing(fn (array $data, ?User $user) => [...]));
*
* Vue-Komponenten liegen unter resources/js/pagebuilder/blocks/<Komponente>.vue
* bzw. plugins-core/<slug>/resources/js/blocks/<Name>.vue („slug::Name“).
*/
class Blocks
{
public const GROUPS = [
'layout' => 'Layout',
'content' => 'Inhalt',
'media' => 'Medien',
'dynamic' => 'Dynamisch',
];
/** @var array<string, BlockType> */
private array $types = [];
public function __construct()
{
$this->registerLayout();
$this->registerContent();
}
public function add(BlockType $type): void
{
$this->types[$type->key] = $type;
}
public function remove(string $key): void
{
unset($this->types[$key]);
}
public function get(string $key): ?BlockType
{
return $this->types[$key] ?? null;
}
/**
* @return array<string, BlockType>
*/
public function all(): array
{
return Hooks::apply('pagebuilder.blocks', $this->types);
}
/**
* @return list<array<string, mixed>>
*/
public function forEditor(): array
{
return array_values(array_map(fn (BlockType $type) => $type->toArray(), $this->all()));
}
public static function imageUrl(?string $path): ?string
{
return $path ? Storage::disk('uploads')->url($path) : null;
}
private function registerLayout(): void
{
$backgrounds = ['none' => 'Ohne', 'muted' => 'Grau', 'card' => 'Weiß mit Rahmen', 'brand-soft' => 'Markenfarbe hell', 'brand' => 'Markenfarbe'];
$this->add(BlockType::make('section', 'Abschnitt', 'square-dashed', 'layout')
->description('Fasst Blöcke zusammen, optional mit Hintergrund.')
->container()
->fields([
Field::select('background', 'Hintergrund', $backgrounds, 'none'),
Field::select('padding', 'Innenabstand', ['none' => 'Ohne', 'normal' => 'Normal', 'large' => 'Groß'], 'normal'),
]));
$this->add(BlockType::make('columns', 'Spalten', 'columns-3', 'layout')
->description('Zwei bis vier Spalten nebeneinander.')
->container(1, 4, label: 'Spalte')
->fields([
Field::select('layout', 'Aufteilung', [
'1-1' => '2 Spalten (1:1)',
'2-1' => '2 Spalten (2:1)',
'1-2' => '2 Spalten (1:2)',
'1-1-1' => '3 Spalten',
'1-2-1' => '3 Spalten (1:2:1)',
'1-1-1-1' => '4 Spalten',
], '1-1'),
Field::select('stack', 'Untereinander auf', ['sm' => 'Smartphones', 'md' => 'Tablets und Smartphones', 'lg' => 'Kleinen Bildschirmen'], 'md'),
Field::select('gap', 'Abstand', ['small' => 'Klein', 'normal' => 'Normal', 'large' => 'Groß'], 'normal'),
Field::select('align', 'Vertikal ausrichten', ['start' => 'Oben', 'center' => 'Mitte', 'stretch' => 'Gleiche Höhe'], 'start'),
]));
$this->add(BlockType::make('tabs', 'Tabs', 'panel-top', 'layout')
->description('Inhalte auf Reiter verteilt.')
->container(1, 12, titled: true, label: 'Tab'));
$this->add(BlockType::make('accordion', 'Akkordeon', 'list-collapse', 'layout')
->description('Aufklappbare Abschnitte, z. B. für häufige Fragen.')
->container(1, 30, titled: true, label: 'Abschnitt')
->fields([
Field::toggle('first_open', 'Ersten Abschnitt geöffnet anzeigen'),
Field::toggle('multiple', 'Mehrere gleichzeitig öffnen'),
]));
$this->add(BlockType::make('box', 'Box', 'message-square-warning', 'layout')
->description('Hervorgehobener Kasten: Info, Hinweis, Warnung …')
->container()
->fields([
Field::select('variant', 'Art', [
'info' => 'Info',
'note' => 'Hinweis',
'warning' => 'Warnung',
'success' => 'Erfolg',
'neutral' => 'Neutral',
'highlight' => 'Hervorgehoben',
], 'info'),
Field::text('title', 'Überschrift', 150),
Field::toggle('show_icon', 'Symbol anzeigen', true),
]));
}
private function registerContent(): void
{
$this->add(BlockType::make('heading', 'Überschrift', 'heading', 'content')
->fields([
Field::text('text', 'Text', 200, placeholder: 'Überschrift'),
Field::select('level', 'Größe', ['2' => 'Groß (H2)', '3' => 'Mittel (H3)', '4' => 'Klein (H4)'], '2'),
Field::select('align', 'Ausrichtung', ['left' => 'Links', 'center' => 'Zentriert'], 'left'),
]));
$this->add(BlockType::make('text', 'Text', 'text', 'content')
->description('Absätze, Listen, Links und Hervorhebungen.')
->fields([Field::html('html', 'Text')]));
$this->add(BlockType::make('quote', 'Zitat', 'quote', 'content')
->fields([
Field::textarea('text', 'Zitat', 1000),
Field::text('source', 'Quelle', 150),
]));
$this->add(BlockType::make('buttons', 'Schaltflächen', 'mouse-pointer-click', 'content')
->fields([
Field::repeater('buttons', 'Schaltflächen', [
Field::text('label', 'Beschriftung', 80),
Field::url('url', 'Link'),
Field::select('variant', 'Darstellung', ['primary' => 'Markenfarbe', 'outline' => 'Umrandet', 'link' => 'Als Link'], 'primary'),
Field::toggle('new_tab', 'In neuem Tab öffnen'),
], 6, 'Schaltfläche'),
Field::select('align', 'Ausrichtung', ['left' => 'Links', 'center' => 'Zentriert'], 'left'),
]));
$this->add(BlockType::make('icon-list', 'Symbolliste', 'list-checks', 'content')
->fields([
Field::repeater('items', 'Einträge', [
Field::icon('icon', 'Symbol'),
Field::text('title', 'Titel', 120),
Field::textarea('text', 'Text', 500),
Field::url('url', 'Link'),
], 30, 'Eintrag'),
Field::select('layout', 'Darstellung', ['list' => 'Liste', 'grid' => 'Kacheln'], 'list'),
]));
$this->add(BlockType::make('table', 'Tabelle', 'table', 'content')
->fields([
Field::table('rows', 'Tabelle'),
Field::toggle('header', 'Erste Zeile als Kopfzeile', true),
Field::text('caption', 'Beschriftung', 200),
]));
$this->add(BlockType::make('divider', 'Trennlinie', 'minus', 'content'));
$this->add(BlockType::make('spacer', 'Abstand', 'move-vertical', 'content')
->fields([Field::select('size', 'Höhe', ['small' => 'Klein', 'medium' => 'Mittel', 'large' => 'Groß'], 'medium')]));
$this->add(BlockType::make('image', 'Bild', 'image', 'media')
->fields([
Field::image('path', 'Bild'),
Field::text('alt', 'Alternativtext', 200)->help('Beschreibt das Bild für Screenreader.'),
Field::text('caption', 'Bildunterschrift', 300),
Field::select('size', 'Breite', ['full' => 'Volle Breite', 'medium' => 'Mittel', 'small' => 'Klein'], 'full'),
Field::url('url', 'Link beim Anklicken'),
])
->resolveUsing(fn (array $data) => ['url' => self::imageUrl($data['path'])]));
$this->add(BlockType::make('gallery', 'Galerie', 'images', 'media')
->fields([
Field::repeater('images', 'Bilder', [
Field::image('path', 'Bild'),
Field::text('alt', 'Alternativtext', 200),
Field::text('caption', 'Bildunterschrift', 300),
], 60, 'Bild'),
Field::select('columns', 'Spalten', ['2' => '2', '3' => '3', '4' => '4'], '3'),
])
->resolveUsing(fn (array $data) => ['urls' => array_map(fn ($image) => self::imageUrl($image['path'] ?? null), $data['images'])]));
$this->add(BlockType::make('video', 'Video', 'play', 'media')
->description('YouTube, Vimeo oder MP4-Datei. Externe Videos laden erst nach Klick.')
->fields([
Field::url('url', 'Adresse des Videos'),
Field::text('title', 'Titel', 200),
])
->resolveUsing(fn (array $data) => ['embed' => VideoEmbed::from($data['url'])]));
$this->add(BlockType::make('hero', 'Titelbild mit Text', 'panorama', 'media')
->fields([
Field::image('path', 'Hintergrundbild'),
Field::text('title', 'Titel', 150),
Field::textarea('text', 'Text', 400),
Field::text('button_label', 'Beschriftung der Schaltfläche', 80),
Field::url('button_url', 'Link der Schaltfläche'),
Field::select('height', 'Höhe', ['small' => 'Niedrig', 'medium' => 'Mittel', 'large' => 'Hoch'], 'medium'),
])
->resolveUsing(fn (array $data) => ['url' => self::imageUrl($data['path'])]));
$this->add(BlockType::make('contacts', 'Ansprechpartner', 'contact', 'dynamic')
->description('Personen aus dem Verzeichnis – immer mit aktuellen Kontaktdaten.')
->fields([
Field::text('title', 'Überschrift', 150),
Field::people('people', 'Personen'),
Field::select('layout', 'Darstellung', ['cards' => 'Karten', 'list' => 'Liste'], 'cards'),
])
->resolveUsing(function (array $data) {
$people = User::query()->active()->whereIn('id', $data['people'])->get()
->sortBy(fn (User $user) => array_search($user->id, $data['people'], true))->values();
return ['people' => PersonResource::collection($people)->resolve()];
}));
}
}

292
app/Pagebuilder/Content.php Normal file
View file

@ -0,0 +1,292 @@
<?php
namespace App\Pagebuilder;
use App\Models\User;
use App\Support\Permissions\Audiences;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Throwable;
/**
* Inhalt einer Seite: ein Baum aus Blöcken.
*
* {"blocks": [{"id": "…", "type": "columns", "data": {…}, "visibility": {…},
* "items": [{"id": "…", "title": "…", "blocks": [ … ]}]}]}
*
* sanitize() läuft beim Speichern: unbekannte Blöcke und Felder fallen weg,
* HTML wird bereinigt, Adressen geprüft. render() läuft bei der Anzeige:
* blendet Blöcke nach Sichtbarkeit aus und ergänzt dynamische Daten.
*/
class Content
{
public const MAX_DEPTH = 6;
public const MAX_BLOCKS = 800;
private int $count = 0;
public function __construct(private readonly Blocks $blocks) {}
/**
* @return array{blocks: list<array<string, mixed>>}
*/
public static function empty(): array
{
return ['blocks' => []];
}
/**
* @param array<mixed>|null $content
* @return array{blocks: list<array<string, mixed>>}
*/
public function sanitize(?array $content): array
{
$this->count = 0;
return ['blocks' => $this->sanitizeList($content['blocks'] ?? [], 1)];
}
/**
* Anzeigefertiger Inhalt für eine Person.
*
* @param array<mixed>|null $content bereits bereinigter Inhalt
* @return array{blocks: list<array<string, mixed>>}
*/
public function render(?array $content, ?User $user, array $context = []): array
{
return ['blocks' => $this->renderList($content['blocks'] ?? [], $user, $context)];
}
/**
* Ein einzelner Block (Editor-Vorschau dynamischer Blöcke).
*
* @param array<mixed> $block
* @return array<string, mixed>|null
*/
public function preview(array $block, ?User $user, array $context = []): ?array
{
$this->count = 0;
$clean = $this->sanitizeList([$block], 1)[0] ?? null;
if (! $clean) {
return null;
}
$type = $this->blocks->get($clean['type']);
return $type?->resolve ? $this->resolve($type, $clean, $user, $context) : [];
}
/**
* Alle Werte eines Feldtyps im Baum, z. B. alle Bildpfade (für Aufräumarbeiten).
*
* @param array<mixed>|null $content
* @return list<mixed>
*/
public function collect(?array $content, callable $picker): array
{
$result = [];
$walk = function (array $blocks) use (&$walk, &$result, $picker) {
foreach ($blocks as $block) {
array_push($result, ...(array) $picker($block));
foreach ($block['items'] ?? [] as $item) {
$walk($item['blocks'] ?? []);
}
}
};
$walk($content['blocks'] ?? []);
return $result;
}
/**
* Reiner Text des Inhalts, z. B. für die Suche.
*
* @param array<mixed>|null $content
*/
public function plainText(?array $content): string
{
$parts = $this->collect($content, function (array $block) {
$texts = [];
array_walk_recursive($block['data'], function ($value) use (&$texts) {
if (is_string($value) && ! str_starts_with($value, 'pagebuilder/')) {
$texts[] = strip_tags($value);
}
});
foreach ($block['items'] ?? [] as $item) {
$texts[] = $item['title'] ?? '';
}
return [implode(' ', $texts)];
});
return trim(preg_replace('/\s+/u', ' ', html_entity_decode(implode(' ', $parts))) ?? '');
}
/**
* @return list<array<string, mixed>>
*/
private function sanitizeList(mixed $blocks, int $depth): array
{
if (! is_array($blocks) || $depth > self::MAX_DEPTH) {
return [];
}
$result = [];
foreach (array_values($blocks) as $block) {
if (! is_array($block) || ++$this->count > self::MAX_BLOCKS) {
continue;
}
$type = $this->blocks->get((string) ($block['type'] ?? ''));
if (! $type) {
continue;
}
$data = is_array($block['data'] ?? null) ? $block['data'] : [];
$clean = [
'id' => self::id($block['id'] ?? null),
'type' => $type->key,
'data' => [],
];
foreach ($type->fields as $field) {
$clean['data'][$field->name] = $field->sanitize(array_key_exists($field->name, $data) ? $data[$field->name] : $field->default());
}
$visibility = $this->sanitizeVisibility($block['visibility'] ?? null);
if ($visibility !== null) {
$clean['visibility'] = $visibility;
}
if ($type->container) {
$clean['items'] = $this->sanitizeItems($type, $clean['data'], $block['items'] ?? [], $depth);
}
$result[] = $clean;
}
return $result;
}
/**
* @param array<string, mixed> $data
* @return list<array<string, mixed>>
*/
private function sanitizeItems(BlockType $type, array $data, mixed $items, int $depth): array
{
$items = is_array($items) ? array_values(array_filter($items, 'is_array')) : [];
$container = $type->container;
// Spalten: Anzahl folgt der Aufteilung. Überzählige Spalten werden an die letzte angehängt, nichts geht verloren.
$count = $type->key === 'columns'
? count(explode('-', (string) ($data['layout'] ?? '1-1')))
: max($container['min'], min($container['max'], count($items)));
if (count($items) > $count && $count > 0) {
$overflow = array_merge(...array_map(fn ($item) => (array) ($item['blocks'] ?? []), array_slice($items, $count)));
$items = array_slice($items, 0, $count);
$items[$count - 1]['blocks'] = array_merge((array) ($items[$count - 1]['blocks'] ?? []), $overflow);
}
$items = array_pad($items, $count, []);
return array_map(fn (array $item) => array_filter([
'id' => self::id($item['id'] ?? null),
'title' => $container['titled'] ? mb_substr(trim((string) ($item['title'] ?? '')), 0, 120) : null,
'blocks' => $this->sanitizeList($item['blocks'] ?? [], $depth + 1),
], fn ($value) => $value !== null), $items);
}
/**
* @return array{role?: list<string>, department?: list<string>, location?: list<string>}|null
*/
private function sanitizeVisibility(mixed $visibility): ?array
{
if (! is_array($visibility)) {
return null;
}
$clean = [];
foreach (['role', 'department', 'location'] as $rule) {
$values = array_values(array_unique(array_filter(array_map(
fn ($value) => is_scalar($value) ? mb_substr(trim((string) $value), 0, 150) : '',
(array) ($visibility[$rule] ?? []),
))));
if ($values !== []) {
$clean[$rule] = array_slice($values, 0, 50);
}
}
return $clean === [] ? null : $clean;
}
/**
* @param list<array<string, mixed>> $blocks
* @return list<array<string, mixed>>
*/
private function renderList(array $blocks, ?User $user, array $context): array
{
$result = [];
foreach ($blocks as $block) {
$type = $this->blocks->get($block['type'] ?? '');
// Blöcke deaktivierter Plugins und fremde Zielgruppen einfach auslassen.
if (! $type || ! Audiences::matches($block['visibility'] ?? null, $user)) {
continue;
}
if ($type->resolve) {
$props = $this->resolve($type, $block, $user, $context);
if ($props === null) {
continue;
}
$block['props'] = $props;
}
unset($block['visibility']);
$block['component'] = $type->component;
if (isset($block['items'])) {
$block['items'] = array_map(fn (array $item) => [...$item, 'blocks' => $this->renderList($item['blocks'] ?? [], $user, $context)], $block['items']);
}
$result[] = $block;
}
return $result;
}
/**
* @param array<string, mixed> $block
* @return array<string, mixed>|null
*/
private function resolve(BlockType $type, array $block, ?User $user, array $context): ?array
{
try {
return ($type->resolve)($block['data'], $user, $context);
} catch (Throwable $e) {
// Ein fehlerhafter Plugin-Block darf die Seite nicht mitreißen.
Log::warning("Pagebuilder-Block {$type->key} konnte nicht geladen werden: ".$e->getMessage());
return null;
}
}
private static function id(mixed $id): string
{
return is_string($id) && preg_match('/^[A-Za-z0-9_-]{4,40}$/', $id) ? $id : Str::random(12);
}
}

209
app/Pagebuilder/Field.php Normal file
View file

@ -0,0 +1,209 @@
<?php
namespace App\Pagebuilder;
use App\Support\QuickLinks;
use App\Support\RichText;
use Closure;
/**
* Ein Eingabefeld eines Blocks. Beschreibt zugleich das Formular im Editor
* (toArray) und die Bereinigung beim Speichern (sanitize) – Plugin-Blöcke
* bekommen so Editor und Absicherung ohne eigenen Code.
*/
final class Field
{
/**
* @param array<string, mixed> $options
*/
private function __construct(
public readonly string $name,
public readonly string $type,
public readonly string $label,
private readonly array $options = [],
) {}
public static function text(string $name, string $label, int $max = 200, string $default = '', ?string $placeholder = null): self
{
return new self($name, 'text', $label, ['max' => $max, 'default' => $default, 'placeholder' => $placeholder]);
}
public static function textarea(string $name, string $label, int $max = 2000, string $default = ''): self
{
return new self($name, 'textarea', $label, ['max' => $max, 'default' => $default]);
}
/** Formatierter Text – im Editor direkt im Block bearbeitet (TipTap). */
public static function html(string $name, string $label): self
{
return new self($name, 'html', $label, ['default' => '']);
}
/**
* @param array<string, string>|Closure(): array<string, string> $choices
*/
public static function select(string $name, string $label, array|Closure $choices, ?string $default = null): self
{
return new self($name, 'select', $label, ['choices' => $choices, 'default' => $default]);
}
public static function toggle(string $name, string $label, bool $default = false): self
{
return new self($name, 'toggle', $label, ['default' => $default]);
}
public static function number(string $name, string $label, int $min, int $max, int $default): self
{
return new self($name, 'number', $label, ['min' => $min, 'max' => $max, 'default' => $default]);
}
public static function url(string $name, string $label, string $default = ''): self
{
return new self($name, 'url', $label, ['default' => $default]);
}
/** Hochgeladenes Bild (Pfad im Upload-Speicher). */
public static function image(string $name, string $label): self
{
return new self($name, 'image', $label, ['default' => null]);
}
/** Personen aus dem Verzeichnis (IDs). */
public static function people(string $name, string $label, int $max = 24): self
{
return new self($name, 'people', $label, ['max' => $max, 'default' => []]);
}
/** Einfache Tabelle: Zeilen aus Textzellen. */
public static function table(string $name, string $label): self
{
return new self($name, 'table', $label, ['default' => [['', ''], ['', '']]]);
}
/** Symbol aus dem Symbolsatz der Schnellzugriffe. */
public static function icon(string $name, string $label, string $default = 'link'): self
{
return new self($name, 'icon', $label, ['default' => $default, 'choices' => QuickLinks::ICONS]);
}
/** Liste gleichartiger Einträge, z. B. Schaltflächen oder Galeriebilder. */
public static function repeater(string $name, string $label, array $fields, int $max = 20, string $itemLabel = 'Eintrag'): self
{
return new self($name, 'repeater', $label, ['fields' => $fields, 'max' => $max, 'default' => [], 'itemLabel' => $itemLabel]);
}
/** Beliebige Liste von IDs, deren Einträge der Block selbst verwaltet (z. B. Dateien). */
public static function ids(string $name, string $label, string $kind, int $max = 50): self
{
return new self($name, 'ids', $label, ['kind' => $kind, 'max' => $max, 'default' => []]);
}
public function default(): mixed
{
if ($this->type === 'repeater') {
return [];
}
return $this->options['default'] ?? null;
}
public function help(string $help): self
{
return new self($this->name, $this->type, $this->label, [...$this->options, 'help' => $help]);
}
/**
* @return array<string, mixed> Beschreibung für das Editor-Formular
*/
public function toArray(): array
{
$options = $this->options;
if (isset($options['choices'])) {
$choices = $options['choices'] instanceof Closure ? ($options['choices'])() : $options['choices'];
$options['choices'] = collect($choices)->map(fn ($label, $value) => ['value' => (string) $value, 'label' => $label])->values()->all();
}
if (isset($options['fields'])) {
$options['fields'] = array_map(fn (Field $field) => $field->toArray(), $options['fields']);
}
return ['name' => $this->name, 'type' => $this->type, 'label' => $this->label, ...$options];
}
public function sanitize(mixed $value): mixed
{
return match ($this->type) {
'text', 'textarea' => mb_substr(trim(is_scalar($value) ? (string) $value : ''), 0, $this->options['max']),
'html' => app(RichText::class)->sanitize(is_string($value) ? mb_substr($value, 0, 200_000) : ''),
'select' => $this->sanitizeChoice($value),
'toggle' => (bool) $value,
'number' => max($this->options['min'], min($this->options['max'], is_numeric($value) ? (int) $value : $this->options['default'])),
'url' => self::safeUrl($value),
'image' => is_string($value) && preg_match('#^pagebuilder/[A-Za-z0-9/_.-]+$#', $value) && ! str_contains($value, '..') ? $value : null,
'people', 'ids' => array_values(array_slice(array_unique(array_filter(array_map('intval', is_array($value) ? $value : []))), 0, $this->options['max'])),
'table' => $this->sanitizeTable($value),
'icon' => is_string($value) && array_key_exists($value, QuickLinks::ICONS) ? $value : $this->options['default'],
'repeater' => $this->sanitizeRepeater($value),
default => null,
};
}
public static function safeUrl(mixed $value): string
{
$url = trim(is_string($value) ? $value : '');
if ($url === '' || mb_strlen($url) > 2000) {
return '';
}
// Relative Adressen im Portal, Anker oder http(s)/mailto/tel – nichts anderes (kein javascript:).
if (preg_match('#^(/(?!/)|\#)#', $url) || preg_match('#^(https?://|mailto:|tel:)#i', $url)) {
return $url;
}
return preg_match('#^[a-z0-9.-]+\.[a-z]{2,}(/|$)#i', $url) ? 'https://'.$url : '';
}
private function sanitizeChoice(mixed $value): ?string
{
$choices = $this->options['choices'] instanceof Closure ? ($this->options['choices'])() : $this->options['choices'];
$value = is_scalar($value) ? (string) $value : null;
return $value !== null && array_key_exists($value, $choices) ? $value : $this->options['default'];
}
/**
* @return list<list<string>>
*/
private function sanitizeTable(mixed $value): array
{
$rows = array_slice(is_array($value) ? array_values($value) : [], 0, 100);
$width = min(10, max(1, ...array_map(fn ($row) => is_array($row) ? count($row) : 1, $rows ?: [[]])));
return array_map(function ($row) use ($width) {
$cells = array_slice(is_array($row) ? array_values($row) : [], 0, $width);
return array_pad(array_map(fn ($cell) => mb_substr(is_scalar($cell) ? (string) $cell : '', 0, 1000), $cells), $width, '');
}, $rows);
}
/**
* @return list<array<string, mixed>>
*/
private function sanitizeRepeater(mixed $value): array
{
$items = array_slice(is_array($value) ? array_values($value) : [], 0, $this->options['max']);
return array_map(function ($item) {
$item = is_array($item) ? $item : [];
$clean = [];
foreach ($this->options['fields'] as $field) {
$clean[$field->name] = $field->sanitize($item[$field->name] ?? $field->default());
}
return $clean;
}, $items);
}
}

View file

@ -0,0 +1,34 @@
<?php
namespace App\Pagebuilder;
/**
* Wandelt Video-Adressen in datenschutzfreundliche Einbettungen um.
* YouTube über youtube-nocookie.com; geladen wird erst nach einem Klick.
*/
final class VideoEmbed
{
/**
* @return array{provider: string, src: string}|null
*/
public static function from(string $url): ?array
{
if ($url === '') {
return null;
}
if (preg_match('~(?:youtube\.com/(?:watch\?(?:.*&)?v=|embed/|shorts/)|youtu\.be/)([A-Za-z0-9_-]{11})~', $url, $m)) {
return ['provider' => 'YouTube', 'src' => 'https://www.youtube-nocookie.com/embed/'.$m[1].'?rel=0'];
}
if (preg_match('~vimeo\.com/(?:video/)?(\d+)~', $url, $m)) {
return ['provider' => 'Vimeo', 'src' => 'https://player.vimeo.com/video/'.$m[1].'?dnt=1'];
}
if (preg_match('~\.(mp4|webm)(\?.*)?$~i', $url)) {
return ['provider' => 'file', 'src' => $url];
}
return null;
}
}