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,49 @@
<?php
namespace Inhaus\Plugins\Pages;
use App\Models\User;
use Inhaus\Plugins\Pages\Models\Page;
/**
* „Redaktion → Seiten“: Seiten, die die Person bearbeiten darf, mit Status.
*/
final class EditorialPages
{
/**
* @return array<string, mixed>
*/
public static function props(User $user): array
{
$ids = $user->can('pages.manage') ? true : $user->permissions()->ids('pages.edit', 'page');
$tree = app(PageTree::class);
$options = $tree->options();
$pages = Page::query()
->when($ids !== true, fn ($q) => $q->whereIn('id', $ids))
->with('lockedBy:id,name')
->get(['id', 'parent_id', 'title', 'path', 'published_at', 'draft_updated_at', 'scheduled_at', 'locked_by', 'locked_until', 'updated_at'])
->sortBy(fn (Page $page) => array_search($page->id, array_keys($options), true))
->values();
return [
'pages' => $pages->map(fn (Page $page) => [
'id' => $page->id,
'title' => $page->title,
'depth' => substr_count($page->path, '/'),
'url' => $page->url(),
'edit_url' => route('pages.editor', $page),
'status' => match (true) {
$page->scheduled_at !== null => 'scheduled',
$page->draft_updated_at !== null => 'draft',
$page->published_at !== null => 'published',
default => 'new',
},
'scheduled_at' => $page->scheduled_at?->toIso8601String(),
'changed_at' => ($page->draft_updated_at ?? $page->published_at ?? $page->updated_at)?->toIso8601String(),
'locked_by' => $page->isLockedFor($user) ? $page->lockedBy?->name : null,
])->all(),
'canCreate' => $user->can('pages.manage'),
];
}
}

View file

@ -0,0 +1,174 @@
<?php
namespace Inhaus\Plugins\Pages\Filament\Resources\ContentPages;
use App\Filament\Components\AudienceSection;
use App\Filament\Components\RoleGrantSelect;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Inhaus\Plugins\Pages\Filament\Resources\ContentPages\Pages\CreateContentPage;
use Inhaus\Plugins\Pages\Filament\Resources\ContentPages\Pages\EditContentPage;
use Inhaus\Plugins\Pages\Filament\Resources\ContentPages\Pages\ListContentPages;
use Inhaus\Plugins\Pages\Models\Page;
use Inhaus\Plugins\Pages\PageTree;
use UnitEnum;
/**
* Seitenbaum im Admin: Struktur, Adressen, Sichtbarkeit und Rechte.
* Der Inhalt wird im Portal mit dem Pagebuilder bearbeitet.
*/
class ContentPageResource extends Resource
{
protected static ?string $model = Page::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedDocumentText;
protected static string|UnitEnum|null $navigationGroup = 'Inhalte';
protected static ?int $navigationSort = 0;
protected static ?string $modelLabel = 'Seite';
protected static ?string $pluralModelLabel = 'Seiten';
protected static ?string $slug = 'seiten';
protected static ?string $recordTitleAttribute = 'title';
public static function form(Schema $schema): Schema
{
return $schema
->columns(3)
->components([
Section::make('Seite')
->columnSpan(2)
->columns(2)
->schema([
TextInput::make('title')->label('Titel')->required()->maxLength(200)->columnSpanFull(),
Select::make('parent_id')
->label('Übergeordnete Seite')
->placeholder('– oberste Ebene –')
->options(fn (?Page $record) => collect(app(PageTree::class)->options())
->except($record ? [$record->id, ...app(PageTree::class)->descendantIds([$record->id])] : [])
->all())
->searchable()
->required(fn () => ! auth()->user()->can('pages.manage'))
->live(),
TextInput::make('slug')
->label('Kürzel in der Adresse')
->helperText('Leer lassen = aus dem Titel. Ändert auch die Adressen der Unterseiten.')
->maxLength(120)
->regex('/^[a-z0-9]+(-[a-z0-9]+)*$/')
->validationMessages(['regex' => 'Nur Kleinbuchstaben, Ziffern und Bindestriche.']),
TextInput::make('sort')->label('Reihenfolge')->numeric()->default(0),
Toggle::make('in_navigation')
->label('In der Hauptnavigation anzeigen')
->visible(fn (Get $get) => blank($get('parent_id')))
->inline(false),
]),
Section::make('Status')
->columnSpan(1)
->schema([
TextInput::make('status_display')
->label('Status')
->disabled()
->dehydrated(false)
->formatStateUsing(fn (?Page $record) => match (true) {
$record === null => 'Neu',
$record->scheduled_at !== null => 'Geplant für '.$record->scheduled_at->format('d.m.Y H:i'),
$record->isPublished() && $record->hasDraft() => 'Veröffentlicht, mit Entwurf',
$record->isPublished() => 'Veröffentlicht',
default => 'Entwurf',
}),
])
->visibleOn('edit'),
Section::make('Redaktion')
->description('Rollen, die diese Seite und alle Unterseiten bearbeiten bzw. veröffentlichen dürfen – z. B. die MAV ihre Seite „MAV“.')
->columnSpanFull()
->columns(2)
->visible(fn () => auth()->user()->can('roles.manage') || auth()->user()->can('pages.manage'))
->schema([
RoleGrantSelect::make('editors', 'Dürfen bearbeiten', 'pages.edit', 'page', includeChildren: true),
RoleGrantSelect::make('publishers', 'Dürfen veröffentlichen', 'pages.publish', 'page', includeChildren: true),
]),
AudienceSection::make('page', 'Wer die Seite sieht. Leer lassen = alle. Gilt auch für alle Unterseiten.')->columnSpanFull(),
]);
}
/**
* Redakteure sehen nur Seiten, die sie bearbeiten dürfen.
*/
public static function getEloquentQuery(): Builder
{
$user = auth()->user();
$ids = $user?->can('pages.manage') ? true : ($user?->permissions()->ids('pages.edit', 'page') ?? []);
return parent::getEloquentQuery()->when($ids !== true, fn (Builder $q) => $q->whereIn('id', $ids));
}
public static function table(Table $table): Table
{
return $table
->defaultSort('path')
->paginated([50, 100, 'all'])
->columns([
TextColumn::make('title')
->label('Titel')
->searchable()
->weight('medium')
->formatStateUsing(fn (string $state, Page $record) => str_repeat('— ', substr_count($record->path, '/')).$state),
TextColumn::make('path')->label('Adresse')->formatStateUsing(fn (string $state) => '/seiten/'.$state)->color('gray')->searchable(),
TextColumn::make('status')
->label('Status')
->badge()
->state(fn (Page $record) => match (true) {
$record->scheduled_at !== null => 'Geplant',
$record->isPublished() && $record->hasDraft() => 'Entwurf',
$record->isPublished() => 'Veröffentlicht',
default => 'Neu',
})
->color(fn (string $state) => match ($state) {
'Veröffentlicht' => 'success',
'Geplant', 'Entwurf' => 'warning',
default => 'gray',
}),
TextColumn::make('updated_at')->label('Geändert')->dateTime('d.m.Y H:i')->sortable(),
])
->recordActions([
Action::make('content')
->label('Inhalt bearbeiten')
->icon(Heroicon::OutlinedPencilSquare)
->iconButton()
->tooltip('Inhalt bearbeiten')
->url(fn (Page $record) => route('pages.editor', $record)),
EditAction::make()->label('Einstellungen')->iconButton()->tooltip('Einstellungen')->icon(Heroicon::OutlinedCog6Tooth),
DeleteAction::make()
->iconButton()
->tooltip('Löschen')
->visible(fn (Page $record) => ! $record->children()->exists())
->before(fn (Page $record) => $record->files->each->delete()),
]);
}
public static function getPages(): array
{
return [
'index' => ListContentPages::route('/'),
'create' => CreateContentPage::route('/neu'),
'edit' => EditContentPage::route('/{record}/bearbeiten'),
];
}
}

View file

@ -0,0 +1,34 @@
<?php
namespace Inhaus\Plugins\Pages\Filament\Resources\ContentPages\Pages;
use Filament\Resources\Pages\CreateRecord;
use Inhaus\Plugins\Pages\Filament\Resources\ContentPages\ContentPageResource;
use Inhaus\Plugins\Pages\Models\Page;
use Inhaus\Plugins\Pages\PageTree;
class CreateContentPage extends CreateRecord
{
protected static string $resource = ContentPageResource::class;
protected function mutateFormDataBeforeCreate(array $data): array
{
$parent = filled($data['parent_id'] ?? null) ? Page::query()->find($data['parent_id']) : null;
abort_unless(auth()->user()->can('create', [Page::class, $parent]), 403);
return [...$data, 'created_by' => auth()->id(), 'in_navigation' => $parent ? false : ($data['in_navigation'] ?? false)];
}
protected function afterCreate(): void
{
PageTree::flush(true);
}
/**
* Nach dem Anlegen direkt in den Pagebuilder.
*/
protected function getRedirectUrl(): string
{
return route('pages.editor', $this->record);
}
}

View file

@ -0,0 +1,56 @@
<?php
namespace Inhaus\Plugins\Pages\Filament\Resources\ContentPages\Pages;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
use Filament\Support\Icons\Heroicon;
use Inhaus\Plugins\Pages\Filament\Resources\ContentPages\ContentPageResource;
use Inhaus\Plugins\Pages\Models\Page;
use Inhaus\Plugins\Pages\PageTree;
class EditContentPage extends EditRecord
{
protected static string $resource = ContentPageResource::class;
protected function authorizeAccess(): void
{
abort_unless(auth()->user()->can('configure', $this->record), 403);
}
protected function mutateFormDataBeforeSave(array $data): array
{
$parent = filled($data['parent_id'] ?? null) ? Page::query()->find($data['parent_id']) : null;
// Verschieben: an das neue Ziel muss man Seiten anlegen dürfen.
if (($data['parent_id'] ?? null) != $this->record->parent_id) {
abort_unless(auth()->user()->can('create', [Page::class, $parent]), 403);
}
if ($parent || ! auth()->user()->can('pages.manage')) {
$data['in_navigation'] = $parent ? false : $this->record->in_navigation;
}
return $data;
}
protected function afterSave(): void
{
// Sichtbarkeit und Rechte können sich geändert haben.
PageTree::flush(true);
}
protected function getHeaderActions(): array
{
return [
Action::make('content')->label('Inhalt bearbeiten')->icon(Heroicon::OutlinedPencilSquare)
->url(fn () => route('pages.editor', $this->record)),
Action::make('view')->label('Ansehen')->icon(Heroicon::OutlinedEye)->color('gray')
->url(fn () => $this->record->url())->openUrlInNewTab(),
DeleteAction::make()
->visible(fn () => ! $this->record->children()->exists() && auth()->user()->can('delete', $this->record))
->before(fn () => $this->record->files->each->delete()),
];
}
}

View file

@ -0,0 +1,17 @@
<?php
namespace Inhaus\Plugins\Pages\Filament\Resources\ContentPages\Pages;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
use Inhaus\Plugins\Pages\Filament\Resources\ContentPages\ContentPageResource;
class ListContentPages extends ListRecords
{
protected static string $resource = ContentPageResource::class;
protected function getHeaderActions(): array
{
return [CreateAction::make()->label('Seite anlegen')];
}
}

View file

@ -0,0 +1,73 @@
<?php
namespace Inhaus\Plugins\Pages\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Pagebuilder\Content;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Inertia\Response;
use Inhaus\Plugins\Pages\Models\Page;
use Inhaus\Plugins\Pages\Models\PageFile;
use Inhaus\Plugins\Pages\PageTree;
use Symfony\Component\HttpFoundation\StreamedResponse;
class PageController extends Controller
{
public function index(Request $request, PageTree $tree): Response
{
return Inertia::render('pages::Index', [
'tree' => $tree->visibleTree(null, $request->user()),
'canCreate' => $request->user()->can('pages.manage'),
]);
}
public function show(Request $request, string $path, PageTree $tree, Content $content): Response
{
$page = Page::query()->where('path', trim($path, '/'))->firstOrFail();
$page->publishIfDue();
$user = $request->user();
$canEdit = $user->can('update', $page);
abort_unless($tree->isVisible($page->id, $user) || $canEdit, 404);
$ancestors = $tree->ancestors($page->id);
$root = $ancestors[0]['id'] ?? $page->id;
return Inertia::render('pages::Show', [
'page' => [
'id' => $page->id,
'title' => $page->title,
'url' => $page->url(),
'published_at' => $page->published_at?->toIso8601String(),
'is_published' => $page->isPublished(),
],
'content' => $content->render($page->content, $user, ['page_id' => $page->id]),
'breadcrumbs' => array_map(fn (array $a) => ['title' => $a['title'], 'url' => '/seiten/'.$a['path']], $ancestors),
'section' => [
'title' => $tree->get($root)['title'] ?? $page->title,
'url' => '/seiten/'.($tree->get($root)['path'] ?? $page->path),
'active' => $root === $page->id,
'children' => $tree->visibleTree($root, $user),
],
'editor' => $canEdit ? [
'url' => route('pages.editor', $page),
'has_draft' => $page->hasDraft(),
'scheduled_at' => $page->scheduled_at?->toIso8601String(),
] : null,
]);
}
public function file(Request $request, PageFile $file, PageTree $tree): StreamedResponse
{
$page = $file->page;
abort_unless($tree->isVisible($page->id, $request->user()) || $request->user()->can('update', $page), 404);
return Storage::disk(PageFile::DISK)->download($file->path, $file->name, [
'Content-Type' => $file->mime ?: 'application/octet-stream',
'Cache-Control' => 'private, max-age=3600',
'X-Content-Type-Options' => 'nosniff',
]);
}
}

View file

@ -0,0 +1,432 @@
<?php
namespace Inhaus\Plugins\Pages\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\Role;
use App\Models\User;
use App\Notifications\PortalNotification;
use App\Pagebuilder\Blocks;
use App\Pagebuilder\Content;
use App\Support\Audit;
use App\Support\Images;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\File;
use Inertia\Inertia;
use Inertia\Response;
use Inhaus\Plugins\Pages\Models\Page;
use Inhaus\Plugins\Pages\Models\PageFile;
use Inhaus\Plugins\Pages\Models\PageRevision;
use Inhaus\Plugins\Pages\PageTree;
use Inhaus\Plugins\Pages\Publishers;
/**
* Pagebuilder im Portal. Speichert laufend einen Entwurf; veröffentlicht wird
* erst ausdrücklich (oder zeitgesteuert). Wer nicht veröffentlichen darf,
* fordert eine Freigabe an.
*/
class PageEditorController extends Controller
{
/** Dateiendungen, die nie als Download angenommen werden. */
private const BLOCKED_EXTENSIONS = ['php', 'phtml', 'phar', 'php3', 'php4', 'php5', 'php7', 'php8', 'pht', 'shtml', 'htaccess', 'exe', 'bat', 'cmd', 'com', 'sh', 'js', 'mjs', 'html', 'htm', 'svg', 'xhtml', 'jsp', 'asp', 'aspx', 'cgi', 'pl', 'py'];
public function __construct(private readonly Content $content) {}
public function store(Request $request): RedirectResponse
{
$data = $request->validate([
'title' => ['required', 'string', 'max:200'],
'parent_id' => ['nullable', 'integer', Rule::exists('pages', 'id')],
]);
$parent = isset($data['parent_id']) ? Page::query()->findOrFail($data['parent_id']) : null;
Gate::authorize('create', [Page::class, $parent]);
$page = Page::query()->create([
'parent_id' => $parent?->id,
'title' => $data['title'],
'sort' => $parent ? (int) $parent->children()->max('sort') + 1 : (int) Page::query()->whereNull('parent_id')->max('sort') + 1,
'created_by' => $request->user()->id,
]);
Audit::log('page.created', ['page' => $page->id, 'title' => $page->title]);
return to_route('pages.editor', $page);
}
public function edit(Request $request, Page $page, Blocks $blocks, PageTree $tree): Response
{
Gate::authorize('update', $page);
$user = $request->user();
$lockedBy = $page->isLockedFor($user) ? $page->lockedBy : null;
if (! $lockedBy) {
$page->lockFor($user);
}
return Inertia::render('pages::Editor', [
'page' => $this->pageState($page, $user),
'working' => $page->workingCopy(),
'lockedBy' => $lockedBy ? ['id' => $lockedBy->id, 'name' => $lockedBy->name] : null,
'blockTypes' => $blocks->forEditor(),
'blockGroups' => Blocks::GROUPS,
'files' => $page->files()->latest()->get()->map->toBlockArray(),
'audienceOptions' => $this->audienceOptions(),
'breadcrumbs' => array_map(fn (array $a) => ['title' => $a['title'], 'url' => '/seiten/'.$a['path']], $tree->ancestors($page->id)),
'uploadsUrl' => rtrim(Storage::disk('uploads')->url(''), '/'),
]);
}
public function saveDraft(Request $request, Page $page): JsonResponse
{
Gate::authorize('update', $page);
if ($response = $this->lockConflict($request, $page)) {
return $response;
}
[$title, $content] = $this->validatedWorkingCopy($request);
// Stimmt der Stand mit dem veröffentlichten überein, gibt es keinen Entwurf.
$unchanged = $page->isPublished() && $title === $page->title && $content === $page->content;
$page->forceFill([
'draft_title' => $unchanged ? null : $title,
'draft' => $unchanged ? null : $content,
'draft_updated_at' => $unchanged ? null : now(),
'draft_updated_by' => $unchanged ? null : $request->user()->id,
])->save();
$page->lockFor($request->user());
return response()->json(['page' => $this->pageState($page, $request->user())]);
}
public function discardDraft(Request $request, Page $page): JsonResponse
{
Gate::authorize('update', $page);
if ($response = $this->lockConflict($request, $page)) {
return $response;
}
$page->forceFill(['draft' => null, 'draft_title' => null, 'draft_updated_at' => null, 'draft_updated_by' => null])->save();
return response()->json(['page' => $this->pageState($page, $request->user()), 'working' => $page->workingCopy()]);
}
public function publish(Request $request, Page $page): JsonResponse
{
Gate::authorize('publish', $page);
if ($response = $this->lockConflict($request, $page)) {
return $response;
}
[$title, $content] = $this->validatedWorkingCopy($request);
$request->validate(['scheduled_at' => ['nullable', 'date', 'after:now']]);
if ($request->filled('scheduled_at')) {
$at = Carbon::parse($request->input('scheduled_at'));
$page->schedule($title, $content, $at, $request->user());
Audit::log('page.scheduled', ['page' => $page->id, 'title' => $title, 'at' => $at->toIso8601String()]);
} else {
$page->publish($title, $content, $request->user());
Audit::log('page.published', ['page' => $page->id, 'title' => $title]);
}
return response()->json(['page' => $this->pageState($page->fresh(), $request->user())]);
}
public function requestReview(Request $request, Page $page): JsonResponse
{
Gate::authorize('update', $page);
$request->validate(['message' => ['nullable', 'string', 'max:1000']]);
$recipients = Publishers::for($page, $request->user());
if ($recipients->isEmpty()) {
return response()->json(['message' => 'Für diese Seite ist niemand zum Veröffentlichen berechtigt. Bitte wenden Sie sich an die Administration.'], 422);
}
// Höchstens eine Anfrage je Seite und Person in 10 Minuten.
if (! Cache::add('pages.review.'.$page->id.'.'.$request->user()->id, true, 600)) {
return response()->json(['message' => 'Die Freigabe wurde gerade erst angefordert.'], 429);
}
Notification::send($recipients, new PortalNotification(
'Freigabe angefordert: '.($page->draft_title ?? $page->title),
trim($request->user()->name.' bittet um Veröffentlichung. '.$request->input('message', '')),
route('pages.editor', $page),
'file-check',
));
Audit::log('page.review_requested', ['page' => $page->id]);
return response()->json(['recipients' => $recipients->count()]);
}
public function cancelSchedule(Request $request, Page $page): JsonResponse
{
Gate::authorize('publish', $page);
// Der geplante Stand wird wieder zum Entwurf – nichts geht verloren.
$page->forceFill([
'draft' => $page->scheduled_content,
'draft_title' => $page->scheduled_title,
'draft_updated_at' => now(),
'draft_updated_by' => $request->user()->id,
]);
$page->cancelSchedule();
return response()->json(['page' => $this->pageState($page, $request->user()), 'working' => $page->workingCopy()]);
}
public function unpublish(Request $request, Page $page): JsonResponse
{
Gate::authorize('publish', $page);
$page->forceFill([
'draft' => $page->draft ?? $page->content,
'draft_title' => $page->draft_title ?? $page->title,
'draft_updated_at' => now(),
'content' => null,
'published_at' => null,
])->save();
Audit::log('page.unpublished', ['page' => $page->id, 'title' => $page->title]);
return response()->json(['page' => $this->pageState($page, $request->user())]);
}
public function settings(Request $request, Page $page): JsonResponse
{
Gate::authorize('configure', $page);
$data = $request->validate([
'slug' => ['required', 'string', 'max:120', 'regex:/^[a-z0-9]+(-[a-z0-9]+)*$/'],
'in_navigation' => ['boolean'],
], ['slug.regex' => 'Nur Kleinbuchstaben, Ziffern und Bindestriche.']);
$page->slug = $data['slug'];
// Hauptnavigation nur für Seiten der obersten Ebene – und nur mit „Seiten verwalten“.
if ($page->parent_id === null && $request->user()->can('pages.manage')) {
$page->in_navigation = (bool) ($data['in_navigation'] ?? false);
}
$page->save();
return response()->json(['page' => $this->pageState($page, $request->user())]);
}
public function destroy(Request $request, Page $page): RedirectResponse|JsonResponse
{
Gate::authorize('delete', $page);
if ($page->children()->exists()) {
return response()->json(['message' => 'Die Seite hat Unterseiten. Bitte diese zuerst löschen oder verschieben.'], 422);
}
$parent = $page->parent;
$page->files->each->delete();
$page->delete();
Audit::log('page.deleted', ['page' => $page->id, 'title' => $page->title]);
return response()->json(['redirect' => $parent?->url() ?? '/seiten']);
}
public function revisions(Page $page): JsonResponse
{
Gate::authorize('update', $page);
return response()->json(['revisions' => $page->revisions()->with('user:id,name')->limit(50)->get(['id', 'page_id', 'title', 'action', 'user_id', 'created_at'])
->map(fn (PageRevision $revision) => [
'id' => $revision->id,
'title' => $revision->title,
'action' => PageRevision::ACTIONS[$revision->action] ?? $revision->action,
'user' => $revision->user?->name,
'created_at' => $revision->created_at?->toIso8601String(),
])]);
}
public function revision(Request $request, Page $page, PageRevision $revision): JsonResponse
{
Gate::authorize('update', $page);
abort_unless($revision->page_id === $page->id, 404);
return response()->json([
'title' => $revision->title,
'content' => $this->content->render($revision->content, $request->user(), ['page_id' => $page->id]),
]);
}
public function restore(Request $request, Page $page, PageRevision $revision): JsonResponse
{
Gate::authorize('update', $page);
abort_unless($revision->page_id === $page->id, 404);
if ($response = $this->lockConflict($request, $page)) {
return $response;
}
// Wiederherstellen legt einen Entwurf an – veröffentlicht wird wie immer ausdrücklich.
$page->forceFill([
'draft_title' => $revision->title,
'draft' => $this->content->sanitize($revision->content),
'draft_updated_at' => now(),
'draft_updated_by' => $request->user()->id,
])->save();
return response()->json(['page' => $this->pageState($page, $request->user()), 'working' => $page->workingCopy()]);
}
public function lock(Request $request, Page $page): JsonResponse
{
Gate::authorize('update', $page);
if ($page->isLockedFor($request->user()) && ! $request->boolean('takeover')) {
return response()->json(['lockedBy' => ['id' => $page->locked_by, 'name' => $page->lockedBy?->name]], 423);
}
$page->lockFor($request->user());
return response()->json(['locked_until' => $page->locked_until->toIso8601String()]);
}
public function unlock(Request $request, Page $page): JsonResponse
{
Gate::authorize('update', $page);
$page->unlockFor($request->user());
return response()->json(['ok' => true]);
}
public function uploadImage(Request $request, Page $page, Images $images): JsonResponse
{
Gate::authorize('update', $page);
$request->validate(['image' => ['required', File::image()->types(['jpg', 'jpeg', 'png', 'webp', 'gif'])->max(15 * 1024)]]);
$path = $images->storeContentImage($request->file('image'), 'pagebuilder/pages/'.$page->id);
return response()->json(['path' => $path, 'url' => Blocks::imageUrl($path)]);
}
public function uploadFile(Request $request, Page $page): JsonResponse
{
Gate::authorize('update', $page);
$request->validate(['file' => ['required', 'file', 'max:'.(50 * 1024)]]);
$upload = $request->file('file');
$name = Str::limit(preg_replace('/[^\pL\pN ._()\-]+/u', '_', $upload->getClientOriginalName()) ?: 'datei', 180, '');
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
if (in_array($extension, self::BLOCKED_EXTENSIONS, true) || in_array(strtolower($upload->getClientOriginalExtension()), self::BLOCKED_EXTENSIONS, true)) {
return response()->json(['message' => 'Dieser Dateityp ist aus Sicherheitsgründen nicht erlaubt.', 'errors' => ['file' => ['Dieser Dateityp ist nicht erlaubt.']]], 422);
}
$path = $upload->storeAs('pages/'.$page->id, Str::random(32).($extension ? '.'.$extension : ''), PageFile::DISK);
$file = $page->files()->create([
'name' => $name,
'path' => $path,
'mime' => $upload->getMimeType(),
'size' => $upload->getSize(),
'uploaded_by' => $request->user()->id,
]);
return response()->json(['file' => $file->toBlockArray()]);
}
public function preview(Request $request, Page $page): JsonResponse
{
Gate::authorize('update', $page);
$request->validate(['blocks' => ['required', 'array', 'max:100'], 'blocks.*' => ['array']]);
$props = [];
foreach ($request->input('blocks') as $block) {
if (is_string($block['id'] ?? null)) {
$props[$block['id']] = $this->content->preview($block, $request->user(), ['page_id' => $page->id]);
}
}
return response()->json(['props' => (object) $props]);
}
/**
* @return array{0: string, 1: array<string, mixed>}
*/
private function validatedWorkingCopy(Request $request): array
{
$request->validate([
'title' => ['required', 'string', 'max:200'],
'content' => ['present', 'array'],
]);
return [trim($request->input('title')), $this->content->sanitize($request->input('content'))];
}
private function lockConflict(Request $request, Page $page): ?JsonResponse
{
if ($page->isLockedFor($request->user())) {
return response()->json([
'message' => ($page->lockedBy?->name ?? 'Jemand anderes').' bearbeitet diese Seite gerade.',
'lockedBy' => ['id' => $page->locked_by, 'name' => $page->lockedBy?->name],
], 423);
}
return null;
}
/**
* @return array<string, mixed>
*/
private function pageState(Page $page, User $user): array
{
return [
'id' => $page->id,
'title' => $page->title,
'slug' => $page->slug,
'url' => $page->url(),
'parent_id' => $page->parent_id,
'in_navigation' => $page->in_navigation,
'is_published' => $page->isPublished(),
'published_at' => $page->published_at?->toIso8601String(),
'has_draft' => $page->hasDraft(),
'draft_updated_at' => $page->draft_updated_at?->toIso8601String(),
'scheduled_at' => $page->scheduled_at?->toIso8601String(),
'can' => [
'publish' => $user->can('publish', $page),
'configure' => $user->can('configure', $page),
'delete' => $user->can('delete', $page),
'create_child' => $user->can('create', [Page::class, $page]),
'navigation' => $page->parent_id === null && $user->can('pages.manage'),
],
];
}
/**
* Auswahl für „Sichtbar für“ an einzelnen Blöcken.
*
* @return array{role: list<array{value: string, label: string}>, department: list<string>, location: list<string>}
*/
private function audienceOptions(): array
{
return Cache::remember('pagebuilder.audience-options', 300, fn () => [
'role' => Role::query()->orderBy('name')->get(['id', 'name'])->map(fn (Role $role) => ['value' => (string) $role->id, 'label' => $role->name])->all(),
'department' => User::query()->active()->whereNotNull('department')->distinct()->orderBy('department')->pluck('department')->all(),
'location' => User::query()->active()->whereNotNull('location')->distinct()->orderBy('location')->pluck('location')->all(),
]);
}
}

View file

@ -0,0 +1,239 @@
<?php
namespace Inhaus\Plugins\Pages\Models;
use App\Models\User;
use App\Pagebuilder\Content;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inhaus\Plugins\Pages\PageTree;
/**
* Eine Inhaltsseite im Seitenbaum. Inhalt, Entwurf und geplanter Stand sind
* bereinigtes Block-JSON (siehe App\Pagebuilder\Content).
*/
#[Fillable(['parent_id', 'title', 'slug', 'sort', 'in_navigation', 'created_by'])]
class Page extends Model
{
/** So lange hält eine Bearbeitungssperre ohne Lebenszeichen des Editors. */
public const LOCK_SECONDS = 120;
protected static function booted(): void
{
static::saving(function (Page $page) {
$page->slug = Str::slug($page->slug ?: $page->title, language: 'de') ?: 'seite';
if ($page->isDirty(['slug', 'parent_id']) || $page->path === null) {
$page->path = static::uniquePath($page);
}
});
// Unterseiten ziehen mit, wenn sich die Adresse ändert.
static::saved(function (Page $page) {
if (! $page->wasRecentlyCreated && $page->wasChanged('path')) {
$old = $page->getOriginal('path');
DB::table('pages')->where('path', 'like', str_replace(['%', '_'], ['\%', '\_'], $old).'/%')->update([
'path' => DB::raw('CONCAT('.DB::getPdo()->quote($page->path).', SUBSTRING(path, '.(mb_strlen($old) + 1).'))'),
]);
}
if ($page->wasRecentlyCreated || $page->wasChanged(['title', 'path', 'parent_id', 'sort', 'in_navigation', 'published_at'])) {
PageTree::flush($page->wasRecentlyCreated || $page->wasChanged('parent_id'));
}
});
static::deleted(fn () => PageTree::flush(true));
}
protected function casts(): array
{
return [
'content' => 'array',
'draft' => 'array',
'scheduled_content' => 'array',
'in_navigation' => 'boolean',
'published_at' => 'datetime',
'draft_updated_at' => 'datetime',
'scheduled_at' => 'datetime',
'locked_until' => 'datetime',
'locked_by' => 'integer',
];
}
/**
* @return array{0: string, 1: int}
*/
public function permissionResource(): array
{
return ['page', $this->id];
}
/**
* @return BelongsTo<Page, $this>
*/
public function parent(): BelongsTo
{
return $this->belongsTo(Page::class, 'parent_id');
}
/**
* @return HasMany<Page, $this>
*/
public function children(): HasMany
{
return $this->hasMany(Page::class, 'parent_id')->orderBy('sort')->orderBy('title');
}
/**
* @return HasMany<PageRevision, $this>
*/
public function revisions(): HasMany
{
return $this->hasMany(PageRevision::class)->latest('id');
}
/**
* @return HasMany<PageFile, $this>
*/
public function files(): HasMany
{
return $this->hasMany(PageFile::class);
}
/**
* @return BelongsTo<User, $this>
*/
public function lockedBy(): BelongsTo
{
return $this->belongsTo(User::class, 'locked_by');
}
public function isPublished(): bool
{
return $this->content !== null;
}
public function hasDraft(): bool
{
return $this->draft !== null;
}
public function url(): string
{
return '/seiten/'.$this->path;
}
/**
* Stand, mit dem der Editor startet: Entwurf, sonst veröffentlichter Inhalt.
*
* @return array{title: string, content: array<string, mixed>}
*/
public function workingCopy(): array
{
return [
'title' => $this->draft_title ?? $this->title,
'content' => $this->draft ?? $this->content ?? Content::empty(),
];
}
public function isLockedFor(User $user): bool
{
return $this->locked_by !== null && $this->locked_by !== $user->id && $this->locked_until?->isFuture();
}
public function lockFor(User $user): void
{
$this->forceFill(['locked_by' => $user->id, 'locked_until' => now()->addSeconds(self::LOCK_SECONDS)])->saveQuietly();
}
public function unlockFor(User $user): void
{
if ($this->locked_by === $user->id) {
$this->forceFill(['locked_by' => null, 'locked_until' => null])->saveQuietly();
}
}
/**
* Stand veröffentlichen und als Version ablegen.
*
* @param array<string, mixed> $content bereinigt
*/
public function publish(string $title, array $content, ?User $user, string $action = 'published'): void
{
DB::transaction(function () use ($title, $content, $user, $action) {
$this->forceFill([
'title' => $title,
'content' => $content,
'published_at' => now(),
'published_by' => $user?->id,
'draft' => null,
'draft_title' => null,
'draft_updated_at' => null,
'draft_updated_by' => null,
])->save();
$this->revisions()->create(['title' => $title, 'content' => $content, 'action' => $action, 'user_id' => $user?->id, 'created_at' => now()]);
// Nur die letzten 50 Versionen behalten.
$keep = $this->revisions()->limit(50)->pluck('id');
$this->revisions()->whereNotIn('id', $keep)->delete();
});
}
public function schedule(string $title, array $content, Carbon $at, User $user): void
{
$this->forceFill([
'scheduled_at' => $at,
'scheduled_title' => $title,
'scheduled_content' => $content,
'scheduled_by' => $user->id,
'draft' => null,
'draft_title' => null,
'draft_updated_at' => null,
'draft_updated_by' => null,
])->save();
}
public function cancelSchedule(): void
{
$this->forceFill(['scheduled_at' => null, 'scheduled_title' => null, 'scheduled_content' => null, 'scheduled_by' => null])->save();
}
/**
* Fälligen geplanten Stand veröffentlichen (Hintergrundaufgabe und beim Aufruf).
*/
public function publishIfDue(): bool
{
if (! $this->scheduled_at || $this->scheduled_at->isFuture()) {
return false;
}
$by = $this->scheduled_by ? User::query()->find($this->scheduled_by) : null;
$title = $this->scheduled_title ?? $this->title;
$content = $this->scheduled_content ?? Content::empty();
$this->cancelSchedule();
$this->publish($title, $content, $by, 'scheduled');
return true;
}
public static function uniquePath(Page $page): string
{
$prefix = $page->parent_id ? static::query()->whereKey($page->parent_id)->value('path').'/' : '';
$slug = $page->slug;
for ($i = 2; static::query()->where('path', $prefix.$slug)->when($page->exists, fn ($q) => $q->whereKeyNot($page->id))->exists(); $i++) {
$slug = $page->slug.'-'.$i;
}
$page->slug = $slug;
return $prefix.$slug;
}
}

View file

@ -0,0 +1,50 @@
<?php
namespace Inhaus\Plugins\Pages\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;
/**
* Datei zum Herunterladen (Block „Downloads“). Liegt außerhalb von public/ und
* wird nur an Personen ausgeliefert, die die Seite sehen dürfen.
*/
#[Fillable(['page_id', 'name', 'path', 'mime', 'size', 'uploaded_by'])]
class PageFile extends Model
{
public const DISK = 'local';
protected static function booted(): void
{
static::deleted(fn (PageFile $file) => Storage::disk(self::DISK)->delete($file->path));
}
/**
* @return BelongsTo<Page, $this>
*/
public function page(): BelongsTo
{
return $this->belongsTo(Page::class);
}
public function url(): string
{
return route('pages.file', ['file' => $this->id, 'name' => $this->name]);
}
/**
* @return array{id: int, name: string, size: int, extension: string, url: string}
*/
public function toBlockArray(): array
{
return [
'id' => $this->id,
'name' => $this->name,
'size' => (int) $this->size,
'extension' => strtoupper(pathinfo($this->name, PATHINFO_EXTENSION)),
'url' => $this->url(),
];
}
}

View file

@ -0,0 +1,41 @@
<?php
namespace Inhaus\Plugins\Pages\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable(['page_id', 'title', 'content', 'action', 'user_id', 'created_at'])]
class PageRevision extends Model
{
public const UPDATED_AT = null;
public const ACTIONS = [
'published' => 'Veröffentlicht',
'scheduled' => 'Zeitgesteuert veröffentlicht',
'restored' => 'Wiederhergestellt',
];
protected function casts(): array
{
return ['content' => 'array'];
}
/**
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* @return BelongsTo<Page, $this>
*/
public function page(): BelongsTo
{
return $this->belongsTo(Page::class);
}
}

View file

@ -0,0 +1,204 @@
<?php
namespace Inhaus\Plugins\Pages;
use App\Models\User;
use App\Support\Permissions\Audiences;
use App\Support\Permissions\Permissions;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
/**
* Der Seitenbaum als gecachte Struktur (nur Arrays): Titel, Adressen,
* Reihenfolge und Zielgruppen aller Seiten. Navigation, Seitenleiste,
* Brotkrumen und Sichtbarkeit kommen ohne weitere Abfragen aus – auch bei
* tausenden Seiten.
*
* Sichtbar ist eine Seite, wenn sie veröffentlicht ist und die Person die
* Zielgruppe der Seite und aller übergeordneten Seiten erfüllt.
*/
class PageTree
{
private const CACHE_KEY = 'pages.tree';
/** @var array{pages: array<int, array<string, mixed>>, children: array<int, list<int>>}|null */
private ?array $data = null;
/** @var array<int, array<int, bool>> */
private array $visible = [];
public static function flush(bool $structureChanged = false): void
{
Cache::forget(self::CACHE_KEY);
app(self::class)->data = null;
app(self::class)->visible = [];
// Rechte „inkl. Unterseiten“ hängen am Baum.
if ($structureChanged) {
Permissions::flush();
}
}
/**
* @return array<string, mixed>|null
*/
public function get(int $id): ?array
{
return $this->data()['pages'][$id] ?? null;
}
/**
* @return list<int>
*/
public function childIds(?int $id): array
{
return $this->data()['children'][$id ?? 0] ?? [];
}
/**
* @param list<int> $ids
* @return list<int>
*/
public function descendantIds(array $ids): array
{
$result = [];
$queue = $ids;
while ($queue !== []) {
foreach ($this->childIds(array_shift($queue)) as $child) {
if (! in_array($child, $result, true)) {
$result[] = $child;
$queue[] = $child;
}
}
}
return $result;
}
/**
* Übergeordnete Seiten, beginnend bei der obersten.
*
* @return list<array<string, mixed>>
*/
public function ancestors(int $id): array
{
$result = [];
$parent = $this->get($id)['parent_id'] ?? null;
while ($parent !== null && ($page = $this->get($parent)) && count($result) < 50) {
array_unshift($result, $page);
$parent = $page['parent_id'];
}
return $result;
}
public function isVisible(int $id, ?User $user): bool
{
$key = $user?->id ?? 0;
if (isset($this->visible[$key][$id])) {
return $this->visible[$key][$id];
}
$page = $this->get($id);
$visible = $page !== null
&& $page['published']
&& Audiences::matches($page['audience'], $user)
&& ($page['parent_id'] === null || $this->isVisible($page['parent_id'], $user));
return $this->visible[$key][$id] = $visible;
}
/**
* Sichtbare Unterseiten als verschachtelte Liste.
*
* @return list<array{id: int, title: string, url: string, children: list<mixed>}>
*/
public function visibleTree(?int $rootId, ?User $user, int $maxDepth = 6): array
{
if ($maxDepth <= 0) {
return [];
}
$result = [];
foreach ($this->childIds($rootId) as $id) {
if ($this->isVisible($id, $user)) {
$page = $this->get($id);
$result[] = [
'id' => $id,
'title' => $page['title'],
'url' => '/seiten/'.$page['path'],
'children' => $this->visibleTree($id, $user, $maxDepth - 1),
];
}
}
return $result;
}
/**
* Seiten der obersten Ebene, die in der Hauptnavigation stehen sollen.
*
* @return list<array{id: int, title: string, path: string, sort: int}>
*/
public function navigation(?User $user): array
{
return collect($this->childIds(null))
->map(fn (int $id) => $this->get($id))
->filter(fn (array $page) => $page['in_navigation'] && $this->isVisible($page['id'], $user))
->map(fn (array $page) => ['id' => $page['id'], 'title' => $page['title'], 'path' => $page['path'], 'sort' => $page['sort']])
->values()
->all();
}
/**
* Alle Seiten mit Einrückung – für Auswahllisten.
*
* @return array<int, string>
*/
public function options(?int $rootId = null, int $depth = 0): array
{
$options = [];
foreach ($this->childIds($rootId) as $id) {
$options[$id] = str_repeat('— ', $depth).$this->get($id)['title'];
$options += $this->options($id, $depth + 1);
}
return $options;
}
/**
* @return array{pages: array<int, array<string, mixed>>, children: array<int, list<int>>}
*/
private function data(): array
{
return $this->data ??= Cache::rememberForever(self::CACHE_KEY, function () {
$audiences = Audiences::allOfType('page');
$pages = [];
$children = [];
$rows = DB::table('pages')->orderBy('sort')->orderBy('title')
->get(['id', 'parent_id', 'title', 'path', 'sort', 'in_navigation', 'published_at']);
foreach ($rows as $row) {
$pages[$row->id] = [
'id' => (int) $row->id,
'parent_id' => $row->parent_id !== null ? (int) $row->parent_id : null,
'title' => $row->title,
'path' => $row->path,
'sort' => (int) $row->sort,
'in_navigation' => (bool) $row->in_navigation,
'published' => $row->published_at !== null,
'audience' => $audiences[$row->id] ?? null,
];
$children[(int) ($row->parent_id ?? 0)][] = (int) $row->id;
}
return ['pages' => $pages, 'children' => $children];
});
}
}

View file

@ -0,0 +1,102 @@
<?php
namespace Inhaus\Plugins\Pages;
use App\Editorial\Editorial;
use App\Models\User;
use App\Pagebuilder\Blocks;
use App\Pagebuilder\BlockType;
use App\Pagebuilder\Field;
use App\Plugins\Plugin;
use App\Support\Abilities;
use App\Support\Navigation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Schedule;
use Inhaus\Plugins\Pages\Models\Page;
use Inhaus\Plugins\Pages\Models\PageFile;
use Inhaus\Plugins\Pages\Policies\PagePolicy;
class PagesPlugin extends Plugin
{
public function register(): void
{
$this->app->singleton(PageTree::class);
$abilities = $this->app->make(Abilities::class);
$abilities->define('pages.manage', 'Seiten: alle Seiten verwalten', 'Seiten');
$abilities->define('pages.edit', 'Seiten bearbeiten', 'Seiten', resource: 'page');
$abilities->define('pages.publish', 'Seiten veröffentlichen', 'Seiten', resource: 'page');
$abilities->resourceType(
'page',
'Seite',
fn () => $this->app->make(PageTree::class)->options(),
fn (array $ids) => $this->app->make(PageTree::class)->descendantIds($ids),
);
Gate::policy(Page::class, PagePolicy::class);
// Seiten der obersten Ebene mit „In der Hauptnavigation“ erscheinen dort.
$this->app->make(Navigation::class)->provider('pages', function (Request $request, ?User $user) {
$current = trim((string) $request->route('path'), '/');
return array_map(fn (array $page) => [
'key' => 'page-'.$page['id'],
'label' => $page['title'],
'href' => '/seiten/'.$page['path'],
'active' => $request->routeIs('pages.show') && ($current === $page['path'] || str_starts_with($current, $page['path'].'/')),
'sort' => 40 + $page['sort'],
], $this->app->make(PageTree::class)->navigation($user));
});
$this->app->make(Editorial::class)->add(
'pages',
'Seiten',
'pages::EditorialPages',
20,
fn (User $user) => app(PagePolicy::class)->viewAny($user),
fn (User $user) => EditorialPages::props($user),
);
$this->registerBlocks($this->app->make(Blocks::class));
}
public function boot(): void
{
// Zeitgesteuerte Veröffentlichungen. Beim Aufruf einer Seite wird ein fälliger Stand zusätzlich sofort übernommen.
Schedule::call(function () {
Page::query()->whereNotNull('scheduled_at')->where('scheduled_at', '<=', now())->get()->each->publishIfDue();
})->everyMinute()->name('pages-scheduled')->withoutOverlapping(5);
}
private function registerBlocks(Blocks $blocks): void
{
$blocks->add(BlockType::make('downloads', 'Downloads', 'file-down', 'media', 'pages::Downloads')
->description('Dateien zum Herunterladen – nur für Personen, die die Seite sehen dürfen.')
->fields([
Field::text('title', 'Überschrift', 150),
Field::ids('files', 'Dateien', 'page-file'),
])
->resolveUsing(function (array $data, ?User $user, array $context) {
$files = PageFile::query()->whereIn('id', $data['files'])
->when(isset($context['page_id']), fn ($q) => $q->where('page_id', $context['page_id']))
->get()->keyBy('id');
return ['files' => collect($data['files'])->map(fn ($id) => $files->get($id)?->toBlockArray())->filter()->values()->all()];
}));
$blocks->add(BlockType::make('subpages', 'Unterseiten', 'folder-tree', 'dynamic', 'pages::Subpages')
->description('Verweise auf die Unterseiten dieser Seite.')
->fields([
Field::text('title', 'Überschrift', 150),
Field::select('layout', 'Darstellung', ['cards' => 'Kacheln', 'list' => 'Liste'], 'cards'),
])
->resolveUsing(function (array $data, ?User $user, array $context) {
$tree = $this->app->make(PageTree::class);
return ['pages' => isset($context['page_id'])
? array_map(fn (array $page) => ['id' => $page['id'], 'title' => $page['title'], 'url' => $page['url']], $tree->visibleTree($context['page_id'], $user, 1))
: []];
}));
}
}

View file

@ -0,0 +1,47 @@
<?php
namespace Inhaus\Plugins\Pages\Policies;
use App\Models\User;
use Inhaus\Plugins\Pages\Models\Page;
/**
* Rechte an Seiten: „Seiten verwalten“ gilt für den ganzen Baum. „Bearbeiten“
* und „Veröffentlichen“ werden je Seite vergeben, meist inkl. Unterseiten –
* z. B. darf die MAV die Seite „MAV“ und alles darunter pflegen.
*/
class PagePolicy
{
public function viewAny(User $user): bool
{
return $user->can('pages.manage') || $user->permissions()->ids('pages.edit', 'page') !== [];
}
public function create(User $user, ?Page $parent = null): bool
{
return $user->can('pages.manage') || ($parent !== null && $this->update($user, $parent));
}
public function update(User $user, Page $page): bool
{
return $user->can('pages.manage') || $user->can('pages.edit', ['page', $page->id]);
}
public function publish(User $user, Page $page): bool
{
return $user->can('pages.manage') || $user->can('pages.publish', ['page', $page->id]);
}
/**
* Adresse, Navigation und Sichtbarkeit: wer veröffentlichen darf.
*/
public function configure(User $user, Page $page): bool
{
return $this->publish($user, $page);
}
public function delete(User $user, Page $page): bool
{
return $this->publish($user, $page) && ($page->parent_id !== null || $user->can('pages.manage'));
}
}

View file

@ -0,0 +1,38 @@
<?php
namespace Inhaus\Plugins\Pages;
use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Inhaus\Plugins\Pages\Models\Page;
/**
* Wer eine Seite veröffentlichen darf – Empfänger von Freigabe-Anfragen.
*/
final class Publishers
{
/**
* @return Collection<int, User>
*/
public static function for(Page $page, ?User $except = null): Collection
{
$ancestors = array_column(app(PageTree::class)->ancestors($page->id), 'id');
$roleIds = DB::table('grants')
->where(function ($q) use ($page, $ancestors) {
$q->whereIn('ability', ['*', 'pages.manage'])->whereNull('resource_type');
$q->orWhere(fn ($q) => $q->where('ability', 'pages.publish')->where('resource_type', 'page')->where(fn ($q) => $q
->whereNull('resource_id')
->orWhere('resource_id', $page->id)
->orWhere(fn ($q) => $q->whereIn('resource_id', $ancestors ?: [0])->where('include_children', true))));
})
->pluck('role_id');
return User::query()->active()
->whereIn('id', DB::table('role_user')->whereIn('role_id', $roleIds)->select('user_id'))
->when($except, fn ($q) => $q->whereKeyNot($except->id))
->limit(50)
->get();
}
}