diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml index 2685b99a..41f96c4f 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -67,8 +67,9 @@ jobs: - name: vendor/ entspricht composer.lock (ohne Dev-Pakete) run: | composer install --no-dev --optimize-autoloader --no-interaction --no-progress --no-scripts - git status --porcelain vendor - test -z "$(git status --porcelain vendor)" + # installed.php enthält den Git-Commit des Projekts selbst und ändert sich daher immer. + git status --porcelain -- vendor ':!vendor/composer/installed.php' + test -z "$(git status --porcelain -- vendor ':!vendor/composer/installed.php')" - name: public/build/ entspricht dem Quellcode run: | npm ci --no-audit --no-fund diff --git a/.gitignore b/.gitignore index 61397b2b..703206f1 100644 --- a/.gitignore +++ b/.gitignore @@ -24,5 +24,9 @@ /storage/.version /storage/.update-progress /storage/.maintenance +# Laufzeitzustand der Installation – nie ausliefern (ein manuelles Update würde sonst fällige Migrationen überspringen) +/storage/.migrations-fingerprint +/storage/.background-heartbeat +/storage/.background.lock _ide_helper.php Thumbs.db diff --git a/.htaccess b/.htaccess new file mode 100644 index 00000000..a5b89fc3 --- /dev/null +++ b/.htaccess @@ -0,0 +1,18 @@ +# Nur nötig, wenn der Hoster das Installationsverzeichnis selbst als Webroot +# verwendet und sich dieser nicht auf „public/“ umstellen lässt: +# Alle Anfragen werden intern nach public/ geleitet – .env, storage/, vendor/ +# usw. sind so von außen nicht erreichbar. +# Diese Datei wird von Aktualisierungen nicht überschrieben (geschützter Pfad). + +Options -Indexes + + + RewriteEngine On + RewriteCond %{REQUEST_URI} !/public/ + RewriteRule ^(.*)$ public/$1 [L] + + + + # Ohne mod_rewrite lieber gar nichts ausliefern als Konfigurationsdateien. + Require all denied + diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a28ab54..65072955 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,79 @@ Neueste Version oben. Jeder Abschnitt beginnt mit `## MAJOR.MINOR.PATCH` und enthält kurze Stichpunkte für Anwenderinnen und Anwender – keine Commit-Texte. Der Self-Updater zeigt diese Abschnitte bei neuen Versionen an. +## 0.7.0 + +- Erscheinungsbild vollständig anpassbar: Portalname, Logos für helle und dunkle Flächen, Signet für Smartphones, App-Symbol für Favicon und Homescreen +- Markenfarbe wird exakt übernommen, optional eine zweite Akzentfarbe; Kopfleiste hell, in der Markenfarbe oder dunkel +- Kontrastprüfung nach WCAG AA: zu helle Markenfarben bekommen automatisch gut lesbare Linkfarben +- Schriften zur Auswahl oder als eigene Datei, auch getrennt für Überschriften – immer vom eigenen Server, nie von Google +- Ecken, Abstände und Dunkelmodus (frei wählbar, immer hell oder immer dunkel) einstellbar +- Anmeldeseite mit Hintergrundbild, eigenem Begrüßungstext und zwei Aufteilungen +- Fußzeile mit Links (z. B. Impressum, Datenschutz); E-Mails im gleichen Design mit eigener Fußzeile +- Entwurf, Live-Vorschau (Startseite, Anmeldung, Beispielseite – hell und dunkel) und Veröffentlichen; Export, Import und Zurücksetzen +- Eigenes CSS für Fortgeschrittene +- Der Admin-Bereich übernimmt Logo, Farbe und Favicon; „Inhaus“ erscheint nirgends mehr zwingend +- Hochgeladene SVG-Logos werden von Skripten bereinigt + +## 0.6.0 + +- Formulare: Anträge, Anmeldungen, Umfragen und Meldungen im visuellen Baukasten zusammenstellen – so, wie das Formular später aussieht: Bezeichnungen und Auswahlmöglichkeiten direkt bearbeiten, Felder per Ziehen und Ablegen anordnen, Vorschau mit Bedingungen +- Felder lassen sich abhängig von anderen Antworten ein- und ausblenden und aus dem Profil vorbelegen +- Einsendungen landen im Backend und per E-Mail bei festen Empfängern; auf Wunsch eine Kopie an die ausfüllende Person +- Zugriff auf die Ergebnisse je Formular und Rolle – ansehen und exportieren (CSV für Excel) bzw. löschen getrennt vergebbar +- Anonyme Formulare, „nur einmal ausfüllen“, Einsendeschluss, Sichtbarkeit und automatische Löschfrist +- Formularfelder lassen sich fest mit Profilangaben füllen (z. B. Vorname, Personalnummer, Abteilung) – nicht änderbar, beim Absenden gilt immer der Profilwert +- Formulare lassen sich mit dem Pagebuilder in Seiten und unter Neuigkeiten-Beiträgen einbinden +- Ergebnisse als CSV herunterladen – alle oder nur ausgewählte Einsendungen +- WordPress-Import: Beiträge mit Kategorien, Autorinnen und Autoren, Beitragsbildern und Bildern im Text übernehmen, auf Wunsch auch Seiten – wiederholbar, ohne Doppelungen +- E-Mail-Versand im Admin einrichten (SMTP), mit Test-Mail +- Startseite anpassen: Kacheln je Bereich sortieren und ausblenden, eigene Kacheln anlegen – Bild mit Link, Text oder Hinweis, mit Zeitraum und Zielgruppe +- Geburtstage (optional, unter „Plugins“ zu aktivieren): Mitarbeitende tragen freiwillig Tag und Monat im Profil ein; Kachel und Liste der anstehenden Geburtstage, Glückwunsch auf der Startseite am eigenen Geburtstag + +## 0.5.0 + +- Seiten: eigener Seitenbaum für Bereiche, Abteilungen und Gremien – mit Seitennavigation, Brotkrumen und optional in der Hauptnavigation +- Pagebuilder im Portal: Abschnitte, Spalten, Tabs, Akkordeon, Boxen, Text, Bilder, Galerie, Video, Tabellen, Schaltflächen, Ansprechpartner, Downloads und mehr – per Ziehen und Ablegen +- Entwürfe werden laufend gespeichert; veröffentlicht wird ausdrücklich oder zeitgesteuert, jede Veröffentlichung bleibt als Version erhalten +- Rechte je Seite inklusive Unterseiten, z. B. darf die MAV ihre Seite und alles darunter pflegen; ohne Veröffentlichungsrecht wird eine Freigabe angefordert +- Sichtbarkeit je Seite und je Block (Rollen, Abteilungen, Standorte) +- Bearbeitungssperre verhindert, dass zwei Personen gleichzeitig dieselbe Seite ändern +- Neuigkeiten direkt im Portal schreiben – mit Titelbild und Bildern im Text +- Freigabe-Workflow für Beiträge: einreichen, freigeben oder mit Anmerkung zurückgeben; wer veröffentlichen darf, kann auch planen und hervorheben +- Neuer Bereich „Redaktion“ mit Entwürfen, Freigaben und Geplantem +- Benachrichtigungen im Portal (Glocke im Kopfbereich), z. B. bei Freigabe-Anfragen +- Rechte für einzelne Seiten lassen sich im Rollen-Formular „inkl. Unterseiten“ vergeben +- Behoben: Nach einem manuellen Update per FTP wurde die Datenbank unter Umständen nicht aktualisiert + +## 0.4.0 + +- Anmeldung mit Microsoft Entra ID („Mit Microsoft anmelden“) – Konten werden bei der ersten Anmeldung angelegt oder per E-Mail verknüpft +- Entra-Gruppen und App-Rollen lassen sich Rollen im Portal zuordnen; manuell vergebene Rollen bleiben erhalten +- Profil, Vorgesetzte*r und Profilfoto werden aus Entra übernommen – übernommene Felder sind im Portal schreibgeschützt +- Beliebige Entra-Attribute lassen sich Profilfeldern zuordnen – auch Personalnummer, Kostenstelle, lokale Erweiterungsattribute und eigene Verzeichniserweiterungen +- Eigene Profilfelder (z. B. Personalnummer, Eintrittsdatum) mit Typ, Sichtbarkeit und Angabe, ob die Person sie selbst pflegen darf +- Hintergrund-Abgleich: Änderungen und in Entra deaktivierte Konten werden auch ohne Anmeldung übernommen, optional alle Konten vorab angelegt +- „Mapping testen“ zeigt, welche Gruppen Entra für eine Person liefert und welche Rollen daraus entstehen +- Profilseite zeigt Vorgesetzte*n und Mitarbeitende + +## 0.3.0 + +- Rollen und Rechte: eigene Rollen anlegen, Rechte global oder für einzelne Kategorien vergeben – z. B. darf die MAV nur in „MAV-Info“ schreiben +- Veröffentlichen ist ein eigenes Recht; ohne dieses Recht bleiben Beiträge Entwürfe +- Sichtbarkeit: Kategorien und Termine lassen sich auf Rollen, Abteilungen oder Standorte beschränken +- „Rechte prüfen“ zeigt, was eine Person darf und warum +- Redaktion und Sichtbarkeit direkt an der Kategorie einstellen +- Plugins: Funktionen lassen sich einzeln aktivieren und deaktivieren, eigene Plugins per ZIP installieren +- Neuigkeiten und Termine sind jetzt mitgelieferte Plugins + +## 0.2.0 + +- Aktualisierung per Klick im Admin-Bereich – ohne Serverzugang, mit Wartungsseite und Fortschrittsanzeige +- Lizenz hinterlegen und prüfen, Laufzeit und belegte Geräteplätze einsehen +- Update-Kanäle „Stabil“ und „Entwicklung“ +- Datenbank wird nach einem Update automatisch auf den neuen Stand gebracht +- Änderungsprotokoll im Admin-Bereich + ## 0.1.0 - Erste Fassung des Mitarbeiterportals diff --git a/CLAUDE.md b/CLAUDE.md index 9b90c045..3ddd154c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,3 +9,6 @@ - UI-Texte Deutsch mit Umlauten, Schlüssel/Routen ASCII. Kein Node/Shell auf dem Kundenserver voraussetzen. - Design: Tailwind + shadcn-vue (`resources/js/components/ui`), Lucide-Icons, Inter. Farben nur über Tokens (`brand`, `brand-text`, `card`, `muted-foreground` …); Markenfarbe kommt serverseitig als CSS-Variable. +- Funktionen als Plugins: mitgeliefert in `plugins-core/` (Namespace `Inhaus\Plugins\…`), Kunden in `plugins/`. Kern stellt + Registries bereit (Navigation, Dashboard\\Widgets, Abilities) – siehe `docs/PLUGINS.md`. +- Rechte immer über `$user->can('ability', ['typ', id])` bzw. Policies; Sichtbarkeit über `Audiences::constrain`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2efe91d9..20a5ccb6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -66,3 +66,10 @@ und danach `bin/build` ausführen, damit `vendor/` nachzieht. `text-muted-foreground` …), nie fest verdrahtet – sonst greift das Branding nicht - N+1-Abfragen vermeiden: `Model::preventLazyLoading()` ist außerhalb der Produktion aktiv + +## Schriften + +Die mitgelieferten Schriften kommen aus `@fontsource`-Paketen, eingebunden nur +mit den Zeichensätzen Latein und Latein-Erweitert. Nach dem Hinzufügen einer +Schrift `python3 scripts/generate-fonts-css.py` ausführen und die Schrift in +`App\Support\Theme\Fonts` eintragen. diff --git a/README.md b/README.md index 4a8d764c..cf17959a 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,8 @@ Webhosting. Laravel 13, Filament 5 (Admin), Inertia + Vue 3 + Tailwind CSS + shadcn-vue im Portal, MySQL/MariaDB, Apache. - Projektplan: [`docs/PLAN.md`](docs/PLAN.md) +- Installation beim Kunden (auch Shared Hosting): [`docs/INSTALLATION.md`](docs/INSTALLATION.md) +- Plugins entwickeln: [`docs/PLUGINS.md`](docs/PLUGINS.md) - Mitarbeit, Entwicklungsumgebung und Release-Ablauf: [`CONTRIBUTING.md`](CONTRIBUTING.md) - Änderungen: [`CHANGELOG.md`](CHANGELOG.md) diff --git a/app/Dashboard/CoreWidgets.php b/app/Dashboard/CoreWidgets.php new file mode 100644 index 00000000..ab49798b --- /dev/null +++ b/app/Dashboard/CoreWidgets.php @@ -0,0 +1,47 @@ +add('core.greeting', 'core::Greeting', 'aside', sort: 0, props: fn (User $user) => [ + 'profile' => [ + 'job_title' => $user->job_title, + 'department' => $user->department, + 'location' => $user->location, + 'avatar_url' => $user->avatarUrl(256), + ], + ], label: 'Begrüßung mit Profil', mobileSort: 0); + + $widgets->add('core.quick-links', 'core::QuickLinks', 'main', sort: 10, props: fn () => [ + 'links' => app(QuickLinks::class)->all(), + ], label: 'Schnellzugriffe', mobileSort: 40); + + $widgets->add('core.new-colleagues', 'core::NewColleagues', 'main', sort: 90, props: function (User $user) { + $people = User::query() + ->active() + ->whereKeyNot($user->getKey()) + ->where('created_at', '>=', now()->subDays(90)) + ->latest() + ->limit(6) + ->get(); + + return $people->isEmpty() ? null : ['people' => PersonResource::collection($people)->resolve()]; + }, label: 'Neue Kolleginnen und Kollegen', mobileSort: 60); + + $widgets->add('core.profile-incomplete', 'core::ProfileIncomplete', 'aside', sort: 50, props: fn (User $user) => $user->avatar_path && $user->job_title ? null : [], label: 'Hinweis „Profil vervollständigen“', mobileSort: 70); + + $widgets->add('core.people-search', 'core::PeopleSearch', 'aside', sort: 60, props: fn () => [ + 'count' => User::query()->active()->count(), + ], label: 'Personen finden', mobileSort: 80); + } +} diff --git a/app/Dashboard/Widgets.php b/app/Dashboard/Widgets.php new file mode 100644 index 00000000..1e3069dc --- /dev/null +++ b/app/Dashboard/Widgets.php @@ -0,0 +1,149 @@ + */ + private array $widgets = []; + + /** + * @param string $component Vue-Komponente, z. B. „core::QuickLinks“ oder „news::Hero“ + * @param callable(User, Request): (array|null) $props + * @param int|null $mobileSort Reihenfolge in der einspaltigen Mobilansicht (Standard: nach Bereich) + * @param string|null $label Name im Admin unter „Startseite“ + */ + public function add(string $key, string $component, string $area, int $sort, callable $props, ?int $mobileSort = null, ?string $label = null): void + { + if (! in_array($area, self::AREAS, true)) { + throw new \InvalidArgumentException("Unbekannter Bereich „{$area}“ für Kachel {$key}."); + } + + $mobileSort ??= ['top' => -100, 'hero' => 10, 'feed' => 20, 'aside' => 30, 'main' => 50][$area] + $sort; + + $label ??= $key; + $this->widgets[$key] = compact('component', 'area', 'sort', 'mobileSort', 'props', 'label'); + } + + public function remove(string $key): void + { + unset($this->widgets[$key]); + } + + /** + * Alle Kacheln eines Bereichs für den Admin: mitgelieferte und eigene, + * in gespeicherter Reihenfolge, mit Sichtbarkeit. + * + * @return list + */ + public function forAdmin(string $area): array + { + $layout = $this->layout(); + + return $this->candidates() + ->filter(fn (array $w) => $w['area'] === $area) + ->map(fn (array $w, string $key) => [ + 'key' => $key, + 'label' => $w['label'], + 'area' => $w['area'], + 'visible' => $layout[$key]['visible'] ?? true, + 'custom' => $w['custom'] ?? false, + ]) + ->values() + ->all(); + } + + /** + * Mitgelieferte Kacheln plus eigene Kacheln, sortiert nach gespeicherter Anordnung. + * + * @return Collection> + */ + private function candidates(?User $user = null) + { + $widgets = collect($this->widgets); + + try { + $tiles = DashboardTile::query()->when($user, fn ($q) => $q->visibleTo($user))->get(); + } catch (Throwable) { + $tiles = collect(); // Tabelle noch nicht angelegt (Aktualisierung läuft) + } + + foreach ($tiles as $tile) { + $widgets[$tile->widgetKey()] = [ + 'component' => 'core::CustomTile', + 'area' => array_key_exists($tile->area, DashboardTile::AREAS) ? $tile->area : 'aside', + 'sort' => 1000 + $tile->id, + 'mobileSort' => ['top' => -50, 'main' => 45, 'aside' => 32][$tile->area] ?? 32, + 'props' => fn () => $tile->toWidgetProps(), + 'label' => 'Eigene Kachel: '.$tile->name, + 'custom' => true, + ]; + } + + $layout = $this->layout(); + + return $widgets->sortBy(fn (array $w, string $key) => $layout[$key]['sort'] ?? $w['sort']); + } + + /** + * Gespeicherte Anordnung: Schlüssel => [sort, visible]. + * + * @return array + */ + private function layout(): array + { + return (array) app(Settings::class)->get('dashboard.layout', []); + } + + /** + * @return list}> + */ + public function resolve(User $user, Request $request): array + { + $result = []; + + $layout = $this->layout(); + + foreach ($this->candidates($user) as $key => $widget) { + if (($layout[$key]['visible'] ?? true) === false) { + continue; + } + + try { + $props = ($widget['props'])($user, $request); + } catch (Throwable $e) { + // Eine fehlerhafte Kachel darf die Startseite nicht lahmlegen. + Log::error("Startseiten-Kachel {$key} fehlgeschlagen: ".$e->getMessage(), ['exception' => $e]); + + continue; + } + + if ($props !== null) { + $result[] = ['key' => $key, 'component' => $widget['component'], 'area' => $widget['area'], 'mobileSort' => $widget['mobileSort'], 'props' => $props]; + } + } + + return $result; + } +} diff --git a/app/Editorial/Editorial.php b/app/Editorial/Editorial.php new file mode 100644 index 00000000..690565ee --- /dev/null +++ b/app/Editorial/Editorial.php @@ -0,0 +1,66 @@ + */ + private array $sections = []; + + /** + * @param Closure(User): bool $visible schnelle Rechteprüfung (ohne Abfragen) + * @param Closure(User): array $props + */ + public function add(string $key, string $label, string $component, int $sort, Closure $visible, Closure $props): void + { + $this->sections[$key] = compact('label', 'component', 'sort', 'visible', 'props'); + } + + public function remove(string $key): void + { + unset($this->sections[$key]); + } + + public function visibleFor(User $user): bool + { + foreach ($this->sections as $section) { + if (($section['visible'])($user)) { + return true; + } + } + + return false; + } + + /** + * @return list}> + */ + public function resolve(User $user): array + { + $result = []; + + foreach (collect($this->sections)->sortBy('sort') as $key => $section) { + if (! ($section['visible'])($user)) { + continue; + } + + try { + $result[] = ['key' => $key, 'label' => $section['label'], 'component' => $section['component'], 'props' => ($section['props'])($user)]; + } catch (Throwable $e) { + Log::error("Redaktionsbereich {$key} fehlgeschlagen: ".$e->getMessage(), ['exception' => $e]); + } + } + + return $result; + } +} diff --git a/app/Filament/Components/AudienceSection.php b/app/Filament/Components/AudienceSection.php new file mode 100644 index 00000000..2eed503a --- /dev/null +++ b/app/Filament/Components/AudienceSection.php @@ -0,0 +1,53 @@ + Select::make("audience_{$rule}") + ->label($label) + ->multiple() + ->searchable() + ->options($options) + ->afterStateHydrated(fn (Select $component, ?Model $record) => $component->state($record ? Audiences::get($type, $record->getKey())[$rule] : [])) + ->saveRelationshipsUsing(function (Model $record, Select $component) use ($type) { + // Alle drei Felder zusammen speichern (einmal pro Formular reicht, aber schadet nicht). + $state = $component->getContainer()->getRawState(); + Audiences::sync($type, $record->getKey(), [ + 'role' => $state['audience_role'] ?? [], + 'department' => $state['audience_department'] ?? [], + 'location' => $state['audience_location'] ?? [], + ]); + }) + ->dehydrated(false); + + return Section::make('Sichtbarkeit') + ->description($description) + ->collapsible() + ->schema([ + $field('role', 'Rollen', fn () => Role::query()->orderBy('name')->pluck('name', 'id')->mapWithKeys(fn ($name, $id) => [(string) $id => $name])->all()), + $field('department', 'Abteilungen', fn () => self::distinct('department')), + $field('location', 'Standorte', fn () => self::distinct('location')), + ]); + } + + /** + * @return array + */ + private static function distinct(string $column): array + { + return User::query()->whereNotNull($column)->distinct()->orderBy($column)->pluck($column, $column)->all(); + } +} diff --git a/app/Filament/Components/RoleGrantSelect.php b/app/Filament/Components/RoleGrantSelect.php new file mode 100644 index 00000000..6a84d6ed --- /dev/null +++ b/app/Filament/Components/RoleGrantSelect.php @@ -0,0 +1,38 @@ +label($label) + ->multiple() + ->preload() + ->options(fn () => Role::query()->where('slug', '!=', Role::ADMINISTRATION)->orderBy('name')->pluck('name', 'id')->all()) + ->afterStateHydrated(fn (Select $component, ?Model $record) => $component->state($record + ? Grant::query()->where('ability', $ability)->where('resource_type', $resourceType)->where('resource_id', $record->getKey())->pluck('role_id')->all() + : [])) + ->saveRelationshipsUsing(function (Model $record, ?array $state) use ($ability, $resourceType, $includeChildren) { + $roleIds = array_map('intval', $state ?? []); + $existing = Grant::query()->where('ability', $ability)->where('resource_type', $resourceType)->where('resource_id', $record->getKey()); + + (clone $existing)->whereNotIn('role_id', $roleIds)->get()->each->delete(); + + foreach (array_diff($roleIds, (clone $existing)->pluck('role_id')->all()) as $roleId) { + Grant::query()->create(['role_id' => $roleId, 'ability' => $ability, 'resource_type' => $resourceType, 'resource_id' => $record->getKey(), 'include_children' => $includeChildren]); + } + }) + ->dehydrated(false); + } +} diff --git a/app/Filament/Pages/Appearance.php b/app/Filament/Pages/Appearance.php index 532765fc..2a33af5c 100644 --- a/app/Filament/Pages/Appearance.php +++ b/app/Filament/Pages/Appearance.php @@ -2,27 +2,46 @@ namespace App\Filament\Pages; +use App\Support\Audit; use App\Support\Branding; -use App\Support\Settings; +use App\Support\Theme\Contrast; +use App\Support\Theme\Fonts; +use App\Support\Theme\Icons; +use App\Support\Theme\Theme; +use App\Support\Theme\ThemeCompiler; +use App\Support\Theme\ThemeTransfer; use BackedEnum; +use Filament\Actions\Action; +use Filament\Actions\ActionGroup; use Filament\Forms\Components\ColorPicker; use Filament\Forms\Components\FileUpload; +use Filament\Forms\Components\Radio; +use Filament\Forms\Components\Repeater; +use Filament\Forms\Components\Select; +use Filament\Forms\Components\Textarea; use Filament\Forms\Components\TextInput; use Filament\Notifications\Notification; use Filament\Pages\Page; use Filament\Schemas\Components\Section; +use Filament\Schemas\Components\Tabs; +use Filament\Schemas\Components\Tabs\Tab; +use Filament\Schemas\Components\Text; +use Filament\Schemas\Components\Utilities\Get; use Filament\Schemas\Schema; use Filament\Support\Icons\Heroicon; use Illuminate\Support\Facades\Storage; +use Illuminate\Support\HtmlString; +use Symfony\Component\HttpFoundation\StreamedResponse; +use Throwable; use UnitEnum; /** - * Basis-Branding (Phase 0). Die vollständige Seite „Erscheinungsbild“ mit - * Logo-Varianten, Schriften, Vorschau usw. folgt in Phase 5. + * „Erscheinungsbild“ (docs/PLAN.md, Abschnitt 12): Entwurf bearbeiten, in der + * Vorschau ansehen, dann für alle veröffentlichen. */ class Appearance extends Page { - protected string $view = 'filament.pages.settings-form'; + protected string $view = 'filament.pages.appearance'; protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedPaintBrush; @@ -37,65 +56,189 @@ class Appearance extends Page /** @var array|null */ public ?array $data = []; - public function mount(Branding $branding): void + public static function canAccess(): bool { - $this->form->fill([ - 'portal_name' => $branding->portalName(), - 'primary_color' => $branding->primaryColor(), - 'logo_path' => $branding->logoPath(), - ]); + return auth()->user()?->can('appearance.manage') ?? false; + } + + public function mount(Theme $theme): void + { + $this->form->fill($theme->working()); + } + + public function hasDraft(): bool + { + return app(Theme::class)->hasDraft(); } public function form(Schema $schema): Schema { - return $schema - ->components([ - Section::make('Portal') - ->description('Name und Logo erscheinen im Kopfbereich, auf der Anmeldeseite und im Browser-Tab.') - ->schema([ - TextInput::make('portal_name') - ->label('Name des Portals') - ->placeholder(Branding::DEFAULT_NAME) - ->maxLength(60), - FileUpload::make('logo_path') - ->label('Logo') - ->helperText('SVG, PNG oder WebP, am besten mit transparentem Hintergrund.') - ->disk('uploads') - ->directory('branding') - ->visibility('public') - ->acceptedFileTypes(['image/svg+xml', 'image/png', 'image/webp']) - ->maxSize(2048), + $image = fn (string $name, string $label, string $help) => FileUpload::make($name)->label($label)->helperText($help) + ->disk('uploads')->directory('theme')->visibility('public')->maxSize(4096); + + return $schema->statePath('data')->components([ + Tabs::make()->persistTabInQueryString()->tabs([ + Tab::make('Identität')->icon(Heroicon::OutlinedIdentification)->columns(2)->schema([ + TextInput::make('portal_name')->label('Name des Portals')->required()->maxLength(60) + ->helperText('Erscheint im Kopfbereich, im Browser-Tab, in E-Mails und auf dem Homescreen.')->columnSpanFull(), + $image('logo_light', 'Logo für helle Flächen', 'SVG, PNG oder WebP mit transparentem Hintergrund.') + ->acceptedFileTypes(['image/svg+xml', 'image/png', 'image/webp']), + $image('logo_dark', 'Logo für dunkle Flächen', 'Für den Dunkelmodus und farbige Kopfleisten, z. B. in Weiß. Leer = wie hell.') + ->acceptedFileTypes(['image/svg+xml', 'image/png', 'image/webp']), + $image('logo_mark', 'Signet (quadratisch)', 'Kurzform für Smartphones, z. B. nur das Bildzeichen.') + ->acceptedFileTypes(['image/svg+xml', 'image/png', 'image/webp']), + $image('app_icon', 'App-Symbol', 'Quadratisch, mindestens 512 × 512 Pixel (PNG oder JPG). Daraus entstehen Favicon und Homescreen-Symbole.') + ->image()->acceptedFileTypes(['image/png', 'image/jpeg', 'image/webp']), + ]), + + Tab::make('Farben')->icon(Heroicon::OutlinedSwatch)->columns(2)->schema([ + ColorPicker::make('primary_color')->label('Markenfarbe')->required()->regex('/^#[0-9a-fA-F]{6}$/')->live(onBlur: true) + ->helperText('Wird exakt übernommen: Schaltflächen, aktive Navigation, Begrüßungskarte. Die Abstufungen werden berechnet.'), + ColorPicker::make('secondary_color')->label('Zweite Akzentfarbe (optional)')->regex('/^#[0-9a-fA-F]{6}$/')->live(onBlur: true) + ->helperText('Für Kategorien und Datumsangaben. Leer = Markenfarbe.'), + Radio::make('header_style')->label('Kopfleiste')->options(Theme::HEADER_STYLES)->inline()->required()->columnSpanFull(), + Section::make('Kontrastprüfung (WCAG AA)')->columnSpanFull()->compact()->schema([ + Text::make(fn (Get $get) => $this->contrastReport((string) $get('primary_color'), $get('secondary_color'))), ]), - Section::make('Farben') - ->description('Aus der Primärfarbe wird die komplette Farbpalette für den hellen und den dunklen Modus berechnet.') - ->schema([ - ColorPicker::make('primary_color') - ->label('Primärfarbe') - ->regex('/^#[0-9a-fA-F]{6}$/') - ->required(), - ]), - ]) - ->statePath('data'); + ]), + + Tab::make('Schrift & Form')->icon(Heroicon::OutlinedLanguage)->columns(2)->schema([ + Select::make('font_body')->label('Schrift')->options(fn (Get $get) => Fonts::options((bool) $get('custom_font')))->required()->native(false), + Select::make('font_heading')->label('Schrift für Überschriften')->options(fn (Get $get) => ['same' => 'Wie die Schrift'] + Fonts::options((bool) $get('custom_font')))->required()->native(false), + FileUpload::make('custom_font')->label('Eigene Schrift (WOFF2)') + ->helperText('Z. B. die Hausschrift aus dem Corporate Design. Wird lokal ausgeliefert – keine Verbindung zu Google oder anderen Diensten. Bitte die Lizenz für die Nutzung im Web beachten.') + ->disk('uploads')->directory('theme/fonts')->visibility('public')->maxSize(2048) + ->acceptedFileTypes(['font/woff2', 'application/font-woff2', 'application/octet-stream']) + ->rule('extensions:woff2')->live()->columnSpanFull(), + Radio::make('radius')->label('Ecken')->options(collect(Theme::RADII)->map(fn ($r) => $r[0])->all())->inline()->required(), + Radio::make('density')->label('Abstände')->options(collect(Theme::DENSITIES)->map(fn ($d) => $d[0])->all())->inline()->required(), + Radio::make('dark_mode')->label('Dunkelmodus')->options(Theme::DARK_MODES)->required()->columnSpanFull(), + ]), + + Tab::make('Anmeldeseite')->icon(Heroicon::OutlinedArrowRightOnRectangle)->columns(2)->schema([ + Radio::make('login_layout')->label('Aufteilung')->options(Theme::LOGIN_LAYOUTS)->required()->columnSpanFull(), + TextInput::make('login_title')->label('Begrüßung')->maxLength(200)->columnSpanFull(), + Textarea::make('login_text')->label('Text darunter')->rows(2)->maxLength(500)->columnSpanFull(), + $image('login_image', 'Hintergrundbild', 'Querformat, mindestens 1600 Pixel breit. Leer = Fläche in der Markenfarbe.') + ->image()->acceptedFileTypes(['image/jpeg', 'image/png', 'image/webp'])->maxSize(8192)->columnSpanFull(), + ]), + + Tab::make('Fußzeile & E-Mails')->icon(Heroicon::OutlinedEnvelope)->schema([ + TextInput::make('footer_text')->label('Text in der Fußzeile')->placeholder('© 2027 Musterstift gGmbH')->maxLength(200), + Repeater::make('footer_links')->label('Links in der Fußzeile')->columns(2)->defaultItems(0)->reorderable() + ->addActionLabel('Link hinzufügen')->maxItems(8) + ->schema([ + TextInput::make('label')->label('Bezeichnung')->required()->maxLength(60)->placeholder('Impressum'), + TextInput::make('url')->label('Adresse')->required()->maxLength(500)->placeholder('https://… oder /seiten/impressum'), + ]), + Textarea::make('email_footer')->label('Fußzeile in E-Mails')->rows(3)->maxLength(500) + ->helperText('Z. B. Anschrift und Hinweis. Logo und Markenfarbe übernehmen die E-Mails automatisch.'), + ]), + + Tab::make('Erweitert')->icon(Heroicon::OutlinedCodeBracket)->schema([ + Textarea::make('custom_css')->label('Eigenes CSS')->rows(12)->maxLength(50000) + ->extraInputAttributes(['class' => 'font-mono text-xs', 'spellcheck' => 'false']) + ->helperText('Für Fortgeschrittene. Wird nach dem Portal-CSS geladen und bei Aktualisierungen unverändert übernommen. Klassennamen können sich mit neuen Versionen ändern – bitte nach jedem Update prüfen. Verfügbare Variablen: --brand, --brand-50 … --brand-950, --radius, --font-body, --font-heading.'), + ]), + ]), + ]); } - public function save(Settings $settings, Branding $branding): void + private function contrastReport(string $primary, ?string $secondary): HtmlString { - $data = $this->form->getState(); - $previousLogo = $branding->logoPath(); - - $settings->setMany([ - 'branding.portal_name' => filled($data['portal_name']) ? trim($data['portal_name']) : null, - 'branding.primary_color' => strtoupper($data['primary_color']), - 'branding.logo_path' => $data['logo_path'] ?: null, - ]); - - if ($previousLogo && $previousLogo !== $data['logo_path']) { - Storage::disk('uploads')->delete($previousLogo); + if (! preg_match('/^#[0-9a-fA-F]{6}$/', $primary)) { + return new HtmlString(''); } - Notification::make() - ->success() - ->title('Erscheinungsbild gespeichert') - ->send(); + $colors = ['ok' => '#15803d', 'info' => '#0369a1', 'warning' => '#b45309']; + $icons = ['ok' => '✓', 'info' => 'i', 'warning' => '!']; + + return new HtmlString(collect(Contrast::report(strtoupper($primary), $secondary && preg_match('/^#[0-9a-fA-F]{6}$/', $secondary) ? strtoupper($secondary) : null)) + ->map(fn ($note) => '

'.$icons[$note['level']].''.e($note['text']).'

') + ->implode('')); + } + + /** + * Entwurf speichern und die Vorschau aktualisieren. + */ + public function save(Theme $theme, Branding $branding): void + { + $theme->saveDraft($this->form->getState()); + session()->put(Branding::PREVIEW_SESSION_KEY, true); + $branding->refresh(); + + $this->dispatch('theme-preview-reload'); + Notification::make()->success()->title('Entwurf gespeichert')->body('Die Vorschau zeigt jetzt den Entwurf. Für alle sichtbar wird er erst mit „Veröffentlichen“.')->send(); + } + + protected function getHeaderActions(): array + { + return [ + Action::make('publish')->label('Veröffentlichen')->icon(Heroicon::OutlinedRocketLaunch) + ->requiresConfirmation() + ->modalHeading('Erscheinungsbild veröffentlichen?') + ->modalDescription('Der gespeicherte Entwurf wird für alle sichtbar. Ungespeicherte Änderungen im Formular werden vorher als Entwurf gespeichert.') + ->action(function (Theme $theme, ThemeCompiler $compiler, Icons $icons, Branding $branding) { + $theme->saveDraft($this->form->getState()); + $theme->publish($compiler, $icons); + session()->forget(Branding::PREVIEW_SESSION_KEY); + $branding->refresh(); + Audit::log('appearance.published'); + + $this->form->fill($theme->working()); + $this->dispatch('theme-preview-reload'); + Notification::make()->success()->title('Erscheinungsbild veröffentlicht')->send(); + }), + Action::make('discard')->label('Entwurf verwerfen')->icon(Heroicon::OutlinedArrowUturnLeft)->color('gray') + ->visible(fn () => $this->hasDraft()) + ->requiresConfirmation() + ->action(function (Theme $theme, Branding $branding) { + $theme->discardDraft(); + session()->forget(Branding::PREVIEW_SESSION_KEY); + $branding->refresh(); + $this->form->fill($theme->working()); + $this->dispatch('theme-preview-reload'); + }), + ActionGroup::make([ + Action::make('export')->label('Exportieren')->icon(Heroicon::OutlinedArrowDownTray) + ->action(fn (ThemeTransfer $transfer): StreamedResponse => response()->streamDownload( + fn () => print (json_encode($transfer->export(app(Theme::class)->working()), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)), + 'erscheinungsbild-'.now()->format('Y-m-d').'.json', + ['Content-Type' => 'application/json'], + )), + Action::make('import')->label('Importieren')->icon(Heroicon::OutlinedArrowUpTray) + ->modalDescription('Erscheinungsbild aus einer exportierten Datei übernehmen – als Entwurf, damit Sie es erst ansehen können.') + ->schema([ + FileUpload::make('file')->label('Datei (.json)')->disk('local')->directory('theme-import') + ->acceptedFileTypes(['application/json', 'text/plain'])->maxSize(20 * 1024)->required(), + ]) + ->action(function (array $data, ThemeTransfer $transfer, Theme $theme) { + try { + $values = $transfer->import((string) Storage::disk('local')->get($data['file'])); + } catch (Throwable $e) { + Notification::make()->danger()->title('Import nicht möglich')->body($e->getMessage())->send(); + + return; + } finally { + Storage::disk('local')->delete($data['file']); + } + + $theme->saveDraft($values); + session()->put(Branding::PREVIEW_SESSION_KEY, true); + $this->form->fill($theme->working()); + $this->dispatch('theme-preview-reload'); + Notification::make()->success()->title('Als Entwurf importiert')->send(); + }), + Action::make('reset')->label('Auf Standard zurücksetzen')->icon(Heroicon::OutlinedArrowPath)->color('danger') + ->requiresConfirmation() + ->modalDescription('Setzt Farben, Schriften, Logos und Texte auf die Standardwerte zurück – als Entwurf. Der Portalname bleibt.') + ->action(function (Theme $theme) { + $theme->resetToDefaults(); + session()->put(Branding::PREVIEW_SESSION_KEY, true); + $this->form->fill($theme->working()); + $this->dispatch('theme-preview-reload'); + }), + ])->label('Mehr')->icon(Heroicon::OutlinedEllipsisVertical)->button()->color('gray'), + ]; } } diff --git a/app/Filament/Pages/DashboardSettings.php b/app/Filament/Pages/DashboardSettings.php new file mode 100644 index 00000000..9213394f --- /dev/null +++ b/app/Filament/Pages/DashboardSettings.php @@ -0,0 +1,108 @@ + ['Ganz oben (volle Breite)', 'Hinweise und Banner über allem.'], + 'hero' => ['Groß links oben', 'Nur die erste sichtbare Kachel wird gezeigt.'], + 'feed' => ['Neben dem großen Bereich', ''], + 'main' => ['Hauptspalte', ''], + 'aside' => ['Seitenleiste (rechts)', ''], + ]; + + /** @var array|null */ + public ?array $data = []; + + public static function canAccess(): bool + { + return auth()->user()?->can('appearance.manage') ?? false; + } + + public function mount(Widgets $widgets): void + { + $this->form->fill(collect(self::AREAS)->mapWithKeys(fn ($info, $area) => [$area => $widgets->forAdmin($area)])->all()); + } + + public function form(Schema $schema): Schema + { + return $schema->statePath('data')->components( + collect(self::AREAS)->map(fn ($info, $area) => Section::make($info[0]) + ->description($info[1] ?: null) + ->visible(fn () => app(Widgets::class)->forAdmin($area) !== []) + ->schema([ + Repeater::make($area) + ->hiddenLabel() + ->reorderable() + ->reorderableWithDragAndDrop() + ->addable(false) + ->deletable(false) + ->itemLabel(fn (array $state) => $state['label'] ?? $state['key']) + ->schema([ + Hidden::make('key'), + Hidden::make('label'), + Toggle::make('visible')->label('Anzeigen'), + ]), + ]))->values()->all() + ); + } + + public function save(Settings $settings): void + { + $layout = []; + + foreach (array_keys(self::AREAS) as $area) { + foreach (array_values($this->data[$area] ?? []) as $index => $item) { + $layout[$item['key']] = ['sort' => $index * 10, 'visible' => (bool) ($item['visible'] ?? true)]; + } + } + + $settings->set('dashboard.layout', $layout); + + Notification::make()->success()->title('Startseite gespeichert')->send(); + } + + protected function getHeaderActions(): array + { + return [ + Action::make('tiles')->label('Eigene Kacheln')->icon(Heroicon::OutlinedRectangleGroup)->color('gray') + ->url(fn () => DashboardTileResource::getUrl()), + Action::make('preview')->label('Startseite ansehen')->icon(Heroicon::OutlinedEye)->color('gray') + ->url('/')->openUrlInNewTab(), + ]; + } +} diff --git a/app/Filament/Pages/Feedback.php b/app/Filament/Pages/Feedback.php new file mode 100644 index 00000000..741ab67a --- /dev/null +++ b/app/Filament/Pages/Feedback.php @@ -0,0 +1,142 @@ +user()?->can('feedback.send') ?? false; + } + + protected static ?string $slug = 'rueckmeldung'; + + public string $type = ''; + + public string $subject = ''; + + public string $body = ''; + + public string $severity = 'normal'; + + public string $email = ''; + + public string $name = ''; + + public ?string $lastReference = null; + + public ?string $notice = null; + + public function mount(FeedbackChannels $channels): void + { + $this->type = (string) array_key_first($channels->available()); + } + + public function submit(FeedbackChannels $channels, FeedbackOutbox $outbox, TechnicalInfo $info): void + { + $available = $channels->available(); + + $this->validate([ + 'type' => ['required', 'in:'.implode(',', array_keys($available))], + 'subject' => ['required', 'string', 'max:255'], + 'body' => ['required', 'string', 'min:10', 'max:20000'], + 'severity' => ['required', 'in:low,normal,high,critical'], + 'email' => ['nullable', 'email', 'max:255'], + 'name' => ['nullable', 'string', 'max:255'], + ], attributes: [ + 'type' => 'Art der Meldung', 'subject' => 'Betreff', 'body' => 'Beschreibung', + 'email' => 'E-Mail-Adresse', 'name' => 'Name', + ]); + + $this->notice = null; + $this->lastReference = null; + + $payload = array_filter([ + 'title' => $this->subject, + 'body' => $this->body, + 'email' => $this->email ?: null, + 'name' => $this->name ?: null, + 'severity' => $this->type === 'bugreport' ? $this->severity : null, + ...$info->collect(), + ], fn ($value) => $value !== null); + + $result = $outbox->submit(auth()->user(), $this->type, $payload); + + switch ($result->status) { + case FeedbackResult::SENT: + Audit::log('feedback.sent', ['type' => $this->type, 'reference' => $result->reference]); + $this->lastReference = $result->reference; + $this->reset(['subject', 'body', 'severity']); + Notification::make()->success()->title('Vielen Dank – Ihre Meldung ist eingegangen')->body("Referenznummer: {$result->reference}")->persistent()->send(); + break; + + case FeedbackResult::RETRY: + $this->reset(['subject', 'body', 'severity']); + $this->notice = 'Der Server ist gerade nicht erreichbar. Ihre Meldung ist gespeichert und wird automatisch gesendet, sobald es wieder geht. Die Referenznummer erscheint dann unten in der Liste.'; + break; + + case FeedbackResult::INVALID: + // Fehler direkt am betroffenen Feld anzeigen (API-Feld „title“ = Formularfeld „subject“). + foreach ($result->errors as $field => $message) { + $field = $field === 'title' ? 'subject' : $field; + $this->addError(in_array($field, ['subject', 'body', 'email', 'name', 'severity'], true) ? $field : 'body', $message); + } + + if ($result->errors === []) { + $this->addError('body', $result->message ?? 'Die Eingabe ist unvollständig.'); + } + break; + + case FeedbackResult::RATE_LIMITED: + $minutes = $result->retryAfter ? max(1, (int) ceil($result->retryAfter / 60)) : null; + $this->notice = 'Es wurden zu viele Meldungen in kurzer Zeit gesendet. Bitte versuchen Sie es '.($minutes ? "in etwa {$minutes} Minute(n)" : 'später').' noch einmal – Ihre Eingabe bleibt erhalten.'; + break; + + case FeedbackResult::DISABLED: + $channels->disable($this->type); + $this->notice = 'Dieser Meldeweg steht nicht mehr zur Verfügung. Ihre Eingabe bleibt erhalten'.(count($channels->available()) ? ' – bitte wählen Sie eine andere Art der Meldung.' : '.'); + $this->type = (string) array_key_first($channels->available()); + break; + } + } + + /** + * @return array + */ + protected function getViewData(): array + { + return [ + 'types' => app(FeedbackChannels::class)->available(), + 'technical' => app(TechnicalInfo::class)->collect(), + 'hasLicense' => app(LicenseStore::class)->hasLicense(), + 'history' => VendorFeedback::query()->where('user_id', auth()->id())->latest()->limit(20)->get(), + ]; + } +} diff --git a/app/Filament/Pages/MailSettingsPage.php b/app/Filament/Pages/MailSettingsPage.php new file mode 100644 index 00000000..05d6316a --- /dev/null +++ b/app/Filament/Pages/MailSettingsPage.php @@ -0,0 +1,109 @@ +|null */ + public ?array $data = []; + + public static function canAccess(): bool + { + return auth()->user()?->can('mail.manage') ?? false; + } + + public function mount(MailSettings $mail): void + { + $this->form->fill([...$mail->values(), 'password' => null]); + } + + public function form(Schema $schema): Schema + { + $smtp = fn (Get $get) => $get('mailer') === 'smtp'; + + return $schema + ->components([ + Section::make('Versand') + ->description('Die Zugangsdaten erhalten Sie von Ihrem Hoster oder Ihrer IT (z. B. Microsoft 365: smtp.office365.com, Port 587, TLS).') + ->columns(2) + ->schema([ + Select::make('mailer')->label('Versandart')->options(MailSettings::MAILERS)->required()->live()->native(false)->columnSpanFull(), + TextInput::make('host')->label('SMTP-Server')->required($smtp)->visible($smtp)->maxLength(255), + TextInput::make('port')->label('Port')->numeric()->required($smtp)->visible($smtp)->minValue(1)->maxValue(65535), + Select::make('encryption')->label('Verschlüsselung')->visible($smtp)->native(false) + ->options(['tls' => 'STARTTLS (meist Port 587)', 'ssl' => 'SSL/TLS (meist Port 465)', 'none' => 'Keine']), + TextInput::make('username')->label('Benutzername')->visible($smtp)->maxLength(255)->autocomplete('off'), + TextInput::make('password')->label('Passwort')->password()->revealable()->visible($smtp)->maxLength(255) + ->helperText('Leer lassen, um das gespeicherte Passwort zu behalten.')->autocomplete('new-password'), + ]), + Section::make('Absender') + ->columns(2) + ->schema([ + TextInput::make('from_address')->label('Absenderadresse')->email()->required()->maxLength(255)->placeholder('intranet@firma.de'), + TextInput::make('from_name')->label('Absendername')->maxLength(100)->placeholder('Name des Portals'), + ]), + ]) + ->statePath('data'); + } + + public function save(MailSettings $mail): void + { + $mail->save($this->form->getState()); + Audit::log('mail.settings_updated'); + + Notification::make()->success()->title('E-Mail-Versand gespeichert')->send(); + } + + protected function getHeaderActions(): array + { + return [ + Action::make('test') + ->label('Test-Mail senden') + ->icon(Heroicon::OutlinedPaperAirplane) + ->color('gray') + ->action(function () { + $to = auth()->user()->email; + + try { + Mail::raw('Diese Test-Mail bestätigt, dass der E-Mail-Versand des Portals funktioniert.', fn ($m) => $m->to($to)->subject('Test-Mail aus dem Portal')); + Notification::make()->success()->title('Test-Mail an '.$to.' gesendet')->send(); + } catch (Throwable $e) { + Notification::make()->danger()->title('Versand fehlgeschlagen')->body($e->getMessage())->persistent()->send(); + } + }), + ]; + } +} diff --git a/app/Filament/Pages/PermissionChecker.php b/app/Filament/Pages/PermissionChecker.php new file mode 100644 index 00000000..6686f24e --- /dev/null +++ b/app/Filament/Pages/PermissionChecker.php @@ -0,0 +1,102 @@ +user()?->can('roles.manage') ?? false; + } + + public function mount(): void + { + $this->userId = request()->integer('person') ?: null; + } + + public function selectUser(int $id): void + { + $this->userId = $id; + $this->search = ''; + } + + /** + * @return array + */ + protected function getViewData(): array + { + $abilities = app(Abilities::class); + $user = $this->userId ? User::query()->find($this->userId) : null; + + $results = strlen($this->search) >= 2 + ? User::query()->where(fn ($q) => $q->where('name', 'like', "%{$this->search}%")->orWhere('email', 'like', "%{$this->search}%"))->orderBy('name')->limit(8)->get() + : collect(); + + $roles = collect(); + $global = collect(); + $objects = collect(); + + if ($user) { + $roles = DB::table('role_user')->join('roles', 'roles.id', '=', 'role_user.role_id') + ->where('role_user.user_id', $user->id) + ->orderBy('roles.name') + ->get(['roles.id', 'roles.name', 'role_user.source', 'role_user.source_ref']); + + $grants = Grant::query()->with('role')->whereIn('role_id', $roles->pluck('id')->unique())->get(); + $types = $abilities->resourceTypes(); + + $global = $grants->whereNull('resource_type')->map(fn (Grant $g) => [ + 'label' => $g->ability === '*' ? 'Alle Rechte (voller Zugriff)' : $abilities->label($g->ability), + 'role' => $g->role->name, + ])->sortBy('label')->values(); + + $objects = $grants->whereNotNull('resource_type')->map(function (Grant $g) use ($abilities, $types) { + $options = isset($types[$g->resource_type]) ? ($types[$g->resource_type]['options'])() : []; + + return [ + 'label' => $abilities->label($g->ability), + 'object' => ($types[$g->resource_type]['label'] ?? $g->resource_type).': '.($g->resource_id === null ? 'alle' : ($options[$g->resource_id] ?? '#'.$g->resource_id)), + 'role' => $g->role->name, + ]; + })->sortBy('label')->values(); + } + + return [ + 'user' => $user, + 'results' => $results, + 'roles' => $roles, + 'global' => $global, + 'objects' => $objects, + 'canAdmin' => $user?->canAccessAdmin() ?? false, + ]; + } +} diff --git a/app/Filament/Pages/Plugins.php b/app/Filament/Pages/Plugins.php new file mode 100644 index 00000000..d1b35528 --- /dev/null +++ b/app/Filament/Pages/Plugins.php @@ -0,0 +1,102 @@ +user()?->can('plugins.manage') ?? false; + } + + public function activate(string $slug, PluginManager $plugins): void + { + $this->run(fn () => $plugins->activate($slug), 'Plugin aktiviert', 'Die Änderungen sind ab dem nächsten Seitenaufruf sichtbar.'); + } + + public function deactivate(string $slug, PluginManager $plugins): void + { + $this->run(fn () => $plugins->deactivate($slug), 'Plugin deaktiviert', 'Die Daten bleiben erhalten und stehen nach erneuter Aktivierung wieder zur Verfügung.'); + } + + public function delete(string $slug, bool $removeData, PluginManager $plugins): void + { + $this->run(fn () => $plugins->delete($slug, $removeData), 'Plugin gelöscht', $removeData ? 'Das Plugin und seine Daten wurden entfernt.' : 'Die Daten des Plugins sind noch in der Datenbank.'); + } + + public function upload(PluginInstaller $installer): void + { + $this->validate(['archive' => ['required', 'file', 'mimes:zip', 'max:51200']], attributes: ['archive' => 'ZIP-Archiv']); + + try { + $manifest = $installer->install($this->archive->getRealPath()); + $this->archive = null; + + Notification::make() + ->success() + ->title("„{$manifest->name}“ {$manifest->version} installiert") + ->body('Das Plugin kann jetzt aktiviert werden.') + ->send(); + } catch (Throwable $e) { + $this->addError('archive', $e->getMessage()); + } + } + + private function run(callable $action, string $title, string $body): void + { + try { + $action(); + Notification::make()->success()->title($title)->body($body)->send(); + $this->redirect(static::getUrl()); + } catch (Throwable $e) { + Notification::make()->danger()->title('Nicht möglich')->body($e->getMessage())->send(); + } + } + + /** + * @return array + */ + protected function getViewData(): array + { + $plugins = app(PluginManager::class); + + return [ + 'plugins' => collect($plugins->all())->map(fn (PluginManifest $m) => [ + 'manifest' => $m, + 'enabled' => $plugins->isEnabled($m->slug), + 'problem' => $plugins->problem($m->slug) ?? (($issues = $m->incompatibilities()) ? implode(', ', $issues) : null), + 'dependents' => $plugins->dependents($m->slug), + ])->sortBy(fn (array $p) => [$p['manifest']->core ? 0 : 1, $p['manifest']->name])->values(), + 'uploadsAllowed' => PluginInstaller::uploadsAllowed(), + ]; + } +} diff --git a/app/Filament/Pages/QuickLinksSettings.php b/app/Filament/Pages/QuickLinksSettings.php index d3b14a6e..d9be1c6f 100644 --- a/app/Filament/Pages/QuickLinksSettings.php +++ b/app/Filament/Pages/QuickLinksSettings.php @@ -28,6 +28,11 @@ class QuickLinksSettings extends Page protected static ?string $title = 'Schnellzugriffe'; + public static function canAccess(): bool + { + return auth()->user()?->can('appearance.manage') ?? false; + } + protected static ?string $slug = 'schnellzugriffe'; /** @var array|null */ diff --git a/app/Filament/Pages/SystemHealth.php b/app/Filament/Pages/SystemHealth.php new file mode 100644 index 00000000..708550f0 --- /dev/null +++ b/app/Filament/Pages/SystemHealth.php @@ -0,0 +1,44 @@ +user()?->can('updates.manage') ?? false; + } + + protected static ?string $slug = 'systemzustand'; + + /** + * @return array + */ + protected function getViewData(): array + { + return [ + 'groups' => app(SiteHealth::class)->all(), + 'cronLine' => '* * * * * cd '.base_path().' && php artisan schedule:run >> /dev/null 2>&1', + 'webCronUrl' => url('/cron/'.app(BackgroundTasks::class)->webCronToken()), + ]; + } +} diff --git a/app/Filament/Pages/Updates.php b/app/Filament/Pages/Updates.php new file mode 100644 index 00000000..2c5b20af --- /dev/null +++ b/app/Filament/Pages/Updates.php @@ -0,0 +1,136 @@ +user()?->can('updates.manage') ?? false; + } + + protected static ?string $slug = 'aktualisierung'; + + public string $licenseEmail = ''; + + public string $licenseKey = ''; + + public ?string $licenseError = null; + + public function mount(LicenseStore $license): void + { + $this->licenseEmail = (string) $license->email(); + } + + public function saveLicense(LicenseStore $license, LicenseService $service): void + { + $this->validate([ + 'licenseEmail' => ['required', 'email', 'max:255'], + 'licenseKey' => [$license->hasLicense() ? 'nullable' : 'required', 'string', 'max:500'], + ], attributes: ['licenseEmail' => 'Lizenz-E-Mail', 'licenseKey' => 'Lizenzschlüssel']); + + $license->setLicense($this->licenseEmail, filled($this->licenseKey) ? $this->licenseKey : (string) $license->key()); + $this->licenseKey = ''; + Audit::log('license.saved', ['email' => $this->licenseEmail]); + + $this->checkLicense($service); + } + + public function checkLicense(LicenseService $service): void + { + $this->licenseError = null; + + try { + $service->check(); + + Notification::make()->success()->title('Lizenz geprüft')->send(); + } catch (ServerError $e) { + $this->licenseError = ServerMessages::for($e); + } catch (Throwable $e) { + $this->licenseError = 'Die Lizenz konnte nicht geprüft werden: '.$e->getMessage(); + } + } + + public function releaseDevice(LicenseService $service, LicenseStore $license): void + { + try { + $service->releaseDevice(); + Audit::log('license.device_released', ['device_label' => $license->deviceLabel()]); + + Notification::make() + ->success() + ->title('Installation abgemeldet') + ->body('Der Geräteplatz ist wieder frei. Updates sind erst nach erneuter Lizenzprüfung wieder möglich.') + ->send(); + } catch (ServerError $e) { + Notification::make()->danger()->title('Abmelden fehlgeschlagen')->body(ServerMessages::for($e))->send(); + } + } + + /** + * @return array + */ + protected function getViewData(): array + { + $version = app(InstalledVersion::class); + $license = app(LicenseStore::class); + $channels = app(Channels::class); + + try { + $migrations = app(Migrations::class)->status(); + } catch (Throwable) { + $migrations = []; + } + + return [ + 'release' => $version->release(), + 'shortSha' => $version->short(), + 'channels' => $channels->all(), + 'activeChannel' => $channels->active(), + 'progress' => app(UpdateProgress::class)->get(), + 'migrations' => $migrations, + 'pendingMigrations' => count(array_filter($migrations, fn (array $m) => ! $m['ran'])), + 'changelog' => app(Changelog::class)->sections(), + 'hasLicense' => $license->hasLicense(), + 'maskedKey' => ($key = $license->key()) ? str_repeat('•', 8).substr($key, -4) : null, + 'licenseSummary' => app(LicenseService::class)->summary(), + 'licenseStatusError' => ($code = $license->lastStatus()['error_code'] ?? null) + ? ServerMessages::for(new ServerError($code, 0, $code)) + : null, + 'deviceLabel' => $license->deviceLabel(), + ]; + } +} diff --git a/app/Filament/Resources/DashboardTiles/DashboardTileResource.php b/app/Filament/Resources/DashboardTiles/DashboardTileResource.php new file mode 100644 index 00000000..91ce484f --- /dev/null +++ b/app/Filament/Resources/DashboardTiles/DashboardTileResource.php @@ -0,0 +1,104 @@ +user()?->can('appearance.manage') ?? false; + } + + public static function form(Schema $schema): Schema + { + $type = fn (string ...$types) => fn (Get $get) => in_array($get('type'), $types, true); + + return $schema->columns(2)->components([ + TextInput::make('name')->label('Name (nur im Admin)')->required()->maxLength(100), + Select::make('type')->label('Art')->options(DashboardTile::TYPES)->default('image')->required()->live()->native(false), + Select::make('area')->label('Bereich')->options(DashboardTile::AREAS)->default('aside')->required()->native(false) + ->helperText('Die Reihenfolge innerhalb des Bereichs legen Sie unter „Startseite“ fest.'), + TextInput::make('title')->label(fn (Get $get) => $get('type') === 'image' ? 'Bildunterschrift (optional)' : 'Überschrift')->maxLength(150), + + FileUpload::make('image_path')->label('Bild')->image()->disk('uploads')->directory('dashboard')->visibility('public') + ->maxSize(8 * 1024)->required($type('image'))->visible($type('image'))->columnSpanFull() + ->helperText('Für die Seitenleiste z. B. 800 × 600 Pixel, für „ganz oben“ ein breites Banner (z. B. 2400 × 500).'), + TextInput::make('alt')->label('Alternativtext')->maxLength(200)->visible($type('image'))->helperText('Beschreibt das Bild für Screenreader.'), + + RichEditor::make('body')->label('Text')->toolbarButtons([['bold', 'italic', 'link'], ['bulletList', 'orderedList'], ['undo', 'redo']]) + ->required($type('text', 'notice'))->visible($type('text', 'notice'))->columnSpanFull(), + Select::make('variant')->label('Farbe')->options(DashboardTile::VARIANTS)->default('brand')->visible($type('notice'))->native(false), + + TextInput::make('url')->label('Link')->placeholder('https://… oder /seiten/…')->maxLength(2000), + Toggle::make('new_tab')->label('In neuem Tab öffnen')->inline(false), + + Section::make('Anzeige')->columnSpanFull()->columns(3)->schema([ + Toggle::make('is_active')->label('Aktiv')->default(true)->inline(false), + DateTimePicker::make('starts_at')->label('Ab')->native(false)->seconds(false)->displayFormat('d.m.Y H:i'), + DateTimePicker::make('ends_at')->label('Bis')->native(false)->seconds(false)->displayFormat('d.m.Y H:i')->after('starts_at'), + ]), + AudienceSection::make('dashboard_tile', 'Wer die Kachel sieht. Leer lassen = alle.')->columnSpanFull(), + ]); + } + + public static function table(Table $table): Table + { + return $table + ->columns([ + ImageColumn::make('image_path')->label('')->disk('uploads')->width(64)->height(40), + TextColumn::make('name')->label('Name')->weight('medium')->searchable(), + TextColumn::make('type')->label('Art')->formatStateUsing(fn (string $state) => DashboardTile::TYPES[$state] ?? $state), + TextColumn::make('area')->label('Bereich')->formatStateUsing(fn (string $state) => DashboardTile::AREAS[$state] ?? $state), + IconColumn::make('is_active')->label('Aktiv')->boolean(), + TextColumn::make('ends_at')->label('Bis')->dateTime('d.m.Y H:i')->placeholder('–'), + ]) + ->recordActions([EditAction::make(), DeleteAction::make()]) + ->emptyStateHeading('Noch keine eigenen Kacheln') + ->emptyStateDescription('Zum Beispiel ein verlinktes Bild in der Seitenleiste oder ein Hinweis ganz oben.'); + } + + public static function getPages(): array + { + return ['index' => ManageDashboardTiles::route('/')]; + } +} diff --git a/app/Filament/Resources/DashboardTiles/Pages/ManageDashboardTiles.php b/app/Filament/Resources/DashboardTiles/Pages/ManageDashboardTiles.php new file mode 100644 index 00000000..11df25ef --- /dev/null +++ b/app/Filament/Resources/DashboardTiles/Pages/ManageDashboardTiles.php @@ -0,0 +1,24 @@ +label('Anordnung der Startseite')->icon(Heroicon::OutlinedSquares2x2)->color('gray') + ->url(fn () => DashboardSettings::getUrl()), + CreateAction::make()->label('Kachel anlegen'), + ]; + } +} diff --git a/app/Filament/Resources/IdentityProviders/IdentityProviderResource.php b/app/Filament/Resources/IdentityProviders/IdentityProviderResource.php new file mode 100644 index 00000000..6aafee32 --- /dev/null +++ b/app/Filament/Resources/IdentityProviders/IdentityProviderResource.php @@ -0,0 +1,269 @@ +user()?->can('identity.manage') ?? false; + } + + public static function form(Schema $schema): Schema + { + $guid = '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i'; + + return $schema + ->columns(1) + ->components([ + Section::make('Microsoft Entra ID') + ->columns(2) + ->schema([ + Hidden::make('type')->default(IdentityProvider::ENTRA), + TextInput::make('name')->label('Bezeichnung')->required()->maxLength(100)->default('Microsoft Entra ID'), + TextInput::make('config.button_label')->label('Text auf dem Anmeldeknopf')->placeholder('Mit Microsoft anmelden')->maxLength(60), + Toggle::make('enabled')->label('Anmeldung aktiv')->helperText('Zeigt „Mit Microsoft anmelden“ auf der Anmeldeseite. Die Anmeldung mit Passwort bleibt für Notfälle erhalten.')->columnSpanFull(), + ]), + + Section::make('App-Registrierung') + ->description('Aus dem Microsoft Entra Admin Center → App-Registrierungen.') + ->columns(2) + ->schema([ + Text::make(fn (?IdentityProvider $record) => new HtmlString( + 'Umleitungs-URI (Typ „Web“): '.e($record ? IdentityLoginController::callbackUrlFor($record) : url('/auth//callback')).'
' + .'API-Berechtigungen (Microsoft Graph): delegiert User.Read, GroupMember.Read.All; ' + .'für den Hintergrund-Abgleich zusätzlich Anwendung User.Read.All, GroupMember.Read.All und Application.Read.All (für App-Rollen) – jeweils mit Administratorzustimmung.' + ))->columnSpanFull(), + TextInput::make('config.tenant_id')->label('Verzeichnis-ID (Mandant)')->required()->regex($guid) + ->validationMessages(['regex' => 'Bitte die Verzeichnis-ID als GUID angeben (nicht den Domainnamen).']), + TextInput::make('config.client_id')->label('Anwendungs-ID (Client)')->required()->regex($guid) + ->validationMessages(['regex' => 'Bitte die Anwendungs-ID als GUID angeben.']), + TextInput::make('config.client_secret')->label('Geheimer Clientschlüssel')->password()->revealable() + ->required(fn (string $operation) => $operation === 'create') + ->helperText(fn (string $operation) => $operation === 'edit' ? 'Leer lassen, um den gespeicherten Schlüssel zu behalten.' : 'Der Wert (nicht die ID) des Geheimnisses.'), + ]), + + Section::make('Konten') + ->columns(2) + ->schema([ + Toggle::make('config.auto_provision')->label('Konto bei erster Anmeldung anlegen')->default(true), + Toggle::make('config.link_by_email')->label('Bestehende Konten über die E-Mail-Adresse verknüpfen')->default(true), + TagsInput::make('config.allowed_domains')->label('Erlaubte E-Mail-Domains')->placeholder('firma.de') + ->helperText('Leer = alle Konten des Mandanten.'), + Select::make('config.default_role_id')->label('Standardrolle für alle') + ->options(fn () => Role::query()->where('slug', '!=', Role::ADMINISTRATION)->orderBy('name')->pluck('name', 'id')->all()) + ->helperText('z. B. „Mitarbeitende“ – erhält jede Person, die sich über Entra anmeldet.'), + ]), + + Section::make('Profil') + ->key('profile') + ->description('Jedes Microsoft-Graph-Attribut lässt sich einem Profilfeld zuordnen – auch Personalnummer, Kostenstelle, lokale Erweiterungsattribute oder eigene Verzeichniserweiterungen. Zugeordnete Felder sind im Portal schreibgeschützt. Eigene Felder legen Sie unter „Profilfelder“ an.') + ->afterHeader([ + Action::make('loadExtensions')->label('Erweiterungsattribute laden')->icon(Heroicon::OutlinedArrowPath) + ->color('gray')->size('sm') + ->visible(fn (string $operation) => $operation === 'edit') + ->action(function (IdentityProvider $record) { + try { + $names = app(MappingTester::class)->loadExtensionProperties($record); + Notification::make()->success()->title(count($names).' Verzeichniserweiterungen gefunden') + ->body($names === [] ? 'Im Mandanten sind keine Erweiterungen für Benutzer registriert.' : 'Sie stehen jetzt in der Attributauswahl zur Verfügung.') + ->send(); + } catch (Throwable $e) { + Notification::make()->danger()->title('Erweiterungen konnten nicht geladen werden') + ->body($e->getMessage().' Benötigt die Anwendungsberechtigung Directory.Read.All.')->send(); + } + }), + ]) + ->schema([ + Repeater::make('config.attribute_map') + ->hiddenLabel() + ->columns(3) + ->addActionLabel('Zuordnung hinzufügen') + ->reorderable(false) + ->default(fn () => collect(EntraAttributes::DEFAULT_MAP)->map(fn ($attribute, $target) => ['target' => $target, 'attribute' => $attribute])->values()->all()) + ->itemLabel(fn (array $state) => static::profileTargets()[$state['target'] ?? ''] ?? null) + ->collapsible(false) + ->schema([ + Select::make('target')->label('Profilfeld')->required()->native(false) + ->options(fn () => static::profileTargets()) + ->disableOptionsWhenSelectedInSiblingRepeaterItems(), + Select::make('suggestion')->label('Attribut auswählen')->placeholder('Aus der Liste übernehmen …')->searchable()->native(false) + ->options(fn (?IdentityProvider $record) => collect(EntraAttributes::suggestions($record)) + ->mapWithKeys(fn ($label, $path) => [$path => $label.' · '.$path])->all()) + ->live() + ->afterStateUpdated(fn (?string $state, Set $set) => $state ? $set('attribute', $state) : null) + ->dehydrated(false), + TextInput::make('attribute')->label('Graph-Attribut')->required()->maxLength(191) + ->regex(EntraAttributes::PATH_PATTERN) + ->validationMessages(['regex' => 'Attributname oder Pfad mit Punkten, z. B. employeeOrgData.costCenter.']) + ->datalist(fn (?IdentityProvider $record) => array_keys(EntraAttributes::suggestions($record))) + ->placeholder('z. B. employeeId'), + ]), + Text::make('Pfade mit Punkt lesen verschachtelte Werte (employeeOrgData.costCenter, businessPhones.0). Listen werden mit Komma verbunden. Manche Attribute brauchen zusätzliche Berechtigungen, z. B. employeeHireDate die Berechtigung User-LifeCycleInfo.Read.All.'), + Toggle::make('config.sync_manager')->label('Vorgesetzte*n aus Entra übernehmen')->default(true), + Toggle::make('config.sync_photo')->label('Profilfoto aus Entra übernehmen')->default(true), + ]), + + Section::make('Hintergrund-Abgleich') + ->description('Übernimmt Änderungen und deaktiviert Konten, die in Entra deaktiviert oder gelöscht wurden – auch ohne Anmeldung. Läuft alle 15 Minuten mit den Hintergrundaufgaben.') + ->columns(2) + ->schema([ + Toggle::make('config.directory_sync')->label('Abgleich aktiv')->live(), + Toggle::make('config.directory_create_users')->label('Alle Konten vorab anlegen') + ->helperText('Sonst werden Konten erst bei der ersten Anmeldung angelegt.') + ->visible(fn (Get $get) => (bool) $get('config.directory_sync')), + Text::make(fn (?IdentityProvider $record) => static::syncStatus($record))->columnSpanFull() + ->visible(fn (?IdentityProvider $record, Get $get) => $record && $get('config.directory_sync')), + ]), + + Section::make('Gruppen und App-Rollen → Rollen') + ->description('Personen in diesen Entra-Gruppen bzw. mit diesen App-Rollen erhalten die Rolle im Portal. Rollen sind additiv; manuell vergebene Rollen bleiben unberührt. Mehrere Zeilen je Gruppe für mehrere Rollen.') + ->schema([ + Repeater::make('mappings') + ->relationship() + ->hiddenLabel() + ->columns(4) + ->defaultItems(0) + ->addActionLabel('Zuordnung hinzufügen') + ->schema([ + Select::make('kind')->label('Art')->options([IdpGroupMapping::GROUP => 'Gruppe', IdpGroupMapping::APP_ROLE => 'App-Rolle']) + ->default(IdpGroupMapping::GROUP)->required()->live(), + Select::make('group_lookup')->label('Gruppe suchen') + ->searchable() + ->visible(fn (Get $get) => $get('kind') === IdpGroupMapping::GROUP) + ->getSearchResultsUsing(function (string $search, $livewire) { + try { + return app(MappingTester::class)->searchGroups($livewire->getRecord(), $search); + } catch (Throwable) { + return []; + } + }) + ->getOptionLabelUsing(fn (?string $value) => $value) + ->live() + ->afterStateUpdated(function (?string $state, Set $set, $component) { + if ($state) { + $set('external_id', $state); + $set('external_name', trim(preg_replace('/\s*\([0-9a-f]{8}…\)$/', '', (string) $component->getOptionLabel()))); + } + }) + ->helperText('Erfordert den Hintergrund-Abgleich (Anwendungsberechtigung).') + ->dehydrated(false), + TextInput::make('external_id') + ->label(fn (Get $get) => $get('kind') === IdpGroupMapping::APP_ROLE ? 'Wert der App-Rolle' : 'Objekt-ID der Gruppe') + ->required()->maxLength(191), + TextInput::make('external_name')->label('Bezeichnung')->maxLength(191), + Select::make('role_id')->label('Rolle im Portal')->required() + ->options(fn () => Role::query()->orderBy('name')->pluck('name', 'id')->all()), + ]) + ->visible(fn (string $operation) => $operation === 'edit'), + Text::make('Zuordnungen lassen sich nach dem ersten Speichern pflegen.')->visible(fn (string $operation) => $operation === 'create'), + ]), + ]); + } + + /** + * @return array Zielfeld => Bezeichnung + */ + public static function profileTargets(): array + { + return IdentityProvider::PROFILE_TARGETS + + collect(app(ProfileFields::class)->options())->mapWithKeys(fn ($label, $key) => ['custom.'.$key => $label.' (Profilfeld)'])->all(); + } + + public static function syncStatus(?IdentityProvider $record): HtmlString + { + if (! $record) { + return new HtmlString(''); + } + + $status = app(EntraDirectorySync::class)->status($record); + $when = fn (?int $ts) => $ts ? Carbon::createFromTimestamp($ts)->locale('de')->diffForHumans() : 'noch nie'; + + return new HtmlString( + 'Letzter Lauf: '.e($when($status['last_run_at'] ?? null)) + .' · Benutzer vollständig abgeglichen: '.e($when($status['users_synced_at'] ?? null)) + .' · Gruppen: '.e($when($status['groups_synced_at'] ?? null)) + .(! empty($status['last_error']) ? '
Fehler: '.e($status['last_error']).'' : '') + ); + } + + public static function table(Table $table): Table + { + return $table + ->columns([ + TextColumn::make('name')->label('Bezeichnung')->weight('medium'), + TextColumn::make('type')->label('Typ')->formatStateUsing(fn () => 'Microsoft Entra ID'), + IconColumn::make('enabled')->label('Aktiv')->boolean(), + TextColumn::make('mappings_count')->label('Zuordnungen')->counts('mappings'), + TextColumn::make('identities_count')->label('Verknüpfte Konten')->counts('identities'), + ]) + ->recordActions([ + Action::make('test')->label('Mapping testen')->icon(Heroicon::OutlinedBeaker) + ->url(fn (IdentityProvider $record) => static::getUrl('test', ['record' => $record])), + EditAction::make(), + ]); + } + + public static function getPages(): array + { + return [ + 'index' => ListIdentityProviders::route('/'), + 'create' => CreateIdentityProvider::route('/neu'), + 'edit' => EditIdentityProvider::route('/{record}/bearbeiten'), + 'test' => TestMapping::route('/{record}/testen'), + ]; + } +} diff --git a/app/Filament/Resources/IdentityProviders/Pages/CreateIdentityProvider.php b/app/Filament/Resources/IdentityProviders/Pages/CreateIdentityProvider.php new file mode 100644 index 00000000..83a5c3d2 --- /dev/null +++ b/app/Filament/Resources/IdentityProviders/Pages/CreateIdentityProvider.php @@ -0,0 +1,30 @@ + $this->record->name]); + } + + protected function getRedirectUrl(): string + { + return IdentityProviderResource::getUrl('edit', ['record' => $this->record]); + } +} diff --git a/app/Filament/Resources/IdentityProviders/Pages/EditIdentityProvider.php b/app/Filament/Resources/IdentityProviders/Pages/EditIdentityProvider.php new file mode 100644 index 00000000..1319ab4f --- /dev/null +++ b/app/Filament/Resources/IdentityProviders/Pages/EditIdentityProvider.php @@ -0,0 +1,63 @@ +record->attributeMap()) + ->map(fn ($attribute, $target) => ['target' => $target, 'attribute' => $attribute])->values()->all(); + $data['config']['sync_manager'] = $this->record->syncsManager(); + } + + return $data; + } + + /** + * Leeres Geheimnis = gespeichertes behalten. + */ + protected function mutateFormDataBeforeSave(array $data): array + { + if (blank($data['config']['client_secret'] ?? null)) { + $data['config']['client_secret'] = $this->record->setting('client_secret'); + } + + // Geladene Erweiterungen liegen nur in der Datenbank, nicht im Formular. + $data['config']['extension_properties'] = $this->record->fresh()?->setting('extension_properties', []) ?? []; + $data['config']['attribute_map'] = array_values((array) ($data['config']['attribute_map'] ?? [])); + unset($data['config']['synced_fields']); + + return $data; + } + + protected function afterSave(): void + { + Audit::log('identity.provider_updated', ['provider' => $this->record->name, 'enabled' => $this->record->enabled]); + } + + protected function getHeaderActions(): array + { + return [ + Action::make('test')->label('Mapping testen')->icon(Heroicon::OutlinedBeaker)->color('gray') + ->url(fn () => IdentityProviderResource::getUrl('test', ['record' => $this->record])), + DeleteAction::make()->modalDescription('Verknüpfungen und Rollen aus Entra-Gruppen werden entfernt. Die Konten selbst bleiben bestehen.'), + ]; + } +} diff --git a/app/Filament/Resources/IdentityProviders/Pages/ListIdentityProviders.php b/app/Filament/Resources/IdentityProviders/Pages/ListIdentityProviders.php new file mode 100644 index 00000000..d2426bdd --- /dev/null +++ b/app/Filament/Resources/IdentityProviders/Pages/ListIdentityProviders.php @@ -0,0 +1,17 @@ +label('Microsoft Entra ID anbinden')]; + } +} diff --git a/app/Filament/Resources/IdentityProviders/Pages/TestMapping.php b/app/Filament/Resources/IdentityProviders/Pages/TestMapping.php new file mode 100644 index 00000000..c34be9ac --- /dev/null +++ b/app/Filament/Resources/IdentityProviders/Pages/TestMapping.php @@ -0,0 +1,49 @@ +|null */ + public ?array $result = null; + + public ?string $error = null; + + public function mount(int|string $record): void + { + $this->record = $this->resolveRecord($record); + } + + public function test(MappingTester $tester): void + { + $this->validate(['person' => ['required', 'string', 'max:255']], attributes: ['person' => 'E-Mail-Adresse']); + $this->result = null; + $this->error = null; + + try { + $this->result = $tester->test($this->record, trim($this->person)); + } catch (Throwable $e) { + $this->error = $e->getMessage(); + } + } +} diff --git a/app/Filament/Resources/NewsPosts/Pages/EditNewsPost.php b/app/Filament/Resources/NewsPosts/Pages/EditNewsPost.php deleted file mode 100644 index 40b1336b..00000000 --- a/app/Filament/Resources/NewsPosts/Pages/EditNewsPost.php +++ /dev/null @@ -1,19 +0,0 @@ -label('Profilfeld anlegen'), + ]; + } +} diff --git a/app/Filament/Resources/ProfileFields/ProfileFieldResource.php b/app/Filament/Resources/ProfileFields/ProfileFieldResource.php new file mode 100644 index 00000000..28ebbef1 --- /dev/null +++ b/app/Filament/Resources/ProfileFields/ProfileFieldResource.php @@ -0,0 +1,96 @@ +user()?->can('users.manage') ?? false; + } + + public static function form(Schema $schema): Schema + { + return $schema + ->columns(2) + ->components([ + TextInput::make('label')->label('Bezeichnung')->required()->maxLength(100), + TextInput::make('key')->label('Technischer Schlüssel') + ->helperText('Wird aus der Bezeichnung erzeugt, wenn leer. Nachträglich nicht änderbar.') + ->regex('/^[a-z][a-z0-9_]*$/') + ->validationMessages(['regex' => 'Nur Kleinbuchstaben, Ziffern und Unterstriche, beginnend mit einem Buchstaben.']) + ->maxLength(60) + ->unique(ignoreRecord: true) + ->disabledOn('edit'), + Select::make('type')->label('Typ')->options(ProfileField::TYPES)->default('text')->required()->native(false), + Select::make('visibility')->label('Sichtbarkeit')->options(ProfileField::VISIBILITIES)->default('public')->required()->native(false), + Toggle::make('editable')->label('Von der Person selbst pflegbar')->default(true) + ->helperText('Aus Entra ID übernommene Felder sind unabhängig davon schreibgeschützt.'), + TextInput::make('sort')->label('Reihenfolge')->numeric()->default(0)->minValue(0), + TextInput::make('help')->label('Hinweis im Profilformular')->maxLength(255)->columnSpanFull(), + ]); + } + + public static function table(Table $table): Table + { + return $table + ->defaultSort('sort') + ->reorderable('sort') + ->columns([ + TextColumn::make('label')->label('Bezeichnung')->weight('medium'), + TextColumn::make('key')->label('Schlüssel')->fontFamily('mono')->color('gray'), + TextColumn::make('type')->label('Typ')->formatStateUsing(fn (string $state) => ProfileField::TYPES[$state] ?? $state), + TextColumn::make('visibility')->label('Sichtbarkeit')->badge() + ->formatStateUsing(fn (string $state) => $state === 'public' ? 'Alle' : 'Eingeschränkt') + ->color(fn (string $state) => $state === 'public' ? 'gray' : 'warning'), + IconColumn::make('editable')->label('Selbst pflegbar')->boolean(), + ]) + ->recordActions([ + EditAction::make(), + DeleteAction::make()->modalDescription('Die gespeicherten Werte bleiben erhalten, werden aber nicht mehr angezeigt.'), + ]) + ->emptyStateHeading('Noch keine Profilfelder') + ->emptyStateDescription('Zum Beispiel Personalnummer, Kostenstelle oder Eintrittsdatum – selbst gepflegt oder aus Entra ID übernommen.'); + } + + public static function getPages(): array + { + return [ + 'index' => ManageProfileFields::route('/'), + ]; + } +} diff --git a/app/Filament/Resources/Roles/Pages/CreateRole.php b/app/Filament/Resources/Roles/Pages/CreateRole.php new file mode 100644 index 00000000..b957070c --- /dev/null +++ b/app/Filament/Resources/Roles/Pages/CreateRole.php @@ -0,0 +1,17 @@ + $this->record->name]); + } +} diff --git a/app/Filament/Resources/Roles/Pages/EditRole.php b/app/Filament/Resources/Roles/Pages/EditRole.php new file mode 100644 index 00000000..1f4cee6d --- /dev/null +++ b/app/Filament/Resources/Roles/Pages/EditRole.php @@ -0,0 +1,30 @@ + $this->record->name, + 'grants' => $this->record->grants()->get(['ability', 'resource_type', 'resource_id'])->toArray(), + ]); + } + + protected function getHeaderActions(): array + { + return [ + DeleteAction::make()->visible(fn () => ! $this->record->is_system), + ]; + } +} diff --git a/app/Filament/Resources/Roles/Pages/ListRoles.php b/app/Filament/Resources/Roles/Pages/ListRoles.php new file mode 100644 index 00000000..0991f2af --- /dev/null +++ b/app/Filament/Resources/Roles/Pages/ListRoles.php @@ -0,0 +1,22 @@ +label('Rechte prüfen')->color('gray')->url(PermissionChecker::getUrl()), + CreateAction::make()->label('Neue Rolle'), + ]; + } +} diff --git a/app/Filament/Resources/Roles/RoleResource.php b/app/Filament/Resources/Roles/RoleResource.php new file mode 100644 index 00000000..d1cbfb24 --- /dev/null +++ b/app/Filament/Resources/Roles/RoleResource.php @@ -0,0 +1,217 @@ +columns(1) + ->components([ + Section::make('Rolle') + ->columns(2) + ->schema([ + TextInput::make('name')->label('Name')->required()->maxLength(100)->disabled(fn (?Role $record) => $record?->is_system), + Textarea::make('description')->label('Beschreibung')->rows(2)->maxLength(500), + ]), + + Section::make('Globale Rechte') + ->description('Gelten im ganzen Portal.') + ->visible(fn (?Role $record) => ! $record?->isAdministration()) + ->schema([ + CheckboxList::make('global_abilities') + ->hiddenLabel() + ->columns(2) + ->options(fn () => collect($abilities->global())->map(fn (array $a) => $a['label'])->all()) + ->descriptions(fn () => collect($abilities->global())->map(fn (array $a) => $a['group'])->all()) + ->bulkToggleable() + ->afterStateHydrated(fn (CheckboxList $component, ?Role $record) => $component->state( + $record?->grants()->whereNull('resource_type')->pluck('ability')->all() ?? [] + )) + ->saveRelationshipsUsing(function (Role $record, ?array $state) { + $record->grants()->whereNull('resource_type')->where('ability', '!=', '*')->delete(); + + foreach (array_unique($state ?? []) as $ability) { + $record->grants()->create(['ability' => $ability]); + } + }) + ->dehydrated(false), + ]), + + Section::make('Rechte für einzelne Objekte') + ->description('Zum Beispiel: Beiträge schreiben nur in der Kategorie „MAV-Info“.') + ->visible(fn (?Role $record) => ! $record?->isAdministration() && $abilities->resourceTypes() !== []) + ->schema([ + Repeater::make('object_grants') + ->hiddenLabel() + ->columns(3) + ->addActionLabel('Recht hinzufügen') + ->defaultItems(0) + ->schema([ + Select::make('ability') + ->label('Recht') + ->required() + ->live() + ->options(fn () => collect($abilities->all()) + ->filter(fn (array $a) => $a['resource'] !== null) + ->map(fn (array $a) => $a['group'].': '.$a['label']) + ->all()), + Select::make('resource_ids') + ->label('Für') + ->multiple() + ->required() + ->options(function (Get $get) use ($abilities) { + $type = $abilities->all()[$get('ability')]['resource'] ?? null; + $options = $type ? ($abilities->resourceTypes()[$type]['options'])() : []; + + return ['*' => 'Alle'] + $options; + }), + Toggle::make('include_children') + ->label('Inkl. Unterseiten') + ->inline(false) + ->default(true) + ->visible(fn (Get $get) => $abilities->isHierarchical($abilities->all()[$get('ability')]['resource'] ?? null)), + ]) + ->afterStateHydrated(fn (Repeater $component, ?Role $record) => $component->state( + $record?->grants()->whereNotNull('resource_type')->get() + ->groupBy(fn (Grant $g) => $g->ability.'|'.(int) $g->include_children) + ->map(fn ($grants) => [ + 'ability' => $grants->first()->ability, + 'resource_ids' => $grants->map(fn (Grant $g) => $g->resource_id === null ? '*' : (string) $g->resource_id)->values()->all(), + 'include_children' => (bool) $grants->first()->include_children, + ])->values()->all() ?? [] + )) + ->saveRelationshipsUsing(function (Role $record, ?array $state) use ($abilities) { + $record->grants()->whereNotNull('resource_type')->delete(); + + foreach ($state ?? [] as $item) { + $type = $abilities->all()[$item['ability'] ?? '']['resource'] ?? null; + + if (! $type) { + continue; + } + + $ids = in_array('*', (array) $item['resource_ids'], true) ? [null] : array_map('intval', (array) $item['resource_ids']); + + $inherit = $abilities->isHierarchical($type) && ($item['include_children'] ?? false); + + foreach (array_unique($ids) as $id) { + $record->grants()->create(['ability' => $item['ability'], 'resource_type' => $type, 'resource_id' => $id, 'include_children' => $inherit && $id !== null]); + } + } + }) + ->dehydrated(false), + ]), + + Section::make('Mitglieder') + ->description('Manuell zugewiesene Personen. Personen aus Identity-Provider-Gruppen kommen automatisch dazu.') + ->schema([ + Select::make('members') + ->hiddenLabel() + ->multiple() + ->searchable() + ->getSearchResultsUsing(fn (string $search) => User::query() + ->where(fn ($q) => $q->where('name', 'like', "%{$search}%")->orWhere('email', 'like', "%{$search}%")) + ->orderBy('name')->limit(50)->pluck('name', 'id')->all()) + ->getOptionLabelsUsing(fn (array $values) => User::query()->whereIn('id', $values)->pluck('name', 'id')->all()) + ->afterStateHydrated(fn (Select $component, ?Role $record) => $component->state( + $record?->users()->wherePivot('source', 'manual')->pluck('users.id')->all() ?? [] + )) + ->rule(fn (?Role $record) => function (string $attribute, mixed $value, \Closure $fail) use ($record) { + if ($record?->isAdministration() && ! in_array(auth()->id(), array_map('intval', (array) $value), true)) { + $fail('Sie können sich nicht selbst aus der Rolle „Administration“ entfernen.'); + } + }) + ->saveRelationshipsUsing(function (Role $record, ?array $state) { + $ids = array_map('intval', $state ?? []); + $current = $record->users()->wherePivot('source', 'manual')->pluck('users.id')->all(); + + foreach (array_diff($current, $ids) as $userId) { + $record->users()->wherePivot('source', 'manual')->detach($userId); + } + + foreach (array_diff($ids, $current) as $userId) { + $record->users()->attach($userId, ['source' => 'manual', 'created_at' => now()]); + } + + Permissions::flush(); + }) + ->dehydrated(false), + ]), + ]); + } + + public static function table(Table $table): Table + { + return $table + ->defaultSort('name') + ->modifyQueryUsing(fn ($query) => $query->withCount(['users', 'grants'])) + ->columns([ + TextColumn::make('name')->label('Name')->searchable()->weight('medium') + ->description(fn (Role $record) => $record->description), + IconColumn::make('is_system')->label('System')->boolean()->trueIcon(Heroicon::LockClosed)->falseIcon(false), + TextColumn::make('users_count')->label('Mitglieder'), + TextColumn::make('grants_count')->label('Rechte') + ->formatStateUsing(fn (Role $record, $state) => $record->isAdministration() ? 'alle' : $state), + ]) + ->recordActions([ + EditAction::make(), + DeleteAction::make()->visible(fn (Role $record) => ! $record->is_system), + ]); + } + + public static function getPages(): array + { + return [ + 'index' => ListRoles::route('/'), + 'create' => CreateRole::route('/neu'), + 'edit' => EditRole::route('/{record}/bearbeiten'), + ]; + } +} diff --git a/app/Filament/Resources/Users/Schemas/UserForm.php b/app/Filament/Resources/Users/Schemas/UserForm.php index 73bb6ad8..025f4cd4 100644 --- a/app/Filament/Resources/Users/Schemas/UserForm.php +++ b/app/Filament/Resources/Users/Schemas/UserForm.php @@ -2,10 +2,16 @@ namespace App\Filament\Resources\Users\Schemas; +use App\Models\ProfileField; +use App\Models\Role; use App\Models\User; +use App\Support\ProfileFields; +use Filament\Forms\Components\DatePicker; +use Filament\Forms\Components\Select; use Filament\Forms\Components\Textarea; use Filament\Forms\Components\TextInput; use Filament\Forms\Components\Toggle; +use Filament\Schemas\Components\Component; use Filament\Schemas\Components\Section; use Filament\Schemas\Schema; use Illuminate\Validation\Rules\Password; @@ -14,6 +20,30 @@ class UserForm { public const PHONE_REGEX = '/^[0-9+()\/\-.\s]{3,50}$/'; + /** + * Eingabefelder für die frei definierten Profilfelder. + * + * @return list + */ + private static function customFields(): array + { + return app(ProfileFields::class)->all()->map(function (ProfileField $field) { + $name = 'custom_fields.'.$field->key; + $hint = $field->visibility === 'restricted' ? 'Nur für die Person und die Personalverwaltung sichtbar.' : null; + + $component = match ($field->type) { + 'textarea' => Textarea::make($name)->rows(3)->maxLength(5000)->columnSpanFull(), + 'date' => DatePicker::make($name)->native(false)->displayFormat('d.m.Y'), + 'email' => TextInput::make($name)->email()->maxLength(255), + 'url' => TextInput::make($name)->url()->maxLength(500), + 'phone' => TextInput::make($name)->tel()->telRegex(self::PHONE_REGEX)->maxLength(50), + default => TextInput::make($name)->maxLength(255), + }; + + return $component->label($field->label)->helperText($hint); + })->values()->all(); + } + public static function configure(Schema $schema): Schema { return $schema @@ -47,10 +77,26 @@ class UserForm ->label('Aktiv') ->helperText('Deaktivierte Konten können sich nicht anmelden und erscheinen nicht im Portal.') ->default(true), - Toggle::make('is_admin') - ->label('Administrator') - ->helperText('Zugriff auf diesen Admin-Bereich. Wird später durch Rollen ersetzt.') - ->disabled(fn (?User $record) => $record?->is(auth()->user()) ?? false), + Select::make('manual_roles') + ->label('Rollen') + ->helperText('Rollen sind additiv. Rollen aus Identity-Provider-Gruppen werden automatisch vergeben.') + ->multiple() + ->preload() + ->options(fn () => Role::query()->orderByDesc('is_system')->orderBy('name')->pluck('name', 'id')->all()) + ->afterStateHydrated(function (Select $component, ?User $record) { + $component->state($record?->roles()->wherePivot('source', 'manual')->pluck('roles.id')->all() ?? []); + }) + ->rule(function (?User $record) { + // Die eigene Administrationsrolle kann man sich nicht selbst entziehen. + return function (string $attribute, mixed $value, \Closure $fail) use ($record) { + if ($record?->is(auth()->user()) && $record->hasRole(Role::ADMINISTRATION) + && ! in_array(Role::administration()->id, array_map('intval', (array) $value), true)) { + $fail('Die eigene Rolle „Administration“ kann nicht entfernt werden.'); + } + }; + }) + ->saveRelationshipsUsing(fn (User $record, ?array $state) => $record->syncManualRoles(array_map('intval', $state ?? []))) + ->dehydrated(false), TextInput::make('password') ->label(fn (string $operation) => $operation === 'create' ? 'Passwort' : 'Neues Passwort') ->helperText(fn (string $operation) => $operation === 'create' @@ -61,6 +107,11 @@ class UserForm ->rule(Password::default()) ->dehydrated(fn (?string $state) => filled($state)), ]), + Section::make('Weitere Angaben') + ->columnSpan(2) + ->columns(2) + ->schema(fn () => self::customFields()) + ->visible(fn () => app(ProfileFields::class)->all()->isNotEmpty()), ]); } } diff --git a/app/Filament/Resources/Users/Tables/UsersTable.php b/app/Filament/Resources/Users/Tables/UsersTable.php index cee98272..4f6b893a 100644 --- a/app/Filament/Resources/Users/Tables/UsersTable.php +++ b/app/Filament/Resources/Users/Tables/UsersTable.php @@ -28,7 +28,7 @@ class UsersTable TextColumn::make('job_title')->label('Funktion')->toggleable(), TextColumn::make('department')->label('Abteilung')->sortable()->toggleable(), TextColumn::make('location')->label('Standort')->sortable()->toggleable(isToggledHiddenByDefault: true), - IconColumn::make('is_admin')->label('Admin')->boolean(), + TextColumn::make('roles.name')->label('Rollen')->badge()->color('gray'), IconColumn::make('is_active')->label('Aktiv')->boolean(), TextColumn::make('last_login_at') ->label('Letzte Anmeldung') @@ -38,7 +38,7 @@ class UsersTable ]) ->filters([ TernaryFilter::make('is_active')->label('Aktiv'), - TernaryFilter::make('is_admin')->label('Administrator'), + SelectFilter::make('roles')->label('Rolle')->relationship('roles', 'name'), SelectFilter::make('department') ->label('Abteilung') ->options(fn () => User::query()->whereNotNull('department')->distinct()->orderBy('department')->pluck('department', 'department')->all()), diff --git a/app/Filament/Resources/Users/UserResource.php b/app/Filament/Resources/Users/UserResource.php index 7d29f388..8b2c8e6a 100644 --- a/app/Filament/Resources/Users/UserResource.php +++ b/app/Filament/Resources/Users/UserResource.php @@ -13,6 +13,7 @@ use Filament\Resources\Resource; use Filament\Schemas\Schema; use Filament\Support\Icons\Heroicon; use Filament\Tables\Table; +use Illuminate\Database\Eloquent\Builder; class UserResource extends Resource { @@ -20,6 +21,10 @@ class UserResource extends Resource protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedUsers; + protected static string|\UnitEnum|null $navigationGroup = 'Benutzer & Rechte'; + + protected static ?int $navigationSort = 1; + protected static ?string $modelLabel = 'Benutzer'; protected static ?string $pluralModelLabel = 'Benutzer'; @@ -28,6 +33,11 @@ class UserResource extends Resource protected static ?string $recordTitleAttribute = 'name'; + public static function getEloquentQuery(): Builder + { + return parent::getEloquentQuery()->with('roles'); + } + public static function form(Schema $schema): Schema { return UserForm::configure($schema); diff --git a/app/Http/Controllers/Admin/UpdateController.php b/app/Http/Controllers/Admin/UpdateController.php new file mode 100644 index 00000000..c80f7781 --- /dev/null +++ b/app/Http/Controllers/Admin/UpdateController.php @@ -0,0 +1,97 @@ +json(['ok' => true, 'result' => $check->run()]); + } catch (ServerError $e) { + return $this->serverError($e); + } + } + + public function install(Request $request, Updater $updater, UpdateProgress $progress): JsonResponse + { + if ($progress->isRunning()) { + return response()->json(['ok' => false, 'message' => 'Es läuft bereits eine Aktualisierung.'], 409); + } + + // Der Ablauf läuft serverseitig zu Ende, auch wenn der Browser die Verbindung trennt. + @set_time_limit(0); + @ignore_user_abort(true); + + try { + $result = $updater->installUpdate($request->user()?->id); + + return response()->json(['ok' => true, 'result' => $result]); + } catch (ServerError $e) { + return $this->serverError($e); + } catch (Throwable $e) { + return response()->json(['ok' => false, 'message' => $e->getMessage()], 500); + } + } + + public function progress(UpdateProgress $progress): JsonResponse + { + return response()->json($progress->get()); + } + + public function channel(Request $request, Channels $channels): JsonResponse + { + $validated = $request->validate([ + 'channel' => ['required', 'string', Rule::in(array_keys($channels->all()))], + ]); + + $channels->setActive($validated['channel']); + Audit::log('update.channel_changed', ['channel' => $validated['channel']]); + + return response()->json(['ok' => true, 'channel' => $validated['channel']]); + } + + public function migrations(Migrations $migrations): JsonResponse + { + @set_time_limit(0); + + try { + $count = $migrations->run(); + @file_put_contents(storage_path('.migrations-fingerprint'), $migrations->fingerprint()); + Audit::log('update.migrations', ['migrations' => $count]); + + return response()->json(['ok' => true, 'count' => $count, 'status' => $migrations->status()]); + } catch (Throwable $e) { + Audit::log('update.migrations_failed', ['error' => $e->getMessage()]); + + return response()->json(['ok' => false, 'message' => 'Migrationen fehlgeschlagen: '.$e->getMessage()], 500); + } + } + + private function serverError(ServerError $e): JsonResponse + { + return response()->json([ + 'ok' => false, + 'code' => $e->errorCode, + 'message' => ServerMessages::for($e), + 'license_input' => $e->needsLicenseInput(), + ], 200); + } +} diff --git a/app/Http/Controllers/AppearanceController.php b/app/Http/Controllers/AppearanceController.php new file mode 100644 index 00000000..f7ceef73 --- /dev/null +++ b/app/Http/Controllers/AppearanceController.php @@ -0,0 +1,86 @@ +get('icons') ?? []) + ->reject(fn ($path, $size) => (int) $size < 192) + ->map(fn ($path, $size) => ['src' => $branding->url($path), 'sizes' => "{$size}x{$size}", 'type' => 'image/png', 'purpose' => 'any']) + ->values(); + + if ($icons->isEmpty()) { + $icons = collect([['src' => $branding->faviconUrl(), 'sizes' => 'any', 'type' => 'image/svg+xml']]); + } + + return response()->json([ + 'name' => $branding->portalName(), + 'short_name' => mb_substr($branding->portalName(), 0, 12), + 'start_url' => '/', + 'scope' => '/', + 'display' => 'standalone', + 'lang' => 'de', + 'theme_color' => $branding->primaryColor(), + 'background_color' => '#F4F5F7', + 'icons' => $icons->all(), + ], 200, ['Content-Type' => 'application/manifest+json', 'Cache-Control' => 'public, max-age=3600']); + } + + /** + * Anmeldeseite im aktuellen Entwurf – für die Vorschau (Formular ohne Funktion). + */ + public function loginPreview(Request $request): Response + { + return Inertia::render('Auth/Login', [ + 'canResetPassword' => true, + 'providers' => IdentityProvider::query()->where('enabled', true)->get() + ->map(fn (IdentityProvider $p) => ['slug' => $p->slug, 'type' => $p->type, 'label' => $p->buttonLabel()])->values(), + 'preview' => true, + ]); + } + + /** + * Beispielseite mit Boxen, Tabs, Akkordeon, Tabelle und Schaltflächen. + */ + public function sample(Request $request, Content $content): Response + { + $text = fn (string $html) => ['type' => 'text', 'data' => ['html' => $html]]; + $box = fn (string $variant, string $title, string $html) => ['type' => 'box', 'data' => ['variant' => $variant, 'title' => $title, 'show_icon' => true], 'items' => [['blocks' => [$text($html)]]]]; + + $blocks = [ + ['type' => 'heading', 'data' => ['text' => 'Überschrift der Seite', 'level' => '2']], + $text('

Fließtext mit einem Link in der Akzentfarbe, Hervorhebungen und einer Liste:

  • erster Punkt
  • zweiter Punkt
'), + ['type' => 'columns', 'data' => ['layout' => '1-1'], 'items' => [ + ['blocks' => [$box('info', 'Info', '

Sprechstunde dienstags 14–16 Uhr.

'), $box('warning', 'Warnung', '

Bitte bis Freitag einreichen.

')]], + ['blocks' => [$box('success', 'Erfolg', '

Das neue Verfahren gilt ab sofort.

'), $box('highlight', 'Hervorgehoben', '

In der Markenfarbe.

')]], + ]], + ['type' => 'tabs', 'items' => [ + ['title' => 'Erster Tab', 'blocks' => [$text('

Inhalt des ersten Tabs.

')]], + ['title' => 'Zweiter Tab', 'blocks' => [$text('

Inhalt des zweiten Tabs.

')]], + ]], + ['type' => 'accordion', 'data' => ['first_open' => true], 'items' => [ + ['title' => 'Häufige Frage', 'blocks' => [$text('

Die Antwort steht hier.

')]], + ['title' => 'Noch eine Frage', 'blocks' => [$text('

Noch eine Antwort.

')]], + ]], + ['type' => 'table', 'data' => ['header' => true, 'rows' => [['Bereich', 'Ansprechpartner', 'Durchwahl'], ['Personal', 'A. Beispiel', '123'], ['IT', 'B. Muster', '456']]]], + ['type' => 'buttons', 'data' => ['buttons' => [['label' => 'Primäre Schaltfläche', 'url' => '#', 'variant' => 'primary'], ['label' => 'Umrandet', 'url' => '#', 'variant' => 'outline']]]], + ]; + + return Inertia::render('Appearance/Sample', [ + 'content' => $content->render($content->sanitize(['blocks' => $blocks]), $request->user()), + ]); + } +} diff --git a/app/Http/Controllers/Auth/IdentityLoginController.php b/app/Http/Controllers/Auth/IdentityLoginController.php new file mode 100644 index 00000000..0387dc0b --- /dev/null +++ b/app/Http/Controllers/Auth/IdentityLoginController.php @@ -0,0 +1,83 @@ +enabled && $provider->type === IdentityProvider::ENTRA, 404); + + $start = $login->start($provider, $this->callbackUrl($provider)); + $request->session()->put('identity_login', $start['session']); + + return redirect()->away($start['url']); + } + + public function callback(IdentityProvider $provider, EntraLogin $login, Request $request): RedirectResponse + { + abort_unless($provider->enabled && $provider->type === IdentityProvider::ENTRA, 404); + + $session = $request->session()->pull('identity_login'); + + if ($request->filled('error')) { + // z. B. Abbruch durch die Person oder fehlende Zustimmung in Entra + Log::notice('Entra-Anmeldung abgebrochen: '.$request->string('error').' '.$request->string('error_description')); + + return $this->fail($request->string('error')->toString() === 'access_denied' + ? 'Die Anmeldung wurde abgebrochen.' + : 'Microsoft hat die Anmeldung abgelehnt. Bitte wenden Sie sich an die Administration.'); + } + + if (! is_array($session) || ! hash_equals($session['state'] ?? '', (string) $request->query('state')) || ($session['provider'] ?? null) !== (string) $provider->id) { + return $this->fail('Die Anmeldung ist abgelaufen. Bitte erneut versuchen.'); + } + + try { + $user = $login->complete($provider, (string) $request->query('code'), $this->callbackUrl($provider), $session); + } catch (IdentityException $e) { + return $this->fail($e->getMessage()); + } catch (Throwable $e) { + report($e); + + return $this->fail('Die Anmeldung über Microsoft ist fehlgeschlagen. Bitte später erneut versuchen.'); + } + + Auth::login($user, remember: true); + $request->session()->regenerate(); + $user->forceFill(['last_login_at' => now()])->saveQuietly(); + Audit::log('identity.login', ['provider' => $provider->name], $user->id); + + return redirect()->intended('/'); + } + + public static function callbackUrlFor(IdentityProvider $provider): string + { + return url('/auth/'.$provider->slug.'/callback'); + } + + private function callbackUrl(IdentityProvider $provider): string + { + return self::callbackUrlFor($provider); + } + + private function fail(string $message): RedirectResponse + { + return redirect('/login')->with('identity_error', $message); + } +} diff --git a/app/Http/Controllers/CronController.php b/app/Http/Controllers/CronController.php new file mode 100644 index 00000000..e134a597 --- /dev/null +++ b/app/Http/Controllers/CronController.php @@ -0,0 +1,23 @@ +webCronToken(), $token), 404); + + @ignore_user_abort(true); + $tasks->run('webcron'); + + return response()->noContent(); + } +} diff --git a/app/Http/Controllers/DashboardController.php b/app/Http/Controllers/DashboardController.php index 856efc96..e3384283 100644 --- a/app/Http/Controllers/DashboardController.php +++ b/app/Http/Controllers/DashboardController.php @@ -2,59 +2,17 @@ namespace App\Http\Controllers; -use App\Http\Resources\EventResource; -use App\Http\Resources\NewsPostResource; -use App\Http\Resources\PersonResource; -use App\Models\Event; -use App\Models\NewsPost; -use App\Models\User; -use App\Support\QuickLinks; +use App\Dashboard\Widgets; use Illuminate\Http\Request; use Inertia\Inertia; use Inertia\Response; class DashboardController extends Controller { - public function __invoke(Request $request, QuickLinks $quickLinks): Response + public function __invoke(Request $request, Widgets $widgets): Response { - $user = $request->user(); - - // Hervorgehobene Beiträge für den Slider; ohne Hervorhebung die neuesten mit Bild. - $featured = NewsPost::query()->published()->with('category') - ->where('is_featured', true)->whereNotNull('cover_path') - ->latest('published_at')->limit(5)->get(); - - if ($featured->isEmpty()) { - $featured = NewsPost::query()->published()->with('category') - ->whereNotNull('cover_path')->latest('published_at')->limit(3)->get(); - } - - $recent = NewsPost::query()->published()->with('category') - ->whereKeyNot($featured->modelKeys()) - ->latest('published_at')->limit(8)->get(); - return Inertia::render('Dashboard', [ - 'profile' => [ - 'job_title' => $user->job_title, - 'department' => $user->department, - 'location' => $user->location, - 'avatar_url' => $user->avatarUrl(256), - ], - 'quickLinks' => $quickLinks->all(), - 'featuredNews' => NewsPostResource::collection($featured), - 'latestNews' => NewsPostResource::collection($recent->take(4)->values()), - 'moreNews' => NewsPostResource::collection($recent->slice(4)->values()), - 'upcomingEvents' => EventResource::collection(Event::query()->upcoming()->limit(4)->get()), - 'newColleagues' => PersonResource::collection( - User::query() - ->active() - ->whereKeyNot($user->getKey()) - ->where('created_at', '>=', now()->subDays(90)) - ->latest() - ->limit(6) - ->get() - ), - 'peopleCount' => User::query()->active()->count(), + 'widgets' => $widgets->resolve($request->user(), $request), ]); } } diff --git a/app/Http/Controllers/EditorialController.php b/app/Http/Controllers/EditorialController.php new file mode 100644 index 00000000..49bcf98c --- /dev/null +++ b/app/Http/Controllers/EditorialController.php @@ -0,0 +1,20 @@ +visibleFor($request->user()), 403); + + return Inertia::render('Editorial/Index', [ + 'sections' => $editorial->resolve($request->user()), + ]); + } +} diff --git a/app/Http/Controllers/InstallController.php b/app/Http/Controllers/InstallController.php new file mode 100644 index 00000000..e946abcc --- /dev/null +++ b/app/Http/Controllers/InstallController.php @@ -0,0 +1,162 @@ +requirements(); + + return view('install.requirements', [ + 'checks' => $checks, + 'canContinue' => collect($checks)->doesntContain('status', SiteHealth::ERROR) && is_file(app()->environmentFilePath()), + 'envWritable' => is_file(app()->environmentFilePath()) && is_writable(app()->environmentFilePath()), + ]); + } + + public function database(): View + { + return view('install.database', [ + 'values' => [ + 'host' => config('database.connections.mysql.host', 'localhost'), + 'port' => config('database.connections.mysql.port', 3306), + 'database' => config('database.connections.mysql.database'), + 'username' => config('database.connections.mysql.username'), + ], + ]); + } + + public function saveDatabase(Request $request): RedirectResponse + { + $data = $request->validate([ + 'host' => ['required', 'string', 'max:255'], + 'port' => ['required', 'integer', 'between:1,65535'], + 'database' => ['required', 'string', 'max:64'], + 'username' => ['required', 'string', 'max:255'], + 'password' => ['nullable', 'string', 'max:255'], + ], attributes: ['host' => 'Server', 'port' => 'Port', 'database' => 'Datenbank', 'username' => 'Benutzer', 'password' => 'Passwort']); + + try { + $pdo = new PDO( + "mysql:host={$data['host']};port={$data['port']};dbname={$data['database']};charset=utf8mb4", + $data['username'], + $data['password'] ?? '', + [PDO::ATTR_TIMEOUT => 5, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION], + ); + $version = (string) $pdo->query('select version()')->fetchColumn(); + } catch (Throwable $e) { + return back()->withInput($request->except('password')) + ->withErrors(['host' => 'Verbindung fehlgeschlagen: '.$this->pdoMessage($e->getMessage())]); + } + + $mariadb = str_contains(strtolower($version), 'mariadb'); + $number = preg_replace('/^(\d+\.\d+\.\d+).*$/', '$1', $version); + + if (! version_compare($number, $mariadb ? '10.6.0' : '8.0.0', '>=')) { + return back()->withInput($request->except('password')) + ->withErrors(['host' => ($mariadb ? 'MariaDB ' : 'MySQL ').$number.' wird nicht unterstützt. Benötigt wird MySQL ab 8.0 oder MariaDB ab 10.6.']); + } + + EnvFile::set(app()->environmentFilePath(), [ + 'APP_URL' => $request->getSchemeAndHttpHost().$request->getBaseUrl(), + 'DB_CONNECTION' => 'mysql', + 'DB_HOST' => $data['host'], + 'DB_PORT' => (string) $data['port'], + 'DB_DATABASE' => $data['database'], + 'DB_USERNAME' => $data['username'], + 'DB_PASSWORD' => $data['password'] ?? '', + ]); + + return redirect('/install/konto'); + } + + public function account(): View|RedirectResponse + { + return view('install.account'); + } + + public function saveAccount(Request $request, Settings $settings, LicenseStore $license, Migrations $migrations): RedirectResponse + { + $data = $request->validate([ + 'portal_name' => ['required', 'string', 'max:60'], + 'first_name' => ['required', 'string', 'max:100'], + 'last_name' => ['required', 'string', 'max:100'], + 'email' => ['required', 'email', 'max:255'], + 'password' => ['required', 'confirmed', Password::min(10)->letters()->numbers()], + 'license_email' => ['nullable', 'email', 'max:255', 'required_with:license_key'], + 'license_key' => ['nullable', 'string', 'max:500', 'required_with:license_email'], + ], attributes: [ + 'portal_name' => 'Name des Portals', 'first_name' => 'Vorname', 'last_name' => 'Nachname', + 'email' => 'E-Mail-Adresse', 'password' => 'Passwort', + 'license_email' => 'Lizenz-E-Mail', 'license_key' => 'Lizenzschlüssel', + ]); + + @set_time_limit(300); + + try { + Artisan::call('migrate', ['--force' => true]); + } catch (Throwable $e) { + return back()->withInput($request->except('password', 'password_confirmation', 'license_key')) + ->withErrors(['portal_name' => 'Die Datenbank konnte nicht eingerichtet werden: '.$e->getMessage()]); + } + + $admin = User::query()->updateOrCreate(['email' => strtolower($data['email'])], [ + 'first_name' => $data['first_name'], + 'last_name' => $data['last_name'], + 'password' => $data['password'], + 'is_active' => true, + ]); + + $admin->syncManualRoles([Role::administration()->id]); + $settings->set('branding.portal_name', $data['portal_name']); + + if (filled($data['license_email'] ?? null)) { + $license->setLicense($data['license_email'], $data['license_key']); + } + + $license->deviceId(); + file_put_contents(storage_path('.migrations-fingerprint'), $migrations->fingerprint()); + Installation::markInstalled(); + Audit::log('install.completed', ['portal_name' => $data['portal_name']], $admin->id); + + // Kein Flash: Ab jetzt liegen die Sitzungen in der Datenbank, die bisherige Sitzung ist weg. + return redirect('/login?eingerichtet=1'); + } + + private function pdoMessage(string $message): string + { + return match (true) { + str_contains($message, 'Access denied') => 'Benutzername oder Passwort sind falsch, oder der Benutzer hat keinen Zugriff auf diese Datenbank.', + str_contains($message, 'Unknown database') => 'Die Datenbank existiert nicht. Bitte zuerst beim Hoster anlegen.', + str_contains($message, 'getaddrinfo'), str_contains($message, 'Connection refused'), str_contains($message, 'timed out') => 'Der Datenbankserver ist nicht erreichbar. Bitte Server und Port prüfen.', + default => $message, + }; + } +} diff --git a/app/Http/Controllers/NotificationController.php b/app/Http/Controllers/NotificationController.php new file mode 100644 index 00000000..193bc533 --- /dev/null +++ b/app/Http/Controllers/NotificationController.php @@ -0,0 +1,50 @@ +user()->notifications()->limit(20)->get(); + + return response()->json([ + 'notifications' => $notifications->map(fn (DatabaseNotification $n) => [ + 'id' => $n->id, + 'title' => (string) ($n->data['title'] ?? ''), + 'body' => (string) ($n->data['body'] ?? ''), + 'icon' => (string) ($n->data['icon'] ?? 'bell'), + 'has_url' => filled($n->data['url'] ?? null), + 'read' => $n->read_at !== null, + 'created_at' => $n->created_at?->toIso8601String(), + ]), + 'unread' => $request->user()->unreadNotifications()->count(), + ]); + } + + public function open(Request $request, string $id): RedirectResponse + { + $notification = $request->user()->notifications()->whereKey($id)->firstOrFail(); + $notification->markAsRead(); + $url = (string) ($notification->data['url'] ?? ''); + + // Nur Adressen innerhalb des Portals ansteuern. + return redirect()->to($url !== '' && (Str::startsWith($url, '/') && ! Str::startsWith($url, '//') || Str::startsWith($url, url('/'))) ? $url : '/'); + } + + public function markAllRead(Request $request): JsonResponse + { + $request->user()->unreadNotifications()->update(['read_at' => now()]); + + return response()->json(['unread' => 0]); + } +} diff --git a/app/Http/Controllers/PeopleController.php b/app/Http/Controllers/PeopleController.php index 3cd85b7f..bf742df3 100644 --- a/app/Http/Controllers/PeopleController.php +++ b/app/Http/Controllers/PeopleController.php @@ -4,7 +4,9 @@ namespace App\Http\Controllers; use App\Http\Resources\PersonResource; use App\Models\User; +use App\Support\ProfileFields; use Illuminate\Database\Eloquent\Builder; +use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; use Inertia\Inertia; @@ -54,9 +56,34 @@ class PeopleController extends Controller ]); } + /** + * Personenauswahl in Formularen (z. B. Block „Ansprechpartner“): Suche oder Abruf per ID. + */ + public function search(Request $request): JsonResponse + { + $data = $request->validate([ + 'q' => ['nullable', 'string', 'max:100'], + 'ids' => ['nullable', 'array', 'max:50'], + 'ids.*' => ['integer'], + ]); + + $search = trim($data['q'] ?? ''); + $like = '%'.str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $search).'%'; + + $people = User::query()->active() + ->when(isset($data['ids']), fn (Builder $q) => $q->whereIn('id', $data['ids'])) + ->when(! isset($data['ids']), fn (Builder $q) => $q->where(fn (Builder $q) => $q->where('name', 'like', $like)->orWhere('email', 'like', $like))) + ->orderBy('name') + ->limit(20) + ->get(); + + return response()->json(['people' => PersonResource::collection($people)->resolve()]); + } + public function show(User $user): Response { abort_unless($user->is_active, 404); + $user->load('manager'); return Inertia::render('Profile/Show', [ 'person' => [ @@ -70,7 +97,16 @@ class PeopleController extends Controller 'phone' => $user->phone, 'mobile' => $user->mobile, 'about' => $user->about, + 'fields' => app(ProfileFields::class)->visibleValues($user, auth()->user()), 'avatar_url' => $user->avatarUrl(256), + 'manager' => $user->manager?->is_active ? [ + 'id' => $user->manager->id, + 'name' => $user->manager->name, + 'initials' => $user->manager->initials, + 'job_title' => $user->manager->job_title, + 'avatar_url' => $user->manager->avatarUrl(96), + ] : null, + 'reports' => PersonResource::collection($user->reports()->active()->orderBy('name')->limit(12)->get())->resolve(), ], 'isOwnProfile' => $user->is(auth()->user()), ]); diff --git a/app/Http/Controllers/ProfileController.php b/app/Http/Controllers/ProfileController.php index 47d23b49..50036fe4 100644 --- a/app/Http/Controllers/ProfileController.php +++ b/app/Http/Controllers/ProfileController.php @@ -4,7 +4,9 @@ namespace App\Http\Controllers; use App\Http\Requests\UpdateProfileRequest; use App\Models\User; +use App\Profile\ProfileSections; use App\Support\Avatars; +use App\Support\ProfileFields; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Validation\Rule; @@ -19,9 +21,10 @@ class ProfileController extends Controller return to_route('people.show', $request->user()); } - public function edit(Request $request): Response + public function edit(Request $request, ProfileFields $profileFields): Response { $user = $request->user(); + $managed = $user->managedFields(); return Inertia::render('Profile/Edit', [ 'profile' => [ @@ -34,12 +37,22 @@ class ProfileController extends Controller 'avatar_url' => $user->avatarUrl(256), 'has_password' => $user->password !== null, ], + // Felder, die Microsoft Entra ID pflegt – im Portal nur lesbar. + 'managed' => $managed, + 'customFields' => $profileFields->formFor($user, $managed), + 'sections' => app(ProfileSections::class)->resolve($user), ]); } - public function update(UpdateProfileRequest $request): RedirectResponse + public function update(UpdateProfileRequest $request, ProfileFields $profileFields): RedirectResponse { - $request->user()->update($request->validated()); + $user = $request->user(); + $managed = $user->managedFields(); + $user->update(collect($request->validated())->except([...$managed, 'custom_fields'])->all()); + + if ($request->has('custom_fields')) { + $profileFields->mergeUserInput($user, (array) $request->validated('custom_fields', []), $managed); + } return back()->with('status', 'profile-updated'); } diff --git a/app/Http/Middleware/EnsureNotInMaintenance.php b/app/Http/Middleware/EnsureNotInMaintenance.php new file mode 100644 index 00000000..d3140f73 --- /dev/null +++ b/app/Http/Middleware/EnsureNotInMaintenance.php @@ -0,0 +1,35 @@ +maintenance->isActive() || $request->is(...self::EXCEPT)) { + return $next($request); + } + + $retryAfter = $this->maintenance->retryAfter(); + + if ($request->expectsJson() || $request->header('X-Inertia')) { + return response()->json(['message' => 'Das Portal wird gerade aktualisiert.'], 503, ['Retry-After' => $retryAfter]); + } + + return response()->view('maintenance', ['retryAfter' => $retryAfter], 503, ['Retry-After' => $retryAfter]); + } +} diff --git a/app/Http/Middleware/HandleInertiaRequests.php b/app/Http/Middleware/HandleInertiaRequests.php index 17114485..7cb20982 100644 --- a/app/Http/Middleware/HandleInertiaRequests.php +++ b/app/Http/Middleware/HandleInertiaRequests.php @@ -35,12 +35,14 @@ class HandleInertiaRequests extends Middleware 'job_title' => $user->job_title, 'avatar_url' => $user->avatarUrl(96), 'theme' => $user->theme, - 'is_admin' => $user->is_admin, + 'can_admin' => $user->canAccessAdmin(), ] : null, ], - 'navigation' => fn () => $user ? $this->navigation->items($request) : [], + 'navigation' => fn () => $user ? $this->navigation->items($request, $user) : [], + 'notifications' => fn () => $user ? ['unread' => $user->unreadNotifications()->count()] : null, 'flash' => [ 'status' => fn () => $request->session()->get('status'), + 'form_submitted' => fn () => $request->session()->get('form_submitted'), ], ]; } diff --git a/app/Http/Middleware/RedirectToInstaller.php b/app/Http/Middleware/RedirectToInstaller.php new file mode 100644 index 00000000..af19b9e3 --- /dev/null +++ b/app/Http/Middleware/RedirectToInstaller.php @@ -0,0 +1,23 @@ +is('install', 'install/*', 'up')) { + return redirect('/install'); + } + + return $next($request); + } +} diff --git a/app/Http/Middleware/RunPendingMigrations.php b/app/Http/Middleware/RunPendingMigrations.php new file mode 100644 index 00000000..3d030c3b --- /dev/null +++ b/app/Http/Middleware/RunPendingMigrations.php @@ -0,0 +1,72 @@ +runningUnitTests() || ! Installation::isInstalled()) { + return $next($request); + } + + $stored = @file_get_contents(storage_path('.migrations-fingerprint')); + + try { + $current = $this->migrations->fingerprint(); + + if ($stored !== $current) { + $this->migrateWithLock($current); + } + } catch (Throwable $e) { + Log::error('Automatische Migration fehlgeschlagen: '.$e->getMessage(), ['exception' => $e]); + } + + return $next($request); + } + + private function migrateWithLock(string $fingerprint): void + { + $lock = @fopen(storage_path('.migrate.lock'), 'c'); + + if ($lock === false || ! flock($lock, LOCK_EX | LOCK_NB)) { + return; // Läuft gerade in einer anderen Anfrage. + } + + try { + // Nach dem Warten auf die Sperre erneut prüfen – vielleicht war jemand schneller. + if (@file_get_contents(storage_path('.migrations-fingerprint')) === $fingerprint) { + return; + } + + @set_time_limit(300); + $count = $this->migrations->run(); + file_put_contents(storage_path('.migrations-fingerprint'), $fingerprint); + + if ($count > 0) { + Log::info("Automatische Migration: {$count} Migration(en) ausgeführt."); + } + } finally { + flock($lock, LOCK_UN); + fclose($lock); + } + } +} diff --git a/app/Http/Middleware/RunPseudoCron.php b/app/Http/Middleware/RunPseudoCron.php new file mode 100644 index 00000000..8b3fd235 --- /dev/null +++ b/app/Http/Middleware/RunPseudoCron.php @@ -0,0 +1,33 @@ +runningUnitTests() || ! Installation::isInstalled() || ! $this->tasks->pseudoCronDue()) { + return; + } + + $this->tasks->run('pseudo'); + } +} diff --git a/app/Http/Middleware/ThemePreview.php b/app/Http/Middleware/ThemePreview.php new file mode 100644 index 00000000..d9a81cd2 --- /dev/null +++ b/app/Http/Middleware/ThemePreview.php @@ -0,0 +1,32 @@ +query('vorschau'); + + if ($value !== null && $request->hasSession()) { + if ($value === 'entwurf' && $request->user()?->can('appearance.manage')) { + $request->session()->put(Branding::PREVIEW_SESSION_KEY, true); + } elseif ($value === 'aus') { + $request->session()->forget(Branding::PREVIEW_SESSION_KEY); + } + } + + app(Branding::class)->refresh(); + + return $next($request); + } +} diff --git a/app/Http/Requests/UpdateProfileRequest.php b/app/Http/Requests/UpdateProfileRequest.php index fef53ab3..5e56d08a 100644 --- a/app/Http/Requests/UpdateProfileRequest.php +++ b/app/Http/Requests/UpdateProfileRequest.php @@ -2,6 +2,7 @@ namespace App\Http\Requests; +use App\Support\ProfileFields; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; @@ -12,11 +13,13 @@ class UpdateProfileRequest extends FormRequest */ public function rules(): array { + $managed = $this->user()->managedFields(); + return [ - 'first_name' => ['required', 'string', 'max:100'], - 'last_name' => ['required', 'string', 'max:100'], + 'first_name' => [in_array('first_name', $managed, true) ? 'nullable' : 'required', 'string', 'max:100'], + 'last_name' => [in_array('last_name', $managed, true) ? 'nullable' : 'required', 'string', 'max:100'], 'email' => [ - 'required', 'string', 'lowercase', 'email', 'max:255', + in_array('email', $managed, true) ? 'nullable' : 'required', 'string', 'lowercase', 'email', 'max:255', Rule::unique('users')->ignore($this->user()->id), ], 'job_title' => ['nullable', 'string', 'max:150'], @@ -25,6 +28,8 @@ class UpdateProfileRequest extends FormRequest 'phone' => ['nullable', 'string', 'max:50'], 'mobile' => ['nullable', 'string', 'max:50'], 'about' => ['nullable', 'string', 'max:2000'], + 'custom_fields' => ['nullable', 'array'], + ...app(ProfileFields::class)->rules(), ]; } @@ -43,6 +48,7 @@ class UpdateProfileRequest extends FormRequest 'phone' => 'Telefon', 'mobile' => 'Mobil', 'about' => 'Über mich', + ...app(ProfileFields::class)->all()->mapWithKeys(fn ($field) => ['custom_fields.'.$field->key => $field->label])->all(), ]; } } diff --git a/app/Identity/Entra/EntraAttributes.php b/app/Identity/Entra/EntraAttributes.php new file mode 100644 index 00000000..a4f5570a --- /dev/null +++ b/app/Identity/Entra/EntraAttributes.php @@ -0,0 +1,141 @@ +_personalnummer“. + */ +final class EntraAttributes +{ + /** Wird immer abgefragt – für Kontoanlage, Verknüpfung und Offboarding. */ + public const BASE_SELECT = ['id', 'displayName', 'givenName', 'surname', 'mail', 'userPrincipalName', 'accountEnabled', 'userType']; + + /** Standardzuordnung Profilfeld => Attribut (entspricht dem bisherigen Verhalten). */ + public const DEFAULT_MAP = [ + 'first_name' => 'givenName', + 'last_name' => 'surname', + 'email' => 'mail', + 'job_title' => 'jobTitle', + 'department' => 'department', + 'location' => 'officeLocation', + 'phone' => 'businessPhones.0', + 'mobile' => 'mobilePhone', + ]; + + /** Häufige Attribute als Vorschläge im Formular. */ + public const COMMON = [ + 'givenName' => 'Vorname', + 'surname' => 'Nachname', + 'displayName' => 'Anzeigename', + 'mail' => 'E-Mail-Adresse', + 'userPrincipalName' => 'Benutzerprinzipalname', + 'jobTitle' => 'Position', + 'department' => 'Abteilung', + 'companyName' => 'Firmenname', + 'officeLocation' => 'Büro', + 'businessPhones.0' => 'Telefon (geschäftlich)', + 'mobilePhone' => 'Mobiltelefon', + 'faxNumber' => 'Fax', + 'streetAddress' => 'Straße', + 'postalCode' => 'Postleitzahl', + 'city' => 'Ort', + 'state' => 'Bundesland', + 'country' => 'Land', + 'usageLocation' => 'Nutzungsstandort', + 'preferredLanguage' => 'Bevorzugte Sprache', + 'employeeId' => 'Personalnummer', + 'employeeType' => 'Mitarbeitertyp', + 'employeeHireDate' => 'Eintrittsdatum', + 'employeeLeaveDateTime' => 'Austrittsdatum', + 'employeeOrgData.costCenter' => 'Kostenstelle', + 'employeeOrgData.division' => 'Bereich', + 'otherMails' => 'Weitere E-Mail-Adressen', + 'proxyAddresses' => 'Proxyadressen', + 'onPremisesSamAccountName' => 'Anmeldename (lokal)', + 'onPremisesDistinguishedName' => 'Distinguished Name (lokal)', + 'onPremisesExtensionAttributes.extensionAttribute1' => 'Erweiterungsattribut 1 (lokal)', + 'onPremisesExtensionAttributes.extensionAttribute2' => 'Erweiterungsattribut 2 (lokal)', + 'onPremisesExtensionAttributes.extensionAttribute3' => 'Erweiterungsattribut 3 (lokal)', + 'onPremisesExtensionAttributes.extensionAttribute4' => 'Erweiterungsattribut 4 (lokal)', + 'onPremisesExtensionAttributes.extensionAttribute5' => 'Erweiterungsattribut 5 (lokal)', + 'onPremisesExtensionAttributes.extensionAttribute6' => 'Erweiterungsattribut 6 (lokal)', + 'onPremisesExtensionAttributes.extensionAttribute7' => 'Erweiterungsattribut 7 (lokal)', + 'onPremisesExtensionAttributes.extensionAttribute8' => 'Erweiterungsattribut 8 (lokal)', + 'onPremisesExtensionAttributes.extensionAttribute9' => 'Erweiterungsattribut 9 (lokal)', + 'onPremisesExtensionAttributes.extensionAttribute10' => 'Erweiterungsattribut 10 (lokal)', + 'onPremisesExtensionAttributes.extensionAttribute11' => 'Erweiterungsattribut 11 (lokal)', + 'onPremisesExtensionAttributes.extensionAttribute12' => 'Erweiterungsattribut 12 (lokal)', + 'onPremisesExtensionAttributes.extensionAttribute13' => 'Erweiterungsattribut 13 (lokal)', + 'onPremisesExtensionAttributes.extensionAttribute14' => 'Erweiterungsattribut 14 (lokal)', + 'onPremisesExtensionAttributes.extensionAttribute15' => 'Erweiterungsattribut 15 (lokal)', + ]; + + /** Erlaubte Schreibweise eines Attributpfads. */ + public const PATH_PATTERN = '/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)*$/'; + + /** + * $select für /me, /users/{id} und /users/delta. + */ + public static function select(IdentityProvider $provider): string + { + $top = array_map(fn (string $path) => self::topLevel($path), array_values($provider->attributeMap())); + + return implode(',', array_values(array_unique([...self::BASE_SELECT, ...$top]))); + } + + public static function topLevel(string $path): string + { + return explode('.', $path, 2)[0]; + } + + /** + * Wert eines Attributpfads als Text. Listen werden mit Komma verbunden, + * Wahrheitswerte als „Ja“/„Nein“ ausgegeben; leere Werte ergeben null. + * + * @param array $graphUser + */ + public static function value(array $graphUser, string $path): ?string + { + $value = $graphUser; + + foreach (explode('.', $path) as $segment) { + if (! is_array($value) || ! array_key_exists($segment, $value)) { + return null; + } + + $value = $value[$segment]; + } + + if (is_array($value)) { + $value = implode(', ', array_filter(Arr::flatten($value), fn ($v) => is_scalar($v) && $v !== '')); + } elseif (is_bool($value)) { + $value = $value ? 'Ja' : 'Nein'; + } + + $value = is_scalar($value) ? trim((string) $value) : ''; + + return $value === '' ? null : $value; + } + + /** + * Vorschlagsliste fürs Formular: häufige Attribute plus geladene Verzeichniserweiterungen. + * + * @return array Pfad => Beschreibung + */ + public static function suggestions(?IdentityProvider $provider): array + { + $extensions = collect((array) $provider?->setting('extension_properties', [])) + ->mapWithKeys(fn ($name) => [(string) $name => 'Verzeichniserweiterung']) + ->all(); + + return self::COMMON + $extensions; + } +} diff --git a/app/Identity/Entra/EntraClient.php b/app/Identity/Entra/EntraClient.php new file mode 100644 index 00000000..176b7fd3 --- /dev/null +++ b/app/Identity/Entra/EntraClient.php @@ -0,0 +1,185 @@ +provider->setting('tenant_id'); + } + + public function clientId(): string + { + return (string) $this->provider->setting('client_id'); + } + + public function issuer(): string + { + return self::LOGIN_URL.'/'.$this->tenant().'/v2.0'; + } + + /** + * @param array{state: string, nonce: string, code_challenge: string} $security + */ + public function authorizationUrl(string $redirectUri, array $security): string + { + return self::LOGIN_URL.'/'.$this->tenant().'/oauth2/v2.0/authorize?'.http_build_query([ + 'client_id' => $this->clientId(), + 'response_type' => 'code', + 'redirect_uri' => $redirectUri, + 'response_mode' => 'query', + 'scope' => self::SCOPES, + 'state' => $security['state'], + 'nonce' => $security['nonce'], + 'code_challenge' => $security['code_challenge'], + 'code_challenge_method' => 'S256', + 'prompt' => 'select_account', + ]); + } + + /** + * Autorisierungscode gegen Token tauschen (mit PKCE-Verifier). + * + * @return array{id_token: string, access_token: string} + */ + public function exchangeCode(string $code, string $redirectUri, string $codeVerifier): array + { + $response = $this->tokenRequest([ + 'grant_type' => 'authorization_code', + 'code' => $code, + 'redirect_uri' => $redirectUri, + 'code_verifier' => $codeVerifier, + 'scope' => self::SCOPES, + ]); + + if (! is_string($response['id_token'] ?? null) || ! is_string($response['access_token'] ?? null)) { + throw new IdentityException('Microsoft hat keine gültige Anmeldung zurückgegeben.'); + } + + return ['id_token' => $response['id_token'], 'access_token' => $response['access_token']]; + } + + /** + * App-Token (Client Credentials) für den Hintergrund-Abgleich – benötigt + * Anwendungsberechtigungen User.Read.All und GroupMember.Read.All. + */ + public function appToken(): string + { + return Cache::remember('entra.app-token.'.$this->provider->id, 3000, fn () => (string) $this->tokenRequest([ + 'grant_type' => 'client_credentials', + 'scope' => 'https://graph.microsoft.com/.default', + ])['access_token']); + } + + public function forgetAppToken(): void + { + Cache::forget('entra.app-token.'.$this->provider->id); + } + + /** + * Öffentliche Signaturschlüssel von Microsoft (gecacht, bei unbekanntem + * Schlüssel einmal neu geladen – Microsoft wechselt sie regelmäßig). + * + * @return array{keys: list>} + */ + public function jwks(bool $refresh = false): array + { + $key = 'entra.jwks.'.$this->tenant(); + + if ($refresh) { + Cache::forget($key); + } + + return Cache::remember($key, 86400, function () { + $response = Http::timeout(10)->acceptJson()->get(self::LOGIN_URL.'/'.$this->tenant().'/discovery/v2.0/keys'); + + if (! $response->successful() || ! is_array($response->json('keys'))) { + throw new IdentityException('Die Schlüssel von Microsoft konnten nicht geladen werden. Bitte später erneut versuchen.'); + } + + return ['keys' => $response->json('keys')]; + }); + } + + public function graph(string $token): PendingRequest + { + return Http::timeout(20)->connectTimeout(10)->acceptJson()->withToken($token)->baseUrl(self::GRAPH_URL); + } + + /** + * Alle Seiten einer Graph-Abfrage (@odata.nextLink), höchstens $maxPages. + * + * @param array $headers + * @return list> + */ + public function graphAll(string $token, string $url, int $maxPages = 50, array $headers = []): array + { + $items = []; + + for ($page = 0; $page < $maxPages && $url; $page++) { + $response = $this->graph($token)->withHeaders($headers)->get($url); + $this->assertGraph($response); + $items = array_merge($items, (array) $response->json('value', [])); + $url = ($response->json() ?? [])['@odata.nextLink'] ?? null; + } + + return $items; + } + + public function assertGraph(Response $response): void + { + if ($response->status() === 403) { + throw new IdentityException('Microsoft Graph verweigert den Zugriff. Bitte die API-Berechtigungen der App-Registrierung und die Administratorzustimmung prüfen.'); + } + + if (! $response->successful()) { + throw new IdentityException('Microsoft Graph antwortet mit einem Fehler (HTTP '.$response->status().').'); + } + } + + /** + * @param array $params + * @return array + */ + private function tokenRequest(array $params): array + { + $response = Http::asForm()->timeout(15)->acceptJson()->post(self::LOGIN_URL.'/'.$this->tenant().'/oauth2/v2.0/token', [ + 'client_id' => $this->clientId(), + 'client_secret' => (string) $this->provider->setting('client_secret'), + ...$params, + ]); + + if (! $response->successful()) { + $code = (string) $response->json('error'); + + throw new IdentityException(match (true) { + str_contains((string) $response->json('error_description'), 'AADSTS7000215') => 'Das Client-Secret der App-Registrierung ist ungültig oder abgelaufen.', + $code === 'invalid_grant' => 'Die Anmeldung ist abgelaufen. Bitte erneut versuchen.', + $code === 'unauthorized_client', $code === 'invalid_client' => 'Die App-Registrierung in Entra ID ist nicht korrekt eingerichtet (Client-ID oder Secret).', + default => 'Microsoft hat die Anmeldung abgelehnt ('.($code ?: 'HTTP '.$response->status()).').', + }); + } + + return (array) $response->json(); + } +} diff --git a/app/Identity/Entra/EntraDirectorySync.php b/app/Identity/Entra/EntraDirectorySync.php new file mode 100644 index 00000000..eacb02bb --- /dev/null +++ b/app/Identity/Entra/EntraDirectorySync.php @@ -0,0 +1,280 @@ +where('enabled', true)->where('type', IdentityProvider::ENTRA)->get() + ->filter(fn (IdentityProvider $p) => (bool) $p->setting('directory_sync', false)) + ->each(fn (IdentityProvider $p) => $this->run($p, $budgetSeconds)); + } + + public function run(IdentityProvider $provider, int $budgetSeconds = 45): void + { + $deadline = microtime(true) + $budgetSeconds; + $client = new EntraClient($provider); + + try { + $token = $client->appToken(); + $this->syncUsers($provider, $client, $token, $deadline); + $this->syncPhotosAndManagers($provider, $client, $token, $deadline); + + if (now()->getTimestamp() - (int) $this->state($provider, 'groups_synced_at', 0) >= self::GROUP_SYNC_INTERVAL) { + $this->syncGroups($provider, $client, $token); + $this->saveState($provider, ['groups_synced_at' => now()->getTimestamp()]); + } + + $this->saveState($provider, ['last_run_at' => now()->getTimestamp(), 'last_error' => null]); + } catch (Throwable $e) { + $client->forgetAppToken(); + Log::error("Entra-Abgleich ({$provider->name}) fehlgeschlagen: ".$e->getMessage()); + $this->saveState($provider, ['last_run_at' => now()->getTimestamp(), 'last_error' => $e->getMessage()]); + } + } + + /** + * @return array + */ + public function status(IdentityProvider $provider): array + { + return (array) $this->settings->get('identity.'.$provider->id.'.sync', []); + } + + private function syncUsers(IdentityProvider $provider, EntraClient $client, string $token, float $deadline): void + { + $select = EntraAttributes::select($provider); + + // Neue Attribute zugeordnet: Der alte Delta-Link liefert sie nicht – einmal komplett abgleichen. + if ($this->state($provider, 'select') !== $select) { + $this->saveState($provider, ['delta_link' => null, 'next_link' => null, 'select' => $select]); + } + + $url = $this->state($provider, 'next_link') ?: $this->state($provider, 'delta_link') ?: '/users/delta?$select='.$select; + + while ($url && microtime(true) < $deadline) { + $response = $client->graph($token)->get($url); + + // Abgelaufener Delta-Link: von vorn beginnen. + if ($response->status() === 410) { + $this->saveState($provider, ['delta_link' => null, 'next_link' => null]); + + return; + } + + $client->assertGraph($response); + + foreach ((array) $response->json('value', []) as $graphUser) { + $this->applyUser($provider, (array) $graphUser); + } + + if ($next = ($response->json() ?? [])['@odata.nextLink'] ?? null) { + $url = $next; + $this->saveState($provider, ['next_link' => $next]); + } else { + $this->saveState($provider, ['delta_link' => ($response->json() ?? [])['@odata.deltaLink'] ?? null, 'next_link' => null, 'users_synced_at' => now()->getTimestamp()]); + $url = null; + } + } + } + + /** + * @param array $graphUser + */ + private function applyUser(IdentityProvider $provider, array $graphUser): void + { + $subject = (string) ($graphUser['id'] ?? ''); + + if ($subject === '') { + return; + } + + $identity = UserIdentity::query()->with('user')->where('identity_provider_id', $provider->id)->where('subject', $subject)->first(); + + if (isset($graphUser['@removed']) || ($graphUser['accountEnabled'] ?? true) === false) { + if ($identity?->user) { + $this->sync->deactivate($provider, $identity); + } + + return; + } + + if (! $identity) { + $createAllowed = $provider->setting('directory_create_users', false) + && ($graphUser['userType'] ?? 'Member') === 'Member' + && ! empty($graphUser['mail']); + + // Ohne Vorab-Anlage: nur bestehende Konten per E-Mail verknüpfen. + try { + $user = $this->sync->resolveUser($provider, $subject, EntraProfile::fromGraph($provider, $graphUser), (bool) $createAllowed); + } catch (IdentityException) { + return; // z. B. nicht erlaubte E-Mail-Domain – dieses Konto überspringen + } + + if (! $user) { + return; + } + + $identity = UserIdentity::query()->with('user')->where('identity_provider_id', $provider->id)->where('subject', $subject)->first(); + } + + // Delta liefert nur geänderte Felder – fehlende Felder nicht leeren. + $profile = EntraProfile::fromGraph($provider, $graphUser, partial: true); + + $this->sync->syncProfile($provider, $identity->user, $profile); + } + + private function syncPhotosAndManagers(IdentityProvider $provider, EntraClient $client, string $token, float $deadline): void + { + $withPhoto = (bool) $provider->setting('sync_photo', true); + $withManager = $provider->syncsManager(); + + if (! $withPhoto && ! $withManager) { + return; + } + + $identities = UserIdentity::query()->with('user') + ->where('identity_provider_id', $provider->id) + ->whereHas('user', fn ($q) => $q->where('is_active', true)) + ->orderByRaw('synced_at is not null')->orderBy('synced_at') + ->limit(self::PHOTOS_PER_RUN)->get(); + + foreach ($identities as $identity) { + if (microtime(true) >= $deadline) { + return; + } + + if ($withPhoto) { + $response = $client->graph($token)->accept('image/*')->get('/users/'.$identity->subject.'/photo/$value'); + + if ($response->successful() || $response->status() === 404) { + $this->sync->syncPhoto($identity, $response->successful() ? $response->body() : null); + } + } + + if ($withManager) { + $manager = $client->graph($token)->get('/users/'.$identity->subject.'/manager', ['$select' => 'id']); + + if ($manager->successful() || $manager->status() === 404) { + $this->sync->syncProfile($provider, $identity->user, ['manager_subject' => $manager->successful() ? $manager->json('id') : null]); + } + } + + $identity->forceFill(['synced_at' => now()])->save(); + } + } + + /** + * Gruppen- und App-Rollen-Zuordnungen für alle verknüpften Konten neu berechnen. + */ + private function syncGroups(IdentityProvider $provider, EntraClient $client, string $token): void + { + $mappings = $provider->mappings()->get(); + $groupsBySubject = []; + $appRolesBySubject = []; + + foreach ($mappings->where('kind', IdpGroupMapping::GROUP)->pluck('external_id')->unique() as $groupId) { + foreach ($this->transitiveUserIds($client, $token, $groupId) as $subject) { + $groupsBySubject[$subject][] = $groupId; + } + } + + if ($mappings->where('kind', IdpGroupMapping::APP_ROLE)->isNotEmpty()) { + $appRolesBySubject = $this->appRoleAssignments($provider, $client, $token); + } + + UserIdentity::query()->with('user')->where('identity_provider_id', $provider->id) + ->whereHas('user', fn ($q) => $q->where('is_active', true)) + ->each(fn (UserIdentity $identity) => $this->sync->syncRoles( + $provider, + $identity->user, + $groupsBySubject[$identity->subject] ?? [], + array_values(array_unique($appRolesBySubject[$identity->subject] ?? [])), + )); + } + + /** + * @return list + */ + private function transitiveUserIds(EntraClient $client, string $token, string $groupId): array + { + return array_column($client->graphAll($token, '/groups/'.$groupId.'/transitiveMembers/microsoft.graph.user?$select=id&$top=999'), 'id'); + } + + /** + * App-Rollen der App-Registrierung: direkt zugewiesene Personen und Gruppen (aufgelöst). + * + * @return array> Objekt-ID => Rollen-Werte + */ + private function appRoleAssignments(IdentityProvider $provider, EntraClient $client, string $token): array + { + $servicePrincipal = $client->graph($token)->get("/servicePrincipals(appId='".$client->clientId()."')", ['$select' => 'id,appRoles']); + $client->assertGraph($servicePrincipal); + + $values = collect((array) $servicePrincipal->json('appRoles', []))->pluck('value', 'id')->all(); + $result = []; + + foreach ($client->graphAll($token, '/servicePrincipals/'.$servicePrincipal->json('id').'/appRoleAssignedTo?$top=999') as $assignment) { + $value = $values[$assignment['appRoleId'] ?? ''] ?? null; + + if (! $value) { + continue; + } + + $subjects = ($assignment['principalType'] ?? '') === 'Group' + ? $this->transitiveUserIds($client, $token, $assignment['principalId']) + : [$assignment['principalId']]; + + foreach ($subjects as $subject) { + $result[$subject][] = $value; + } + } + + return $result; + } + + private function state(IdentityProvider $provider, string $key, mixed $default = null): mixed + { + return $this->status($provider)[$key] ?? $default; + } + + /** + * @param array $values + */ + private function saveState(IdentityProvider $provider, array $values): void + { + $this->settings->set('identity.'.$provider->id.'.sync', array_merge($this->status($provider), $values)); + } +} diff --git a/app/Identity/Entra/EntraLogin.php b/app/Identity/Entra/EntraLogin.php new file mode 100644 index 00000000..9bfda00f --- /dev/null +++ b/app/Identity/Entra/EntraLogin.php @@ -0,0 +1,139 @@ +} + */ + public function start(IdentityProvider $provider, string $redirectUri): array + { + $verifier = Str::random(64); + $security = [ + 'state' => Str::random(40), + 'nonce' => Str::random(40), + 'code_challenge' => rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '='), + ]; + + return [ + 'url' => (new EntraClient($provider))->authorizationUrl($redirectUri, $security), + 'session' => ['state' => $security['state'], 'nonce' => $security['nonce'], 'verifier' => $verifier, 'provider' => (string) $provider->id], + ]; + } + + /** + * @param array $session aus start() + */ + public function complete(IdentityProvider $provider, string $code, string $redirectUri, array $session): User + { + $client = new EntraClient($provider); + $tokens = $client->exchangeCode($code, $redirectUri, $session['verifier']); + $claims = (new IdTokenValidator($client))->validate($tokens['id_token'], $session['nonce']); + $subject = (string) $claims['oid']; + + [$profile, $groupIds, $photo] = $this->fetchFromGraph($client, $provider, $tokens['access_token'], $claims); + + $user = $this->sync->resolveUser($provider, $subject, $profile, (bool) $provider->setting('auto_provision', true)); + + if (! $user) { + throw new IdentityException('Für Ihr Microsoft-Konto gibt es kein Konto in diesem Portal. Bitte wenden Sie sich an die Administration.'); + } + + if (! $user->is_active) { + throw new IdentityException('Ihr Konto ist deaktiviert. Bitte wenden Sie sich an die Administration.'); + } + + $identity = UserIdentity::query()->where('identity_provider_id', $provider->id)->where('subject', $subject)->firstOrFail(); + $identity->update(['last_login_at' => now(), 'email' => $profile['email'] ?? $identity->email]); + + $this->sync->syncProfile($provider, $user, $profile); + $this->sync->syncRoles($provider, $user, $groupIds, array_values(array_filter((array) ($claims['roles'] ?? []), 'is_string'))); + + if ($provider->setting('sync_photo', true) && $photo !== false) { + $this->sync->syncPhoto($identity->fresh('user'), $photo); + } + + return $user->fresh(); + } + + /** + * Profil, Gruppen und Foto über Graph (mit dem Token der angemeldeten Person). + * Fällt Graph aus, reichen die Angaben aus dem ID-Token für die Anmeldung. + * + * @param array $claims + * @return array{0: array, 1: list, 2: string|null|false} false = Foto unbekannt + */ + private function fetchFromGraph(EntraClient $client, IdentityProvider $provider, string $token, array $claims): array + { + $groups = array_values(array_filter((array) ($claims['groups'] ?? []), 'is_string')); + $overage = isset($claims['_claim_names']['groups']) || ($claims['hasgroups'] ?? false); + + try { + $me = $client->graph($token)->get('/me', ['$select' => EntraAttributes::select($provider)]); + + // Einzelne Attribute brauchen weitere Berechtigungen (z. B. employeeHireDate) – + // dann wenigstens die Grundangaben übernehmen. + if ($me->clientError() && $me->status() !== 401) { + Log::warning('Entra-Anmeldung: Zugeordnete Attribute nicht abrufbar ('.$me->status().'), nutze Grundangaben.'); + $me = $client->graph($token)->get('/me', ['$select' => implode(',', EntraAttributes::BASE_SELECT)]); + } + + $client->assertGraph($me); + + $withManager = $provider->syncsManager(); + $managerSubject = null; + + if ($withManager) { + $manager = $client->graph($token)->get('/me/manager', ['$select' => 'id']); + $managerSubject = $manager->successful() ? $manager->json('id') : null; + } + + $profile = EntraProfile::fromGraph($provider, (array) $me->json(), $managerSubject, $withManager); + } catch (Throwable $e) { + Log::warning('Entra-Anmeldung: Profil aus Graph nicht abrufbar, nutze ID-Token. '.$e->getMessage()); + $profile = EntraProfile::fromClaims($claims); + } + + // Group-Overage: Bei vielen Gruppen stehen sie nicht im Token – dann über Graph + // (transitiv, also inklusive verschachtelter Gruppen). + if ($overage || $groups === []) { + try { + $groups = array_column($client->graphAll($token, '/me/transitiveMemberOf/microsoft.graph.group?$select=id&$top=999'), 'id'); + } catch (Throwable $e) { + if ($overage) { + Log::error('Entra-Anmeldung: Gruppen konnten nicht ermittelt werden. '.$e->getMessage()); + + throw new IdentityException('Ihre Gruppenmitgliedschaften konnten nicht ermittelt werden. Bitte später erneut versuchen.'); + } + } + } + + $photo = false; + + if ($provider->setting('sync_photo', true)) { + try { + $response = $client->graph($token)->accept('image/*')->get('/me/photo/$value'); + $photo = $response->successful() ? $response->body() : ($response->status() === 404 ? null : false); + } catch (Throwable) { + $photo = false; + } + } + + return [$profile, $groups, $photo]; + } +} diff --git a/app/Identity/Entra/EntraProfile.php b/app/Identity/Entra/EntraProfile.php new file mode 100644 index 00000000..f91f8970 --- /dev/null +++ b/app/Identity/Entra/EntraProfile.php @@ -0,0 +1,79 @@ + $graphUser Antwort von /me, /users/{id} oder /users/delta + * @param bool $partial Delta-Antwort: nur Felder liefern, deren Attribut enthalten ist + * @return array + */ + public static function fromGraph(IdentityProvider $provider, array $graphUser, ?string $managerSubject = null, bool $withManager = false, bool $partial = false): array + { + $present = fn (string $path) => ! $partial || array_key_exists(EntraAttributes::topLevel($path), $graphUser); + $profile = []; + + if ($present('displayName')) { + $profile['display_name'] = EntraAttributes::value($graphUser, 'displayName'); + } + + // Grundwerte für Kontoanlage und Verknüpfung; die Zuordnung überschreibt sie. + foreach (['first_name' => 'givenName', 'last_name' => 'surname', 'email' => 'mail'] as $field => $path) { + if ($present($path)) { + $profile[$field] = EntraAttributes::value($graphUser, $path); + } + } + + foreach ($provider->attributeMap() as $target => $path) { + if (! $present($path)) { + continue; + } + + $value = EntraAttributes::value($graphUser, $path); + + if (str_starts_with($target, 'custom.')) { + $profile['custom'][substr($target, 7)] = $value; + } else { + $profile[$target] = $value; + } + } + + // Gastkonten haben oft keine „mail“; der UPN ist dann eine #EXT#-Adresse. + if (array_key_exists('email', $profile) && $profile['email'] === null && ! $partial) { + $upn = (string) ($graphUser['userPrincipalName'] ?? ''); + $profile['email'] = $upn !== '' && ! str_contains($upn, '#EXT#') ? $upn : null; + } + + if ($withManager) { + $profile['manager_subject'] = $managerSubject; + } + + return $profile; + } + + /** + * Rückfall, wenn Graph nicht erreichbar ist: Angaben aus dem ID-Token. + * + * @param array $claims + * @return array + */ + public static function fromClaims(array $claims): array + { + return [ + 'display_name' => $claims['name'] ?? null, + 'first_name' => $claims['given_name'] ?? null, + 'last_name' => $claims['family_name'] ?? null, + 'email' => $claims['email'] ?? $claims['preferred_username'] ?? null, + ]; + } +} diff --git a/app/Identity/Entra/IdTokenValidator.php b/app/Identity/Entra/IdTokenValidator.php new file mode 100644 index 00000000..6d16bea7 --- /dev/null +++ b/app/Identity/Entra/IdTokenValidator.php @@ -0,0 +1,74 @@ + Claims + */ + public function validate(string $idToken, string $expectedNonce): array + { + JWT::$leeway = 120; + + try { + $claims = $this->decode($idToken, $this->client->jwks()); + } catch (UnexpectedValueException $e) { + if (! str_contains($e->getMessage(), '"kid"')) { + throw new IdentityException('Die Anmeldung von Microsoft konnte nicht bestätigt werden.', previous: $e); + } + + // Unbekannter Schlüssel: Microsoft hat die Schlüssel gewechselt – einmal neu laden. + try { + $claims = $this->decode($idToken, $this->client->jwks(refresh: true)); + } catch (UnexpectedValueException $e) { + throw new IdentityException('Die Anmeldung von Microsoft konnte nicht bestätigt werden.', previous: $e); + } + } + + if (($claims['iss'] ?? null) !== $this->client->issuer()) { + throw new IdentityException('Die Anmeldung stammt nicht aus dem erwarteten Microsoft-Mandanten.'); + } + + if (($claims['aud'] ?? null) !== $this->client->clientId()) { + throw new IdentityException('Die Anmeldung war für eine andere Anwendung bestimmt.'); + } + + if (! hash_equals($expectedNonce, (string) ($claims['nonce'] ?? ''))) { + throw new IdentityException('Die Anmeldung konnte nicht zugeordnet werden. Bitte erneut versuchen.'); + } + + if (! is_string($claims['oid'] ?? null) || $claims['oid'] === '') { + throw new IdentityException('Microsoft hat keine Benutzerkennung übermittelt.'); + } + + return $claims; + } + + /** + * @param array{keys: list>} $jwks + * @return array + */ + private function decode(string $token, array $jwks): array + { + try { + return (array) json_decode(json_encode(JWT::decode($token, JWK::parseKeySet($jwks, 'RS256'))), true); + } catch (UnexpectedValueException $e) { + throw $e; + } catch (Throwable $e) { + throw new IdentityException('Die Anmeldung von Microsoft konnte nicht bestätigt werden.', previous: $e); + } + } +} diff --git a/app/Identity/Entra/MappingTester.php b/app/Identity/Entra/MappingTester.php new file mode 100644 index 00000000..49c72f94 --- /dev/null +++ b/app/Identity/Entra/MappingTester.php @@ -0,0 +1,124 @@ +, groups: list}>, app_roles: list}>, roles: list} + */ + public function test(IdentityProvider $provider, string $userPrincipal): array + { + $client = new EntraClient($provider); + $token = $client->appToken(); + + $user = $client->graph($token)->get('/users/'.rawurlencode($userPrincipal), ['$select' => 'id,displayName,mail,userPrincipalName,accountEnabled']); + + if ($user->status() === 404) { + throw new IdentityException('Diese Person gibt es in Entra ID nicht.'); + } + + $client->assertGraph($user); + $id = (string) $user->json('id'); + + $groups = $client->graphAll($token, '/users/'.$id.'/transitiveMemberOf/microsoft.graph.group?$select=id,displayName&$top=999'); + + $servicePrincipal = $client->graph($token)->get("/servicePrincipals(appId='".$client->clientId()."')", ['$select' => 'id,appRoles']); + $appRoles = []; + + if ($servicePrincipal->successful()) { + $values = collect((array) $servicePrincipal->json('appRoles', []))->pluck('value', 'id'); + $assignments = $client->graphAll($token, '/users/'.$id.'/appRoleAssignments?$top=999'); + $groupIds = array_column($groups, 'id'); + + foreach ($assignments as $assignment) { + if (($assignment['resourceId'] ?? null) === $servicePrincipal->json('id') && $values->has($assignment['appRoleId'] ?? '')) { + $appRoles[] = $values[$assignment['appRoleId']]; + } + } + + // Über Gruppen zugewiesene App-Rollen + foreach ($client->graphAll($token, '/servicePrincipals/'.$servicePrincipal->json('id').'/appRoleAssignedTo?$top=999') as $assignment) { + if (($assignment['principalType'] ?? '') === 'Group' && in_array($assignment['principalId'], $groupIds, true) && $values->has($assignment['appRoleId'] ?? '')) { + $appRoles[] = $values[$assignment['appRoleId']]; + } + } + } + + $mappings = $provider->mappings()->with('role')->get(); + $roleNames = fn (string $kind, string $external) => $mappings + ->filter(fn (IdpGroupMapping $m) => $m->kind === $kind && strtolower($m->external_id) === strtolower($external)) + ->map(fn (IdpGroupMapping $m) => $m->role->name)->values()->all(); + + $groupRows = array_map(fn (array $g) => ['id' => $g['id'], 'name' => $g['displayName'] ?? $g['id'], 'roles' => $roleNames(IdpGroupMapping::GROUP, $g['id'])], $groups); + usort($groupRows, fn ($a, $b) => [empty($a['roles']), $a['name']] <=> [empty($b['roles']), $b['name']]); + $appRoleRows = array_map(fn (string $v) => ['value' => $v, 'roles' => $roleNames(IdpGroupMapping::APP_ROLE, $v)], array_values(array_unique($appRoles))); + + $roles = collect($groupRows)->pluck('roles')->flatten()->merge(collect($appRoleRows)->pluck('roles')->flatten()); + + if ($default = $provider->setting('default_role_id')) { + $roles->push(Role::query()->find($default)?->name.' (Standardrolle)'); + } + + return [ + 'user' => [ + 'name' => $user->json('displayName'), + 'email' => $user->json('mail') ?: $user->json('userPrincipalName'), + 'enabled' => (bool) $user->json('accountEnabled', true), + ], + 'groups' => $groupRows, + 'app_roles' => $appRoleRows, + 'roles' => $roles->filter()->unique()->values()->all(), + ]; + } + + /** + * Gruppensuche für das Mapping-Formular. + * + * @return array Objekt-ID => Anzeigename + */ + public function searchGroups(IdentityProvider $provider, string $search): array + { + $client = new EntraClient($provider); + $response = $client->graph($client->appToken()) + ->withHeaders(['ConsistencyLevel' => 'eventual']) + ->get('/groups', ['$search' => '"displayName:'.str_replace('"', '', $search).'"', '$select' => 'id,displayName', '$top' => 20]); + + $client->assertGraph($response); + + return collect((array) $response->json('value', []))->mapWithKeys(fn ($g) => [$g['id'] => $g['displayName'].' ('.substr($g['id'], 0, 8).'…)'])->all(); + } + + /** + * Verzeichniserweiterungen des Mandanten (extension__) für Benutzer – + * etwa aus Entra Connect synchronisierte AD-Attribute. Wird in der Konfiguration + * gespeichert und im Formular als Vorschlag angeboten. + * + * @return list + */ + public function loadExtensionProperties(IdentityProvider $provider): array + { + $client = new EntraClient($provider); + $response = $client->graph($client->appToken())->post('/directoryObjects/getAvailableExtensionProperties', (object) []); + $client->assertGraph($response); + + $names = collect((array) $response->json('value', [])) + ->filter(fn ($property) => in_array('User', (array) ($property['targetObjects'] ?? []), true)) + ->pluck('name') + ->filter(fn ($name) => is_string($name) && preg_match(EntraAttributes::PATH_PATTERN, $name)) + ->unique()->sort()->values()->all(); + + $provider->update(['config' => array_merge((array) $provider->config, ['extension_properties' => $names])]); + + return $names; + } +} diff --git a/app/Identity/IdentityException.php b/app/Identity/IdentityException.php new file mode 100644 index 00000000..8ff456c9 --- /dev/null +++ b/app/Identity/IdentityException.php @@ -0,0 +1,11 @@ + $profile normalisiertes Profil (siehe EntraProfile) + */ + public function resolveUser(IdentityProvider $provider, string $subject, array $profile, bool $allowCreate): ?User + { + $identity = UserIdentity::query()->with('user') + ->where('identity_provider_id', $provider->id)->where('subject', $subject)->first(); + + if ($identity?->user) { + return $identity->user; + } + + $email = isset($profile['email']) ? Str::lower((string) $profile['email']) : null; + + if ($email && ! $provider->isEmailDomainAllowed($email)) { + throw new IdentityException('Konten mit dieser E-Mail-Domain dürfen sich hier nicht anmelden.'); + } + + $user = $email && $provider->setting('link_by_email', true) + ? User::query()->where('email', $email)->first() + : null; + + if (! $user) { + if (! $allowCreate) { + return null; + } + + if (! $email) { + throw new IdentityException('Für dieses Microsoft-Konto ist keine E-Mail-Adresse hinterlegt.'); + } + + $user = User::query()->create([ + 'email' => $email, + 'first_name' => $profile['first_name'] ?? null, + 'last_name' => $profile['last_name'] ?? null, + 'name' => $profile['display_name'] ?? $email, + 'password' => null, + 'is_active' => true, + ]); + + Audit::log('identity.user_created', ['provider' => $provider->name, 'email' => $email], null); + } + + UserIdentity::query()->create([ + 'user_id' => $user->id, + 'identity_provider_id' => $provider->id, + 'subject' => $subject, + 'email' => $email, + ]); + + return $user; + } + + /** + * Profilfelder übernehmen – nur die in der Konfiguration gewählten. + * + * @param array $profile + */ + public function syncProfile(IdentityProvider $provider, User $user, array $profile): void + { + $fields = $provider->syncedFields(); + $changes = []; + + foreach (['first_name', 'last_name', 'job_title', 'department', 'location', 'phone', 'mobile'] as $field) { + if (in_array($field, $fields, true) && array_key_exists($field, $profile)) { + $changes[$field] = $profile[$field] !== '' ? $profile[$field] : null; + } + } + + if (in_array('first_name', $fields, true) && empty($profile['first_name']) && empty($profile['last_name']) && ! empty($profile['display_name'])) { + $changes['name'] = $profile['display_name']; + } + + if (in_array('email', $fields, true) && ! empty($profile['email'])) { + $email = Str::lower($profile['email']); + + if (User::query()->where('email', $email)->whereKeyNot($user->id)->exists()) { + Log::warning("Entra-Abgleich: E-Mail {$email} ist bereits einem anderen Konto zugeordnet – nicht übernommen."); + } else { + $changes['email'] = $email; + } + } + + if (in_array('manager', $fields, true) && array_key_exists('manager_subject', $profile)) { + $changes['manager_id'] = $profile['manager_subject'] + ? UserIdentity::query()->where('identity_provider_id', $provider->id)->where('subject', $profile['manager_subject'])->value('user_id') + : null; + } + + $custom = $this->customFieldChanges($user, $fields, (array) ($profile['custom'] ?? [])); + + if ($custom !== null) { + $changes['custom_fields'] = $custom; + } + + if ($changes !== []) { + $user->forceFill($changes)->save(); + } + } + + /** + * Freie Profilfelder aus dem Anbieter übernehmen. Datumswerte werden als + * Y-m-d gespeichert, Werte ohne Felddefinition ignoriert. + * + * @param list $fields + * @param array $incoming + * @return array|null null = keine Änderung + */ + private function customFieldChanges(User $user, array $fields, array $incoming): ?array + { + $definitions = $this->profileFields->all()->keyBy('key'); + $values = (array) ($user->custom_fields ?? []); + $before = $values; + + foreach ($incoming as $key => $value) { + $field = $definitions->get($key); + + if (! $field || ! in_array('custom.'.$key, $fields, true)) { + continue; + } + + if ($value !== null && $field->type === 'date') { + try { + $value = Carbon::parse($value)->format('Y-m-d'); + } catch (Throwable) { + // Unlesbares Datum: unverändert übernehmen. + } + } + + if ($value === null) { + unset($values[$key]); + } else { + $values[$key] = $value; + } + } + + return $values === $before ? null : $values; + } + + /** + * Profilfoto übernehmen, wenn es sich geändert hat. null = kein Foto beim Anbieter. + */ + public function syncPhoto(UserIdentity $identity, ?string $binary): void + { + $user = $identity->user; + + try { + if ($binary === null) { + // Nur ein Foto entfernen, das auch aus Entra stammte. + if ($identity->photo_hash !== null) { + $this->avatars->delete($user); + $identity->update(['photo_hash' => null]); + } + + return; + } + + $hash = hash('sha256', $binary); + + if ($hash !== $identity->photo_hash || $user->avatar_path === null) { + $this->avatars->storeFromBinary($user, $binary); + $identity->update(['photo_hash' => $hash]); + } + } catch (Throwable $e) { + Log::warning("Profilfoto für {$user->email} konnte nicht übernommen werden: ".$e->getMessage()); + } + } + + /** + * Rollen aus Gruppen und App-Rollen abgleichen. Nur Zuweisungen dieses + * Anbieters werden hinzugefügt oder entfernt – manuelle bleiben unberührt. + * + * @param list $groupIds Objekt-IDs der Gruppen + * @param list $appRoles Werte der App-Rollen + * @return list resultierende Rollen-IDs aus diesem Anbieter + */ + public function syncRoles(IdentityProvider $provider, User $user, array $groupIds, array $appRoles): array + { + $desired = []; + + foreach ($provider->mappings()->get() as $mapping) { + $values = $mapping->kind === IdpGroupMapping::APP_ROLE ? $appRoles : array_map('strtolower', $groupIds); + $external = $mapping->kind === IdpGroupMapping::APP_ROLE ? $mapping->external_id : strtolower($mapping->external_id); + + if (in_array($external, $values, true)) { + $desired[$mapping->role_id.'|'.$provider->sourcePrefix().$mapping->kind.':'.$mapping->external_id] = $mapping->role_id; + } + } + + if ($defaultRole = $provider->setting('default_role_id')) { + $desired[$defaultRole.'|'.$provider->sourcePrefix().'default'] = (int) $defaultRole; + } + + $current = DB::table('role_user') + ->where('user_id', $user->id) + ->where('source', 'idp') + ->where('source_ref', 'like', $provider->sourcePrefix().'%') + ->get(['id', 'role_id', 'source_ref']) + ->keyBy(fn ($row) => $row->role_id.'|'.$row->source_ref); + + $removed = $current->keys()->diff(array_keys($desired)); + $added = collect(array_keys($desired))->diff($current->keys()); + + if ($removed->isNotEmpty()) { + DB::table('role_user')->whereIn('id', $removed->map(fn ($key) => $current[$key]->id)->all())->delete(); + } + + foreach ($added as $key) { + [$roleId, $sourceRef] = explode('|', $key, 2); + DB::table('role_user')->insert(['role_id' => (int) $roleId, 'user_id' => $user->id, 'source' => 'idp', 'source_ref' => $sourceRef, 'created_at' => now()]); + } + + if ($removed->isNotEmpty() || $added->isNotEmpty()) { + Permissions::flush(); + Audit::log('identity.roles_synced', [ + 'provider' => $provider->name, + 'user' => $user->email, + 'added' => $added->values()->all(), + 'removed' => $removed->values()->all(), + ], null); + } + + return array_values(array_unique($desired)); + } + + /** + * Konto wurde beim Anbieter deaktiviert oder gelöscht: im Portal deaktivieren + * und die Rollen aus diesem Anbieter entfernen. + */ + public function deactivate(IdentityProvider $provider, UserIdentity $identity): void + { + $user = $identity->user; + + if ($user->is_active) { + $user->forceFill(['is_active' => false])->save(); + Audit::log('identity.user_deactivated', ['provider' => $provider->name, 'email' => $user->email], null); + } + + $this->syncRoles($provider, $user, [], []); + DB::table('sessions')->where('user_id', $user->id)->delete(); + } +} diff --git a/app/Models/Audience.php b/app/Models/Audience.php new file mode 100644 index 00000000..6eb2c47d --- /dev/null +++ b/app/Models/Audience.php @@ -0,0 +1,18 @@ + 'Rolle', 'department' => 'Abteilung', 'location' => 'Standort']; + + public $timestamps = false; +} diff --git a/app/Models/AuditLog.php b/app/Models/AuditLog.php new file mode 100644 index 00000000..b44d36d5 --- /dev/null +++ b/app/Models/AuditLog.php @@ -0,0 +1,29 @@ + 'array', + 'created_at' => 'datetime', + ]; + } + + /** + * @return BelongsTo + */ + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } +} diff --git a/app/Models/DashboardTile.php b/app/Models/DashboardTile.php new file mode 100644 index 00000000..6eb59f6d --- /dev/null +++ b/app/Models/DashboardTile.php @@ -0,0 +1,94 @@ + 'Bild mit Link', + 'text' => 'Text', + 'notice' => 'Hinweis', + ]; + + public const AREAS = [ + 'aside' => 'Seitenleiste (rechts)', + 'main' => 'Hauptspalte (breit)', + 'top' => 'Ganz oben (volle Breite)', + ]; + + public const VARIANTS = [ + 'brand' => 'Markenfarbe', + 'info' => 'Info (blau)', + 'success' => 'Erfolg (grün)', + 'warning' => 'Warnung (rot)', + 'neutral' => 'Neutral (grau)', + ]; + + protected static function booted(): void + { + static::saving(function (DashboardTile $tile) { + $tile->url = filled($tile->url) ? (Field::safeUrl($tile->url) ?: null) : null; + + if ($tile->isDirty('body')) { + $tile->body_html = app(RichText::class)->toSafeHtml($tile->body); + } + }); + + static::deleted(fn (DashboardTile $tile) => $tile->image_path && Storage::disk('uploads')->delete($tile->image_path)); + } + + protected function casts(): array + { + return ['new_tab' => 'boolean', 'is_active' => 'boolean', 'starts_at' => 'datetime', 'ends_at' => 'datetime']; + } + + public function widgetKey(): string + { + return 'tile.'.$this->id; + } + + /** + * Aktiv, im Zeitraum und für die Person sichtbar. + * + * @param Builder $query + */ + public function scopeVisibleTo(Builder $query, User $user): void + { + $query->where('is_active', true) + ->where(fn ($q) => $q->whereNull('starts_at')->orWhere('starts_at', '<=', now())) + ->where(fn ($q) => $q->whereNull('ends_at')->orWhere('ends_at', '>', now())); + + Audiences::constrain($query, 'dashboard_tile', 'dashboard_tiles.id', $user); + } + + /** + * @return array + */ + public function toWidgetProps(): array + { + return [ + 'tile' => [ + 'type' => $this->type, + 'title' => $this->title, + 'image_url' => $this->image_path ? Storage::disk('uploads')->url($this->image_path) : null, + 'url' => $this->url, + 'new_tab' => $this->new_tab, + 'alt' => $this->alt ?: '', + 'html' => $this->body_html, + 'variant' => $this->variant ?: 'brand', + ], + ]; + } +} diff --git a/app/Models/Grant.php b/app/Models/Grant.php new file mode 100644 index 00000000..848146ff --- /dev/null +++ b/app/Models/Grant.php @@ -0,0 +1,35 @@ + Permissions::flush()); + static::deleted(fn () => Permissions::flush()); + } + + protected function casts(): array + { + return ['include_children' => 'boolean', 'resource_id' => 'integer']; + } + + /** + * @return BelongsTo + */ + public function role(): BelongsTo + { + return $this->belongsTo(Role::class); + } +} diff --git a/app/Models/IdentityProvider.php b/app/Models/IdentityProvider.php new file mode 100644 index 00000000..fbe98591 --- /dev/null +++ b/app/Models/IdentityProvider.php @@ -0,0 +1,141 @@ + 'Vorname', + 'last_name' => 'Nachname', + 'email' => 'E-Mail-Adresse', + 'job_title' => 'Funktion', + 'department' => 'Abteilung', + 'location' => 'Standort', + 'phone' => 'Telefon', + 'mobile' => 'Mobil', + ]; + + protected static function booted(): void + { + static::saving(function (IdentityProvider $provider) { + $provider->slug = $provider->slug ?: Str::slug($provider->name) ?: $provider->type; + }); + } + + protected function casts(): array + { + return [ + 'enabled' => 'boolean', + 'config' => 'encrypted:array', + ]; + } + + public function setting(string $key, mixed $default = null): mixed + { + return data_get($this->config, $key, $default); + } + + /** + * Zuordnung Profilfeld => Graph-Attribut. Ziele sind Kernfelder („job_title“) + * oder freie Profilfelder („custom.personalnummer“). Ohne gespeicherte Zuordnung + * gilt die Standardzuordnung für die früher gewählten Felder. + * + * @return array + */ + public function attributeMap(): array + { + $rows = $this->setting('attribute_map'); + + if (! is_array($rows)) { + $legacy = (array) $this->setting('synced_fields', array_keys(EntraAttributes::DEFAULT_MAP)); + + return array_intersect_key(EntraAttributes::DEFAULT_MAP, array_flip($legacy)); + } + + $map = []; + + foreach ($rows as $row) { + $target = (string) ($row['target'] ?? ''); + $attribute = trim((string) ($row['attribute'] ?? '')); + + if ($attribute !== '' && preg_match(EntraAttributes::PATH_PATTERN, $attribute) + && (array_key_exists($target, self::PROFILE_TARGETS) || str_starts_with($target, 'custom.'))) { + $map[$target] = $attribute; + } + } + + return $map; + } + + public function syncsManager(): bool + { + return (bool) $this->setting('sync_manager', in_array('manager', (array) $this->setting('synced_fields', ['manager']), true)); + } + + /** + * Felder, die dieser Anbieter pflegt (im Portal schreibgeschützt). + * + * @return list + */ + public function syncedFields(): array + { + return [...array_keys($this->attributeMap()), ...($this->syncsManager() ? ['manager'] : [])]; + } + + public function buttonLabel(): string + { + return $this->setting('button_label') ?: 'Mit Microsoft anmelden'; + } + + public function isEmailDomainAllowed(?string $email): bool + { + $domains = array_filter(array_map(fn ($d) => strtolower(trim((string) $d)), (array) $this->setting('allowed_domains', []))); + + if ($domains === []) { + return true; + } + + return $email !== null && in_array(strtolower(substr(strrchr($email, '@') ?: '', 1)), $domains, true); + } + + public function sourcePrefix(): string + { + return $this->id.':'; + } + + /** + * @return HasMany + */ + public function mappings(): HasMany + { + return $this->hasMany(IdpGroupMapping::class); + } + + /** + * @return HasMany + */ + public function identities(): HasMany + { + return $this->hasMany(UserIdentity::class); + } +} diff --git a/app/Models/IdpGroupMapping.php b/app/Models/IdpGroupMapping.php new file mode 100644 index 00000000..e82526e1 --- /dev/null +++ b/app/Models/IdpGroupMapping.php @@ -0,0 +1,33 @@ + Permissions::flush()); + static::deleted(fn () => Permissions::flush()); + } + + /** + * @return BelongsTo + */ + public function role(): BelongsTo + { + return $this->belongsTo(Role::class); + } +} diff --git a/app/Models/NewsCategory.php b/app/Models/NewsCategory.php deleted file mode 100644 index 9940f5b9..00000000 --- a/app/Models/NewsCategory.php +++ /dev/null @@ -1,22 +0,0 @@ - - */ - public function posts(): HasMany - { - return $this->hasMany(NewsPost::class, 'category_id'); - } -} diff --git a/app/Models/ProfileField.php b/app/Models/ProfileField.php new file mode 100644 index 00000000..6d8be0c5 --- /dev/null +++ b/app/Models/ProfileField.php @@ -0,0 +1,41 @@ + 'Text', + 'textarea' => 'Mehrzeiliger Text', + 'email' => 'E-Mail-Adresse', + 'phone' => 'Telefonnummer', + 'url' => 'Link', + 'date' => 'Datum', + ]; + + public const VISIBILITIES = [ + 'public' => 'Für alle sichtbar', + 'restricted' => 'Nur die Person selbst und die Personalverwaltung', + ]; + + protected static function booted(): void + { + static::saving(function (ProfileField $field) { + $field->key = $field->key ?: Str::slug($field->label, '_', 'de'); + }); + + static::saved(fn () => app(ProfileFields::class)->flush()); + static::deleted(fn () => app(ProfileFields::class)->flush()); + } + + protected function casts(): array + { + return ['editable' => 'boolean']; + } +} diff --git a/app/Models/Role.php b/app/Models/Role.php new file mode 100644 index 00000000..b95ff67e --- /dev/null +++ b/app/Models/Role.php @@ -0,0 +1,70 @@ +slug = $role->slug ?: Str::slug($role->name, language: 'de'); + }); + + static::saved(fn () => Permissions::flush()); + static::deleted(fn () => Permissions::flush()); + } + + protected function casts(): array + { + return ['is_system' => 'boolean']; + } + + public static function administration(): self + { + $role = static::query()->firstOrCreate(['slug' => self::ADMINISTRATION], [ + 'name' => 'Administration', + 'description' => 'Voller Zugriff auf alle Bereiche und Einstellungen.', + 'is_system' => true, + ]); + + if (! $role->grants()->where('ability', '*')->exists()) { + $role->grants()->create(['ability' => '*']); + } + + return $role; + } + + /** + * @return BelongsToMany + */ + public function users(): BelongsToMany + { + return $this->belongsToMany(User::class)->withPivot('source', 'source_ref', 'created_at'); + } + + /** + * @return HasMany + */ + public function grants(): HasMany + { + return $this->hasMany(Grant::class); + } + + public function isAdministration(): bool + { + return $this->slug === self::ADMINISTRATION; + } +} diff --git a/app/Models/User.php b/app/Models/User.php index dd9e3189..c01a83e0 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -3,6 +3,8 @@ namespace App\Models; use App\Support\Avatars; +use App\Support\Permissions\Permissions; +use App\Support\Permissions\PermissionSet; use Database\Factories\UserFactory; use Filament\Models\Contracts\FilamentUser; use Filament\Models\Contracts\HasAvatar; @@ -12,14 +14,17 @@ use Illuminate\Database\Eloquent\Attributes\Hidden; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Factories\HasFactory; +use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\BelongsToMany; +use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Support\Str; #[Fillable([ 'name', 'first_name', 'last_name', 'email', 'password', - 'job_title', 'department', 'location', 'phone', 'mobile', 'about', - 'is_admin', 'is_active', 'theme', + 'job_title', 'department', 'location', 'phone', 'mobile', 'about', 'custom_fields', + 'is_active', 'theme', ])] #[Hidden(['password', 'remember_token'])] class User extends Authenticatable implements FilamentUser, HasAvatar @@ -46,19 +51,107 @@ class User extends Authenticatable implements FilamentUser, HasAvatar return [ 'email_verified_at' => 'datetime', 'last_login_at' => 'datetime', + 'custom_fields' => 'array', 'password' => 'hashed', - 'is_admin' => 'boolean', 'is_active' => 'boolean', ]; } /** - * Vorläufig: Zugriff auf das Admin-Backend über das Flag is_admin. - * Wird in Phase 2 durch das Rollen- und Rechtesystem ersetzt. + * Admin-Backend: für alle mit irgendeinem Recht (z. B. Redaktion einer + * Kategorie). Was sie dort sehen, regeln die Policies der einzelnen Seiten. */ public function canAccessPanel(Panel $panel): bool { - return $this->is_admin && $this->is_active; + return $this->canAccessAdmin(); + } + + public function canAccessAdmin(): bool + { + $permissions = $this->permissions(); + + return $this->is_active && ($permissions->global !== [] || $permissions->hasAnyObjectGrant()); + } + + public function permissions(): PermissionSet + { + return app(Permissions::class)->for($this); + } + + /** + * @return HasMany + */ + public function identities(): HasMany + { + return $this->hasMany(UserIdentity::class); + } + + /** + * @return BelongsTo + */ + public function manager(): BelongsTo + { + return $this->belongsTo(User::class, 'manager_id'); + } + + /** + * @return HasMany + */ + public function reports(): HasMany + { + return $this->hasMany(User::class, 'manager_id'); + } + + /** + * Profilfelder, die ein Identity Provider pflegt – im Portal nur lesbar. + * + * @return list + */ + public function managedFields(): array + { + return $this->identities()->with('provider')->get() + ->filter(fn (UserIdentity $identity) => $identity->provider?->enabled) + ->flatMap(fn (UserIdentity $identity) => $identity->provider->syncedFields()) + ->unique()->values()->all(); + } + + /** + * @return BelongsToMany + */ + public function roles(): BelongsToMany + { + return $this->belongsToMany(Role::class)->withPivot('source', 'source_ref', 'created_at'); + } + + public function hasRole(string $slug): bool + { + return $this->roles()->where('slug', $slug)->exists(); + } + + public function isAdministrator(): bool + { + return $this->permissions()->isSuperuser(); + } + + /** + * Manuell vergebene Rollen setzen. Rollen aus Identity-Provider-Gruppen + * (Quelle „idp“) bleiben unberührt – Rollen sind additiv. + * + * @param list $roleIds + */ + public function syncManualRoles(array $roleIds): void + { + $current = $this->roles()->wherePivot('source', 'manual')->pluck('roles.id')->all(); + + foreach (array_diff($current, $roleIds) as $roleId) { + $this->roles()->wherePivot('source', 'manual')->detach($roleId); + } + + foreach (array_diff($roleIds, $current) as $roleId) { + $this->roles()->attach($roleId, ['source' => 'manual', 'created_at' => now()]); + } + + Permissions::flush(); } public function getFilamentAvatarUrl(): ?string diff --git a/app/Models/UserIdentity.php b/app/Models/UserIdentity.php new file mode 100644 index 00000000..c0ee8877 --- /dev/null +++ b/app/Models/UserIdentity.php @@ -0,0 +1,32 @@ + 'datetime', 'synced_at' => 'datetime']; + } + + /** + * @return BelongsTo + */ + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } + + /** + * @return BelongsTo + */ + public function provider(): BelongsTo + { + return $this->belongsTo(IdentityProvider::class, 'identity_provider_id'); + } +} diff --git a/app/Models/VendorFeedback.php b/app/Models/VendorFeedback.php new file mode 100644 index 00000000..1db7e9ba --- /dev/null +++ b/app/Models/VendorFeedback.php @@ -0,0 +1,40 @@ + 'Fehlerbericht', + 'featurerequest' => 'Funktionswunsch', + ]; + + protected $table = 'vendor_feedback'; + + protected function casts(): array + { + return [ + 'payload' => 'array', + 'next_attempt_at' => 'datetime', + ]; + } + + /** + * @return BelongsTo + */ + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } +} diff --git a/app/Notifications/PortalNotification.php b/app/Notifications/PortalNotification.php new file mode 100644 index 00000000..0b481bec --- /dev/null +++ b/app/Notifications/PortalNotification.php @@ -0,0 +1,40 @@ +notify(new PortalNotification('Beitrag freigegeben', '„Sommerfest“ ist online.', '/neuigkeiten/sommerfest', 'check')); + */ +class PortalNotification extends Notification +{ + use Queueable; + + public function __construct( + public readonly string $title, + public readonly string $body = '', + public readonly ?string $url = null, + public readonly string $icon = 'bell', + ) {} + + /** + * @return list + */ + public function via(object $notifiable): array + { + return ['database']; + } + + /** + * @return array + */ + public function toArray(object $notifiable): array + { + return ['title' => $this->title, 'body' => $this->body, 'url' => $this->url, 'icon' => $this->icon]; + } +} diff --git a/app/Pagebuilder/BlockType.php b/app/Pagebuilder/BlockType.php new file mode 100644 index 00000000..12118a80 --- /dev/null +++ b/app/Pagebuilder/BlockType.php @@ -0,0 +1,94 @@ + $fields + * @param array{min: int, max: int, titled: bool, label: string}|null $container + * @param (Closure(array, User|null, array): (array|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 $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 + */ + public function defaults(): array + { + $data = []; + + foreach ($this->fields as $field) { + $data[$field->name] = $field->default(); + } + + return $data; + } + + /** + * @return array + */ + 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, + ]; + } +} diff --git a/app/Pagebuilder/Blocks.php b/app/Pagebuilder/Blocks.php new file mode 100644 index 00000000..fd11e8c5 --- /dev/null +++ b/app/Pagebuilder/Blocks.php @@ -0,0 +1,239 @@ +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/.vue + * bzw. plugins-core//resources/js/blocks/.vue („slug::Name“). + */ +class Blocks +{ + public const GROUPS = [ + 'layout' => 'Layout', + 'content' => 'Inhalt', + 'media' => 'Medien', + 'dynamic' => 'Dynamisch', + ]; + + /** @var array */ + 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 + */ + public function all(): array + { + return Hooks::apply('pagebuilder.blocks', $this->types); + } + + /** + * @return list> + */ + 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()]; + })); + } +} diff --git a/app/Pagebuilder/Content.php b/app/Pagebuilder/Content.php new file mode 100644 index 00000000..4bbc50f1 --- /dev/null +++ b/app/Pagebuilder/Content.php @@ -0,0 +1,292 @@ +>} + */ + public static function empty(): array + { + return ['blocks' => []]; + } + + /** + * @param array|null $content + * @return array{blocks: list>} + */ + public function sanitize(?array $content): array + { + $this->count = 0; + + return ['blocks' => $this->sanitizeList($content['blocks'] ?? [], 1)]; + } + + /** + * Anzeigefertiger Inhalt für eine Person. + * + * @param array|null $content bereits bereinigter Inhalt + * @return array{blocks: list>} + */ + 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 $block + * @return array|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|null $content + * @return list + */ + 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|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> + */ + 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 $data + * @return list> + */ + 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, department?: list, location?: list}|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> $blocks + * @return list> + */ + 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 $block + * @return array|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); + } +} diff --git a/app/Pagebuilder/Field.php b/app/Pagebuilder/Field.php new file mode 100644 index 00000000..a3b342e2 --- /dev/null +++ b/app/Pagebuilder/Field.php @@ -0,0 +1,209 @@ + $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|Closure(): array $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 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> + */ + 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> + */ + 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); + } +} diff --git a/app/Pagebuilder/VideoEmbed.php b/app/Pagebuilder/VideoEmbed.php new file mode 100644 index 00000000..9abe41c0 --- /dev/null +++ b/app/Pagebuilder/VideoEmbed.php @@ -0,0 +1,34 @@ + '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; + } +} diff --git a/app/Plugins/Hooks.php b/app/Plugins/Hooks.php new file mode 100644 index 00000000..21fb0963 --- /dev/null +++ b/app/Plugins/Hooks.php @@ -0,0 +1,67 @@ + …); // Action + * Hooks::do('post.published', $post); + * + * Hooks::filter('navigation.items', fn (array $items) => [...]); // Filter + * $items = Hooks::apply('navigation.items', $items); + * + * Niedrigere Priorität läuft zuerst (Standard 10). + */ +class Hooks +{ + /** @var array>> */ + private array $actions = []; + + /** @var array>> */ + private array $filters = []; + + public static function on(string $name, callable $callback, int $priority = 10): void + { + app(self::class)->actions[$name][$priority][] = $callback; + } + + public static function do(string $name, mixed ...$arguments): void + { + foreach (app(self::class)->sorted(app(self::class)->actions[$name] ?? []) as $callback) { + $callback(...$arguments); + } + } + + public static function filter(string $name, callable $callback, int $priority = 10): void + { + app(self::class)->filters[$name][$priority][] = $callback; + } + + public static function apply(string $name, mixed $value, mixed ...$arguments): mixed + { + foreach (app(self::class)->sorted(app(self::class)->filters[$name] ?? []) as $callback) { + $value = $callback($value, ...$arguments); + } + + return $value; + } + + public static function has(string $name): bool + { + $hooks = app(self::class); + + return ! empty($hooks->actions[$name]) || ! empty($hooks->filters[$name]); + } + + /** + * @param array> $byPriority + * @return list + */ + private function sorted(array $byPriority): array + { + ksort($byPriority); + + return array_merge(...array_values($byPriority) ?: [[]]); + } +} diff --git a/app/Plugins/Plugin.php b/app/Plugins/Plugin.php new file mode 100644 index 00000000..b3215c43 --- /dev/null +++ b/app/Plugins/Plugin.php @@ -0,0 +1,39 @@ +manifest->path.($path !== '' ? '/'.ltrim($path, '/') : ''); + } +} diff --git a/app/Plugins/PluginInstaller.php b/app/Plugins/PluginInstaller.php new file mode 100644 index 00000000..684f7246 --- /dev/null +++ b/app/Plugins/PluginInstaller.php @@ -0,0 +1,75 @@ +. + * Nutzt denselben ZIP-Slip-Schutz wie der Self-Updater. Ein vorhandenes Plugin + * mit gleichem Kürzel wird ersetzt (Update), seine Daten bleiben erhalten. + */ +class PluginInstaller +{ + public function __construct( + private readonly PluginManager $plugins, + private readonly ZipExtractor $extractor, + ) {} + + public static function uploadsAllowed(): bool + { + return ! filter_var(config('inhaus.disallow_file_mods'), FILTER_VALIDATE_BOOL); + } + + public function install(string $zipFile): PluginManifest + { + if (! self::uploadsAllowed()) { + throw new RuntimeException('Das Installieren von Plugins ist in dieser Installation abgeschaltet.'); + } + + $staging = storage_path('framework/plugin-upload-'.bin2hex(random_bytes(4))); + + try { + $this->extractor->extract($zipFile, $staging); + + try { + $manifest = PluginManifest::fromDirectory($staging, core: false); + } catch (Throwable $e) { + throw new RuntimeException('Das Archiv enthält kein gültiges Plugin: '.$e->getMessage()); + } + + $existing = $this->plugins->find($manifest->slug); + + if ($existing?->core) { + throw new RuntimeException("Das Kürzel „{$manifest->slug}“ gehört zu einem mitgelieferten Plugin."); + } + + if (! is_file($staging.'/src/'.str_replace('\\', '/', substr($manifest->class, strlen($manifest->namespace))).'.php')) { + throw new RuntimeException("Die Plugin-Klasse {$manifest->class} fehlt im Archiv (erwartet unter src/)."); + } + + $target = $this->plugins->customerPath().'/'.$manifest->slug; + + if (! is_dir(dirname($target)) && ! @mkdir(dirname($target), 0775, true)) { + throw new RuntimeException('Das Verzeichnis plugins/ ist nicht beschreibbar.'); + } + + Filesystem::deleteDirectory($target); + + if (! Filesystem::moveDirectory($staging, $target)) { + throw new RuntimeException('Das Plugin konnte nicht nach plugins/ verschoben werden. Bitte Schreibrechte prüfen.'); + } + + $this->plugins->forgetDiscovered(); + Audit::log($existing ? 'plugin.updated' : 'plugin.installed', ['plugin' => $manifest->slug, 'version' => $manifest->version]); + + return PluginManifest::fromDirectory($target, core: false); + } finally { + Filesystem::deleteDirectory($staging); + } + } +} diff --git a/app/Plugins/PluginManager.php b/app/Plugins/PluginManager.php new file mode 100644 index 00000000..7ff87083 --- /dev/null +++ b/app/Plugins/PluginManager.php @@ -0,0 +1,411 @@ +/ mitgeliefert (Teil jedes Updates) + * plugins// vom Kunden installiert (geschützt, Updates lassen sie in Ruhe) + * + * Wiederherstellungsmodus: Vor dem Laden eines Plugins wird eine Markierung + * geschrieben und danach entfernt. Bleibt sie liegen, ist der Prozess beim + * Laden abgestürzt (Fatal Error) – das Plugin wird beim nächsten Aufruf + * deaktiviert, das Portal bleibt erreichbar. Ausnahmen führen sofort dazu. + */ +class PluginManager +{ + /** Ab diesem Alter gilt eine liegengebliebene Lade-Markierung als Absturz. */ + private const CRASH_AFTER_SECONDS = 30; + + /** @var array|null */ + private ?array $manifests = null; + + /** @var array */ + private array $loaded = []; + + /** @var array Slug => Grund */ + private array $problems = []; + + /** @var array */ + private array $autoloaded = []; + + public function __construct( + private readonly Application $app, + private readonly PluginState $state, + private readonly ?string $corePath = null, + private readonly ?string $customerPath = null, + ) {} + + /** + * @return array + */ + public function all(): array + { + if ($this->manifests !== null) { + return $this->manifests; + } + + $this->manifests = []; + + foreach ([[$this->corePath(), true], [$this->customerPath(), false]] as [$directory, $core]) { + foreach (glob($directory.'/*/plugin.json') ?: [] as $file) { + try { + $manifest = PluginManifest::fromDirectory(dirname($file), $core); + } catch (Throwable $e) { + $this->problems[basename(dirname($file))] = $e->getMessage(); + + continue; + } + + if (isset($this->manifests[$manifest->slug])) { + $this->problems[$manifest->slug] = 'Ein Plugin mit diesem Kürzel ist bereits vorhanden.'; + + continue; + } + + $this->manifests[$manifest->slug] = $manifest; + } + } + + ksort($this->manifests); + + return $this->manifests; + } + + public function find(string $slug): ?PluginManifest + { + return $this->all()[$slug] ?? null; + } + + public function isEnabled(string $slug): bool + { + $manifest = $this->find($slug); + + return $manifest !== null && $this->state->isEnabled($manifest); + } + + public function isLoaded(string $slug): bool + { + return isset($this->loaded[$slug]); + } + + /** + * @return array + */ + public function loaded(): array + { + return $this->loaded; + } + + public function problem(string $slug): ?string + { + return $this->problems[$slug] ?? $this->state->disabledReason($slug); + } + + /** + * Aktive, lauffähige Plugins in Abhängigkeitsreihenfolge. + * + * @return list + */ + public function bootOrder(): array + { + $candidates = array_filter($this->all(), fn (PluginManifest $m) => $this->state->isEnabled($m)); + $ordered = []; + $visiting = []; + + $visit = function (PluginManifest $manifest) use (&$visit, &$ordered, &$visiting, $candidates): bool { + if (isset($ordered[$manifest->slug])) { + return true; + } + + if (isset($visiting[$manifest->slug]) || $manifest->incompatibilities() !== []) { + $this->problems[$manifest->slug] ??= implode(', ', $manifest->incompatibilities()) ?: 'Zirkuläre Abhängigkeit.'; + + return false; + } + + $visiting[$manifest->slug] = true; + + foreach ($manifest->requiredPlugins() as $dependency) { + if (! isset($candidates[$dependency]) || ! $visit($candidates[$dependency])) { + $this->problems[$manifest->slug] ??= "benötigt das Plugin „{$dependency}“"; + unset($visiting[$manifest->slug]); + + return false; + } + } + + unset($visiting[$manifest->slug]); + $ordered[$manifest->slug] = $manifest; + + return true; + }; + + foreach ($candidates as $manifest) { + $visit($manifest); + } + + return array_values($ordered); + } + + /** + * Phase 1: Autoload und register() aller aktiven Plugins. + */ + public function registerAll(): void + { + $this->recoverFromCrash(); + + foreach ($this->bootOrder() as $manifest) { + $this->guard($manifest, function () use ($manifest) { + $this->registerAutoload($manifest); + $plugin = $this->instantiate($manifest); + $plugin->register(); + $this->loaded[$manifest->slug] = $plugin; + }); + } + } + + /** + * Phase 2: Migrationen, Views, Routen und boot(). + */ + public function bootAll(): void + { + foreach ($this->loaded as $slug => $plugin) { + $manifest = $plugin->manifest; + + $this->guard($manifest, function () use ($plugin, $manifest) { + if (is_dir($manifest->migrationsPath())) { + $this->app['migrator']->path($manifest->migrationsPath()); + } + + if (is_dir($manifest->path.'/resources/views')) { + $this->app['view']->addNamespace($manifest->slug, $manifest->path.'/resources/views'); + } + + if (is_file($manifest->path.'/routes/web.php') && ! $this->app->routesAreCached()) { + Route::middleware('web')->group($manifest->path.'/routes/web.php'); + } + + $plugin->boot(); + }); + } + } + + public function activate(string $slug): void + { + $manifest = $this->find($slug) ?? throw new RuntimeException('Plugin nicht gefunden.'); + + if ($problems = $manifest->incompatibilities()) { + throw new RuntimeException('Das Plugin kann nicht aktiviert werden: '.implode(', ', $problems).'.'); + } + + foreach ($manifest->requiredPlugins() as $dependency) { + if (! $this->isEnabled($dependency)) { + throw new RuntimeException("Bitte zuerst das Plugin „{$dependency}“ aktivieren."); + } + } + + $this->registerAutoload($manifest); + + if (is_dir($manifest->migrationsPath())) { + Artisan::call('migrate', ['--path' => $manifest->migrationsPath(), '--realpath' => true, '--force' => true]); + } + + $this->instantiate($manifest)->activate(); + $this->state->setEnabled($slug, true); + Audit::log('plugin.activated', ['plugin' => $slug, 'version' => $manifest->version]); + } + + public function deactivate(string $slug, ?string $reason = null): void + { + $manifest = $this->find($slug) ?? throw new RuntimeException('Plugin nicht gefunden.'); + + if ($reason === null && ($dependents = $this->dependents($slug)) !== []) { + throw new RuntimeException('Wird noch benötigt von: '.implode(', ', $dependents).'.'); + } + + if ($reason === null && isset($this->loaded[$slug])) { + $this->loaded[$slug]->deactivate(); + } + + $this->state->setEnabled($slug, false, $reason); + Audit::log('plugin.deactivated', ['plugin' => $slug, 'reason' => $reason]); + } + + /** + * Kunden-Plugin löschen, optional samt Daten (Tabellen aus den Migrationen). + */ + public function delete(string $slug, bool $removeData): void + { + $manifest = $this->find($slug) ?? throw new RuntimeException('Plugin nicht gefunden.'); + + if ($manifest->core) { + throw new RuntimeException('Mitgelieferte Plugins können nur deaktiviert werden.'); + } + + if ($this->isEnabled($slug)) { + $this->deactivate($slug); + } + + if ($removeData) { + $this->registerAutoload($manifest); + $this->instantiate($manifest)->uninstall(); + + if (is_dir($manifest->migrationsPath())) { + Artisan::call('migrate:reset', ['--path' => $manifest->migrationsPath(), '--realpath' => true, '--force' => true]); + } + } + + Filesystem::deleteDirectory($manifest->path); + $this->state->forget($slug); + $this->manifests = null; + Audit::log('plugin.deleted', ['plugin' => $slug, 'data_removed' => $removeData]); + } + + /** + * @return list + */ + public function dependents(string $slug): array + { + return array_values(array_map( + fn (PluginManifest $m) => $m->name, + array_filter($this->all(), fn (PluginManifest $m) => $this->isEnabled($m->slug) && in_array($slug, $m->requiredPlugins(), true)), + )); + } + + /** + * Verzeichnisse für Filament (Ressourcen, Seiten, Widgets) der geladenen Plugins. + * + * @return list + */ + public function filamentDiscovery(): array + { + $result = []; + + foreach ($this->loaded as $plugin) { + foreach (['Resources', 'Pages', 'Widgets'] as $type) { + $path = $plugin->manifest->path."/src/Filament/{$type}"; + + if (is_dir($path)) { + $result[] = ['type' => $type, 'path' => $path, 'namespace' => $plugin->manifest->namespace."Filament\\{$type}"]; + } + } + } + + return $result; + } + + public function corePath(): string + { + return $this->corePath ?? base_path('plugins-core'); + } + + public function customerPath(): string + { + return $this->customerPath ?? base_path('plugins'); + } + + public function forgetDiscovered(): void + { + $this->manifests = null; + } + + private function instantiate(PluginManifest $manifest): Plugin + { + if (! class_exists($manifest->class)) { + throw new RuntimeException("Plugin-Klasse {$manifest->class} nicht gefunden."); + } + + $plugin = new ($manifest->class)($this->app, $manifest); + + if (! $plugin instanceof Plugin) { + throw new RuntimeException("{$manifest->class} muss von ".Plugin::class.' erben.'); + } + + return $plugin; + } + + private function registerAutoload(PluginManifest $manifest): void + { + if (isset($this->autoloaded[$manifest->slug])) { + return; + } + + $prefix = $manifest->namespace; + $base = $manifest->path.'/src/'; + + spl_autoload_register(function (string $class) use ($prefix, $base) { + if (str_starts_with($class, $prefix)) { + $file = $base.str_replace('\\', '/', substr($class, strlen($prefix))).'.php'; + + if (is_file($file)) { + require $file; + } + } + }); + + // Eigene Abhängigkeiten eines Plugins (gescoped, siehe docs/PLAN.md 4.2). + if (is_file($manifest->path.'/vendor/autoload.php')) { + require_once $manifest->path.'/vendor/autoload.php'; + } + + $this->autoloaded[$manifest->slug] = true; + } + + private function guard(PluginManifest $manifest, callable $callback): void + { + $marker = $this->markerPath($manifest->slug); + @file_put_contents($marker, (string) time()); + + try { + $callback(); + } catch (Throwable $e) { + unset($this->loaded[$manifest->slug]); + $this->problems[$manifest->slug] = $e->getMessage(); + Log::error("Plugin {$manifest->slug} wurde wegen eines Fehlers deaktiviert: ".$e->getMessage(), ['exception' => $e]); + + try { + $this->deactivate($manifest->slug, 'Fehler beim Laden: '.$e->getMessage()); + } catch (Throwable) { + $this->state->setEnabled($manifest->slug, false, 'Fehler beim Laden: '.$e->getMessage()); + } + } finally { + @unlink($marker); + } + } + + private function recoverFromCrash(): void + { + foreach (glob($this->markerPath('*')) ?: [] as $marker) { + if (time() - (int) @filemtime($marker) < self::CRASH_AFTER_SECONDS) { + continue; // Lädt vermutlich gerade in einer parallelen Anfrage. + } + + $slug = substr(basename($marker), strlen('booting-')); + Log::critical("Plugin {$slug} hat beim Laden einen schweren Fehler verursacht und wurde deaktiviert."); + $this->state->setEnabled($slug, false, 'Schwerer Fehler beim Laden (das Portal wurde dadurch unterbrochen).'); + @unlink($marker); + } + } + + private function markerPath(string $slug): string + { + $dir = storage_path('framework/plugins'); + + if (! is_dir($dir)) { + @mkdir($dir, 0775, true); + } + + return $dir.'/booting-'.$slug; + } +} diff --git a/app/Plugins/PluginManifest.php b/app/Plugins/PluginManifest.php new file mode 100644 index 00000000..51291a3d --- /dev/null +++ b/app/Plugins/PluginManifest.php @@ -0,0 +1,130 @@ +=0.3.0", "php": ">=8.3", "plugins": ["news"] }, + * "update_url": "https://…" + * } + */ +final class PluginManifest +{ + public const SLUG_PATTERN = '/^[a-z0-9]+(?:-[a-z0-9]+)*$/'; + + /** + * @param array $data + */ + private function __construct( + public readonly string $slug, + public readonly string $name, + public readonly string $version, + public readonly string $description, + public readonly string $author, + public readonly string $namespace, + public readonly string $class, + public readonly string $path, + public readonly bool $core, + public readonly array $requires, + public readonly ?string $updateUrl, + public readonly bool $enabledByDefault = true, + ) {} + + public static function fromDirectory(string $path, bool $core): self + { + $file = rtrim($path, '/').'/plugin.json'; + $data = json_decode((string) @file_get_contents($file), true); + + if (! is_array($data)) { + throw new InvalidArgumentException('plugin.json fehlt oder ist kein gültiges JSON.'); + } + + return self::fromArray($data, $path, $core); + } + + /** + * @param array $data + */ + public static function fromArray(array $data, string $path, bool $core): self + { + foreach (['slug', 'name', 'version', 'namespace', 'class'] as $field) { + if (! is_string($data[$field] ?? null) || trim($data[$field]) === '') { + throw new InvalidArgumentException("plugin.json: Feld „{$field}“ fehlt."); + } + } + + if (! preg_match(self::SLUG_PATTERN, $data['slug'])) { + throw new InvalidArgumentException('plugin.json: „slug“ darf nur Kleinbuchstaben, Ziffern und Bindestriche enthalten.'); + } + + $namespace = rtrim($data['namespace'], '\\').'\\'; + + if (! str_starts_with(ltrim($data['class'], '\\'), $namespace)) { + throw new InvalidArgumentException('plugin.json: „class“ muss im angegebenen Namespace liegen.'); + } + + if (str_starts_with($namespace, 'App\\') || str_starts_with($namespace, 'Illuminate\\')) { + throw new InvalidArgumentException('plugin.json: Der Namespace „App\\“ ist dem Kern vorbehalten.'); + } + + return new self( + slug: $data['slug'], + name: $data['name'], + version: $data['version'], + description: (string) ($data['description'] ?? ''), + author: (string) ($data['author'] ?? ''), + namespace: $namespace, + class: ltrim($data['class'], '\\'), + path: rtrim($path, '/'), + core: $core, + requires: is_array($data['requires'] ?? null) ? $data['requires'] : [], + updateUrl: is_string($data['update_url'] ?? null) ? $data['update_url'] : null, + enabledByDefault: (bool) ($data['enabled_by_default'] ?? true), + ); + } + + /** + * @return list + */ + public function requiredPlugins(): array + { + return array_values(array_filter((array) ($this->requires['plugins'] ?? []), 'is_string')); + } + + /** + * Gründe, warum das Plugin in dieser Umgebung nicht laufen kann. + * + * @return list + */ + public function incompatibilities(): array + { + $problems = []; + + if (! VersionConstraint::satisfies(Version::VERSION, $this->requires['core'] ?? null)) { + $problems[] = 'benötigt Inhaus '.$this->requires['core']; + } + + if (! VersionConstraint::satisfies(PHP_VERSION, $this->requires['php'] ?? null)) { + $problems[] = 'benötigt PHP '.$this->requires['php']; + } + + return $problems; + } + + public function migrationsPath(): string + { + return $this->path.'/database/migrations'; + } +} diff --git a/app/Plugins/PluginState.php b/app/Plugins/PluginState.php new file mode 100644 index 00000000..29c7a948 --- /dev/null +++ b/app/Plugins/PluginState.php @@ -0,0 +1,87 @@ +>|null */ + private ?array $data = null; + + public function __construct(private readonly ?string $file = null) {} + + public function isEnabled(PluginManifest $manifest): bool + { + $entry = $this->all()[$manifest->slug] ?? null; + + return is_array($entry) ? (bool) ($entry['enabled'] ?? false) : $manifest->core && ($manifest->enabledByDefault || self::$enableOptionalCorePlugins); + } + + public function setEnabled(string $slug, bool $enabled, ?string $reason = null): void + { + $this->update($slug, ['enabled' => $enabled, 'disabled_reason' => $enabled ? null : $reason]); + } + + public function disabledReason(string $slug): ?string + { + return $this->all()[$slug]['disabled_reason'] ?? null; + } + + public function forget(string $slug): void + { + $data = $this->all(); + unset($data[$slug]); + $this->write($data); + } + + /** + * @return array> + */ + public function all(): array + { + if ($this->data === null) { + $decoded = json_decode((string) @file_get_contents($this->path()), true); + $this->data = is_array($decoded) ? $decoded : []; + } + + return $this->data; + } + + /** + * @param array $values + */ + private function update(string $slug, array $values): void + { + $this->data = null; + $data = $this->all(); + $data[$slug] = array_merge($data[$slug] ?? [], $values); + $this->write($data); + } + + /** + * @param array> $data + */ + private function write(array $data): void + { + AtomicFile::write($this->path(), json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); + $this->data = $data; + } + + private function path(): string + { + return $this->file ?? storage_path('app/plugins.json'); + } +} diff --git a/app/Plugins/VersionConstraint.php b/app/Plugins/VersionConstraint.php new file mode 100644 index 00000000..2c686b75 --- /dev/null +++ b/app/Plugins/VersionConstraint.php @@ -0,0 +1,58 @@ +=1.2“, „<2.0“, „^1.4“, + * „~1.4“, „1.2.3“, „*“ – mehrere mit Leerzeichen oder Komma verknüpft (UND). + */ +final class VersionConstraint +{ + public static function satisfies(string $version, ?string $constraint): bool + { + $constraint = trim((string) $constraint); + + if ($constraint === '' || $constraint === '*') { + return true; + } + + foreach (preg_split('/[\s,]+/', $constraint) ?: [] as $part) { + if (! self::check(self::normalize($version), $part)) { + return false; + } + } + + return true; + } + + private static function check(string $version, string $part): bool + { + if (str_starts_with($part, '^')) { + $min = self::normalize(substr($part, 1)); + [$major, $minor] = array_map('intval', explode('.', $min)); + $max = $major > 0 ? ($major + 1).'.0.0' : '0.'.($minor + 1).'.0'; + + return version_compare($version, $min, '>=') && version_compare($version, $max, '<'); + } + + if (str_starts_with($part, '~')) { + $min = self::normalize(substr($part, 1)); + [$major, $minor] = array_map('intval', explode('.', $min)); + + return version_compare($version, $min, '>=') && version_compare($version, $major.'.'.($minor + 1).'.0', '<'); + } + + if (preg_match('/^(>=|<=|>|<|==|=|!=)(.+)$/', $part, $m)) { + return version_compare($version, self::normalize($m[2]), $m[1] === '=' ? '==' : $m[1]); + } + + return version_compare($version, self::normalize($part), '=='); + } + + private static function normalize(string $version): string + { + $parts = explode('.', preg_replace('/[^0-9.].*$/', '', ltrim(trim($version), 'vV'))); + + return implode('.', array_slice(array_pad(array_map('intval', $parts), 3, 0), 0, 3)); + } +} diff --git a/app/Policies/RolePolicy.php b/app/Policies/RolePolicy.php new file mode 100644 index 00000000..c8673ce0 --- /dev/null +++ b/app/Policies/RolePolicy.php @@ -0,0 +1,37 @@ +can('roles.manage'); + } + + public function view(User $user, Role $role): bool + { + return $user->can('roles.manage'); + } + + public function create(User $user): bool + { + return $user->can('roles.manage'); + } + + public function update(User $user, Role $role): bool + { + return $user->can('roles.manage'); + } + + /** + * Systemrollen (Administration) lassen sich nicht löschen. + */ + public function delete(User $user, Role $role): bool + { + return $user->can('roles.manage') && ! $role->is_system; + } +} diff --git a/app/Policies/UserPolicy.php b/app/Policies/UserPolicy.php new file mode 100644 index 00000000..1596ee76 --- /dev/null +++ b/app/Policies/UserPolicy.php @@ -0,0 +1,33 @@ +can('users.manage'); + } + + public function view(User $user, User $model): bool + { + return $user->can('users.manage'); + } + + public function create(User $user): bool + { + return $user->can('users.manage'); + } + + public function update(User $user, User $model): bool + { + return $user->can('users.manage'); + } + + public function delete(User $user, User $model): bool + { + return $user->can('users.manage') && ! $model->is($user); + } +} diff --git a/app/Profile/ProfileSections.php b/app/Profile/ProfileSections.php new file mode 100644 index 00000000..967427ac --- /dev/null +++ b/app/Profile/ProfileSections.php @@ -0,0 +1,52 @@ +/resources/js/profile/.vue („::Name“) + * und speichert über eigene Routen des Plugins. + */ +class ProfileSections +{ + /** @var array */ + private array $sections = []; + + /** + * @param Closure(User): (array|null) $props null = Abschnitt nicht zeigen + */ + public function add(string $key, string $component, int $sort, Closure $props): void + { + $this->sections[$key] = compact('component', 'sort', 'props'); + } + + /** + * @return list}> + */ + public function resolve(User $user): array + { + $result = []; + + foreach (collect($this->sections)->sortBy('sort') as $key => $section) { + try { + $props = ($section['props'])($user); + } catch (Throwable $e) { + Log::error("Profilabschnitt {$key} fehlgeschlagen: ".$e->getMessage()); + + continue; + } + + if ($props !== null) { + $result[] = ['key' => $key, 'component' => $section['component'], 'props' => $props]; + } + } + + return $result; + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 934e6a58..5f10d37a 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -2,12 +2,31 @@ namespace App\Providers; +use App\Dashboard\CoreWidgets; +use App\Dashboard\Widgets; +use App\Editorial\Editorial; +use App\Models\User; +use App\Pagebuilder\Blocks; +use App\Support\Abilities; use App\Support\Avatars; +use App\Support\BackgroundTasks; use App\Support\Branding; +use App\Support\Installation; +use App\Support\License\LicenseStore; +use App\Support\MailSettings; use App\Support\Navigation; +use App\Support\Permissions\PermissionResource; +use App\Support\Permissions\Permissions; +use App\Support\ProfileFields; use App\Support\QuickLinks; use App\Support\Settings; +use App\Support\Theme\Theme; +use App\Support\Theme\ThemeCompiler; +use App\Support\Update\InstalledVersion; +use App\Support\Update\MaintenanceFlag; +use App\Support\Update\UpdateProgress; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\Gate; use Illuminate\Support\ServiceProvider; use Illuminate\Validation\Rules\Password; @@ -15,18 +34,72 @@ class AppServiceProvider extends ServiceProvider { public function register(): void { + // Frisch hochgeladen: .env und Schlüssel anlegen; bis zur Einrichtung ohne Datenbank + // für Sitzungen, Cache und Queue auskommen (der Web-Installer braucht das). + if (! $this->app->runningUnitTests()) { + Installation::prepareEnvironment(); + } + + if (! Installation::isInstalled()) { + config(['session.driver' => 'file', 'cache.default' => 'file', 'queue.default' => 'sync']); + } + $this->app->singleton(Settings::class); + $this->app->singleton(MailSettings::class); $this->app->singleton(Branding::class); + $this->app->singleton(Theme::class); + $this->app->singleton(ThemeCompiler::class); $this->app->singleton(Avatars::class); - $this->app->singleton(Navigation::class); $this->app->singleton(QuickLinks::class); + $this->app->singleton(LicenseStore::class); + $this->app->singleton(Permissions::class); + $this->app->singleton(ProfileFields::class); + $this->app->singleton(Blocks::class); + $this->app->singleton(Editorial::class); + $this->app->singleton(BackgroundTasks::class); + $this->app->singleton(InstalledVersion::class); + $this->app->singleton(UpdateProgress::class); + $this->app->singleton(MaintenanceFlag::class); } public function boot(): void { + CoreWidgets::register($this->app->make(Widgets::class)); + + $this->app->make(Navigation::class)->add('editorial', 'Redaktion', '/redaktion', active: ['editorial', 'pages.editor', 'news.editor.*', 'forms.builder'], sort: 85, + visible: fn (User $user) => $this->app->make(Editorial::class)->visibleFor($user)); + // N+1-Abfragen in Entwicklung und Tests sofort sichtbar machen (docs/PLAN.md, Performance). Model::preventLazyLoading(! $this->app->isProduction()); + // Rechte aus Rollen (App\Support\Abilities) entscheidet das Rechtesystem – Administration + // hat sie alle. Alles andere (z. B. „delete“ auf einem Modell) entscheiden die Policies, + // damit Regeln wie „Systemrollen nie löschen“ auch für Administratoren gelten. + Gate::before(function (User $user, string $ability, array $arguments) { + if (! $user->is_active) { + return false; + } + + if (! $this->app->make(Abilities::class)->exists($ability)) { + return null; + } + + [$type, $id] = PermissionResource::from($arguments); + + return $user->permissions()->can($ability, $type, $id); + }); + Password::defaults(fn () => Password::min(10)->letters()->numbers()); + + if (Installation::isInstalled()) { + $this->app->make(MailSettings::class)->apply(); + + // Whitelabel: Laravel nutzt app.name z. B. in Benachrichtigungs-Mails („Viele Grüße …“). + try { + config(['app.name' => $this->app->make(Branding::class)->portalName()]); + } catch (\Throwable) { + // Datenbank noch nicht bereit + } + } } } diff --git a/app/Providers/Filament/AdminPanelProvider.php b/app/Providers/Filament/AdminPanelProvider.php index c355f28c..31b35592 100644 --- a/app/Providers/Filament/AdminPanelProvider.php +++ b/app/Providers/Filament/AdminPanelProvider.php @@ -3,7 +3,15 @@ namespace App\Providers\Filament; use App\Filament\AvatarProviders\InitialsAvatarProvider; +use App\Filament\Pages\Feedback; +use App\Filament\Resources\DashboardTiles\DashboardTileResource; +use App\Filament\Resources\IdentityProviders\IdentityProviderResource; +use App\Filament\Resources\ProfileFields\ProfileFieldResource; +use App\Filament\Resources\Roles\RoleResource; +use App\Filament\Resources\Users\UserResource; +use App\Plugins\PluginManager; use App\Support\Branding; +use Filament\Actions\Action; use Filament\Http\Middleware\Authenticate; use Filament\Http\Middleware\AuthenticateSession; use Filament\Http\Middleware\DisableBladeIconComponents; @@ -27,24 +35,43 @@ class AdminPanelProvider extends PanelProvider { // Keine eigene Filament-Anmeldung: das Admin-Backend nutzt den Portal-Login // (und damit später auch Entra ID). Nicht angemeldete Personen landen auf /login. - return $panel + $panel = $panel ->default() ->id('admin') ->path('admin') ->defaultAvatarProvider(InitialsAvatarProvider::class) ->brandName(fn () => app(Branding::class)->portalName()) ->brandLogo(fn () => app(Branding::class)->logoUrl()) + ->darkModeBrandLogo(fn () => app(Branding::class)->logoDarkUrl()) + ->brandLogoHeight('2rem') + ->favicon(fn () => app(Branding::class)->faviconUrl()) ->colors(fn () => [ 'primary' => app(Branding::class)->palette(), ]) - ->navigationGroups(['Inhalte', 'Portal']) + ->navigationGroups(['Inhalte', 'Benutzer & Rechte', 'Portal', 'System', 'Hilfe']) + ->databaseNotifications() + ->userMenuItems([ + Action::make('feedback') + ->label('Rückmeldung geben') + ->icon(Heroicon::OutlinedChatBubbleLeftEllipsis) + ->url(fn () => Feedback::getUrl()), + ]) ->navigationItems([ NavigationItem::make('Zum Portal') ->url('/') ->icon(Heroicon::OutlinedArrowTopRightOnSquare) ->sort(100), ]) - ->discoverResources(in: app_path('Filament/Resources'), for: 'App\Filament\Resources') + // Kern-Ressourcen ausdrücklich registrieren statt das Verzeichnis zu durchsuchen: + // Der Self-Updater löscht nie Dateien, verschobene Ressourcen (z. B. nach + // plugins-core/) blieben sonst als Doppelgänger liegen und würden mitgeladen. + ->resources([ + UserResource::class, + RoleResource::class, + ProfileFieldResource::class, + DashboardTileResource::class, + IdentityProviderResource::class, + ]) ->discoverPages(in: app_path('Filament/Pages'), for: 'App\Filament\Pages') ->pages([ Dashboard::class, @@ -67,5 +94,16 @@ class AdminPanelProvider extends PanelProvider ->authMiddleware([ Authenticate::class, ]); + + // Admin-Seiten der aktiven Plugins (src/Filament/{Resources,Pages,Widgets}). + foreach (app(PluginManager::class)->filamentDiscovery() as $discovery) { + match ($discovery['type']) { + 'Resources' => $panel->discoverResources(in: $discovery['path'], for: $discovery['namespace']), + 'Pages' => $panel->discoverPages(in: $discovery['path'], for: $discovery['namespace']), + 'Widgets' => $panel->discoverWidgets(in: $discovery['path'], for: $discovery['namespace']), + }; + } + + return $panel; } } diff --git a/app/Providers/FortifyServiceProvider.php b/app/Providers/FortifyServiceProvider.php index 57225ab4..1fb305db 100644 --- a/app/Providers/FortifyServiceProvider.php +++ b/app/Providers/FortifyServiceProvider.php @@ -4,6 +4,7 @@ namespace App\Providers; use App\Actions\Fortify\ResetUserPassword; use App\Actions\Fortify\UpdateUserPassword; +use App\Models\IdentityProvider; use App\Models\User; use Illuminate\Auth\Events\Login; use Illuminate\Cache\RateLimiting\Limit; @@ -25,7 +26,12 @@ class FortifyServiceProvider extends ServiceProvider Fortify::loginView(fn (Request $request) => Inertia::render('Auth/Login', [ 'canResetPassword' => true, - 'status' => $request->session()->get('status'), + 'providers' => IdentityProvider::query()->where('enabled', true)->orderBy('name')->get() + ->map(fn (IdentityProvider $p) => ['slug' => $p->slug, 'label' => $p->buttonLabel(), 'type' => $p->type])->values(), + 'identityError' => $request->session()->get('identity_error'), + 'status' => $request->boolean('eingerichtet') + ? 'Die Einrichtung ist abgeschlossen. Sie können sich jetzt mit Ihrem Administratorkonto anmelden.' + : $request->session()->get('status'), ])); Fortify::requestPasswordResetLinkView(fn (Request $request) => Inertia::render('Auth/ForgotPassword', [ diff --git a/app/Providers/PluginServiceProvider.php b/app/Providers/PluginServiceProvider.php new file mode 100644 index 00000000..9d57c021 --- /dev/null +++ b/app/Providers/PluginServiceProvider.php @@ -0,0 +1,37 @@ +app->singleton(Hooks::class); + $this->app->singleton(PluginState::class); + $this->app->singleton(PluginManager::class); + $this->app->singleton(Navigation::class); + $this->app->singleton(Widgets::class); + $this->app->singleton(Abilities::class); + $this->app->singleton(ProfileSections::class); + + $this->app->make(PluginManager::class)->registerAll(); + } + + public function boot(): void + { + $this->app->make(PluginManager::class)->bootAll(); + } +} diff --git a/app/Support/Abilities.php b/app/Support/Abilities.php new file mode 100644 index 00000000..665cd40d --- /dev/null +++ b/app/Support/Abilities.php @@ -0,0 +1,97 @@ + */ + private array $abilities = []; + + /** @var array */ + private array $resourceTypes = []; + + public function __construct() + { + $this->define('users.manage', 'Benutzer verwalten', 'System'); + $this->define('roles.manage', 'Rollen und Rechte verwalten', 'System'); + $this->define('identity.manage', 'Anmeldung (Microsoft Entra ID) einrichten', 'System'); + $this->define('plugins.manage', 'Plugins verwalten und installieren', 'System'); + $this->define('appearance.manage', 'Erscheinungsbild und Schnellzugriffe', 'System'); + $this->define('updates.manage', 'Aktualisierungen, Lizenz und Systemzustand', 'System'); + $this->define('mail.manage', 'E-Mail-Versand einrichten', 'System'); + $this->define('feedback.send', 'Rückmeldungen an den Hersteller senden', 'System'); + } + + public function define(string $ability, string $label, string $group, ?string $resource = null): void + { + $this->abilities[$ability] = ['label' => $label, 'group' => $group, 'resource' => $resource]; + } + + /** + * Objekttyp, auf den sich Rechte beziehen können (z. B. „news_category“). + * + * Hierarchische Typen (z. B. Seiten) geben $descendants an: Rechte mit + * „inkl. Unterobjekten“ gelten dann auch für alle Nachfahren. + * + * @param callable(): array $options ID => Bezeichnung + * @param (callable(list): list)|null $descendants IDs => IDs aller Nachfahren + */ + public function resourceType(string $type, string $label, callable $options, ?callable $descendants = null): void + { + $this->resourceTypes[$type] = ['label' => $label, 'options' => $options, 'descendants' => $descendants]; + } + + public function isHierarchical(?string $type): bool + { + return $type !== null && isset($this->resourceTypes[$type]['descendants']); + } + + /** + * @return array + */ + public function all(): array + { + return $this->abilities; + } + + /** + * @return array + */ + public function global(): array + { + return array_filter($this->abilities, fn (array $a) => $a['resource'] === null); + } + + /** + * @return array + */ + public function forResource(string $type): array + { + return array_filter($this->abilities, fn (array $a) => $a['resource'] === $type); + } + + /** + * @return array + */ + public function resourceTypes(): array + { + return $this->resourceTypes; + } + + public function exists(string $ability): bool + { + return isset($this->abilities[$ability]); + } + + public function label(string $ability): string + { + return $this->abilities[$ability]['label'] ?? $ability; + } +} diff --git a/app/Support/Audit.php b/app/Support/Audit.php new file mode 100644 index 00000000..346b6863 --- /dev/null +++ b/app/Support/Audit.php @@ -0,0 +1,30 @@ + $data + */ + public static function log(string $action, array $data = [], ?int $userId = null): void + { + $userId ??= auth()->id(); + + Log::info("audit: {$action}", [...$data, 'user_id' => $userId]); + + try { + AuditLog::query()->create(['user_id' => $userId, 'action' => $action, 'data' => $data]); + } catch (Throwable $e) { + Log::warning('Audit-Eintrag konnte nicht gespeichert werden: '.$e->getMessage()); + } + } +} diff --git a/app/Support/Avatars.php b/app/Support/Avatars.php index 14b20fd4..eaf121aa 100644 --- a/app/Support/Avatars.php +++ b/app/Support/Avatars.php @@ -25,8 +25,28 @@ class Avatars public function store(User $user, UploadedFile $file): void { - Images::raiseMemoryLimitFor($file->getRealPath()); - $image = ImageManager::usingDriver(Driver::class)->decodePath($file->getRealPath()); + $this->storeFromPath($user, $file->getRealPath()); + } + + /** + * Profilbild aus Binärdaten (z. B. Foto aus Microsoft Entra). + */ + public function storeFromBinary(User $user, string $binary): void + { + $temporary = tempnam(sys_get_temp_dir(), 'avatar'); + file_put_contents($temporary, $binary); + + try { + $this->storeFromPath($user, $temporary); + } finally { + @unlink($temporary); + } + } + + private function storeFromPath(User $user, string $path): void + { + Images::raiseMemoryLimitFor($path); + $image = ImageManager::usingDriver(Driver::class)->decodePath($path); $base = 'avatars/'.$user->getKey().'/'.Str::random(12); // Größte Stufe zuerst und danach schrittweise verkleinern – so liegt nur eine diff --git a/app/Support/BackgroundTasks.php b/app/Support/BackgroundTasks.php new file mode 100644 index 00000000..f25a6965 --- /dev/null +++ b/app/Support/BackgroundTasks.php @@ -0,0 +1,80 @@ +heartbeat($source); + Artisan::call('schedule:run'); + } catch (Throwable $e) { + Log::error('Hintergrundaufgaben fehlgeschlagen: '.$e->getMessage(), ['exception' => $e]); + } finally { + flock($lock, LOCK_UN); + fclose($lock); + } + } + + public function heartbeat(string $source): void + { + $beats = $this->heartbeats(); + $beats[$source] = now()->getTimestamp(); + @file_put_contents(storage_path('.background-heartbeat'), json_encode($beats)); + } + + /** + * @return array Quelle (cron, webcron, pseudo) => Zeitpunkt + */ + public function heartbeats(): array + { + $data = json_decode((string) @file_get_contents(storage_path('.background-heartbeat')), true); + + return is_array($data) ? array_map('intval', $data) : []; + } + + public function pseudoCronDue(): bool + { + $beats = $this->heartbeats(); + $external = max($beats['cron'] ?? 0, $beats['webcron'] ?? 0); + + return now()->getTimestamp() - $external > self::PSEUDO_CRON_AFTER_SECONDS + && now()->getTimestamp() - ($beats['pseudo'] ?? 0) >= 60; + } + + public function webCronToken(): string + { + $token = $this->settings->get('system.cron_token'); + + if (! is_string($token) || strlen($token) < 32) { + $token = bin2hex(random_bytes(20)); + $this->settings->set('system.cron_token', $token); + } + + return $token; + } +} diff --git a/app/Support/Branding.php b/app/Support/Branding.php index 58419cd9..a5511f66 100644 --- a/app/Support/Branding.php +++ b/app/Support/Branding.php @@ -2,11 +2,15 @@ namespace App\Support; +use App\Support\Theme\Icons; +use App\Support\Theme\Theme; +use App\Support\Theme\ThemeCompiler; use Illuminate\Support\Facades\Storage; +use Throwable; /** - * Basis-Branding der Installation (Phase 0): Portalname, Logo, Primärfarbe. - * Das vollständige Erscheinungsbild folgt in Phase 5 (docs/PLAN.md, Abschnitt 12). + * Das aktive Erscheinungsbild (docs/PLAN.md, Abschnitt 12): der veröffentlichte + * Stand – oder der Entwurf, wenn eine berechtigte Person gerade die Vorschau nutzt. */ class Branding { @@ -14,31 +18,84 @@ class Branding public const DEFAULT_PRIMARY_COLOR = '#0F4C5C'; - public function __construct(private readonly Settings $settings) {} + public const PREVIEW_SESSION_KEY = 'theme_preview'; + + /** @var array|null */ + private ?array $active = null; + + private ?bool $previewing = null; + + public function __construct( + private readonly Settings $settings, + private readonly Theme $theme, + private readonly ThemeCompiler $compiler, + ) {} + + /** + * @return array + */ + public function active(): array + { + return $this->active ??= $this->isPreviewing() ? ($this->theme->draft() ?? $this->theme->published()) : $this->theme->published(); + } + + public function isPreviewing(): bool + { + if ($this->previewing !== null) { + return $this->previewing; + } + + try { + $request = request(); + + return $this->previewing = $request->hasSession() + && $request->session()->get(self::PREVIEW_SESSION_KEY) === true + && (bool) $request->user()?->can('appearance.manage') + && $this->theme->hasDraft(); + } catch (Throwable) { + return $this->previewing = false; + } + } + + /** Nach dem Speichern eines Entwurfs oder Veröffentlichen neu lesen. */ + public function refresh(): void + { + $this->active = null; + $this->previewing = null; + } + + public function get(string $key): mixed + { + return $this->active()[$key] ?? null; + } public function portalName(): string { - return $this->settings->get('branding.portal_name') ?: self::DEFAULT_NAME; + return $this->get('portal_name') ?: self::DEFAULT_NAME; } public function primaryColor(): string { - $color = $this->settings->get('branding.primary_color'); - - return is_string($color) && preg_match('/^#[0-9a-fA-F]{6}$/', $color) - ? strtoupper($color) - : self::DEFAULT_PRIMARY_COLOR; + return $this->get('primary_color') ?: self::DEFAULT_PRIMARY_COLOR; } public function logoPath(): ?string { - return $this->settings->get('branding.logo_path') ?: null; + return $this->get('logo_light'); } public function logoUrl(): ?string { - $path = $this->logoPath(); + return $this->url($this->get('logo_light')); + } + public function logoDarkUrl(): ?string + { + return $this->url($this->get('logo_dark')) ?? $this->logoUrl(); + } + + public function url(?string $path): ?string + { return $path ? Storage::disk('uploads')->url($path) : null; } @@ -51,33 +108,80 @@ class Branding } /** - * CSS-Variablen für das Portal. Werden serverseitig in die Seite geschrieben – - * ohne Build und ohne Farbberechnung im Browser. + * Stylesheet des veröffentlichten Stands; null = inline ausgeben (Vorschau, noch nie veröffentlicht). */ - public function cssVariables(): string + public function stylesheetUrl(): ?string { - $color = $this->primaryColor(); - $variables = [ - '--brand' => $color, - '--brand-foreground' => ColorPalette::foregroundFor($color), - ]; + $path = $this->isPreviewing() ? null : $this->get('stylesheet'); - foreach ($this->palette() as $shade => $hex) { - $variables["--brand-{$shade}"] = $hex; - } + return $path && Storage::disk('uploads')->exists($path) ? $this->url($path) : null; + } - return collect($variables)->map(fn (string $value, string $name) => "{$name}:{$value}")->implode(';'); + public function inlineCss(): string + { + return $this->compiler->css($this->active()); } /** - * @return array{portal_name: string, primary_color: string, logo_url: string|null} + * @deprecated Nur noch für Übergänge – das Theme liefert alle Variablen. + */ + public function cssVariables(): string + { + return '--brand:'.$this->primaryColor(); + } + + public function faviconUrl(): string + { + $icons = $this->get('icons') ?? []; + + return isset($icons[32]) ? $this->url($icons[32]) : Icons::monogram($this->portalName(), $this->primaryColor(), ColorPalette::foregroundFor($this->primaryColor())); + } + + public function appleTouchIconUrl(): ?string + { + return isset(($this->get('icons') ?? [])[180]) ? $this->url($this->get('icons')[180]) : null; + } + + /** + * Welche Darstellung gilt für eine Person? null = selbst gewählt/Systemeinstellung. + */ + public function forcedColorMode(): ?string + { + return match ($this->get('dark_mode')) { + 'light' => 'light', + 'dark' => 'dark', + default => null, + }; + } + + /** + * Für das Portal (Inertia). + * + * @return array */ public function toArray(): array { + $theme = $this->active(); + return [ 'portal_name' => $this->portalName(), 'primary_color' => $this->primaryColor(), 'logo_url' => $this->logoUrl(), + 'logo_dark_url' => $this->logoDarkUrl(), + 'logo_mark_url' => $this->url($theme['logo_mark']), + 'header_style' => $theme['header_style'], + 'color_mode' => $this->forcedColorMode(), + 'login' => [ + 'layout' => $theme['login_layout'], + 'title' => $theme['login_title'], + 'text' => $theme['login_text'], + 'image_url' => $this->url($theme['login_image']), + ], + 'footer' => [ + 'text' => $theme['footer_text'], + 'links' => $theme['footer_links'], + ], + 'preview' => $this->isPreviewing(), ]; } } diff --git a/app/Support/EnvFile.php b/app/Support/EnvFile.php new file mode 100644 index 00000000..e1b9ddbb --- /dev/null +++ b/app/Support/EnvFile.php @@ -0,0 +1,49 @@ + $values + */ + public static function set(string $path, array $values): void + { + $content = is_file($path) ? (string) file_get_contents($path) : ''; + + foreach ($values as $key => $value) { + $line = $key.'='.self::format($value); + $pattern = '/^#?\s*'.preg_quote($key, '/').'=.*$/m'; + + $content = preg_match($pattern, $content) + ? preg_replace($pattern, str_replace(['\\', '$'], ['\\\\', '\\$'], $line), $content, 1) + : rtrim($content, "\n")."\n".$line."\n"; + } + + AtomicFile::write($path, $content); + } + + private static function format(string|int|bool|null $value): string + { + if ($value === null) { + return ''; + } + + if (is_bool($value)) { + return $value ? 'true' : 'false'; + } + + $value = (string) $value; + + if ($value === '' || preg_match('/^[A-Za-z0-9_.:\/@+=-]+$/', $value)) { + return $value; + } + + return '"'.str_replace(['\\', '"', '$'], ['\\\\', '\\"', '\\$'], $value).'"'; + } +} diff --git a/app/Support/Feedback/FeedbackChannels.php b/app/Support/Feedback/FeedbackChannels.php new file mode 100644 index 00000000..3c755ed9 --- /dev/null +++ b/app/Support/Feedback/FeedbackChannels.php @@ -0,0 +1,58 @@ + Schlüssel => Bezeichnung + */ + public function available(): array + { + $enabled = Cache::remember('feedback.endpoints', now()->addDay(), fn () => $this->fetch()); + $disabled = (array) $this->settings->get('feedback.disabled', []); + + return collect(VendorFeedback::TYPES) + ->only($enabled ?? array_keys(VendorFeedback::TYPES)) + ->except($disabled) + ->all(); + } + + public function disable(string $type): void + { + $disabled = (array) $this->settings->get('feedback.disabled', []); + $this->settings->set('feedback.disabled', array_values(array_unique([...$disabled, $type]))); + } + + /** + * @return list|null null = unbekannt (Server nicht erreichbar) – dann alle anbieten + */ + private function fetch(): ?array + { + try { + $software = Http::timeout(5)->acceptJson()->get(rtrim(config('updater.api_url'), '/').'/software')->json('software'); + + foreach ((array) $software as $entry) { + if (($entry['slug'] ?? null) === config('updater.software')) { + return array_values(array_filter((array) ($entry['endpoints'] ?? []), 'is_string')); + } + } + + return []; + } catch (Throwable) { + return null; + } + } +} diff --git a/app/Support/Feedback/FeedbackClient.php b/app/Support/Feedback/FeedbackClient.php new file mode 100644 index 00000000..901d5551 --- /dev/null +++ b/app/Support/Feedback/FeedbackClient.php @@ -0,0 +1,80 @@ + $payload + */ + public function send(string $type, array $payload, string $idempotencyKey, int $timeout = 10): FeedbackResult + { + try { + $response = VendorHttp::guard(fn () => $this->http->request($timeout, identifyDevice: false) + ->withHeaders(['Idempotency-Key' => $idempotencyKey]) + ->post($this->url($type), $payload)); + } catch (ServerError $e) { + return FeedbackResult::retry('Der Server ist nicht erreichbar.'); + } + + $data = $response->json() ?? []; + + return match (true) { + $response->status() === 201 || ($response->successful() && isset($data['reference'])) => FeedbackResult::sent((string) ($data['reference'] ?? '')), + $response->status() === 404 => FeedbackResult::disabled(), + $response->status() === 422 => FeedbackResult::invalid($this->fieldErrors($data), $data['error'] ?? $data['message'] ?? null), + $response->status() === 429 => FeedbackResult::rateLimited($this->retryAfter($response->header('Retry-After'), $data)), + // 409: dieselbe Meldung wird gerade verarbeitet – kurz warten, dann erneut (kein Fehler). + $response->status() === 409 => FeedbackResult::retry('Wird bereits verarbeitet.', 30), + default => FeedbackResult::retry('Server antwortet mit HTTP '.$response->status().'.', $this->retryAfter($response->header('Retry-After'), $data)), + }; + } + + private function url(string $type): string + { + return rtrim(config('updater.api_url'), '/').'/software/'.config('updater.software').'/'.$type; + } + + /** + * Unterstützt {"errors": {"feld": ["Grund"]}} und {"field": "feld", "error": "Grund"}. + * + * @param array $data + * @return array + */ + private function fieldErrors(array $data): array + { + $errors = []; + + if (is_array($data['errors'] ?? null)) { + foreach ($data['errors'] as $field => $messages) { + $errors[(string) $field] = is_array($messages) ? (string) reset($messages) : (string) $messages; + } + } + + if (is_string($data['field'] ?? null)) { + $errors[$data['field']] = (string) ($data['error'] ?? $data['message'] ?? 'Ungültige Eingabe.'); + } + + return $errors; + } + + /** + * @param array $data + */ + private function retryAfter(?string $header, array $data): ?int + { + $value = $data['retry_after'] ?? $header; + + return is_numeric($value) ? (int) $value : null; + } +} diff --git a/app/Support/Feedback/FeedbackOutbox.php b/app/Support/Feedback/FeedbackOutbox.php new file mode 100644 index 00000000..69cf705e --- /dev/null +++ b/app/Support/Feedback/FeedbackOutbox.php @@ -0,0 +1,137 @@ + $payload + */ + public function submit(?User $user, string $type, array $payload): FeedbackResult + { + $feedback = VendorFeedback::query()->create([ + 'user_id' => $user?->id, + 'type' => $type, + 'payload' => $payload, + // Je Meldung EINMAL erzeugt und bei jedem Wiederholungsversuch mitgeschickt. + 'idempotency_key' => bin2hex(random_bytes(16)), + 'status' => VendorFeedback::PENDING, + 'next_attempt_at' => now(), + ]); + + $result = $this->attempt($feedback, timeout: 8); + + // Eingabe- und Mengenfehler klärt die Person im Formular – nicht die Warteschlange. + // Die Eingabe bleibt im Formular erhalten; eine neue Meldung bekommt einen neuen Schlüssel. + if (in_array($result->status, [FeedbackResult::INVALID, FeedbackResult::RATE_LIMITED, FeedbackResult::DISABLED], true)) { + $feedback->delete(); + } + + return $result; + } + + /** + * Fällige Meldungen erneut senden (Hintergrundlauf). Nacheinander, damit das + * Gerätetoken zwischen den Anfragen nachgeführt wird. + */ + public function processDue(): int + { + $processed = 0; + + VendorFeedback::query() + ->where('status', VendorFeedback::PENDING) + ->where('next_attempt_at', '<=', now()) + ->orderBy('id') + ->limit(20) + ->get() + ->each(function (VendorFeedback $feedback) use (&$processed) { + $this->attempt($feedback); + $processed++; + }); + + return $processed; + } + + private function attempt(VendorFeedback $feedback, int $timeout = 15): FeedbackResult + { + $result = $this->client->send($feedback->type, $feedback->payload, $feedback->idempotency_key, $timeout); + $attempts = $feedback->attempts + 1; + + switch ($result->status) { + case FeedbackResult::SENT: + $feedback->update(['status' => VendorFeedback::SENT, 'attempts' => $attempts, 'reference' => $result->reference, 'last_error' => null]); + Log::info("Rückmeldung zugestellt: {$result->reference}"); + break; + + case FeedbackResult::DISABLED: + $this->channels->disable($feedback->type); + $this->discard($feedback, $attempts, 'Dieser Meldeweg ist für das Programm nicht freigeschaltet.'); + break; + + case FeedbackResult::INVALID: + case FeedbackResult::RATE_LIMITED: + if ($feedback->attempts > 0) { + // Nur im Hintergrund möglich (z. B. 429 bei Wiederholung): später erneut. + $this->reschedule($feedback, $attempts, $result->message ?? 'Später erneut versuchen.', $result->retryAfter); + } + break; + + default: + $this->reschedule($feedback, $attempts, $result->message ?? 'Nicht zugestellt.', $result->retryAfter); + } + + return $result; + } + + private function reschedule(VendorFeedback $feedback, int $attempts, string $error, ?int $retryAfter): void + { + if ($attempts >= self::MAX_ATTEMPTS) { + $this->discard($feedback, $attempts, $error); + + return; + } + + // 1, 5, 15, 60 Minuten – oder so lange, wie der Server es verlangt. + $delay = $retryAfter ?? [60, 300, 900, 3600][min($attempts - 1, 3)]; + + $feedback->update([ + 'attempts' => $attempts, + 'next_attempt_at' => now()->addSeconds(max(30, $delay)), + 'last_error' => mb_substr($error, 0, 500), + ]); + } + + private function discard(VendorFeedback $feedback, int $attempts, string $error): void + { + $feedback->update(['status' => VendorFeedback::DISCARDED, 'attempts' => $attempts, 'last_error' => mb_substr($error, 0, 500)]); + Log::warning("Rückmeldung verworfen nach {$attempts} Versuchen: {$error}"); + + if ($feedback->user) { + Notification::make() + ->danger() + ->title('Rückmeldung konnte nicht zugestellt werden') + ->body('„'.($feedback->payload['title'] ?? '').'“ wurde nach '.$attempts.' Versuchen verworfen. Bitte senden Sie die Meldung später erneut.') + ->sendToDatabase($feedback->user); + } + } +} diff --git a/app/Support/Feedback/FeedbackResult.php b/app/Support/Feedback/FeedbackResult.php new file mode 100644 index 00000000..e5f31c4f --- /dev/null +++ b/app/Support/Feedback/FeedbackResult.php @@ -0,0 +1,58 @@ + $errors Feld => Meldung (bei 422) + */ + private function __construct( + public readonly string $status, + public readonly ?string $reference = null, + public readonly array $errors = [], + public readonly ?int $retryAfter = null, + public readonly ?string $message = null, + ) {} + + public static function sent(string $reference): self + { + return new self(self::SENT, reference: $reference); + } + + /** + * @param array $errors + */ + public static function invalid(array $errors, ?string $message = null): self + { + return new self(self::INVALID, errors: $errors, message: $message); + } + + public static function rateLimited(?int $retryAfter): self + { + return new self(self::RATE_LIMITED, retryAfter: $retryAfter); + } + + public static function disabled(): self + { + return new self(self::DISABLED); + } + + public static function retry(string $message, ?int $retryAfter = null): self + { + return new self(self::RETRY, retryAfter: $retryAfter, message: $message); + } +} diff --git a/app/Support/Feedback/TechnicalInfo.php b/app/Support/Feedback/TechnicalInfo.php new file mode 100644 index 00000000..e45efdf4 --- /dev/null +++ b/app/Support/Feedback/TechnicalInfo.php @@ -0,0 +1,64 @@ +} + */ + public function collect(): array + { + return [ + 'app_version' => Version::VERSION, + 'current_sha' => $this->version->current(), + 'os' => VendorHttp::operatingSystem(), + 'metadata' => array_filter([ + 'php' => PHP_VERSION, + 'datenbank' => $this->database(), + 'webserver' => $this->webserver(), + 'update_kanal' => $this->channels->active(), + 'cache' => (string) config('cache.default'), + 'queue' => (string) config('queue.default'), + 'sprache' => app()->getLocale(), + 'opcache' => function_exists('opcache_get_status') && @opcache_get_status(false) ? 'an' : 'aus', + ], fn ($value) => $value !== null && $value !== ''), + ]; + } + + private function database(): ?string + { + try { + $version = (string) DB::selectOne('select version() as v')->v; + + return (str_contains(strtolower($version), 'mariadb') ? 'MariaDB ' : 'MySQL ').preg_replace('/-.*$/', '', $version); + } catch (Throwable) { + return null; + } + } + + private function webserver(): ?string + { + $software = (string) ($_SERVER['SERVER_SOFTWARE'] ?? ''); + + // Nur Produkt und Version, keine Modul-Liste. + return $software !== '' ? strtok($software, ' ') : PHP_SAPI; + } +} diff --git a/app/Support/Images.php b/app/Support/Images.php index f7a07310..ce33c6c2 100644 --- a/app/Support/Images.php +++ b/app/Support/Images.php @@ -2,7 +2,9 @@ namespace App\Support; +use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Storage; +use Illuminate\Support\Str; use Intervention\Image\Drivers\Gd\Driver; use Intervention\Image\Encoders\WebpEncoder; use Intervention\Image\ImageManager; @@ -46,6 +48,31 @@ class Images } } + /** + * Bild für Inhalte (Pagebuilder, Beiträge): Seitenverhältnis bleibt, höchstens + * 2000 Pixel breit, als WebP. GIFs bleiben unverändert (Animationen). + * + * @return string Pfad im Speicher „uploads“ + */ + public function storeContentImage(UploadedFile $file, string $directory): string + { + $disk = Storage::disk('uploads'); + $name = $directory.'/'.now()->format('Y/m').'/'.Str::random(24); + + if ($file->getMimeType() === 'image/gif') { + $disk->putFileAs(dirname($name), $file, basename($name).'.gif'); + + return $name.'.gif'; + } + + self::raiseMemoryLimitFor($file->getRealPath()); + $image = ImageManager::usingDriver(Driver::class)->decodePath($file->getRealPath()); + $image->scaleDown(width: 2000); + $disk->put($name.'.webp', $image->encode(new WebpEncoder(quality: 84))->toString()); + + return $name.'.webp'; + } + public function deleteWithVariants(?string $path): void { if (! $path) { diff --git a/app/Support/Installation.php b/app/Support/Installation.php new file mode 100644 index 00000000..26645f72 --- /dev/null +++ b/app/Support/Installation.php @@ -0,0 +1,50 @@ +environment('local'); + } + + public static function markInstalled(): void + { + file_put_contents(storage_path('.installed'), date(DATE_ATOM)); + } + + /** + * Frisch hochgeladene Installation: .env aus der Vorlage anlegen und einen + * Anwendungsschlüssel erzeugen – ohne Schlüssel funktionieren weder Sitzungen + * noch Cookies, also auch der Installer nicht. + */ + public static function prepareEnvironment(): void + { + $env = app()->environmentFilePath(); + + if (! is_file($env) && is_file(base_path('.env.example')) && is_writable(base_path())) { + $key = 'base64:'.base64_encode(Encrypter::generateKey(config('app.cipher', 'AES-256-CBC'))); + + copy(base_path('.env.example'), $env); + EnvFile::set($env, [ + 'APP_KEY' => $key, + 'APP_ENV' => 'production', + 'APP_DEBUG' => 'false', + ]); + + config(['app.key' => $key, 'app.env' => 'production', 'app.debug' => false]); + } + } +} diff --git a/app/Support/License/LicenseService.php b/app/Support/License/LicenseService.php new file mode 100644 index 00000000..04feb350 --- /dev/null +++ b/app/Support/License/LicenseService.php @@ -0,0 +1,84 @@ + Antwort von /license (zusätzlich gespeichert) + * + * @throws ServerError + */ + public function check(): array + { + try { + $info = $this->channels->client()->license(); + $this->store->rememberStatus($info); + + return $info; + } catch (ServerError $e) { + Log::notice("Lizenzprüfung: {$e->errorCode}"); + $this->store->rememberStatus(null, $e->errorCode); + + throw $e; + } + } + + /** + * Gibt den Geräteplatz dieser Installation frei. + * + * @throws ServerError + */ + public function releaseDevice(): void + { + $response = VendorHttp::guard(fn () => $this->http->request((int) config('updater.timeouts.json'), identifyDevice: false) + ->post(rtrim(config('updater.api_url'), '/').'/license/release-device?software='.config('updater.software'))); + + if (! $response->successful()) { + throw VendorHttp::errorFrom($response); + } + } + + /** + * Aufbereitete Lizenzdaten für die Anzeige (aus der letzten Prüfung). + * + * @return array|null + */ + public function summary(): ?array + { + $info = $this->store->lastStatus()['info'] ?? null; + + if (! is_array($info)) { + return null; + } + + $license = $info['license'] ?? []; + $unlimited = (bool) ($license['unlimited'] ?? false); + $days = $license['days_remaining'] ?? null; + + return [ + 'status' => $license['status'] ?? null, + // valid_until = null zusammen mit unlimited = true heißt UNBEFRISTET – kein Fehler. + 'unlimited' => $unlimited, + 'valid_until' => $license['valid_until'] ?? null, + 'days_remaining' => is_numeric($days) ? (int) $days : null, + 'expired' => ! $unlimited && (bool) ($license['expired'] ?? false), + 'expires_soon' => ! $unlimited && is_numeric($days) && (int) $days >= 0 && (int) $days < 30, + 'registered_to' => $info['registered_to'] ?? [], + 'devices' => $info['devices'] ?? [], + ]; + } +} diff --git a/app/Support/License/LicenseStore.php b/app/Support/License/LicenseStore.php new file mode 100644 index 00000000..cf4e49d7 --- /dev/null +++ b/app/Support/License/LicenseStore.php @@ -0,0 +1,161 @@ +|null */ + private ?array $data = null; + + public function __construct(private readonly ?string $file = null) {} + + public function email(): ?string + { + return $this->read()['email'] ?? null; + } + + public function key(): ?string + { + $encrypted = $this->read()['key'] ?? null; + + if (! is_string($encrypted) || $encrypted === '') { + return null; + } + + try { + return Crypt::decryptString($encrypted); + } catch (Throwable) { + // APP_KEY hat sich geändert – Schlüssel muss neu eingegeben werden. + return null; + } + } + + public function hasLicense(): bool + { + return filled($this->email()) && filled($this->key()); + } + + public function setLicense(string $email, string $key): void + { + $this->write([ + 'email' => trim($email), + 'key' => Crypt::encryptString(trim($key)), + ]); + } + + public function clearLicense(): void + { + $this->write(['email' => null, 'key' => null, 'device_token' => null]); + } + + public function deviceId(): string + { + $id = $this->read()['device_id'] ?? null; + + if (! is_string($id) || ! preg_match('/^[0-9a-f]{32}$/', $id)) { + $id = bin2hex(random_bytes(16)); + $this->write(['device_id' => $id]); + } + + return $id; + } + + public function deviceToken(): ?string + { + $token = $this->read()['device_token'] ?? null; + + return is_string($token) && $token !== '' ? $token : null; + } + + /** + * Neues Gerätetoken sofort speichern – auch wenn die Antwort ein Fehler war. + */ + public function saveDeviceToken(string $token): void + { + if ($token !== '' && $token !== $this->deviceToken()) { + $this->write(['device_token' => $token]); + } + } + + public function hostname(): string + { + return (string) (gethostname() ?: 'unbekannt'); + } + + /** + * „web01:/var/www/kunde“ – damit der Kunde im Portal erkennt, welcher Geräteplatz welcher ist. + */ + public function deviceLabel(): string + { + return $this->hostname().':'.base_path(); + } + + /** + * Letztes Ergebnis der Lizenzprüfung (für die Anzeige ohne erneute Anfrage). + * + * @param array|null $info + */ + public function rememberStatus(?array $info, ?string $errorCode = null): void + { + $this->write(['last_status' => [ + 'info' => $info, + 'error_code' => $errorCode, + 'checked_at' => time(), + ]]); + } + + /** + * @return array{info: array|null, error_code: string|null, checked_at: int}|null + */ + public function lastStatus(): ?array + { + $status = $this->read()['last_status'] ?? null; + + return is_array($status) ? $status : null; + } + + /** + * @return array + */ + private function read(): array + { + if ($this->data === null) { + $decoded = json_decode((string) @file_get_contents($this->path()), true); + $this->data = is_array($decoded) ? $decoded : []; + } + + return $this->data; + } + + /** + * @param array $changes + */ + private function write(array $changes): void + { + // Immer frisch von der Platte lesen: parallele Anfragen können das Token rotiert haben. + $this->data = null; + $data = array_merge($this->read(), $changes); + + AtomicFile::write($this->path(), json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); + @chmod($this->path(), 0600); + + $this->data = $data; + } + + private function path(): string + { + return $this->file ?? storage_path('app/license.json'); + } +} diff --git a/app/Support/License/ServerError.php b/app/Support/License/ServerError.php new file mode 100644 index 00000000..f0bcae9a --- /dev/null +++ b/app/Support/License/ServerError.php @@ -0,0 +1,38 @@ + $payload + */ + public function __construct( + public readonly string $errorCode, + public readonly int $status, + string $message, + public readonly array $payload = [], + public readonly ?int $retryAfter = null, + ) { + parent::__construct($message); + } + + /** + * Lizenzfehler, bei denen die Eingabemaske die richtige Reaktion ist. + */ + public function needsLicenseInput(): bool + { + return in_array($this->errorCode, ['license_required', 'invalid_key', 'email_mismatch'], true); + } + + public function isTemporary(): bool + { + return in_array($this->errorCode, ['mirror_pending', 'not_released', 'rate_limited', 'maintenance', 'upstream_unavailable', 'unreachable'], true); + } +} diff --git a/app/Support/License/ServerMessages.php b/app/Support/License/ServerMessages.php new file mode 100644 index 00000000..083653bf --- /dev/null +++ b/app/Support/License/ServerMessages.php @@ -0,0 +1,44 @@ +retryAfter ? ' Bitte in etwa '.self::duration($error->retryAfter).' erneut versuchen.' : ' Bitte später erneut versuchen.'; + + return match ($error->errorCode) { + 'license_required' => 'Für Updates ist eine Lizenz nötig. Bitte Lizenz-E-Mail und Lizenzschlüssel hinterlegen.', + 'invalid_key' => 'Der Lizenzschlüssel ist unbekannt. Bitte die Eingabe prüfen.', + 'email_mismatch' => 'Die E-Mail-Adresse passt nicht zu diesem Lizenzschlüssel. Bitte die auf der Lizenz hinterlegte Adresse verwenden.', + 'license_expired' => 'Die Lizenz ist abgelaufen. Updates sind erst nach einer Verlängerung wieder verfügbar – das Portal läuft unverändert weiter.', + 'license_revoked' => 'Die Lizenz wurde gesperrt. Bitte wenden Sie sich an den Support.', + 'device_limit_reached' => sprintf( + 'Alle Geräteplätze der Lizenz sind belegt (%s von %s). Geben Sie im Kundenportal einen Platz frei oder erweitern Sie die Lizenz.', + $error->payload['devices_used'] ?? '?', + $error->payload['devices_max'] ?? '?', + ), + 'device_cloned' => 'Die Lizenz wird offenbar in einer kopierten Installation mehrfach genutzt. Bitte wenden Sie sich an den Support.', + 'device_id_required' => 'Die Lizenz ist gerätegebunden, es wurde aber keine Gerätekennung übermittelt. Bitte wenden Sie sich an den Support.', + 'rate_limited' => 'Zu viele Anfragen in kurzer Zeit.'.$wait, + 'maintenance' => 'Der Update-Server wird gerade gewartet.'.$wait, + 'upstream_unavailable' => 'Der Update-Server ist vorübergehend nicht erreichbar. Die installierte Version bleibt unverändert.'.$wait, + 'mirror_pending' => 'Die neue Version wird gerade bereitgestellt.'.$wait, + 'not_released' => 'Es ist noch keine Version zur Auslieferung freigegeben.'.$wait, + 'unknown_tool' => 'Dieser Update-Kanal ist beim Hersteller noch nicht eingerichtet. Bitte den Kanal „Stabil“ verwenden.', + 'unreachable' => 'Der Update-Server ist nicht erreichbar. Bitte die Internetverbindung des Servers prüfen (ausgehende HTTPS-Verbindungen müssen erlaubt sein).', + 'invalid_response' => 'Der Update-Server hat eine unerwartete Antwort geliefert.'.$wait, + default => 'Der Update-Server meldet einen Fehler ('.$error->errorCode.').'.$wait, + }; + } + + private static function duration(int $seconds): string + { + return $seconds < 90 ? "{$seconds} Sekunden" : (int) ceil($seconds / 60).' Minuten'; + } +} diff --git a/app/Support/License/VendorHttp.php b/app/Support/License/VendorHttp.php new file mode 100644 index 00000000..5297dd2e --- /dev/null +++ b/app/Support/License/VendorHttp.php @@ -0,0 +1,136 @@ +connectTimeout(10) + ->acceptJson() + ->withUserAgent('Inhaus/'.Version::VERSION.' (PHP '.PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION.'; '.PHP_OS_FAMILY.')') + ->withOptions([ + 'allow_redirects' => [ + 'max' => (int) config('updater.max_redirects', 3), + 'protocols' => ['https'], + 'strict' => true, + ], + ]) + ->withResponseMiddleware(fn (ResponseInterface $response) => $this->captureDeviceToken($response)); + + // Ohne hinterlegte Lizenz gar keine Lizenz-Kopfzeilen – nie leere oder erfundene Werte. + if ($this->license->hasLicense()) { + $headers = [ + 'X-License-Email' => $this->license->email(), + 'X-Device-Id' => $this->license->deviceId(), + ]; + + if ($token = $this->license->deviceToken()) { + $headers['X-Device-Token'] = $token; + } + + $request->withToken($this->license->key())->withHeaders($headers); + } + + if ($identifyDevice) { + $request->withQueryParameters(array_filter([ + 'hostname' => $this->license->hostname(), + 'device_label' => $this->license->deviceLabel(), + 'os' => self::operatingSystem(), + 'app_version' => Version::VERSION, + ])); + } + + return $request; + } + + /** + * Wandelt Verbindungsfehler in einen ServerError mit Code „unreachable“ um. + * + * @template T + * + * @param callable(): T $callback + * @return T + */ + public static function guard(callable $callback): mixed + { + try { + return $callback(); + } catch (ConnectionException|ConnectException $e) { + throw new ServerError('unreachable', 0, $e->getMessage()); + } + } + + /** + * Fehlerantwort in einen ServerError übersetzen (Code aus dem JSON, nie aus dem Text). + */ + public static function errorFrom(Response $response, ?string $body = null): ServerError + { + $data = json_decode($body ?? $response->body(), true); + $data = is_array($data) ? $data : []; + $retryAfter = $data['retry_after'] ?? $response->header('Retry-After'); + + return new ServerError( + errorCode: (string) ($data['code'] ?? 'http_'.$response->status()), + status: $response->status(), + message: (string) ($data['error'] ?? $data['message'] ?? 'HTTP '.$response->status()), + payload: $data, + retryAfter: is_numeric($retryAfter) ? (int) $retryAfter : null, + ); + } + + public static function operatingSystem(): string + { + return trim(php_uname('s').' '.php_uname('r')); + } + + private function captureDeviceToken(ResponseInterface $response): ResponseInterface + { + $token = $response->getHeaderLine('X-Device-Token'); + + if ($token === '' && str_contains($response->getHeaderLine('Content-Type'), 'json')) { + $body = $response->getBody(); + $data = json_decode((string) $body, true); + + if ($body->isSeekable()) { + $body->rewind(); + } + + $token = is_array($data) && is_string($data['device_token'] ?? null) ? $data['device_token'] : ''; + } + + if ($token !== '') { + $this->license->saveDeviceToken($token); + } + + return $response; + } +} diff --git a/app/Support/MailSettings.php b/app/Support/MailSettings.php new file mode 100644 index 00000000..9bc6d03d --- /dev/null +++ b/app/Support/MailSettings.php @@ -0,0 +1,100 @@ + 'SMTP-Server', + 'sendmail' => 'Sendmail des Servers', + 'log' => 'Nicht senden (nur ins Protokoll schreiben)', + ]; + + public function __construct(private readonly Settings $settings) {} + + public function configured(): bool + { + return $this->settings->get('mail.mailer') !== null; + } + + /** + * @return array + */ + public function values(): array + { + return [ + 'mailer' => $this->settings->get('mail.mailer', 'log'), + 'host' => $this->settings->get('mail.host'), + 'port' => $this->settings->get('mail.port', 587), + 'encryption' => $this->settings->get('mail.encryption', 'tls'), + 'username' => $this->settings->get('mail.username'), + 'from_address' => $this->settings->get('mail.from_address'), + 'from_name' => $this->settings->get('mail.from_name'), + ]; + } + + /** + * @param array $values + */ + public function save(array $values): void + { + $data = [ + 'mail.mailer' => $values['mailer'], + 'mail.host' => $values['host'] ?? null, + 'mail.port' => isset($values['port']) ? (int) $values['port'] : null, + 'mail.encryption' => $values['encryption'] ?? 'tls', + 'mail.username' => $values['username'] ?? null, + 'mail.from_address' => $values['from_address'] ?? null, + 'mail.from_name' => $values['from_name'] ?? null, + ]; + + // Leeres Passwortfeld = gespeichertes behalten. + if (filled($values['password'] ?? null)) { + $data['mail.password'] = Crypt::encryptString($values['password']); + } + + $this->settings->setMany($data); + $this->apply(); + } + + public function apply(): void + { + if (! $this->configured()) { + return; + } + + $values = $this->values(); + + try { + $password = $this->settings->get('mail.password') ? Crypt::decryptString($this->settings->get('mail.password')) : null; + } catch (Throwable) { + $password = null; // APP_KEY geändert – Passwort muss neu eingegeben werden + } + + config([ + 'mail.default' => $values['mailer'], + 'mail.mailers.smtp.host' => $values['host'], + 'mail.mailers.smtp.port' => (int) $values['port'], + 'mail.mailers.smtp.scheme' => $values['encryption'] === 'ssl' ? 'smtps' : 'smtp', + 'mail.mailers.smtp.username' => $values['username'], + 'mail.mailers.smtp.password' => $password, + 'mail.mailers.smtp.timeout' => 15, + 'mail.from.address' => $values['from_address'] ?: config('mail.from.address'), + 'mail.from.name' => $values['from_name'] ?: app(Branding::class)->portalName(), + ]); + + // Bereits erzeugte Mailer mit alter Konfiguration verwerfen. + app()->forgetInstance('mail.manager'); + app()->forgetInstance('mailer'); + Mail::clearResolvedInstance('mail.manager'); + } +} diff --git a/app/Support/Navigation.php b/app/Support/Navigation.php index 1a8685e1..f3de7f41 100644 --- a/app/Support/Navigation.php +++ b/app/Support/Navigation.php @@ -2,24 +2,83 @@ namespace App\Support; +use App\Models\User; +use App\Plugins\Hooks; +use Closure; use Illuminate\Http\Request; /** - * Hauptnavigation des Portals. Wird ab Phase 2 zu einer Registry, in die - * Plugins eigene Einträge eintragen. + * Hauptnavigation des Portals als Registry: Kern und Plugins tragen Einträge ein. + * + * app(Navigation::class)->add('news', 'Neuigkeiten', '/neuigkeiten', active: 'news.*', sort: 20); + * + * Dynamische Einträge (z. B. Seiten aus dem Seitenbaum) liefert ein Provider: + * + * app(Navigation::class)->provider('pages', fn (Request $request, ?User $user) => [ + * ['key' => 'page-3', 'label' => 'MAV', 'href' => '/seiten/mav', 'active' => true, 'sort' => 40], + * ]); */ class Navigation { - /** - * @return list - */ - public function items(Request $request): array + /** @var array, sort: int, ability: string|null, visible: Closure|null}> */ + private array $items = []; + + /** @var array */ + private array $providers = []; + + public function __construct() { - return [ - ['label' => 'Startseite', 'href' => '/', 'active' => $request->routeIs('dashboard')], - ['label' => 'Neuigkeiten', 'href' => '/neuigkeiten', 'active' => $request->routeIs('news.*')], - ['label' => 'Termine', 'href' => '/termine', 'active' => $request->routeIs('events.*')], - ['label' => 'Personen', 'href' => '/personen', 'active' => $request->routeIs('people.*')], - ]; + $this->add('home', 'Startseite', '/', active: 'dashboard', sort: 0); + $this->add('people', 'Personen', '/personen', active: 'people.*', sort: 90); + } + + /** + * @param string|list $active Routennamen (mit *), bei denen der Eintrag aktiv ist + * @param (Closure(User): bool)|null $visible zusätzliche Bedingung je Person + */ + public function add(string $key, string $label, string $href, string|array $active = [], int $sort = 50, ?string $ability = null, ?Closure $visible = null): void + { + $this->items[$key] = ['label' => $label, 'href' => $href, 'active' => (array) $active, 'sort' => $sort, 'ability' => $ability, 'visible' => $visible]; + } + + public function remove(string $key): void + { + unset($this->items[$key], $this->providers[$key]); + } + + /** + * @param Closure(Request, User|null): list $items + */ + public function provider(string $key, Closure $items): void + { + $this->providers[$key] = $items; + } + + /** + * @return list + */ + public function items(Request $request, ?User $user = null): array + { + $items = collect($this->items) + ->filter(fn (array $item) => $item['ability'] === null || ($user?->can($item['ability']) ?? false)) + ->filter(fn (array $item) => $item['visible'] === null || ($user !== null && ($item['visible'])($user))) + ->map(fn (array $item, string $key) => [ + 'key' => $key, + 'label' => $item['label'], + 'href' => $item['href'], + 'active' => $item['active'] !== [] && $request->routeIs(...$item['active']), + 'sort' => $item['sort'], + ]); + + foreach ($this->providers as $provider) { + $items = $items->merge($provider($request, $user)); + } + + $items = $items->sortBy('sort') + ->map(fn (array $item) => ['key' => $item['key'], 'label' => $item['label'], 'href' => $item['href'], 'active' => (bool) $item['active']]) + ->values() + ->all(); + + return Hooks::apply('navigation.items', $items, $request, $user); } } diff --git a/app/Support/Permissions/Audiences.php b/app/Support/Permissions/Audiences.php new file mode 100644 index 00000000..9f4649af --- /dev/null +++ b/app/Support/Permissions/Audiences.php @@ -0,0 +1,134 @@ + $query + * @param string $column Spalte mit der ID des Objekts, dessen Zielgruppe gilt + */ + public static function constrain(Builder $query, string $type, string $column, ?User $user): void + { + $query->where(function (Builder $q) use ($type, $column, $user) { + $q->whereNotExists(fn (QueryBuilder $sub) => $sub->from('audiences') + ->where('audiences.resource_type', $type) + ->whereColumn('audiences.resource_id', $column)); + + if ($user) { + $q->orWhereExists(fn (QueryBuilder $sub) => $sub->from('audiences') + ->where('audiences.resource_type', $type) + ->whereColumn('audiences.resource_id', $column) + ->where(fn (QueryBuilder $rules) => self::matching($rules, $user))); + } + }); + } + + public static function allows(string $type, int $id, ?User $user): bool + { + $rules = Audience::query()->where('resource_type', $type)->where('resource_id', $id); + + if (! (clone $rules)->exists()) { + return true; + } + + return $user !== null && $rules->where(fn ($q) => self::matching($q->getQuery(), $user))->exists(); + } + + /** + * @param array{role?: list, department?: list, location?: list} $rules + */ + public static function sync(string $type, int $id, array $rules): void + { + Audience::query()->where('resource_type', $type)->where('resource_id', $id)->delete(); + + foreach (array_keys(Audience::TYPES) as $ruleType) { + foreach (array_unique(array_filter((array) ($rules[$ruleType] ?? []), fn ($v) => $v !== null && $v !== '')) as $value) { + Audience::query()->create(['resource_type' => $type, 'resource_id' => $id, 'rule_type' => $ruleType, 'rule_value' => (string) $value]); + } + } + } + + /** + * @return array{role: list, department: list, location: list} + */ + public static function get(string $type, int $id): array + { + $rules = ['role' => [], 'department' => [], 'location' => []]; + + foreach (Audience::query()->where('resource_type', $type)->where('resource_id', $id)->get() as $audience) { + $rules[$audience->rule_type][] = $audience->rule_value; + } + + return $rules; + } + + /** + * Alle Regeln eines Typs auf einmal – für gecachte Strukturen wie den Seitenbaum. + * + * @return array, department: list, location: list}> ID => Regeln + */ + public static function allOfType(string $type): array + { + $result = []; + + foreach (Audience::query()->where('resource_type', $type)->get(['resource_id', 'rule_type', 'rule_value']) as $audience) { + $result[$audience->resource_id] ??= ['role' => [], 'department' => [], 'location' => []]; + $result[$audience->resource_id][$audience->rule_type][] = $audience->rule_value; + } + + return $result; + } + + /** + * Dieselbe Prüfung wie constrain()/allows(), aber in PHP auf bereits geladenen Regeln. + * + * @param array{role?: list, department?: list, location?: list}|null $rules + */ + public static function matches(?array $rules, ?User $user): bool + { + $rules = array_filter((array) $rules); + + if ($rules === []) { + return true; + } + + if ($user === null) { + return false; + } + + $roleIds = array_map('strval', $user->permissions()->roleIds); + + return array_intersect(array_map('strval', $rules['role'] ?? []), $roleIds) !== [] + || (filled($user->department) && in_array($user->department, $rules['department'] ?? [], true)) + || (filled($user->location) && in_array($user->location, $rules['location'] ?? [], true)); + } + + private static function matching(QueryBuilder $rules, User $user): void + { + $roleIds = array_map('strval', $user->permissions()->roleIds); + + $rules->where(fn (QueryBuilder $q) => $q->where('audiences.rule_type', 'role')->whereIn('audiences.rule_value', $roleIds ?: ['-'])); + + if (filled($user->department)) { + $rules->orWhere(fn (QueryBuilder $q) => $q->where('audiences.rule_type', 'department')->where('audiences.rule_value', $user->department)); + } + + if (filled($user->location)) { + $rules->orWhere(fn (QueryBuilder $q) => $q->where('audiences.rule_type', 'location')->where('audiences.rule_value', $user->location)); + } + } +} diff --git a/app/Support/Permissions/PermissionResource.php b/app/Support/Permissions/PermissionResource.php new file mode 100644 index 00000000..ff70eaee --- /dev/null +++ b/app/Support/Permissions/PermissionResource.php @@ -0,0 +1,36 @@ +can('news.post.create', $category) – Modell mit permissionResource() + * $user->can('news.post.create', ['news_category', 5]) – Laravel reicht das als zwei Argumente durch + */ +final class PermissionResource +{ + /** + * @param array $arguments + * @return array{0: string|null, 1: int|null} + */ + public static function from(array $arguments): array + { + $first = $arguments[0] ?? null; + + if (is_object($first) && method_exists($first, 'permissionResource')) { + return $first->permissionResource(); + } + + if (is_array($first)) { + return self::from($first); + } + + if (is_string($first)) { + $id = $arguments[1] ?? null; + + return [$first, is_numeric($id) ? (int) $id : null]; + } + + return [null, null]; + } +} diff --git a/app/Support/Permissions/PermissionSet.php b/app/Support/Permissions/PermissionSet.php new file mode 100644 index 00000000..251b9cd0 --- /dev/null +++ b/app/Support/Permissions/PermissionSet.php @@ -0,0 +1,75 @@ + $roleIds + * @param array $global Ability => true („*“ = alles) + * @param array|true>> $objects Ability => Typ => IDs oder true (alle) + */ + public function __construct( + public readonly array $roleIds, + public readonly array $global, + public readonly array $objects, + ) {} + + public function isSuperuser(): bool + { + return isset($this->global['*']); + } + + public function can(string $ability, ?string $resourceType = null, ?int $resourceId = null): bool + { + if ($this->isSuperuser() || isset($this->global[$ability])) { + return true; + } + + if ($resourceType === null) { + return false; + } + + $ids = $this->objects[$ability][$resourceType] ?? null; + + return $ids === true || ($ids !== null && ($resourceId === null ? $ids !== [] : in_array($resourceId, $ids, true))); + } + + /** + * IDs der Objekte, für die das Recht gilt – für Abfragen („nur meine Kategorien“). + * + * @return list|true true = alle + */ + public function ids(string $ability, string $resourceType): array|true + { + if ($this->isSuperuser() || isset($this->global[$ability])) { + return true; + } + + return $this->objects[$ability][$resourceType] ?? []; + } + + public function hasAnyObjectGrant(): bool + { + return $this->objects !== []; + } + + /** + * @return array + */ + public function toArray(): array + { + return ['roleIds' => $this->roleIds, 'global' => $this->global, 'objects' => $this->objects]; + } + + /** + * @param array $data + */ + public static function fromArray(array $data): self + { + return new self($data['roleIds'], $data['global'], $data['objects']); + } +} diff --git a/app/Support/Permissions/Permissions.php b/app/Support/Permissions/Permissions.php new file mode 100644 index 00000000..61bcf88b --- /dev/null +++ b/app/Support/Permissions/Permissions.php @@ -0,0 +1,92 @@ + */ + private array $resolved = []; + + public function for(User $user): PermissionSet + { + if (! $user->is_active) { + return new PermissionSet([], [], []); + } + + return $this->resolved[$user->id] ??= PermissionSet::fromArray(Cache::rememberForever( + 'permissions.user.'.$user->id.'.'.self::version(), + fn () => $this->resolve($user)->toArray(), + )); + } + + public static function flush(): void + { + Cache::forever(self::VERSION_KEY, self::version() + 1); + app(self::class)->resolved = []; + } + + public static function version(): int + { + return (int) Cache::get(self::VERSION_KEY, 1); + } + + private function resolve(User $user): PermissionSet + { + $roleIds = DB::table('role_user')->where('user_id', $user->id)->distinct()->pluck('role_id')->map(fn ($id) => (int) $id)->all(); + $global = []; + $objects = []; + $inherited = []; + + foreach (Grant::query()->whereIn('role_id', $roleIds)->get(['ability', 'resource_type', 'resource_id', 'include_children']) as $grant) { + if ($grant->resource_type === null) { + $global[$grant->ability] = true; + } elseif ($grant->resource_id === null) { + $objects[$grant->ability][$grant->resource_type] = true; + } elseif (($objects[$grant->ability][$grant->resource_type] ?? null) !== true) { + $objects[$grant->ability][$grant->resource_type][] = $grant->resource_id; + + if ($grant->include_children) { + $inherited[$grant->resource_type][$grant->ability][] = $grant->resource_id; + } + } + } + + // „Inkl. Unterobjekten“: Nachfahren einmalig auflösen – die Prüfung bleibt ein Array-Zugriff. + // Hierarchische Typen leeren den Rechte-Cache, wenn sich ihr Baum ändert. + $types = app(Abilities::class)->resourceTypes(); + + foreach ($inherited as $type => $byAbility) { + $descendants = $types[$type]['descendants'] ?? null; + + foreach ($descendants ? $byAbility : [] as $ability => $ids) { + if (is_array($objects[$ability][$type] ?? null)) { + $objects[$ability][$type] = array_merge($objects[$ability][$type], array_map('intval', $descendants($ids))); + } + } + } + + foreach ($objects as $ability => $types) { + foreach ($types as $type => $ids) { + if (is_array($ids)) { + $objects[$ability][$type] = array_values(array_unique($ids)); + } + } + } + + return new PermissionSet($roleIds, $global, $objects); + } +} diff --git a/app/Support/ProfileFields.php b/app/Support/ProfileFields.php new file mode 100644 index 00000000..47cc7d30 --- /dev/null +++ b/app/Support/ProfileFields.php @@ -0,0 +1,147 @@ +|null */ + private ?Collection $fields = null; + + /** + * @return Collection + */ + public function all(): Collection + { + try { + // Im Cache nur Arrays – Laravel deserialisiert dort keine Objekte. + return $this->fields ??= ProfileField::hydrate(Cache::rememberForever( + self::CACHE_KEY, + fn () => ProfileField::query()->orderBy('sort')->orderBy('label')->get()->map->getAttributes()->all(), + )); + } catch (Throwable $e) { + report($e); + + return collect(); + } + } + + public function flush(): void + { + $this->fields = null; + Cache::forget(self::CACHE_KEY); + } + + /** + * @return array Schlüssel => Bezeichnung + */ + public function options(): array + { + return $this->all()->pluck('label', 'key')->all(); + } + + /** + * Felder mit Werten, die $viewer bei $person sehen darf. + * + * @return list + */ + public function visibleValues(User $person, ?User $viewer): array + { + $seesRestricted = $viewer && ($viewer->is($person) || $viewer->can('users.manage')); + $values = (array) ($person->custom_fields ?? []); + + return $this->all() + ->filter(fn (ProfileField $field) => $field->visibility === 'public' || $seesRestricted) + ->filter(fn (ProfileField $field) => filled($values[$field->key] ?? null)) + ->map(fn (ProfileField $field) => [ + 'key' => $field->key, + 'label' => $field->label, + 'type' => $field->type, + 'value' => $this->display($field, (string) $values[$field->key]), + ]) + ->values() + ->all(); + } + + /** + * Definitionen und Werte für das Bearbeitungsformular der Person selbst. + * + * @param list $managed vom Identity Provider gepflegte Felder („custom.“) + * @return list> + */ + public function formFor(User $user, array $managed): array + { + $values = (array) ($user->custom_fields ?? []); + + return $this->all()->map(fn (ProfileField $field) => [ + 'key' => $field->key, + 'label' => $field->label, + 'type' => $field->type, + 'help' => $field->help, + 'restricted' => $field->visibility === 'restricted', + 'value' => $values[$field->key] ?? '', + 'readonly' => ! $field->editable || in_array('custom.'.$field->key, $managed, true), + 'managed' => in_array('custom.'.$field->key, $managed, true), + ])->values()->all(); + } + + /** + * @return array> + */ + public function rules(string $prefix = 'custom_fields'): array + { + return $this->all()->mapWithKeys(fn (ProfileField $field) => [ + "{$prefix}.{$field->key}" => array_merge(['nullable'], match ($field->type) { + 'email' => ['email', 'max:255'], + 'url' => ['url', 'max:500'], + 'date' => ['date'], + 'phone' => ['string', 'max:50'], + 'textarea' => ['string', 'max:5000'], + default => ['string', 'max:255'], + }), + ])->all(); + } + + /** + * Nur die Felder übernehmen, die die Person selbst pflegen darf. + * + * @param array $input + * @param list $managed + */ + public function mergeUserInput(User $user, array $input, array $managed): void + { + $values = (array) ($user->custom_fields ?? []); + + foreach ($this->all() as $field) { + if ($field->editable && ! in_array('custom.'.$field->key, $managed, true) && array_key_exists($field->key, $input)) { + $values[$field->key] = filled($input[$field->key]) ? (string) $input[$field->key] : null; + } + } + + $user->forceFill(['custom_fields' => array_filter($values, fn ($v) => $v !== null)])->save(); + } + + private function display(ProfileField $field, string $value): string + { + if ($field->type === 'date') { + try { + return Carbon::parse($value)->format('d.m.Y'); + } catch (Throwable) { + return $value; + } + } + + return $value; + } +} diff --git a/app/Support/RichText.php b/app/Support/RichText.php index 96442a04..4364832b 100644 --- a/app/Support/RichText.php +++ b/app/Support/RichText.php @@ -25,6 +25,14 @@ class RichText return $this->sanitizer()->sanitize($html); } + /** + * HTML aus dem Portal-Editor (TipTap) bereinigen. + */ + public function sanitize(?string $html): string + { + return blank($html) ? '' : $this->sanitizer()->sanitize((string) $html); + } + public function readingMinutes(?string $html): int { $words = str_word_count(strip_tags((string) $html), 0, 'ÄÖÜäöüß'); diff --git a/app/Support/Settings.php b/app/Support/Settings.php index 9e283a0f..aaf21fa9 100644 --- a/app/Support/Settings.php +++ b/app/Support/Settings.php @@ -4,6 +4,7 @@ namespace App\Support; use App\Models\Setting; use Illuminate\Support\Facades\Cache; +use Throwable; /** * Systemweite Einstellungen als Schlüssel/Wert-Paare. @@ -47,10 +48,15 @@ class Settings */ public function all(): array { - return $this->values ??= Cache::rememberForever( - self::CACHE_KEY, - fn () => Setting::query()->pluck('value', 'key')->all(), - ); + try { + return $this->values ??= Cache::rememberForever( + self::CACHE_KEY, + fn () => Setting::query()->pluck('value', 'key')->all(), + ); + } catch (Throwable) { + // Noch keine Datenbank (Web-Installer) oder vorübergehend nicht erreichbar. + return []; + } } public function flush(): void diff --git a/app/Support/SiteHealth.php b/app/Support/SiteHealth.php new file mode 100644 index 00000000..ea922d44 --- /dev/null +++ b/app/Support/SiteHealth.php @@ -0,0 +1,262 @@ + + */ + public function requirements(): array + { + $checks = []; + + $checks[] = $this->check( + 'PHP-Version', + version_compare(PHP_VERSION, self::MIN_PHP, '>='), + 'PHP '.PHP_VERSION, + 'Benötigt wird mindestens PHP '.self::MIN_PHP.'. Die Version lässt sich meist in der Verwaltung des Hosters umstellen.', + ); + + $missing = array_values(array_filter(self::REQUIRED_EXTENSIONS, fn (string $ext) => ! extension_loaded($ext))); + $checks[] = $this->check( + 'PHP-Erweiterungen', + $missing === [], + 'Alle vorhanden', + 'Es fehlen: '.implode(', ', $missing).'. Bitte beim Hoster aktivieren.', + ); + + $checks[] = [ + 'label' => 'Ausgehende Verbindungen', + 'status' => function_exists('curl_init') || ini_get('allow_url_fopen') ? self::OK : self::WARNING, + 'message' => function_exists('curl_init') ? 'cURL verfügbar' : 'Weder cURL noch allow_url_fopen – Updates sind so nicht möglich.', + ]; + + foreach (['storage' => storage_path(), 'bootstrap/cache' => base_path('bootstrap/cache'), 'public/uploads' => public_path('uploads')] as $label => $path) { + $checks[] = $this->check( + "Schreibrechte: {$label}", + $this->writable($path), + 'Beschreibbar', + "Das Verzeichnis {$label} muss für den Webserver beschreibbar sein.", + ); + } + + $checks[] = [ + 'label' => 'Schreibrechte für Updates', + 'status' => $this->writable(base_path('app')) && $this->writable(base_path('vendor')) && $this->writable(public_path('build')) ? self::OK : self::WARNING, + 'message' => $this->writable(base_path('app')) + ? 'Programmdateien sind beschreibbar – Aktualisierungen per Klick funktionieren.' + : 'Programmdateien sind nicht beschreibbar – Aktualisierungen per Klick sind so nicht möglich.', + ]; + + return $checks; + } + + /** + * Alle Prüfungen für die Seite „Systemzustand“. + * + * @return array> + */ + public function all(): array + { + return [ + 'Voraussetzungen' => $this->requirements(), + 'Leistung und Grenzen' => $this->performance(), + 'Betrieb' => $this->operations(), + 'Sicherheit' => $this->security(), + ]; + } + + /** + * @return list + */ + private function performance(): array + { + $opcache = function_exists('opcache_get_status') && @opcache_get_status(false); + $memory = self::bytes((string) ini_get('memory_limit')); + $upload = min(self::bytes((string) ini_get('upload_max_filesize')), self::bytes((string) ini_get('post_max_size'))); + + return [ + [ + 'label' => 'OPcache', + 'status' => $opcache ? self::OK : self::WARNING, + 'message' => $opcache ? 'Aktiv' : 'Nicht aktiv – das Portal läuft deutlich langsamer. Bitte beim Hoster aktivieren.', + ], + [ + 'label' => 'Arbeitsspeicher (memory_limit)', + 'status' => $memory === -1 || $memory >= 128 * 1024 ** 2 ? self::OK : self::WARNING, + 'message' => ini_get('memory_limit').($memory !== -1 && $memory < 128 * 1024 ** 2 ? ' – empfohlen sind mindestens 128M.' : ''), + ], + [ + 'label' => 'Maximale Upload-Größe', + 'status' => $upload === -1 || $upload >= 8 * 1024 ** 2 ? self::OK : self::WARNING, + 'message' => ini_get('upload_max_filesize').' / '.ini_get('post_max_size').($upload !== -1 && $upload < 8 * 1024 ** 2 ? ' – für Fotos sind mindestens 8M empfohlen.' : ''), + ], + $this->databaseCheck(), + ]; + } + + /** + * @return list + */ + private function operations(): array + { + $beats = app(BackgroundTasks::class)->heartbeats(); + $cron = max($beats['cron'] ?? 0, $beats['webcron'] ?? 0); + $pseudo = $beats['pseudo'] ?? 0; + + $background = match (true) { + now()->getTimestamp() - $cron < 600 => ['status' => self::OK, 'message' => 'Läuft per '.(($beats['cron'] ?? 0) >= ($beats['webcron'] ?? 0) ? 'Cron' : 'Web-Cron').', zuletzt '.$this->ago($cron).'.'], + $pseudo > 0 => ['status' => self::WARNING, 'message' => 'Läuft nur beim Seitenaufruf (Pseudo-Cron), zuletzt '.$this->ago($pseudo).'. Zuverlässiger ist ein Cronjob.'], + default => ['status' => self::WARNING, 'message' => 'Noch kein Lauf erkannt. Bitte einen Cronjob einrichten (siehe unten).'], + }; + + try { + $pending = count(app(Migrations::class)->pending()); + } catch (Throwable) { + $pending = null; + } + + $license = app(LicenseStore::class); + $code = $license->lastStatus()['error_code'] ?? null; + + return [ + ['label' => 'Hintergrundaufgaben', ...$background], + [ + 'label' => 'Datenbank-Migrationen', + 'status' => $pending === 0 ? self::OK : ($pending === null ? self::ERROR : self::WARNING), + 'message' => match (true) { + $pending === null => 'Status kann nicht gelesen werden.', + $pending === 0 => 'Alle angewendet.', + default => "{$pending} ausstehend – unter „Aktualisierung“ ausführen.", + }, + ], + [ + 'label' => 'Lizenz', + 'status' => ! $license->hasLicense() || $code ? self::WARNING : self::OK, + 'message' => match (true) { + ! $license->hasLicense() => 'Keine Lizenz hinterlegt – Updates sind nicht möglich.', + $code !== null => ServerMessages::for(new ServerError($code, 0, $code)), + default => 'Hinterlegt.', + }, + ], + [ + 'label' => 'Wartungsmodus', + 'status' => app(MaintenanceFlag::class)->isActive() ? self::WARNING : self::OK, + 'message' => app(MaintenanceFlag::class)->isActive() ? 'Aktiv – es läuft gerade eine Aktualisierung.' : 'Aus', + ], + ]; + } + + /** + * @return list + */ + private function security(): array + { + $https = str_starts_with((string) config('app.url'), 'https://'); + + return [ + [ + 'label' => 'Fehlerdetails (APP_DEBUG)', + 'status' => match (true) { + config('app.debug') && app()->isProduction() => self::ERROR, + (bool) config('app.debug') => self::WARNING, + default => self::OK, + }, + 'message' => config('app.debug') ? 'Eingeschaltet – im Betrieb unbedingt ausschalten, sonst werden interne Details angezeigt.' : 'Ausgeschaltet', + ], + [ + 'label' => 'Verschlüsselte Verbindung', + 'status' => $https ? self::OK : self::WARNING, + 'message' => $https ? 'Das Portal läuft über HTTPS.' : 'APP_URL beginnt nicht mit https:// – Anmeldedaten würden unverschlüsselt übertragen.', + ], + [ + 'label' => 'Anwendungsschlüssel', + 'status' => filled(config('app.key')) ? self::OK : self::ERROR, + 'message' => filled(config('app.key')) ? 'Gesetzt' : 'APP_KEY fehlt.', + ], + ]; + } + + /** + * @return array{label: string, status: string, message: string} + */ + private function databaseCheck(): array + { + try { + $version = (string) DB::selectOne('select version() as v')->v; + $mariadb = str_contains(strtolower($version), 'mariadb'); + $number = preg_replace('/^(\d+\.\d+\.\d+).*$/', '$1', $version); + $ok = version_compare($number, $mariadb ? '10.6.0' : '8.0.0', '>='); + + return [ + 'label' => 'Datenbank', + 'status' => $ok ? self::OK : self::WARNING, + 'message' => ($mariadb ? 'MariaDB ' : 'MySQL ').$number.($ok ? '' : ' – unterstützt werden MySQL ab 8.0 und MariaDB ab 10.6.'), + ]; + } catch (Throwable) { + return ['label' => 'Datenbank', 'status' => self::ERROR, 'message' => 'Keine Verbindung.']; + } + } + + /** + * @return array{label: string, status: string, message: string} + */ + private function check(string $label, bool $ok, string $okMessage, string $errorMessage): array + { + return ['label' => $label, 'status' => $ok ? self::OK : self::ERROR, 'message' => $ok ? $okMessage : $errorMessage]; + } + + private function writable(string $path): bool + { + return is_dir($path) ? is_writable($path) : is_writable(dirname($path)); + } + + private function ago(int $timestamp): string + { + return Carbon::createFromTimestamp($timestamp)->locale('de')->diffForHumans(); + } + + public static function bytes(string $value): int + { + $value = trim($value); + + if ($value === '' || $value === '-1') { + return -1; + } + + $number = (int) $value; + + return match (strtolower(substr($value, -1))) { + 'g' => $number * 1024 ** 3, + 'm' => $number * 1024 ** 2, + 'k' => $number * 1024, + default => $number, + }; + } +} diff --git a/app/Support/Theme/Contrast.php b/app/Support/Theme/Contrast.php new file mode 100644 index 00000000..894b5106 --- /dev/null +++ b/app/Support/Theme/Contrast.php @@ -0,0 +1,91 @@ += self::AA) { + return $shade; + } + } + + return 950; + } + + /** + * Farbe für Links und Akzenttext auf dunklem Grund. + */ + public static function textShadeOnDark(string $hex): int + { + $palette = ColorPalette::fromHex($hex); + + foreach ([300, 200, 100, 50] as $shade) { + if (ColorPalette::contrast($palette[$shade], self::DARK_BACKGROUND) >= self::AA) { + return $shade; + } + } + + return 50; + } + + /** + * Hinweise für die Seite „Erscheinungsbild“. + * + * @return list + */ + public static function report(string $primary, ?string $secondary = null): array + { + $notes = []; + $foreground = ColorPalette::foregroundFor($primary); + $onButton = ColorPalette::contrast($primary, $foreground); + $onWhite = ColorPalette::contrast($primary, self::LIGHT_BACKGROUND); + $palette = ColorPalette::fromHex($primary); + + $notes[] = $onButton >= self::AA + ? ['level' => 'ok', 'text' => sprintf('Schrift auf Schaltflächen (%s): Kontrast %s:1 – gut lesbar.', $foreground === '#FFFFFF' ? 'weiß' : 'schwarz', self::format($onButton))] + : ['level' => 'warning', 'text' => sprintf('Schrift auf Schaltflächen erreicht nur %s:1 (empfohlen mindestens 4,5:1). Eine etwas dunklere oder hellere Markenfarbe wäre besser lesbar, z. B. %s.', self::format($onButton), $palette[700])]; + + if ($onWhite >= self::AA) { + $notes[] = ['level' => 'ok', 'text' => sprintf('Links auf hellem Grund: Kontrast %s:1 – die Markenfarbe wird unverändert verwendet.', self::format($onWhite))]; + } else { + $shade = self::textShadeOnLight($primary); + $notes[] = ['level' => 'info', 'text' => sprintf('Die Markenfarbe ist auf Weiß als Textfarbe zu hell (%s:1). Für Links und Akzenttexte wird automatisch die dunklere Abstufung %s verwendet. Schaltflächen und Flächen behalten die Markenfarbe.', self::format($onWhite), $palette[$shade])]; + } + + if ($secondary !== null) { + $onWhite2 = ColorPalette::contrast($secondary, self::LIGHT_BACKGROUND); + + if ($onWhite2 < 3) { + $notes[] = ['level' => 'info', 'text' => sprintf('Die zweite Akzentfarbe ist auf Weiß sehr hell (%s:1). Für Beschriftungen wird automatisch eine dunklere Abstufung verwendet.', self::format($onWhite2))]; + } + } + + return $notes; + } + + private static function format(float $ratio): string + { + return number_format($ratio, 1, ',', ''); + } +} diff --git a/app/Support/Theme/Fonts.php b/app/Support/Theme/Fonts.php new file mode 100644 index 00000000..16c6bc5e --- /dev/null +++ b/app/Support/Theme/Fonts.php @@ -0,0 +1,55 @@ + [Bezeichnung, CSS-Familie, serif?] */ + public const FONTS = [ + 'inter' => ['Inter', 'Inter Variable', false], + 'source-sans-3' => ['Source Sans 3', 'Source Sans 3 Variable', false], + 'open-sans' => ['Open Sans', 'Open Sans Variable', false], + 'nunito-sans' => ['Nunito Sans', 'Nunito Sans Variable', false], + 'roboto' => ['Roboto', 'Roboto Variable', false], + 'ibm-plex-sans' => ['IBM Plex Sans', 'IBM Plex Sans Variable', false], + 'figtree' => ['Figtree', 'Figtree Variable', false], + 'atkinson' => ['Atkinson Hyperlegible (besonders gut lesbar)', 'Atkinson Hyperlegible', false], + 'source-serif-4' => ['Source Serif 4 (Serifen)', 'Source Serif 4 Variable', true], + 'merriweather' => ['Merriweather (Serifen)', 'Merriweather Variable', true], + 'lora' => ['Lora (Serifen)', 'Lora Variable', true], + 'system' => ['Systemschrift des Geräts', null, false], + ]; + + /** Familienname einer hochgeladenen Schrift. */ + public const CUSTOM_FAMILY = 'Portal Eigene Schrift'; + + /** + * @return array + */ + public static function options(bool $withCustom = false): array + { + $options = array_map(fn (array $font) => $font[0], self::FONTS); + + return $withCustom ? $options + ['custom' => 'Eigene Schrift (hochgeladen)'] : $options; + } + + public static function stack(string $key): string + { + if ($key === 'custom') { + return '"'.self::CUSTOM_FAMILY.'", '.self::FALLBACK_SANS; + } + + [, $family, $serif] = self::FONTS[$key] ?? self::FONTS['inter']; + $fallback = $serif ? self::FALLBACK_SERIF : self::FALLBACK_SANS; + + return $family ? '"'.$family.'", '.$fallback : $fallback; + } +} diff --git a/app/Support/Theme/Icons.php b/app/Support/Theme/Icons.php new file mode 100644 index 00000000..2d5c8f06 --- /dev/null +++ b/app/Support/Theme/Icons.php @@ -0,0 +1,66 @@ + $theme + * @return array Größe => Pfad im Speicher „uploads“ + */ + public function generate(array $theme): array + { + $source = $theme['app_icon'] ?? null; + $disk = Storage::disk('uploads'); + + if (! $source || ! $disk->exists($source)) { + return []; + } + + try { + Images::raiseMemoryLimitFor($disk->path($source)); + $manager = ImageManager::usingDriver(Driver::class); + $hash = substr(sha1((string) $disk->get($source)), 0, 10); + $result = []; + + foreach (self::SIZES as $size) { + $image = $manager->decodePath($disk->path($source)); + $image->cover($size, $size); + $path = "theme/icons/icon-{$hash}-{$size}.png"; + $disk->put($path, $image->encode(new PngEncoder)->toString()); + $result[$size] = $path; + } + + return $result; + } catch (Throwable $e) { + report($e); + + return []; + } + } + + /** + * Monogramm als SVG-Favicon (Daten-URL), wenn kein Symbol hochgeladen ist. + */ + public static function monogram(string $name, string $color, string $foreground): string + { + $letter = htmlspecialchars(mb_strtoupper(mb_substr(trim($name), 0, 1)) ?: 'P', ENT_XML1); + $svg = '' + .''.$letter.''; + + return 'data:image/svg+xml;base64,'.base64_encode($svg); + } +} diff --git a/app/Support/Theme/SvgSanitizer.php b/app/Support/Theme/SvgSanitizer.php new file mode 100644 index 00000000..f7e01546 --- /dev/null +++ b/app/Support/Theme/SvgSanitizer.php @@ -0,0 +1,62 @@ +exists($path)) { + return; + } + + $clean = self::sanitize((string) $disk->get($path)); + $clean === null ? $disk->delete($path) : $disk->put($path, $clean); + } + + public static function sanitize(string $svg): ?string + { + $dom = new DOMDocument; + + // Keine externen Entitäten, kein Netzwerkzugriff. + if (str_contains($svg, 'loadXML($svg, LIBXML_NONET) || $dom->documentElement?->localName !== 'svg') { + return null; + } + + $xpath = new DOMXPath($dom); + + foreach (iterator_to_array($xpath->query('//*[local-name()="script" or local-name()="foreignObject" or local-name()="iframe" or local-name()="object" or local-name()="embed"]')) as $node) { + $node->parentNode->removeChild($node); + } + + foreach (iterator_to_array($xpath->query('//*')) as $element) { + /** @var DOMElement $element */ + foreach (iterator_to_array($element->attributes) as $attribute) { + $name = strtolower($attribute->nodeName); + $value = strtolower(preg_replace('/\s+/', '', $attribute->nodeValue)); + + if (str_starts_with($name, 'on') || (in_array($name, ['href', 'xlink:href', 'src'], true) && ! str_starts_with($value, '#') && ! str_starts_with($value, 'data:image/'))) { + $element->removeAttributeNode($attribute); + } + } + } + + return $dom->saveXML($dom->documentElement); + } +} diff --git a/app/Support/Theme/Theme.php b/app/Support/Theme/Theme.php new file mode 100644 index 00000000..34d45f46 --- /dev/null +++ b/app/Support/Theme/Theme.php @@ -0,0 +1,191 @@ + 'Inhaus', + 'logo_light' => null, + 'logo_dark' => null, + 'logo_mark' => null, + 'app_icon' => null, + 'icons' => [], + 'primary_color' => '#0F4C5C', + 'secondary_color' => null, + 'header_style' => 'light', + 'font_body' => 'inter', + 'font_heading' => 'same', + 'custom_font' => null, + 'radius' => 'medium', + 'density' => 'normal', + 'dark_mode' => 'user', + 'login_layout' => 'split', + 'login_title' => 'Alles Wichtige für Ihren Arbeitsalltag – an einem Ort.', + 'login_text' => null, + 'login_image' => null, + 'footer_text' => null, + 'footer_links' => [], + 'email_footer' => null, + 'custom_css' => null, + 'stylesheet' => null, + ]; + + public const HEADER_STYLES = ['light' => 'Hell', 'brand' => 'In der Markenfarbe', 'dark' => 'Dunkel']; + + public const RADII = ['none' => ['Eckig', '0rem'], 'small' => ['Leicht gerundet', '0.25rem'], 'medium' => ['Gerundet', '0.5rem'], 'large' => ['Stark gerundet', '0.75rem'], 'round' => ['Rund', '1rem']]; + + public const DENSITIES = ['compact' => ['Kompakt', '0.225rem'], 'normal' => ['Normal', '0.25rem'], 'comfortable' => ['Luftig', '0.275rem']]; + + public const DARK_MODES = [ + 'user' => 'Jede Person wählt selbst (Standard: wie im System)', + 'light' => 'Immer hell', + 'dark' => 'Immer dunkel', + ]; + + public const LOGIN_LAYOUTS = ['split' => 'Geteilt: Bild bzw. Markenfarbe links, Anmeldung rechts', 'centered' => 'Zentriert: Anmeldung vor dem Hintergrundbild']; + + private const PUBLISHED = 'theme.published'; + + private const DRAFT = 'theme.draft'; + + public function __construct(private readonly Settings $settings) {} + + /** + * @return array + */ + public function published(): array + { + $stored = $this->settings->get(self::PUBLISHED); + + return self::normalize(is_array($stored) ? $stored : $this->legacy()); + } + + /** + * @return array|null + */ + public function draft(): ?array + { + $stored = $this->settings->get(self::DRAFT); + + return is_array($stored) ? self::normalize($stored) : null; + } + + public function hasDraft(): bool + { + return $this->draft() !== null; + } + + /** + * Entwurf, sonst der veröffentlichte Stand – Ausgangspunkt für das Formular. + * + * @return array + */ + public function working(): array + { + return $this->draft() ?? $this->published(); + } + + /** + * @param array $values + */ + public function saveDraft(array $values): void + { + $theme = self::normalize([...$this->working(), ...$values]); + + foreach (['logo_light', 'logo_dark', 'logo_mark'] as $logo) { + SvgSanitizer::sanitizeFile($theme[$logo]); + } + + $this->settings->set(self::DRAFT, $theme); + } + + public function discardDraft(): void + { + $this->settings->set(self::DRAFT, null); + } + + /** + * Entwurf veröffentlichen: statische CSS-Datei erzeugen, Symbole berechnen. + */ + public function publish(ThemeCompiler $compiler, Icons $icons): void + { + $theme = $this->working(); + $theme['icons'] = $icons->generate($theme); + $theme['stylesheet'] = $compiler->write($theme); + + $this->settings->setMany([self::PUBLISHED => $theme, self::DRAFT => null]); + } + + /** + * Auf die Standardwerte zurücksetzen – als Entwurf, damit man es erst ansehen kann. + */ + public function resetToDefaults(): void + { + $this->settings->set(self::DRAFT, self::normalize([...self::DEFAULTS, 'portal_name' => $this->published()['portal_name']])); + } + + /** + * Nur bekannte Schlüssel, gültige Werte. + * + * @param array $theme + * @return array + */ + public static function normalize(array $theme): array + { + $theme = [...self::DEFAULTS, ...Arr::only($theme, array_keys(self::DEFAULTS))]; + $hex = fn ($value) => is_string($value) && preg_match('/^#[0-9a-fA-F]{6}$/', $value) ? strtoupper($value) : null; + + $theme['portal_name'] = mb_substr(trim((string) $theme['portal_name']), 0, 60) ?: self::DEFAULTS['portal_name']; + $theme['primary_color'] = $hex($theme['primary_color']) ?? self::DEFAULTS['primary_color']; + $theme['secondary_color'] = $hex($theme['secondary_color']); + $theme['header_style'] = array_key_exists($theme['header_style'], self::HEADER_STYLES) ? $theme['header_style'] : 'light'; + $theme['font_body'] = array_key_exists($theme['font_body'], Fonts::FONTS) || ($theme['font_body'] === 'custom' && $theme['custom_font']) ? $theme['font_body'] : 'inter'; + $theme['font_heading'] = $theme['font_heading'] === 'same' || array_key_exists($theme['font_heading'], Fonts::FONTS) || ($theme['font_heading'] === 'custom' && $theme['custom_font']) ? $theme['font_heading'] : 'same'; + $theme['radius'] = array_key_exists($theme['radius'], self::RADII) ? $theme['radius'] : 'medium'; + $theme['density'] = array_key_exists($theme['density'], self::DENSITIES) ? $theme['density'] : 'normal'; + $theme['dark_mode'] = array_key_exists($theme['dark_mode'], self::DARK_MODES) ? $theme['dark_mode'] : 'user'; + $theme['login_layout'] = array_key_exists($theme['login_layout'], self::LOGIN_LAYOUTS) ? $theme['login_layout'] : 'split'; + $theme['footer_links'] = array_values(array_filter(array_map( + fn ($link) => is_array($link) && filled($link['label'] ?? null) && filled($link['url'] ?? null) + ? ['label' => mb_substr(trim($link['label']), 0, 60), 'url' => mb_substr(trim($link['url']), 0, 500)] + : null, + (array) $theme['footer_links'], + ))); + $theme['icons'] = is_array($theme['icons']) ? $theme['icons'] : []; + + foreach (['login_title', 'login_text', 'footer_text', 'email_footer'] as $text) { + $theme[$text] = filled($theme[$text]) ? mb_substr(trim((string) $theme[$text]), 0, 500) : null; + } + + foreach (['logo_light', 'logo_dark', 'logo_mark', 'app_icon', 'login_image', 'custom_font'] as $file) { + $theme[$file] = is_string($theme[$file]) && preg_match('#^(theme|branding)/[A-Za-z0-9/_.-]+$#', $theme[$file]) && ! str_contains($theme[$file], '..') ? $theme[$file] : null; + } + + $theme['custom_css'] = filled($theme['custom_css']) ? mb_substr((string) $theme['custom_css'], 0, 50000) : null; + + return $theme; + } + + /** + * Einstellungen aus Phase 0 (Portalname, Logo, Markenfarbe) übernehmen. + * + * @return array + */ + private function legacy(): array + { + return array_filter([ + 'portal_name' => $this->settings->get('branding.portal_name'), + 'primary_color' => $this->settings->get('branding.primary_color'), + 'logo_light' => $this->settings->get('branding.logo_path'), + ]); + } +} diff --git a/app/Support/Theme/ThemeCompiler.php b/app/Support/Theme/ThemeCompiler.php new file mode 100644 index 00000000..875662b9 --- /dev/null +++ b/app/Support/Theme/ThemeCompiler.php @@ -0,0 +1,98 @@ + $theme + */ + public function css(array $theme): string + { + $primary = $theme['primary_color']; + $palette = ColorPalette::fromHex($primary); + $secondary = $theme['secondary_color'] ?? $primary; + $palette2 = ColorPalette::fromHex($secondary); + + $light = [ + '--brand' => $primary, + '--brand-foreground' => ColorPalette::foregroundFor($primary), + '--brand-text' => $palette[Contrast::textShadeOnLight($primary)], + '--accent2' => $secondary, + '--accent2-foreground' => ColorPalette::foregroundFor($secondary), + '--accent2-text' => $palette2[Contrast::textShadeOnLight($secondary)], + '--radius' => Theme::RADII[$theme['radius']][1], + '--spacing' => Theme::DENSITIES[$theme['density']][1], + '--font-body' => Fonts::stack($theme['font_body']), + '--font-heading' => Fonts::stack($theme['font_heading'] === 'same' ? $theme['font_body'] : $theme['font_heading']), + ]; + + foreach ($palette as $shade => $hex) { + $light["--brand-{$shade}"] = $hex; + } + + foreach ($palette2 as $shade => $hex) { + $light["--accent2-{$shade}"] = $hex; + } + + $dark = [ + '--brand-text' => $palette[Contrast::textShadeOnDark($primary)], + '--accent2-text' => $palette2[Contrast::textShadeOnDark($secondary)], + ]; + + $css = ':root{'.$this->declarations($light).'}'."\n" + .'.dark{'.$this->declarations($dark).'}'."\n"; + + if ($theme['custom_font']) { + $url = Storage::disk('uploads')->url($theme['custom_font']); + $css .= '@font-face{font-family:"'.Fonts::CUSTOM_FAMILY.'";src:url("'.$url.'") format("woff2");font-weight:100 900;font-display:swap}'."\n"; + } + + if ($theme['custom_css']) { + // Eigenes CSS steht in einer eigenen CSS-Datei; ein schließendes ist dort bedeutungslos, + // wird aber für die Vorschau (inline) trotzdem entschärft. + $css .= "/* Eigenes CSS */\n".str_ireplace(' $theme + */ + public function write(array $theme): string + { + $css = $this->css($theme); + $path = 'theme/theme-'.substr(sha1($css), 0, 12).'.css'; + $disk = Storage::disk('uploads'); + + if (! $disk->exists($path)) { + $disk->put($path, $css); + } + + // Ältere Fassungen aufräumen (die aktuelle und die vorherige bleiben für offene Seiten). + $old = collect($disk->files('theme'))->filter(fn ($f) => preg_match('#^theme/theme-[0-9a-f]{12}\.css$#', $f) && $f !== $path) + ->sortByDesc(fn ($f) => $disk->lastModified($f))->slice(1); + $disk->delete($old->all()); + + return $path; + } + + /** + * @param array $values + */ + private function declarations(array $values): string + { + return collect($values)->map(fn ($value, $name) => $name.':'.$value)->implode(';'); + } +} diff --git a/app/Support/Theme/ThemeTransfer.php b/app/Support/Theme/ThemeTransfer.php new file mode 100644 index 00000000..78581928 --- /dev/null +++ b/app/Support/Theme/ThemeTransfer.php @@ -0,0 +1,92 @@ + 'svg', 'image/png' => 'png', 'image/jpeg' => 'jpg', 'image/webp' => 'webp', 'font/woff2' => 'woff2', + ]; + + /** + * @param array $theme + * @return array + */ + public function export(array $theme): array + { + $disk = Storage::disk('uploads'); + $files = []; + + foreach (self::FILES as $key) { + if ($theme[$key] && $disk->exists($theme[$key])) { + $mime = $key === 'custom_font' ? 'font/woff2' : ($disk->mimeType($theme[$key]) ?: 'application/octet-stream'); + $files[$key] = 'data:'.$mime.';base64,'.base64_encode((string) $disk->get($theme[$key])); + } + } + + return [ + 'format' => self::FORMAT, + 'version' => 1, + 'exported_at' => now()->toIso8601String(), + 'theme' => collect($theme)->except([...self::FILES, 'icons', 'stylesheet'])->all(), + 'files' => $files, + ]; + } + + /** + * @return array Werte für den Entwurf + */ + public function import(string $json): array + { + $data = json_decode($json, true); + + if (! is_array($data) || ($data['format'] ?? null) !== self::FORMAT || ! is_array($data['theme'] ?? null)) { + throw new RuntimeException('Die Datei ist kein exportiertes Erscheinungsbild.'); + } + + $values = collect($data['theme'])->except([...self::FILES, 'icons', 'stylesheet'])->all(); + + foreach (self::FILES as $key) { + $values[$key] = null; + $uri = $data['files'][$key] ?? null; + + if (! is_string($uri) || ! preg_match('#^data:([a-z0-9.+/-]+);base64,(.+)$#i', $uri, $m)) { + continue; + } + + $extension = self::MIME[strtolower($m[1])] ?? null; + $binary = base64_decode($m[2], true); + + if (! $extension || $binary === false || strlen($binary) > 8 * 1024 * 1024) { + continue; + } + + // Inhalt prüfen: Bilder müssen sich lesen lassen, SVG wird von allem Ausführbaren befreit. + if ($extension === 'svg' && ($binary = SvgSanitizer::sanitize($binary)) === null) { + continue; + } + + if (in_array($extension, ['png', 'jpg', 'webp'], true) && @getimagesizefromstring($binary) === false) { + continue; + } + + $path = ($key === 'custom_font' ? 'theme/fonts/' : 'theme/').'import-'.Str::random(20).'.'.$extension; + Storage::disk('uploads')->put($path, $binary); + $values[$key] = $path; + } + + return Theme::normalize([...Theme::DEFAULTS, ...$values]); + } +} diff --git a/app/Support/Update/AtomicFile.php b/app/Support/Update/AtomicFile.php new file mode 100644 index 00000000..21e8592a --- /dev/null +++ b/app/Support/Update/AtomicFile.php @@ -0,0 +1,33 @@ +“-Abschnitten und rendert Markdown + * sicher (kein Roh-HTML, keine unsicheren Links). + */ +class Changelog +{ + /** + * @return list + */ + public function sections(?string $markdown = null): array + { + $markdown ??= (string) @file_get_contents(base_path('CHANGELOG.md')); + $parts = preg_split('/^## +/m', $markdown) ?: []; + array_shift($parts); // Einleitung vor dem ersten Abschnitt + + return array_values(array_map(function (string $part) { + [$heading, $body] = array_pad(explode("\n", $part, 2), 2, ''); + $heading = trim($heading); + preg_match('/\d+\.\d+\.\d+(?:[-+][\w.]+)?/', $heading, $m); + + return [ + 'version' => $m[0] ?? $heading, + 'heading' => $heading, + 'html' => $this->toHtml(trim($body)), + ]; + }, $parts)); + } + + public function toHtml(string $markdown): string + { + $converter = new GithubFlavoredMarkdownConverter([ + 'html_input' => 'strip', + 'allow_unsafe_links' => false, + 'max_nesting_level' => 20, + ]); + + return (string) $converter->convert($markdown); + } +} diff --git a/app/Support/Update/Channels.php b/app/Support/Update/Channels.php new file mode 100644 index 00000000..334c8183 --- /dev/null +++ b/app/Support/Update/Channels.php @@ -0,0 +1,65 @@ + Schlüssel => Bezeichnung + */ + public function all(): array + { + return collect(config('updater.channels'))->map(fn (array $c) => $c['label'])->all(); + } + + public function active(): string + { + try { + $channel = $this->settings->get('updater.channel'); + } catch (Throwable) { + $channel = null; // Datenbank nicht erreichbar – Standardkanal. + } + + return is_string($channel) && $this->exists($channel) ? $channel : config('updater.default_channel', 'stable'); + } + + public function setActive(string $channel): void + { + $this->assertExists($channel); + $this->settings->set('updater.channel', $channel); + } + + public function client(?string $channel = null): UpdateClient + { + $channel ??= $this->active(); + $this->assertExists($channel); + + return new UpdateClient($this->http, config("updater.channels.{$channel}.url")); + } + + public function exists(string $channel): bool + { + return is_array(config("updater.channels.{$channel}")); + } + + private function assertExists(string $channel): void + { + if (! $this->exists($channel)) { + throw new InvalidArgumentException("Unbekannter Update-Kanal: {$channel}"); + } + } +} diff --git a/app/Support/Update/Filesystem.php b/app/Support/Update/Filesystem.php new file mode 100644 index 00000000..a5f811db --- /dev/null +++ b/app/Support/Update/Filesystem.php @@ -0,0 +1,74 @@ +getPathname(), strlen(rtrim($from, '/')) + 1); + + if ($item->isDir()) { + if (! is_dir($target) && ! @mkdir($target, 0775, true)) { + return false; + } + } elseif (! @copy($item->getPathname(), $target)) { + return false; + } + } + + return true; + } + + public static function deleteDirectory(string $dir): void + { + if (! is_dir($dir)) { + return; + } + + $items = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS), + RecursiveIteratorIterator::CHILD_FIRST, + ); + + foreach ($items as $item) { + $item->isDir() && ! $item->isLink() ? @rmdir($item->getPathname()) : @unlink($item->getPathname()); + } + + @rmdir($dir); + } +} diff --git a/app/Support/Update/InstalledVersion.php b/app/Support/Update/InstalledVersion.php new file mode 100644 index 00000000..d7b329c8 --- /dev/null +++ b/app/Support/Update/InstalledVersion.php @@ -0,0 +1,60 @@ +path()); + + return is_string($sha) && self::isSha(trim($sha)) ? strtolower(trim($sha)) : null; + } + + public function save(string $sha): void + { + if (! self::isSha($sha)) { + throw new InvalidArgumentException('Ungültiger Commit-Stand: erwartet werden 40 Hex-Zeichen.'); + } + + AtomicFile::write($this->path(), strtolower($sha)); + } + + public function short(): ?string + { + return ($sha = $this->current()) ? substr($sha, 0, 7) : null; + } + + public function release(): string + { + return Version::VERSION; + } + + /** + * „1.4.2 (a1b2c3d)“ bzw. nur „1.4.2“, solange kein Stand bekannt ist. + */ + public function full(): string + { + return $this->release().(($short = $this->short()) ? " ({$short})" : ''); + } + + public static function isSha(string $value): bool + { + return (bool) preg_match('/^[0-9a-f]{40}$/i', $value); + } + + private function path(): string + { + return $this->file ?? storage_path('.version'); + } +} diff --git a/app/Support/Update/MaintenanceFlag.php b/app/Support/Update/MaintenanceFlag.php new file mode 100644 index 00000000..dec64578 --- /dev/null +++ b/app/Support/Update/MaintenanceFlag.php @@ -0,0 +1,59 @@ +path(), json_encode([ + 'since' => time(), + 'until' => time() + $maxSeconds, + ])); + } + + public function deactivate(): void + { + @unlink($this->path()); + } + + public function isActive(): bool + { + if (! is_file($this->path())) { + return false; + } + + $data = json_decode((string) @file_get_contents($this->path()), true); + $until = is_array($data) ? (int) ($data['until'] ?? 0) : 0; + + if ($until <= time()) { + $this->deactivate(); + + return false; + } + + return true; + } + + public function retryAfter(): int + { + $data = json_decode((string) @file_get_contents($this->path()), true); + $remaining = is_array($data) ? (int) ($data['until'] ?? 0) - time() : 0; + + return max(5, min(60, $remaining)); + } + + private function path(): string + { + return $this->file ?? storage_path('.maintenance'); + } +} diff --git a/app/Support/Update/Migrations.php b/app/Support/Update/Migrations.php new file mode 100644 index 00000000..178fa42e --- /dev/null +++ b/app/Support/Update/Migrations.php @@ -0,0 +1,81 @@ + + */ + public function status(): array + { + $ran = $this->ran(); + + return array_map(fn (string $name) => [ + 'name' => $name, + 'ran' => in_array($name, $ran, true), + ], array_keys($this->files())); + } + + /** + * @return list + */ + public function pending(): array + { + return array_values(array_diff(array_keys($this->files()), $this->ran())); + } + + /** + * Führt ausstehende Migrationen aus und gibt deren Anzahl zurück. + */ + public function run(): int + { + $before = count($this->ran()); + + Artisan::call('migrate', ['--force' => true]); + + return count($this->ran()) - $before; + } + + /** + * Fingerabdruck über die Liste der Migrationsdateien. Ändert sich nur, wenn + * Migrationen dazukommen – dann lohnt sich ein Blick auf die Datenbank. + */ + public function fingerprint(): string + { + return sha1(implode("\n", array_keys($this->files()))); + } + + /** + * @return array Name => Pfad + */ + private function files(): array + { + $files = $this->migrator->getMigrationFiles(array_merge( + [database_path('migrations')], + $this->migrator->paths(), + )); + + ksort($files); + + return $files; + } + + /** + * @return list + */ + private function ran(): array + { + $repository = $this->migrator->getRepository(); + + return $repository->repositoryExists() ? $repository->getRan() : []; + } +} diff --git a/app/Support/Update/ProtectedPaths.php b/app/Support/Update/ProtectedPaths.php new file mode 100644 index 00000000..8b16534e --- /dev/null +++ b/app/Support/Update/ProtectedPaths.php @@ -0,0 +1,37 @@ + $paths + */ + public function __construct(private readonly array $paths) {} + + public static function fromConfig(): self + { + return new self(config('updater.protected_paths', [])); + } + + public function isProtected(string $relativePath): bool + { + $path = ltrim(str_replace('\\', '/', $relativePath), '/'); + + foreach ($this->paths as $protected) { + if (str_ends_with($protected, '/')) { + if (str_starts_with($path.'/', $protected)) { + return true; + } + } elseif ($path === $protected) { + return true; + } + } + + return false; + } +} diff --git a/app/Support/Update/StagingApplier.php b/app/Support/Update/StagingApplier.php new file mode 100644 index 00000000..ba98ff44 --- /dev/null +++ b/app/Support/Update/StagingApplier.php @@ -0,0 +1,77 @@ +isDir() || $file->isLink()) { + continue; + } + + $relative = ltrim(str_replace('\\', '/', substr($file->getPathname(), strlen($stagingDir))), '/'); + + if ($this->protected->isProtected($relative)) { + $skipped++; + + continue; + } + + $destination = rtrim($targetDir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.$relative; + $directory = dirname($destination); + + if (! is_dir($directory) && ! @mkdir($directory, 0775, true) && ! is_dir($directory)) { + throw new RuntimeException("Verzeichnis {$directory} kann nicht angelegt werden. Bitte Schreibrechte für das Installationsverzeichnis prüfen."); + } + + $temporary = $destination.'.update-'.bin2hex(random_bytes(3)); + + if (! @copy($file->getPathname(), $temporary)) { + throw new RuntimeException("Datei {$relative} ist nicht schreibbar. Bitte Schreibrechte für {$directory} prüfen."); + } + + if (is_file($destination)) { + @chmod($temporary, fileperms($destination) & 0777); + } + + if (! @rename($temporary, $destination)) { + @unlink($temporary); + + throw new RuntimeException("Datei {$relative} kann nicht ersetzt werden. Bitte Schreibrechte für {$directory} prüfen."); + } + + $copied++; + } + + return ['copied' => $copied, 'skipped' => $skipped]; + } +} diff --git a/app/Support/Update/UpdateCheck.php b/app/Support/Update/UpdateCheck.php new file mode 100644 index 00000000..0f003a06 --- /dev/null +++ b/app/Support/Update/UpdateCheck.php @@ -0,0 +1,53 @@ + + */ + public function run(?string $channel = null): array + { + $current = $this->version->current(); + $result = $this->channels->client($channel)->check($current); + $latest = $result['latest_sha'] ?? null; + + // Frische Installation: Die erste Prüfung liefert den Stand zum Merken. + if ($current === null && is_string($latest) && InstalledVersion::isSha($latest)) { + $this->version->save($latest); + } + + $preview = $result['changelog_preview'] ?? null; + $entries = is_array($preview['entries'] ?? null) ? $preview['entries'] : []; + + return [ + 'has_update' => (bool) ($result['has_update'] ?? false), + 'latest_sha' => is_string($latest) ? $latest : null, + 'latest_short' => is_string($latest) ? substr($latest, 0, 7) : null, + 'version' => $result['version'] ?? null, + 'released_at' => $result['released_at'] ?? null, + 'versions_behind' => (int) ($result['versions_behind'] ?? 0), + 'channel_switch' => $result['channel_switch'] ?? null, + // Feld kann fehlen – dann gibt es nichts zu berichten (kein leerer Kasten). + 'changelog' => array_map(fn (array $entry) => [ + 'version' => $entry['version'] ?? null, + 'heading' => $entry['heading'] ?? null, + 'html' => $this->changelog->toHtml((string) ($entry['text'] ?? '')), + ], $entries), + 'changelog_complete' => $preview === null ? true : (bool) ($preview['complete'] ?? true), + 'changelog_url' => config('updater.changelog_url'), + ]; + } +} diff --git a/app/Support/Update/UpdateClient.php b/app/Support/Update/UpdateClient.php new file mode 100644 index 00000000..a65a2856 --- /dev/null +++ b/app/Support/Update/UpdateClient.php @@ -0,0 +1,114 @@ + + */ + public function version(): array + { + return $this->json('version'); + } + + /** + * @return array + */ + public function check(?string $currentSha): array + { + return $this->json('check', $currentSha ? ['current_sha' => $currentSha] : []); + } + + /** + * @return array + */ + public function license(): array + { + return $this->json('license'); + } + + public function changelog(): string + { + $response = $this->send(fn () => $this->http->request((int) config('updater.timeouts.json')) + ->accept('text/markdown') + ->get($this->url('changelog'), ['format' => 'raw'])); + + return $response->body(); + } + + /** + * ZIP in eine Datei streamen – nicht in den Speicher. + * + * @return array{sha: string|null, sha256: string|null} + */ + public function downloadZip(string $sha, string $target): array + { + $response = $this->send(fn () => $this->http->request((int) config('updater.timeouts.zip')) + ->accept('application/zip') + ->sink($target) + ->get($this->url('zip'), ['ref' => $sha]), sinkedTo: $target); + + return [ + 'sha' => $response->header('X-Commit-Sha') ?: null, + 'sha256' => $response->header('X-Content-Sha256') ?: null, + ]; + } + + /** + * @param array $query + * @return array + */ + private function json(string $path, array $query = []): array + { + $response = $this->send(fn () => $this->http->request((int) config('updater.timeouts.json')) + ->get($this->url($path), $query)); + + $data = $response->json(); + + if (! is_array($data)) { + throw new ServerError('invalid_response', $response->status(), 'Antwort ist kein JSON.'); + } + + return $data; + } + + /** + * @param callable(): Response $callback + */ + private function send(callable $callback, ?string $sinkedTo = null): Response + { + $response = VendorHttp::guard($callback); + + if (! $response->successful()) { + // Bei Downloads steht die Fehlerantwort in der Zieldatei. + $body = $sinkedTo && is_file($sinkedTo) ? (string) file_get_contents($sinkedTo) : null; + + throw VendorHttp::errorFrom($response, $body); + } + + return $response; + } + + private function url(string $path): string + { + return rtrim($this->baseUrl, '/').'/'.$path; + } +} diff --git a/app/Support/Update/UpdateProgress.php b/app/Support/Update/UpdateProgress.php new file mode 100644 index 00000000..ac07a695 --- /dev/null +++ b/app/Support/Update/UpdateProgress.php @@ -0,0 +1,70 @@ +path(), json_encode([ + 'pct' => $pct, + 'step' => $step, + 'text' => $text, + 'ts' => time(), + ], JSON_UNESCAPED_UNICODE)); + } + + /** + * Fehlerzustand: pct = -1 unterscheidet ihn eindeutig von „0 % erledigt“. + */ + public function fail(string $text): void + { + $this->set(-1, 'error', $text); + } + + /** + * @return array{pct: int, step: string, text: string, ts: int} + */ + public function get(): array + { + $data = json_decode((string) @file_get_contents($this->path()), true); + + if (! is_array($data) || ! isset($data['pct'], $data['step'])) { + return ['pct' => 0, 'step' => 'idle', 'text' => '', 'ts' => 0]; + } + + return [ + 'pct' => (int) $data['pct'], + 'step' => (string) $data['step'], + 'text' => (string) ($data['text'] ?? ''), + 'ts' => (int) ($data['ts'] ?? 0), + ]; + } + + public function isRunning(): bool + { + $progress = $this->get(); + + return ! in_array($progress['step'], ['idle', 'done', 'error'], true) + && time() - $progress['ts'] < self::STALE_AFTER_SECONDS; + } + + public function clear(): void + { + @unlink($this->path()); + } + + private function path(): string + { + return $this->file ?? storage_path('.update-progress'); + } +} diff --git a/app/Support/Update/Updater.php b/app/Support/Update/Updater.php new file mode 100644 index 00000000..10ecced8 --- /dev/null +++ b/app/Support/Update/Updater.php @@ -0,0 +1,139 @@ +channels->active(); + $zipFile = storage_path('app/update-'.bin2hex(random_bytes(4)).'.zip'); + $staging = storage_path('.update-staging'); + $targetSha = null; + $migrationCount = 0; + + try { + $this->progress->set(0, 'maintenance', 'Wartungsmodus wird aktiviert …'); + $this->maintenance->activate((int) config('updater.maintenance_max_seconds', 600)); + + $this->progress->set(5, 'version', 'Neueste Version wird ermittelt …'); + $client = $this->channels->client($channel); + $targetSha = (string) ($client->version()['sha'] ?? ''); + + if (! InstalledVersion::isSha($targetSha)) { + throw new RuntimeException('Der Update-Server hat keinen gültigen Versionsstand gemeldet.'); + } + + $this->progress->set(20, 'download', 'Neue Version wird heruntergeladen …'); + $headers = $client->downloadZip($targetSha, $zipFile); + $this->verifyZip($zipFile, $headers); + + $this->progress->set(50, 'extract', 'Archiv wird entpackt …'); + $this->extractor->extract($zipFile, $staging); + + $this->progress->set(65, 'apply', 'Dateien werden übernommen …'); + $result = (new StagingApplier(ProtectedPaths::fromConfig()))->apply($staging, $this->basePath ?? base_path()); + + $this->progress->set(80, 'migrate', 'Datenbank wird aktualisiert …'); + $migrationCount = $this->migrations->run(); + + $this->progress->set(90, 'cache', 'Zwischenspeicher werden geleert …'); + $this->clearCaches(); + + $this->version->save($targetSha); + @file_put_contents(storage_path('.migrations-fingerprint'), $this->migrations->fingerprint()); + + Audit::log('update.installed', [ + 'channel' => $channel, + 'sha' => $targetSha, + 'migrations' => $migrationCount, + 'files' => $result['copied'], + ], $userId); + + $this->progress->set(100, 'done', 'Aktualisierung abgeschlossen.'); + + return ['sha' => $targetSha, 'migrations' => $migrationCount, 'files' => $result['copied']]; + } catch (Throwable $e) { + $message = $e instanceof ServerError ? ServerMessages::for($e) : $e->getMessage(); + + $this->progress->fail($message); + Log::error('Update fehlgeschlagen: '.$e->getMessage(), ['exception' => $e]); + Audit::log('update.failed', [ + 'channel' => $channel, + 'sha' => $targetSha, + 'migrations' => $migrationCount, + 'error' => $message, + 'code' => $e instanceof ServerError ? $e->errorCode : null, + ], $userId); + + throw $e; + } finally { + $this->maintenance->deactivate(); + @unlink($zipFile); + Filesystem::deleteDirectory($staging); + } + } + + /** + * @param array{sha: string|null, sha256: string|null} $headers + */ + private function verifyZip(string $file, array $headers): void + { + $handle = @fopen($file, 'rb'); + $magic = $handle ? fread($handle, 2) : ''; + + if ($handle) { + fclose($handle); + } + + if ($magic !== 'PK') { + throw new RuntimeException('Die Antwort des Update-Servers ist kein ZIP-Archiv (vermutlich eine Fehlerseite). Die installierte Version bleibt unverändert.'); + } + + if ($headers['sha256'] && ! hash_equals(strtolower($headers['sha256']), hash_file('sha256', $file))) { + throw new RuntimeException('Das heruntergeladene Archiv ist beschädigt (Prüfsumme stimmt nicht). Bitte erneut versuchen.'); + } + } + + private function clearCaches(): void + { + foreach (['cache:clear', 'view:clear', 'config:clear', 'route:clear', 'event:clear'] as $command) { + try { + Artisan::call($command); + } catch (Throwable $e) { + Log::warning("{$command} fehlgeschlagen: ".$e->getMessage()); + } + } + + // Bytecode-Cache verwerfen – sonst läuft noch eine Weile der alte Code. + if (function_exists('opcache_reset')) { + @opcache_reset(); + } + } +} diff --git a/app/Support/Update/ZipExtractor.php b/app/Support/Update/ZipExtractor.php new file mode 100644 index 00000000..6b22294c --- /dev/null +++ b/app/Support/Update/ZipExtractor.php @@ -0,0 +1,146 @@ +/“). + * + * ZIP-Slip-Schutz in zwei Stufen: + * a) Eintragsnamen vorab ablehnen: absolute Pfade, Laufwerksbuchstaben, + * „..“-Segmente, Null-Bytes. + * b) Nach dem Schreiben den aufgelösten Pfad prüfen – liegt er wirklich im + * Staging? Sonst sofort wieder löschen. Fängt ab, was (a) übersieht. + */ +class ZipExtractor +{ + /** + * @return int Anzahl entpackter Dateien + */ + public function extract(string $zipFile, string $targetDir): int + { + $zip = new ZipArchive; + + if ($zip->open($zipFile) !== true) { + throw new RuntimeException('Das heruntergeladene Archiv kann nicht geöffnet werden.'); + } + + try { + $this->recreate($targetDir); + $root = realpath($targetDir); + $prefix = $this->commonPrefix($zip); + $count = 0; + + for ($i = 0; $i < $zip->numFiles; $i++) { + $name = (string) $zip->getNameIndex($i); + + if (! self::isSafeEntryName($name)) { + throw new RuntimeException("Unsicherer Pfad im Archiv abgelehnt: {$name}"); + } + + $relative = substr($name, strlen($prefix)); + + if ($relative === '' || $relative === false) { + continue; + } + + $destination = $root.DIRECTORY_SEPARATOR.$relative; + + if (str_ends_with($name, '/')) { + $this->makeDirectory($destination); + + continue; + } + + $this->makeDirectory(dirname($destination)); + $stream = $zip->getStream($name); + + if ($stream === false || @file_put_contents($destination, $stream) === false) { + throw new RuntimeException("Datei {$relative} kann nicht entpackt werden. Bitte Schreibrechte für storage/ prüfen."); + } + + fclose($stream); + + // Stufe b: aufgelösten Pfad prüfen (Symlinks, ungewöhnliche Kodierungen). + $resolved = realpath($destination); + + if ($resolved === false || ! str_starts_with($resolved, $root.DIRECTORY_SEPARATOR)) { + @unlink($destination); + + throw new RuntimeException("Datei außerhalb des Entpackverzeichnisses abgelehnt: {$name}"); + } + + $count++; + } + + return $count; + } finally { + $zip->close(); + } + } + + /** + * Stufe a: Eintragsnamen vor dem Schreiben prüfen. + */ + public static function isSafeEntryName(string $name): bool + { + if ($name === '' || str_contains($name, "\0")) { + return false; + } + + $normalized = str_replace('\\', '/', $name); + + if (str_starts_with($normalized, '/') || preg_match('#^[a-zA-Z]:#', $normalized)) { + return false; + } + + foreach (explode('/', $normalized) as $segment) { + if ($segment === '..') { + return false; + } + } + + return true; + } + + /** + * GitHub-Stil: genau EIN gemeinsamer Top-Level-Ordner, der entfernt wird. + */ + private function commonPrefix(ZipArchive $zip): string + { + $prefix = null; + + for ($i = 0; $i < $zip->numFiles; $i++) { + $name = str_replace('\\', '/', (string) $zip->getNameIndex($i)); + $first = explode('/', $name, 2)[0].'/'; + + if (! str_contains($name, '/')) { + return ''; + } + + if ($prefix === null) { + $prefix = $first; + } elseif ($prefix !== $first) { + return ''; + } + } + + return $prefix ?? ''; + } + + private function recreate(string $dir): void + { + Filesystem::deleteDirectory($dir); + $this->makeDirectory($dir); + } + + private function makeDirectory(string $dir): void + { + if (! is_dir($dir) && ! @mkdir($dir, 0775, true) && ! is_dir($dir)) { + throw new RuntimeException("Verzeichnis {$dir} kann nicht angelegt werden. Bitte Schreibrechte prüfen."); + } + } +} diff --git a/app/Version.php b/app/Version.php index 95cd8033..355c9695 100644 --- a/app/Version.php +++ b/app/Version.php @@ -9,5 +9,5 @@ namespace App; */ final class Version { - public const VERSION = '0.1.0'; + public const VERSION = '0.7.0'; } diff --git a/bootstrap/app.php b/bootstrap/app.php index 8a497e80..68a5f95d 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -1,6 +1,11 @@ withMiddleware(function (Middleware $middleware): void { - $middleware->web(append: [ + $middleware->web(prepend: [ + EnsureNotInMaintenance::class, + RedirectToInstaller::class, + ], append: [ + RunPendingMigrations::class, + ThemePreview::class, HandleInertiaRequests::class, + RunPseudoCron::class, ]); }) ->withExceptions(function (Exceptions $exceptions): void { diff --git a/bootstrap/providers.php b/bootstrap/providers.php index d23c829b..af6ae679 100644 --- a/bootstrap/providers.php +++ b/bootstrap/providers.php @@ -3,9 +3,11 @@ use App\Providers\AppServiceProvider; use App\Providers\Filament\AdminPanelProvider; use App\Providers\FortifyServiceProvider; +use App\Providers\PluginServiceProvider; return [ AppServiceProvider::class, + PluginServiceProvider::class, AdminPanelProvider::class, FortifyServiceProvider::class, ]; diff --git a/composer.json b/composer.json index 10f7600d..50fbfacf 100644 --- a/composer.json +++ b/composer.json @@ -13,6 +13,7 @@ "require": { "php": "^8.3", "filament/filament": "^5.8", + "firebase/php-jwt": "^7.2", "inertiajs/inertia-laravel": "^3.4", "intervention/image": "^4.3", "laravel/fortify": "^1.40", diff --git a/composer.lock b/composer.lock index 1c891710..92be4b0f 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "b65e3956292fd80e7d177bd79c895dd6", + "content-hash": "4bfe0ee6adb65f5ee711ad668bd71618", "packages": [ { "name": "anourvalar/eloquent-serialize", @@ -1635,6 +1635,80 @@ }, "time": "2026-09-20T18:53:34+00:00" }, + { + "name": "firebase/php-jwt", + "version": "v7.2.0", + "source": { + "type": "git", + "url": "https://github.com/googleapis/php-jwt.git", + "reference": "f502cdbf279cd7532060b041f7c22a05208c0b93" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/googleapis/php-jwt/zipball/f502cdbf279cd7532060b041f7c22a05208c0b93", + "reference": "f502cdbf279cd7532060b041f7c22a05208c0b93", + "shasum": "" + }, + "require": { + "php": "^8.0" + }, + "require-dev": { + "guzzlehttp/guzzle": "^7.4||^8.0", + "phpfastcache/phpfastcache": "^9.2", + "phpseclib/phpseclib": "~3.0", + "phpspec/prophecy-phpunit": "^2.2", + "phpunit/phpunit": "^9.5", + "psr/cache": "^2.0||^3.0", + "psr/http-client": "^1.0", + "psr/http-factory": "^1.0" + }, + "suggest": { + "ext-sodium": "Support EdDSA (Ed25519) signatures", + "paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present", + "phpseclib/phpseclib": "Support PS256 (RSASSA-PSS) signatures" + }, + "type": "library", + "extra": { + "component": { + "id": "jwt", + "path": "Jwt", + "entry": "README.md", + "target": "googleapis/php-jwt.git" + } + }, + "autoload": { + "psr-4": { + "Firebase\\JWT\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Neuman Vong", + "email": "neuman+pear@twilio.com", + "role": "Developer" + }, + { + "name": "Anant Narayanan", + "email": "anant@php.net", + "role": "Developer" + } + ], + "description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.", + "homepage": "https://github.com/googleapis/php-jwt", + "keywords": [ + "jwt", + "php" + ], + "support": { + "issues": "https://github.com/googleapis/php-jwt/issues", + "source": "https://github.com/googleapis/php-jwt/tree/v7.2.0" + }, + "time": "2026-09-21T19:29:58+00:00" + }, { "name": "fruitcake/php-cors", "version": "v1.4.0", diff --git a/config/inertia.php b/config/inertia.php index 0b4745b9..a5182d28 100644 --- a/config/inertia.php +++ b/config/inertia.php @@ -109,7 +109,8 @@ return [ 'testing' => [ - 'ensure_pages_exist' => true, + // Plugin-Seiten („news::Index“) liegen außerhalb von resources/js/pages. + 'ensure_pages_exist' => false, ], diff --git a/config/inhaus.php b/config/inhaus.php new file mode 100644 index 00000000..2660c051 --- /dev/null +++ b/config/inhaus.php @@ -0,0 +1,13 @@ + env('INHAUS_INSTALLED'), + + // Wie DISALLOW_FILE_MODS bei WordPress: verbietet das Hochladen und Löschen von + // Plugins über den Admin-Bereich (z. B. bei strengen IT-Richtlinien). + 'disallow_file_mods' => env('INHAUS_DISALLOW_FILE_MODS', false), + +]; diff --git a/config/updater.php b/config/updater.php new file mode 100644 index 00000000..3d9d5b9b --- /dev/null +++ b/config/updater.php @@ -0,0 +1,61 @@ + 'mitarbeiterportal', + + // Update-Kanäle: jeweils eigene Proxy-Basis-URL. Standard ist „stable“. + 'channels' => [ + 'stable' => [ + 'label' => 'Stabil', + 'url' => 'https://update.loheide.cloud/mitarbeiterportal', + ], + 'development' => [ + 'label' => 'Entwicklung', + 'url' => 'https://update.loheide.cloud/mitarbeiterportal-development', + ], + ], + + 'default_channel' => 'stable', + + 'api_url' => 'https://api.loheide.cloud/v1', + + 'changelog_url' => 'https://update.loheide.cloud/mitarbeiterportal/changelog', + + 'timeouts' => [ + 'json' => 20, + 'zip' => 180, + ], + + 'max_redirects' => 3, + + // Werden beim Übernehmen eines Updates NIE überschrieben. + // Verzeichnisse mit Schrägstrich am Ende, Dateien exakt. + // Abweichung von der Vorgabe: vendor/ ist bewusst NICHT geschützt (docs/PLAN.md, 5.2). + 'protected_paths' => [ + '.env', + '.git/', + 'storage/', + 'bootstrap/cache/', + 'node_modules/', + 'vendor-dev/', + 'composer.lock', + 'package-lock.json', + 'plugins/', + 'public/storage/', + 'public/uploads/', + 'public/hot', + 'config/local.php', + '.htaccess', + 'database/database.sqlite', + ], + + // Wartungsmodus läuft spätestens nach dieser Zeit von allein aus. + 'maintenance_max_seconds' => 600, + +]; diff --git a/database/factories/UserFactory.php b/database/factories/UserFactory.php index 448946a2..4948c0f3 100644 --- a/database/factories/UserFactory.php +++ b/database/factories/UserFactory.php @@ -2,6 +2,7 @@ namespace Database\Factories; +use App\Models\Role; use App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Facades\Hash; @@ -31,14 +32,21 @@ class UserFactory extends Factory 'department' => fake()->randomElement(['Verwaltung', 'Pflege', 'IT', 'Personal', 'Buchhaltung', 'Technik']), 'location' => fake()->city(), 'phone' => fake()->phoneNumber(), - 'is_admin' => false, 'is_active' => true, ]; } public function admin(): static { - return $this->state(fn () => ['is_admin' => true]); + return $this->afterCreating(fn (User $user) => $user->roles()->attach(Role::administration()->id, ['source' => 'manual', 'created_at' => now()])); + } + + /** + * @param list $roles + */ + public function withRoles(array $roles): static + { + return $this->afterCreating(fn (User $user) => $user->syncManualRoles(array_map(fn ($r) => $r instanceof Role ? $r->id : $r, $roles))); } public function inactive(): static diff --git a/database/migrations/2026_09_26_000003_create_audit_logs_table.php b/database/migrations/2026_09_26_000003_create_audit_logs_table.php new file mode 100644 index 00000000..6fbf80aa --- /dev/null +++ b/database/migrations/2026_09_26_000003_create_audit_logs_table.php @@ -0,0 +1,26 @@ +id(); + $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete(); + $table->string('action', 100); + $table->json('data')->nullable(); + $table->timestamp('created_at')->useCurrent(); + + $table->index(['action', 'created_at']); + }); + } + + public function down(): void + { + Schema::dropIfExists('audit_logs'); + } +}; diff --git a/database/migrations/2026_09_26_000004_create_vendor_feedback_table.php b/database/migrations/2026_09_26_000004_create_vendor_feedback_table.php new file mode 100644 index 00000000..4e0c16ba --- /dev/null +++ b/database/migrations/2026_09_26_000004_create_vendor_feedback_table.php @@ -0,0 +1,37 @@ +id(); + $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete(); + $table->string('type', 30); + $table->json('payload'); + $table->char('idempotency_key', 32)->unique(); + $table->string('status', 20)->default('pending'); + $table->unsignedTinyInteger('attempts')->default(0); + $table->timestamp('next_attempt_at')->nullable(); + $table->string('reference', 50)->nullable(); + $table->string('last_error', 500)->nullable(); + $table->timestamps(); + + $table->index(['status', 'next_attempt_at']); + }); + } + + public function down(): void + { + Schema::dropIfExists('vendor_feedback'); + } +}; diff --git a/database/migrations/2026_09_26_000005_create_permission_tables.php b/database/migrations/2026_09_26_000005_create_permission_tables.php new file mode 100644 index 00000000..60cf11ce --- /dev/null +++ b/database/migrations/2026_09_26_000005_create_permission_tables.php @@ -0,0 +1,101 @@ +id(); + $table->string('name', 100); + $table->string('slug', 100)->unique(); + $table->string('description', 500)->nullable(); + $table->boolean('is_system')->default(false); + $table->timestamps(); + }); + + Schema::create('role_user', function (Blueprint $table) { + $table->id(); + $table->foreignId('role_id')->constrained()->cascadeOnDelete(); + $table->foreignId('user_id')->constrained()->cascadeOnDelete(); + $table->string('source', 20)->default('manual'); + $table->string('source_ref', 191)->nullable(); + $table->timestamp('created_at')->nullable(); + + $table->unique(['role_id', 'user_id', 'source', 'source_ref']); + $table->index(['user_id', 'role_id']); + }); + + Schema::create('grants', function (Blueprint $table) { + $table->id(); + $table->foreignId('role_id')->constrained()->cascadeOnDelete(); + $table->string('ability', 100); + $table->string('resource_type', 50)->nullable(); + $table->unsignedBigInteger('resource_id')->nullable(); + $table->boolean('include_children')->default(false); + $table->timestamps(); + + $table->index(['resource_type', 'resource_id']); + $table->index(['role_id', 'ability']); + }); + + Schema::create('audiences', function (Blueprint $table) { + $table->id(); + $table->string('resource_type', 50); + $table->unsignedBigInteger('resource_id'); + $table->string('rule_type', 20); + $table->string('rule_value', 191); + + $table->index(['resource_type', 'resource_id']); + $table->index(['rule_type', 'rule_value']); + }); + + $now = now(); + $adminRole = DB::table('roles')->insertGetId([ + 'name' => 'Administration', + 'slug' => 'administration', + 'description' => 'Voller Zugriff auf alle Bereiche und Einstellungen.', + 'is_system' => true, + 'created_at' => $now, + 'updated_at' => $now, + ]); + + DB::table('grants')->insert(['role_id' => $adminRole, 'ability' => '*', 'created_at' => $now, 'updated_at' => $now]); + + DB::table('users')->where('is_admin', true)->pluck('id')->each(fn (int $userId) => DB::table('role_user')->insert([ + 'role_id' => $adminRole, 'user_id' => $userId, 'source' => 'manual', 'created_at' => $now, + ])); + + Schema::table('users', fn (Blueprint $table) => $table->dropColumn('is_admin')); + } + + public function down(): void + { + Schema::table('users', fn (Blueprint $table) => $table->boolean('is_admin')->default(false)); + + $adminRole = DB::table('roles')->where('slug', 'administration')->value('id'); + + if ($adminRole) { + DB::table('users')->whereIn('id', DB::table('role_user')->where('role_id', $adminRole)->pluck('user_id'))->update(['is_admin' => true]); + } + + Schema::dropIfExists('audiences'); + Schema::dropIfExists('grants'); + Schema::dropIfExists('role_user'); + Schema::dropIfExists('roles'); + } +}; diff --git a/database/migrations/2026_09_26_000006_create_identity_tables.php b/database/migrations/2026_09_26_000006_create_identity_tables.php new file mode 100644 index 00000000..77978850 --- /dev/null +++ b/database/migrations/2026_09_26_000006_create_identity_tables.php @@ -0,0 +1,69 @@ +id(); + $table->string('type', 20); + $table->string('name', 100); + $table->string('slug', 100)->unique(); + $table->boolean('enabled')->default(false); + // Zugangsdaten und Einstellungen – verschlüsselt mit dem Anwendungsschlüssel. + $table->text('config'); + $table->timestamps(); + }); + + Schema::create('user_identities', function (Blueprint $table) { + $table->id(); + $table->foreignId('user_id')->constrained()->cascadeOnDelete(); + $table->foreignId('identity_provider_id')->constrained()->cascadeOnDelete(); + // Unveränderliche Objekt-ID beim Anbieter (Entra: oid) + $table->string('subject', 191); + $table->string('email')->nullable(); + $table->string('photo_hash', 64)->nullable(); + $table->timestamp('last_login_at')->nullable(); + $table->timestamp('synced_at')->nullable(); + $table->timestamps(); + + $table->unique(['identity_provider_id', 'subject']); + $table->index('user_id'); + }); + + Schema::create('idp_group_mappings', function (Blueprint $table) { + $table->id(); + $table->foreignId('identity_provider_id')->constrained()->cascadeOnDelete(); + // group = Sicherheitsgruppe (Objekt-ID), app_role = App-Rolle (Wert) + $table->string('kind', 20)->default('group'); + $table->string('external_id', 191); + $table->string('external_name')->nullable(); + $table->foreignId('role_id')->constrained()->cascadeOnDelete(); + $table->timestamps(); + + $table->unique(['identity_provider_id', 'kind', 'external_id', 'role_id'], 'idp_group_mappings_unique'); + }); + + Schema::table('users', function (Blueprint $table) { + $table->foreignId('manager_id')->nullable()->after('mobile')->constrained('users')->nullOnDelete(); + }); + } + + public function down(): void + { + Schema::table('users', function (Blueprint $table) { + $table->dropConstrainedForeignId('manager_id'); + }); + + Schema::dropIfExists('idp_group_mappings'); + Schema::dropIfExists('user_identities'); + Schema::dropIfExists('identity_providers'); + } +}; diff --git a/database/migrations/2026_09_26_000007_create_profile_fields.php b/database/migrations/2026_09_26_000007_create_profile_fields.php new file mode 100644 index 00000000..f20f0743 --- /dev/null +++ b/database/migrations/2026_09_26_000007_create_profile_fields.php @@ -0,0 +1,38 @@ +id(); + $table->string('key', 60)->unique(); + $table->string('label', 100); + $table->string('type', 20)->default('text'); + // public = für alle sichtbar, restricted = nur die Person selbst und die Personalverwaltung + $table->string('visibility', 20)->default('public'); + $table->boolean('editable')->default(true); + $table->string('help', 255)->nullable(); + $table->unsignedInteger('sort')->default(0); + $table->timestamps(); + }); + + Schema::table('users', function (Blueprint $table) { + $table->json('custom_fields')->nullable()->after('about'); + }); + } + + public function down(): void + { + Schema::table('users', fn (Blueprint $table) => $table->dropColumn('custom_fields')); + Schema::dropIfExists('profile_fields'); + } +}; diff --git a/database/migrations/2026_09_26_060321_create_notifications_table.php b/database/migrations/2026_09_26_060321_create_notifications_table.php new file mode 100644 index 00000000..d7380322 --- /dev/null +++ b/database/migrations/2026_09_26_060321_create_notifications_table.php @@ -0,0 +1,31 @@ +uuid('id')->primary(); + $table->string('type'); + $table->morphs('notifiable'); + $table->text('data'); + $table->timestamp('read_at')->nullable(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('notifications'); + } +}; diff --git a/database/migrations/2026_09_28_000005_create_dashboard_tiles_table.php b/database/migrations/2026_09_28_000005_create_dashboard_tiles_table.php new file mode 100644 index 00000000..89d673e6 --- /dev/null +++ b/database/migrations/2026_09_28_000005_create_dashboard_tiles_table.php @@ -0,0 +1,38 @@ +id(); + $table->string('name'); + $table->string('type', 20); + $table->string('area', 20)->default('aside'); + $table->string('title')->nullable(); + $table->string('image_path')->nullable(); + $table->string('url', 2000)->nullable(); + $table->boolean('new_tab')->default(false); + $table->string('alt')->nullable(); + $table->longText('body')->nullable(); + $table->longText('body_html')->nullable(); + $table->string('variant', 20)->nullable(); + $table->boolean('is_active')->default(true); + $table->timestamp('starts_at')->nullable(); + $table->timestamp('ends_at')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('dashboard_tiles'); + } +}; diff --git a/database/seeders/DemoContentSeeder.php b/database/seeders/DemoContentSeeder.php index c3722104..28ff817a 100644 --- a/database/seeders/DemoContentSeeder.php +++ b/database/seeders/DemoContentSeeder.php @@ -2,15 +2,16 @@ namespace Database\Seeders; -use App\Models\Event; -use App\Models\NewsCategory; -use App\Models\NewsPost; +use App\Models\Role; use App\Models\User; use App\Support\Branding; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; +use Inhaus\Plugins\Events\Models\Event; +use Inhaus\Plugins\News\Models\NewsCategory; +use Inhaus\Plugins\News\Models\NewsPost; use Throwable; /** @@ -24,7 +25,7 @@ class DemoContentSeeder extends Seeder $authors = User::query()->inRandomOrder()->limit(5)->get(); $categories = collect([ - 'Unternehmen', 'Arbeit & Bildung', 'Menschen', 'Nachhaltigkeit', 'Freizeit & Kultur', 'Verwaltung', + 'Unternehmen', 'Arbeit & Bildung', 'Menschen', 'Nachhaltigkeit', 'Freizeit & Kultur', 'Verwaltung', 'MAV-Info', ])->mapWithKeys(fn (string $name, int $i) => [$name => NewsCategory::query()->create([ 'name' => $name, 'slug' => Str::slug($name, language: 'de'), @@ -59,6 +60,24 @@ class DemoContentSeeder extends Seeder ]); } + // Beispiel für das Rechtesystem: Die MAV schreibt nur in „MAV-Info“. + $mav = Role::query()->create(['name' => 'MAV', 'description' => 'Mitarbeitervertretung – schreibt in „MAV-Info“.']); + $mav->grants()->create(['ability' => 'news.post.create', 'resource_type' => 'news_category', 'resource_id' => $categories['MAV-Info']->id]); + $mav->grants()->create(['ability' => 'news.post.publish', 'resource_type' => 'news_category', 'resource_id' => $categories['MAV-Info']->id]); + $mavMember = User::factory()->withRoles([$mav])->create([ + 'first_name' => 'Grete', 'last_name' => 'Hoffmann', 'email' => 'mav@example.com', + 'job_title' => 'Vorsitzende der MAV', 'department' => 'Mitarbeitervertretung', + ]); + + NewsPost::query()->create([ + 'category_id' => $categories['MAV-Info']->id, + 'author_id' => $mavMember->id, + 'title' => 'MAV-Sprechstunde ab sofort jeden Dienstag', + 'teaser' => 'Wir sind für Ihre Fragen da – persönlich oder per Videoanruf.', + 'body' => $this->body('Wir sind für Ihre Fragen da – persönlich oder per Videoanruf.'), + 'published_at' => now()->subHours(30), + ]); + NewsPost::query()->create([ 'category_id' => $categories['Unternehmen']->id, 'title' => 'Entwurf: Ausblick auf das zweite Halbjahr', diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md new file mode 100644 index 00000000..cfecf48b --- /dev/null +++ b/docs/INSTALLATION.md @@ -0,0 +1,149 @@ +# Installation und Betrieb + +Diese Anleitung richtet sich an die IT bzw. an die Person, die das Portal beim +Hoster einrichtet. Shell-Zugang wird nicht benötigt. + +## Voraussetzungen + +- PHP **8.3** oder neuer mit den Erweiterungen `pdo_mysql`, `mbstring`, + `openssl`, `intl`, `gd`, `zip`, `fileinfo`, `tokenizer`, `ctype`, `xml`, `dom` +- **MySQL ab 8.0** oder **MariaDB ab 10.6** – eine leere Datenbank samt Benutzer +- Apache mit `mod_rewrite` (Einstellungen per `.htaccess` müssen erlaubt sein) +- Empfohlen: OPcache, `memory_limit` ≥ 128M, `upload_max_filesize` ≥ 8M, HTTPS +- Ausgehende HTTPS-Verbindungen zu `update.loheide.cloud` und + `api.loheide.cloud` (für Aktualisierungen und Rückmeldungen) + +## Einrichtung + +1. Das Installationsarchiv entpacken und **alle** Dateien per FTP/SFTP oder + Dateimanager in das gewünschte Verzeichnis hochladen. +2. Webroot festlegen: + - **Empfohlen:** Die Domain zeigt auf das Unterverzeichnis `public/`. + - Lässt der Hoster das nicht zu, zeigt die Domain auf das + Installationsverzeichnis – die mitgelieferte `.htaccess` leitet dann alle + Anfragen nach `public/` weiter. +3. Schreibrechte für den Webserver: `storage/`, `bootstrap/cache/`, + `public/uploads/` und – damit Aktualisierungen per Klick funktionieren – für + das gesamte Installationsverzeichnis. +4. Die Adresse des Portals im Browser aufrufen. Der Einrichtungsassistent führt + durch **Systemprüfung → Datenbank → Administrator**. Lizenz-E-Mail und + Lizenzschlüssel können dabei oder später eingetragen werden. +5. Mit dem Administratorkonto anmelden und unter **Administration → + Systemzustand** die Hinweise durchgehen. + +> Solange die Einrichtung nicht abgeschlossen ist, kann jede Person, die die +> Adresse kennt, den Assistenten ausfüllen. Die Einrichtung daher direkt nach +> dem Hochladen abschließen. + +## Anmeldung mit Microsoft Entra ID + +1. Im [Microsoft Entra Admin Center](https://entra.microsoft.com) unter + **App-Registrierungen → Neue Registrierung** eine App anlegen + („Nur Konten in diesem Organisationsverzeichnis“). +2. **Umleitungs-URI** (Plattform „Web“): die Adresse, die im Portal unter + **Administration → Anmeldung** angezeigt wird (`https://portal.firma.de/auth/entra/callback`). +3. **Zertifikate & Geheimnisse → Neuer geheimer Clientschlüssel** und den *Wert* notieren. +4. **API-Berechtigungen → Microsoft Graph:** + - delegiert: `User.Read`, `GroupMember.Read.All` + - für den Hintergrund-Abgleich zusätzlich als Anwendung: `User.Read.All`, + `GroupMember.Read.All`, `Application.Read.All` (nur für App-Rollen) + - danach **Administratorzustimmung erteilen**. +5. Im Portal unter **Administration → Anmeldung** Verzeichnis-ID, + Anwendungs-ID und Geheimnis eintragen, Gruppen den Rollen zuordnen und die + Anmeldung aktivieren. Mit **Mapping testen** lässt sich vorab prüfen, + welche Rollen eine Person erhalten wird. + +### Entra-Attribute ins Profil übernehmen + +Unter **Anmeldung → Profil** wird jedem Profilfeld ein Microsoft-Graph-Attribut +zugeordnet. Das geht nicht nur für die festen Felder (Name, Funktion, Abteilung, +Telefon …), sondern auch für eigene Felder, die unter **Benutzer & Rechte → +Profilfelder** angelegt werden – etwa Personalnummer, Kostenstelle oder +Eintrittsdatum. Übernommene Felder sind im Portal schreibgeschützt. + +| Beispiel | Graph-Attribut | +| -------------------------------- | ---------------------------------------------------- | +| Personalnummer | `employeeId` | +| Kostenstelle | `employeeOrgData.costCenter` | +| Firma, Ort | `companyName`, `city` | +| lokales AD-Erweiterungsattribut | `onPremisesExtensionAttributes.extensionAttribute1` | +| eigene Verzeichniserweiterung | `extension__` | + +Pfade mit Punkt lesen verschachtelte Werte, Listen werden mit Komma verbunden. +**Erweiterungsattribute laden** holt alle im Mandanten registrierten +Verzeichniserweiterungen (z. B. per Entra Connect synchronisierte AD-Attribute) +in die Auswahl; dafür braucht die App zusätzlich die Anwendungsberechtigung +`Directory.Read.All`. Einzelne Attribute verlangen eigene Berechtigungen – etwa +`employeeHireDate` die Berechtigung `User-LifeCycleInfo.Read.All`. Fehlt eine, +meldet sich die Person trotzdem an; übernommen werden dann nur die Grunddaten. + +Die Anmeldung mit Passwort bleibt für Notfälle erhalten (z. B. wenn Entra ID +nicht erreichbar ist). Den geheimen Clientschlüssel vor Ablauf erneuern – er +ist bei Microsoft befristet. + +## Erscheinungsbild + +Unter **Administration → Portal → Erscheinungsbild** lassen sich Name, Logos, +Farben, Schriften, Anmeldeseite, Fußzeile und E-Mails anpassen. Änderungen +werden zuerst als **Entwurf** gespeichert und sind nur in der Vorschau +sichtbar; für alle gelten sie erst nach **Veröffentlichen**. Über „Mehr“ lässt +sich das Erscheinungsbild als Datei exportieren und auf einem anderen System +(z. B. vom Test- auf das Produktivsystem) importieren. + +Schriften werden immer vom eigenen Server ausgeliefert. Eine eigene Schrift +(WOFF2) darf nur hochgeladen werden, wenn ihre Lizenz die Nutzung im Web erlaubt. + +## E-Mail-Versand + +Unter **Administration → E-Mail-Versand** den SMTP-Zugang eintragen (vom +Hoster oder der IT, z. B. Microsoft 365: `smtp.office365.com`, Port 587, +STARTTLS) und mit **Test-Mail senden** prüfen. Das Passwort wird verschlüsselt +gespeichert. Gebraucht wird der Versand für „Passwort vergessen“ und +Formular-Benachrichtigungen. Mails werden über die Hintergrundaufgaben +verschickt – ohne Cron oder Web-Cron also mit etwas Verzögerung. + +## Umstieg von WordPress + +1. In WordPress unter **Werkzeuge → Daten exportieren** „Alle Inhalte“ wählen + und die XML-Datei herunterladen. +2. Im Portal unter **Administration → Inhalte → WordPress-Import** hochladen + und **Datei prüfen**. +3. Kategorien zuordnen (neu anlegen, vorhandene nutzen oder weglassen), + Autorinnen und Autoren prüfen (Zuordnung über die E-Mail-Adresse) und + entscheiden, ob Entwürfe und WordPress-Seiten mitkommen. +4. **Import starten** – die Seite geöffnet lassen, der Import läuft in Portionen. + +Bilder werden von der alten Website geladen, sie muss dafür noch erreichbar +sein. Ein erneuter Import legt nichts doppelt an; auf Wunsch aktualisiert er +bereits übernommene Einträge. Kommentare, Schlagwörter und Inhalte anderer +WordPress-Plugins werden nicht übernommen. Nach dem Umstieg kann das Plugin +„WordPress-Import“ deaktiviert werden. + +## Hintergrundaufgaben + +Rückmeldungen, geplante Inhalte und Aufräumarbeiten laufen im Hintergrund. Die +genauen Angaben zeigt **Systemzustand** an. + +- **Am besten:** Cronjob beim Hoster, jede Minute: + `cd /pfad/zum/portal && php artisan schedule:run` +- **Ohne Cron-Zugang:** die unter Systemzustand angezeigte geheime + Web-Cron-Adresse jede Minute von einem externen Cron-Dienst aufrufen lassen. +- **Ohne beides** laufen die Aufgaben beim Aufruf von Seiten mit – das + funktioniert, ist aber weniger zuverlässig. + +## Aktualisierungen + +Unter **Administration → Aktualisierung**: „Nach Updates suchen“ und „Jetzt +aktualisieren“. Das Portal zeigt währenddessen eine Wartungsseite, übernimmt +die neue Fassung, bringt die Datenbank auf den neuen Stand und ist nach +wenigen Minuten wieder erreichbar. `.env`, `storage/`, hochgeladene Dateien +und Plugins werden dabei nie verändert. + +Voraussetzung ist eine gültige Lizenz. Ein Lizenzproblem schränkt die Nutzung +des Portals nicht ein – es verhindert nur den Bezug neuer Fassungen. + +## Umzug auf einen anderen Server + +Alle Dateien (inklusive `.env` und `storage/`) und die Datenbank übertragen. +Anschließend unter **Aktualisierung** die alte Installation abmelden bzw. die +Lizenz neu prüfen – jede Installation belegt einen Geräteplatz der Lizenz. diff --git a/docs/PLAN.md b/docs/PLAN.md index fd12fac8..e814dcb0 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -131,6 +131,7 @@ plugins/mav-kalender/ Einstellungsseiten, Admin-Ressourcen, Routen, Suche, Benachrichtigungen, geplante Jobs. - Stabile, versionierte Plugin-API (SemVer); Deprecations mit Vorlauf. +- Entwickleranleitung: [`docs/PLUGINS.md`](PLUGINS.md). ### 4.4 Frontend von Plugins @@ -321,7 +322,9 @@ audiences resource_type, resource_id, rule (Rolle / Abteilung / Standort / - Sicherheitsgruppen (`groups`) und App-Rollen (`roles`) mappbar, über **Objekt-ID**; Gruppensuche per Graph. - Group-Overage → Graph `/me/transitiveMemberOf` (inkl. verschachtelter Gruppen). -- Profil-Sync inkl. **Profilfoto** → Avatar im Header. +- Profil-Sync inkl. **Profilfoto** → Avatar im Header; jedes Graph-Attribut (auch + `employeeOrgData.*`, `onPremisesExtensionAttributes.*`, `extension_…`) frei + einem Kern- oder eigenen Profilfeld zuordenbar. - Hintergrund-Sync mit **Delta-Abfragen**, Offboarding deaktivierter Konten. - JIT-Provisioning, „Mapping testen“. @@ -449,8 +452,8 @@ Entwickler, ohne Build, direkt im Admin unter „Erscheinungsbild“. ## 13. Mitgelieferte Plugins -**Start:** Dashboard, News/Feed mit Kategorien, CMS-Seiten, Verzeichnis & -Organigramm, Dokumente, App-Launcher. +**Start:** Dashboard, News/Feed mit Kategorien, CMS-Seiten, Formulare, +WordPress-Import, Verzeichnis & Organigramm, Dokumente, App-Launcher. **Später:** Events, Umfragen, Geburtstage/Jubiläen, Onboarding, Raumbuchung, Kantinenplan, Ideenbox, Urlaubsanträge. @@ -473,13 +476,14 @@ Kantinenplan, Ideenbox, Urlaubsanträge. | Phase | Inhalt | |---|---| -| **0 – Fundament** | Laravel-Skeleton, Docker-Dev, CI-Matrix, `VERSION` + `CHANGELOG.md` + Build-Workflow (Assets/`vendor` mitversioniert), lokaler Login, User & Profil, Header mit Avatar, Design-System (Tailwind/shadcn-vue) mit Design-Tokens, **Basis-Branding (Portalname, Logo, Markenfarbe)**, Personenverzeichnis, Schnellzugriffe, Filament-Grundgerüst | -| **0b – News & Termine (vorgezogen)** | Neuigkeiten mit Kategorien, Titelbild, Planung, Hervorhebung (Slider); Termine mit .ics-Export; Startseite nach Intranet-Vorbild. Redaktion vorerst nur im Admin-Backend – Rechte pro Kategorie, Redaktion im Portal und Umzug in Plugins folgen mit Phase 2 | -| **1 – Betrieb & Lizenz** | **Self-Updater** (inkl. Wartungsmodus, Auto-Migration, Kanäle), **Lizenz-Speicher & -Client** (rotierendes Token), Seite „Aktualisierung“, **Rückmeldungen**, Web-Installer, Site Health, Cron-Varianten | -| **2 – Plugin-System & Rechte** | Plugin-Loader, Hooks/Filter, Registries, Recovery-Modus, Import-Map-Frontend; Rollen, Grants, Zielgruppen, Rechte-Cache, Rechte-Prüfer | -| **3 – Entra ID** | OIDC-Login, JIT, Gruppen-/App-Rollen-Mapping (additiv), Graph-Profil- & Foto-Sync, Delta-Sync | -| **4 – CMS** | Seitenbaum, Pagebuilder, Versionen; News-Freigabe-Workflow und Redaktion im Portal | -| **5 – Branding & Theming** | Vollständige Seite „Erscheinungsbild“: Logo-Varianten, Farben inkl. Farbtreue & Kontrastprüfung, Schriften, Form, Login-Seite, E-Mails, Live-Vorschau, Entwurf/Veröffentlichen, Export/Import | +| **0 – Fundament** ✅ | Laravel-Skeleton, Docker-Dev, CI-Matrix, `VERSION` + `CHANGELOG.md` + Build-Workflow (Assets/`vendor` mitversioniert), lokaler Login, User & Profil, Header mit Avatar, Design-System (Tailwind/shadcn-vue) mit Design-Tokens, **Basis-Branding (Portalname, Logo, Markenfarbe)**, Personenverzeichnis, Schnellzugriffe, Filament-Grundgerüst | +| **0b – News & Termine (vorgezogen)** ✅ | Neuigkeiten mit Kategorien, Titelbild, Planung, Hervorhebung (Slider); Termine mit .ics-Export; Startseite nach Intranet-Vorbild. Redaktion vorerst nur im Admin-Backend – Rechte pro Kategorie, Redaktion im Portal und Umzug in Plugins folgen mit Phase 2 | +| **1 – Betrieb & Lizenz** ✅ | **Self-Updater** (inkl. Wartungsmodus, Auto-Migration, Kanäle), **Lizenz-Speicher & -Client** (rotierendes Token), Seite „Aktualisierung“, **Rückmeldungen**, Web-Installer, Site Health, Cron-Varianten | +| **2 – Plugin-System & Rechte** ✅ | Plugin-Loader, Hooks/Filter, Registries, Recovery-Modus, Import-Map-Frontend; Rollen, Grants, Zielgruppen, Rechte-Cache, Rechte-Prüfer | +| **3 – Entra ID** ✅ | OIDC-Login, JIT, Gruppen-/App-Rollen-Mapping (additiv), Graph-Profil- & Foto-Sync mit frei zuordenbaren Attributen (inkl. Erweiterungsattributen) und eigenen Profilfeldern, Delta-Sync | +| **4 – CMS** ✅ | Seitenbaum, Pagebuilder (Layout-, Inhalts-, Medien- und dynamische Blöcke, Sichtbarkeit je Block), Entwürfe, Versionen, Zeitsteuerung, Bearbeitungssperre, Freigaben; News-Freigabe-Workflow und Redaktion im Portal; Benachrichtigungen. Offen: Vorlagen und wiederverwendbare Blöcke | +| **4b – Formulare & Umstieg** ✅ | Formular-Plugin (visueller Baukasten im Portal, Bedingungen, Uploads, anonyme Formulare, Mail + Backend, Ergebnis-Rechte je Formular und Rolle, CSV, Löschfristen; eingebunden per Pagebuilder-Block und unter Beiträgen, kein eigener Menüpunkt); WordPress-Import (Beiträge, Kategorien, Bilder, Seiten); E-Mail-Versand im Admin; anpassbare Startseite mit eigenen Kacheln; Geburtstage (optionales Plugin) | +| **5 – Branding & Theming** ✅ | Vollständige Seite „Erscheinungsbild“: Logo-Varianten, Farben inkl. Farbtreue & Kontrastprüfung, Schriften, Form, Login-Seite, E-Mails, Live-Vorschau, Entwurf/Veröffentlichen, Export/Import | | **6 – Weitere Plugins & IdPs** | Verzeichnis/Organigramm, Dokumente, Events …; OIDC generisch, LDAP, SAML; Lasttests 5.000 User | | **7 – Plugin-SDK öffentlich** | Doku, Generator, Beispiel-Plugins (kein Plugin-Verzeichnis) | | **8 – Mobil** | REST-API (Sanctum), Web-Push, native App | diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md new file mode 100644 index 00000000..05ce6368 --- /dev/null +++ b/docs/PLUGINS.md @@ -0,0 +1,149 @@ +# Plugins entwickeln + +Inhaus lässt sich wie WordPress über Plugins erweitern. Auch die mitgelieferten +Funktionen „Neuigkeiten“ und „Termine“ sind Plugins (`plugins-core/news`, +`plugins-core/events`) – sie sind die beste Vorlage. + +## Aufbau + +``` +mein-plugin/ + plugin.json Manifest (Pflicht) + src/Plugin.php Einstiegsklasse, erbt von App\Plugins\Plugin + src/… weiterer PHP-Code (PSR-4 unter „namespace“) + src/Filament/Resources/ Admin-Seiten (werden automatisch gefunden) + src/Filament/Pages/ + database/migrations/ laufen bei Aktivierung und nach Updates + routes/web.php Routen (Middleware „web“ ist gesetzt) + resources/views/ Blade-Views, Namespace = Kürzel: view('mein-plugin::seite') + vendor/ eigene Abhängigkeiten – bitte gescoped (Strauss/PHP-Scoper) +``` + +### plugin.json + +```json +{ + "slug": "mein-plugin", + "name": "Mein Plugin", + "version": "1.0.0", + "description": "Wofür das Plugin da ist.", + "author": "Firma GmbH", + "namespace": "Firma\\MeinPlugin\\", + "class": "Firma\\MeinPlugin\\Plugin", + "requires": { "core": ">=0.3.0", "php": ">=8.3", "plugins": ["news"] } +} +``` + +- `slug`: Kleinbuchstaben, Ziffern, Bindestriche; eindeutig. Kürzel mitgelieferter + Plugins sind vergeben. +- `namespace`: darf nicht mit `App\` beginnen. +- `requires.core` / `requires.php`: Versionsbedingungen (`>=`, `<`, `^`, `~`, exakt). +- `requires.plugins`: Plugins, die aktiv sein müssen. + +### Einstiegsklasse + +```php +namespace Firma\MeinPlugin; + +use App\Dashboard\Widgets; +use App\Plugins\Hooks; +use App\Plugins\Plugin as BasePlugin; +use App\Support\Abilities; +use App\Support\Navigation; + +class Plugin extends BasePlugin +{ + public function register(): void + { + // Menüpunkt im Portal + $this->app->make(Navigation::class)->add('mein-plugin', 'Mein Bereich', '/mein-bereich', active: 'mein-plugin.*', sort: 40); + + // Rechte, die im Rollen-Formular erscheinen + $this->app->make(Abilities::class)->define('mein-plugin.manage', 'Mein Bereich verwalten', 'Mein Plugin'); + } + + public function boot(): void + { + Hooks::on('news.post.published', fn ($post) => /* … */ null); + Hooks::filter('navigation.items', fn (array $items) => $items); + } + + public function activate(): void {} // nach „Aktivieren“ (Migrationen sind schon gelaufen) + public function deactivate(): void {} // vor „Deaktivieren“ + public function uninstall(): void {} // bei „Mit Daten löschen“ (Tabellen entfernt der Kern) +} +``` + +## Rechte und Sichtbarkeit + +- Globale Rechte: `$abilities->define('schluessel', 'Bezeichnung', 'Gruppe')`, + prüfen mit `$user->can('schluessel')`. +- Objekt-Rechte: `define(..., resource: 'mein_typ')` plus + `$abilities->resourceType('mein_typ', 'Bezeichnung', fn () => [id => 'Name'])`; + prüfen mit `$user->can('schluessel', ['mein_typ', $id])` oder einem Modell mit + `permissionResource()`. +- Zielgruppen: `App\Support\Permissions\Audiences::constrain($query, 'mein_typ', 'tabelle.id', $user)` + und im Admin-Formular `App\Filament\Components\AudienceSection::make('mein_typ')`. +- Hierarchische Objekttypen (z. B. Seiten): `resourceType(..., descendants: fn (array $ids) => [...])`. + Rechte mit „inkl. Unterobjekten“ gelten dann auch für alle Nachfahren; ändert sich + der Baum, `App\Support\Permissions\Permissions::flush()` aufrufen. +- Admin-Seiten: Policies registrieren (`Gate::policy(Model::class, Policy::class)`) + bzw. `canAccess()` an Filament-Seiten. + +## Pagebuilder-Blöcke + +Eigene Blöcke erscheinen im Pagebuilder mit Formular und Absicherung – aus der +Feldbeschreibung erzeugt: + +```php +use App\Pagebuilder\{Blocks, BlockType, Field}; + +$this->app->make(Blocks::class)->add(BlockType::make('mein-plugin.liste', 'Meine Liste', 'list-checks', 'dynamic', 'mein-plugin::Liste') + ->fields([ + Field::text('title', 'Überschrift', 150), + Field::number('count', 'Anzahl', 1, 20, 5), + Field::select('layout', 'Darstellung', ['list' => 'Liste', 'cards' => 'Kacheln'], 'list'), + ]) + ->resolveUsing(fn (array $data, ?User $user, array $context) => ['items' => /* für $user sichtbare Einträge */ []])); +``` + +- Feldtypen: `text`, `textarea`, `html`, `select`, `toggle`, `number`, `url`, + `image`, `people`, `table`, `icon`, `repeater`, `ids`. Unbekannte Felder und + Blöcke verwirft der Kern beim Speichern; HTML und Adressen werden bereinigt. +- `resolveUsing` liefert die Daten zur Anzeige (bei jedem Aufruf, je Person). + `null` blendet den Block aus; Fehler blenden nur diesen Block aus. +- Container-Blöcke: `->container(min, max, titled: true, label: 'Tab')`. +- Die Vue-Komponente erhält `block` (`data`, `items`, `props`) – Kinder werden mit + `inject('pagebuilder:list')` gerendert. `inject('pagebuilder:editing')` ist im Editor wahr. + +## Startseite und Profil + +- Kacheln: `app(App\Dashboard\Widgets::class)->add($key, 'mein-plugin::Kachel', 'aside', sort: 20, props: fn (User $user) => [...], label: 'Name im Admin')`. + Bereiche: `top`, `hero`, `feed`, `main`, `aside`. Admins sortieren und blenden Kacheln unter „Startseite“ aus. +- Abschnitt in „Profil bearbeiten“: `app(App\Profile\ProfileSections::class)->add($key, 'mein-plugin::Abschnitt', $sort, fn (User $user) => [...])` + (Komponente unter `resources/js/profile/`, speichert über eigene Routen). +- Optionale mitgelieferte Plugins: `"enabled_by_default": false` in `plugin.json`. + +## Redaktion, Navigation und Benachrichtigungen + +- Arbeitslisten im Bereich „Redaktion“: `app(App\Editorial\Editorial::class)->add($key, $label, 'mein-plugin::Liste', $sort, $sichtbar, $props)`. +- Dynamische Menüpunkte: `app(Navigation::class)->provider('mein-plugin', fn (Request $request, ?User $user) => [...])`; + feste Menüpunkte können mit `visible: fn (User $user) => …` je Person ausgeblendet werden. +- Benachrichtigungen (Glocke im Portal): `$user->notify(new App\Notifications\PortalNotification($titel, $text, $url))`. + +## Installation und Betrieb + +- Als ZIP unter **Administration → Plugins** hochladen (ein gemeinsamer + Ordner im Archiv ist erlaubt), dann aktivieren. +- Kunden-Plugins liegen in `plugins/` und werden von Aktualisierungen nie verändert. +- Wirft ein Plugin beim Laden einen Fehler – oder bringt es den PHP-Prozess zum + Absturz –, wird es automatisch deaktiviert; der Grund steht auf der Plugins-Seite. +- `INHAUS_DISALLOW_FILE_MODS=true` in der `.env` verbietet Hochladen und Löschen. + +## Derzeit noch nicht für Kunden-Plugins + +Vue-Seiten und Startseiten-Kacheln werden beim Build des Kerns mitkompiliert – +das geht nur für mitgelieferte Plugins. Für Kunden-Plugins folgt mit dem +öffentlichen Plugin-SDK (Phase 7) ein Weg über vorkompilierte ES-Module und +eine Import-Map. Bis dahin können Kunden-Plugins Blade-Seiten, Admin-Seiten, +Hooks, Rechte und Menüpunkte beitragen. diff --git a/package-lock.json b/package-lock.json index bd9d08d5..0cef1324 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5,11 +5,26 @@ "packages": { "": { "devDependencies": { + "@fontsource-variable/figtree": "^5.3.0", + "@fontsource-variable/ibm-plex-sans": "^5.3.0", "@fontsource-variable/inter": "^5.3.0", + "@fontsource-variable/lora": "^5.3.0", + "@fontsource-variable/merriweather": "^5.3.0", + "@fontsource-variable/nunito-sans": "^5.3.0", + "@fontsource-variable/open-sans": "^5.3.0", + "@fontsource-variable/roboto": "^5.3.0", + "@fontsource-variable/source-sans-3": "^5.3.0", + "@fontsource-variable/source-serif-4": "^5.3.0", + "@fontsource/atkinson-hyperlegible": "^5.3.0", "@inertiajs/vue3": "^3.7.1", "@lucide/vue": "^1.48.0", "@tailwindcss/typography": "^0.5.20", "@tailwindcss/vite": "^4.3.3", + "@tiptap/extension-image": "^3.31.3", + "@tiptap/extensions": "^3.31.3", + "@tiptap/pm": "^3.31.3", + "@tiptap/starter-kit": "^3.31.3", + "@tiptap/vue-3": "^3.31.3", "@vitejs/plugin-vue": "^6.0.9", "@vueuse/core": "^15.0.0", "class-variance-authority": "^0.7.1", @@ -22,6 +37,7 @@ "typescript": "^5.9.3", "vite": "^8.3.1", "vue": "^3.5.43", + "vue-draggable-plus": "^0.6.1", "vue-sonner": "^2.0.9" } }, @@ -142,6 +158,26 @@ } } }, + "node_modules/@fontsource-variable/figtree": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource-variable/figtree/-/figtree-5.3.0.tgz", + "integrity": "sha512-VRVodD7OiG7apQwE8/2fMjaqpY/a0qRJqL5HtYj8CKIVps+9amaFcdfKmDIf7iqYQx6iPLlArVXAfKeIZmVcNQ==", + "dev": true, + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource-variable/ibm-plex-sans": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource-variable/ibm-plex-sans/-/ibm-plex-sans-5.3.0.tgz", + "integrity": "sha512-agG8tXFEo0hD9+J7npa4vbbWult52eMLVaQ6WQRlhs/iCAojrMAoejru85W9HTVXHfyUj96KM7gp/KGAS87XaQ==", + "dev": true, + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, "node_modules/@fontsource-variable/inter": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz", @@ -152,6 +188,86 @@ "url": "https://github.com/sponsors/ayuhito" } }, + "node_modules/@fontsource-variable/lora": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource-variable/lora/-/lora-5.3.0.tgz", + "integrity": "sha512-2ph8KiZ8Bn141hWuC3ErtpJ+Ui8p2MJQn8TJNRSRmLmnCIOCtHfiBM9R7WLRPeUG/q6hXyHOxWQ8DvRSX+ixvQ==", + "dev": true, + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource-variable/merriweather": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource-variable/merriweather/-/merriweather-5.3.0.tgz", + "integrity": "sha512-wK7S4NtPXWUWll/sZCdub93pqSCnFkpKFbnoOE8fh+9Ut6JFjgkc9UlBxHJ0RVMkDpoWwGwMwYYTMvd3G9aAXA==", + "dev": true, + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource-variable/nunito-sans": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource-variable/nunito-sans/-/nunito-sans-5.3.0.tgz", + "integrity": "sha512-Vk1PSfckNDwgw2yGcsvJP3o/0zEW8Rp6KzbD8Ql/6iRHQshnhhAjt+cSIfAUyp5vQuSlleGHFW2LfYaaex0diw==", + "dev": true, + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource-variable/open-sans": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource-variable/open-sans/-/open-sans-5.3.0.tgz", + "integrity": "sha512-VOfhZfLIOBVa6K/dTEu7scqQXYdGa4jBX8quFpQ0S6574B+W2EOBJf9PkqyVtMEI7WWIWNEbpvPc3vY1mN2mmQ==", + "dev": true, + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource-variable/roboto": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource-variable/roboto/-/roboto-5.3.0.tgz", + "integrity": "sha512-BoaaZiQf8fgtxv07KXkTwx1bKz/EoqIlTXq2OOKKXINxp6qXWdnlChqV+hSaDANS49yyUASFl3OVBMMDTCIHFA==", + "dev": true, + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource-variable/source-sans-3": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource-variable/source-sans-3/-/source-sans-3-5.3.0.tgz", + "integrity": "sha512-dpi0GZk7EQe2tYpg6Q0Fx0OmUgnuGu+0rHPgtXqtKhglYmJuP7jZ12Mu1uN+NfRaJRY1Emn8AQJEWzmoZ4wa9g==", + "dev": true, + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource-variable/source-serif-4": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource-variable/source-serif-4/-/source-serif-4-5.3.0.tgz", + "integrity": "sha512-9vch9WqxjaaA+1o9Ur8pOgIGbCYLjRReOUel23A6lOpD1syptgjtkORevvNmldJ5kGXQL29onQUqI5Ltz0s3bQ==", + "dev": true, + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource/atkinson-hyperlegible": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/atkinson-hyperlegible/-/atkinson-hyperlegible-5.3.0.tgz", + "integrity": "sha512-Sp8Ve8+rQmENY2Lv02VH7sLpntzTTvnncnJMTbRE7DX6TLxGraN4ykZfzaUWIoCFmaomwkvNiqmlPkrKBuDoSA==", + "dev": true, + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, "node_modules/@inertiajs/core": { "version": "3.7.1", "resolved": "https://registry.npmjs.org/@inertiajs/core/-/core-3.7.1.tgz", @@ -1165,6 +1281,478 @@ "vue": "^2.7.0 || ^3.0.0" } }, + "node_modules/@tiptap/core": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/core/-/core-3.31.3.tgz", + "integrity": "sha512-Cz50pvciQrxdSxgTkHOVz0uD0Yl/8Xt0QatGD6ILm47jW8EzyHR9RkUGs/D5IqzXKuVPntfw1ttaT926vXfiRg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/pm": "3.31.3" + } + }, + "node_modules/@tiptap/extension-blockquote": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-blockquote/-/extension-blockquote-3.31.3.tgz", + "integrity": "sha512-fyY2XMbyDDDfOTQ1Qdrnqa1qwC9DWE4n7AfE0EKQI0G8MfLV8RaDlLDcOZDJ9JbMPY7/Gx7EjyK4NKxSW9n2hQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3", + "@tiptap/pm": "3.31.3" + } + }, + "node_modules/@tiptap/extension-bold": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-bold/-/extension-bold-3.31.3.tgz", + "integrity": "sha512-dIuYhKk8TitKU/FeDpoTeWZhU42YgDN5npgWNjAmMmRktPdoxnH3/wGSiwXlqZgJWjehN7kPWDePWpJeAImGpQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3" + } + }, + "node_modules/@tiptap/extension-bubble-menu": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-bubble-menu/-/extension-bubble-menu-3.31.3.tgz", + "integrity": "sha512-EV6ZnwKc++2OM/OcD54n8s1B7C9LP7GKAtdEPwu0t3BYJf3sG8Ueoinf7SgGPO9oMPg96GneOkDNm1urMV167g==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@floating-ui/dom": "^1.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3", + "@tiptap/pm": "3.31.3" + } + }, + "node_modules/@tiptap/extension-bullet-list": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-bullet-list/-/extension-bullet-list-3.31.3.tgz", + "integrity": "sha512-qEyyoPapPef4LO8XKaN83bxtaNzkJ4kFn/IxLnEKd4BJ3Mvi4MH2yJYlyDqwFnMoev4pMA1zBHRAt/C0THRmZw==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/extension-list": "3.31.3" + } + }, + "node_modules/@tiptap/extension-code": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-code/-/extension-code-3.31.3.tgz", + "integrity": "sha512-SzxOqchrD2AcN3uT67PjKmRFEMOU3vNNiwNaamZJUbZrI6Hmy+bvdHJrc3jrIddyyCrAtsnAfRI0cmorW1jGfg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3" + } + }, + "node_modules/@tiptap/extension-code-block": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-code-block/-/extension-code-block-3.31.3.tgz", + "integrity": "sha512-nvknt4FhyJQjYcvxptmeUlFsIAc8ibua3E5BN4Pim374/9RWepH4cdE9X0/qUTtguHElLx0iKtSIY3rW2qGTFA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3", + "@tiptap/pm": "3.31.3" + } + }, + "node_modules/@tiptap/extension-document": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-document/-/extension-document-3.31.3.tgz", + "integrity": "sha512-EexgmqnyDNyGlISxo7SMrp5MygpJYmqD+0cY5jB6L1U6L4CpKKRWUt8OO1sWzEHDE1+TTvwt+WIFoIWAziOtEA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3" + } + }, + "node_modules/@tiptap/extension-dropcursor": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-dropcursor/-/extension-dropcursor-3.31.3.tgz", + "integrity": "sha512-NWomSfu5CSC7VacnMSDzKT8qm66SzMfZwVPEtwY5bPpRTJgTiT1rNK0neDrrzfMN27MfylGyKWWf7Q5Qf8w/fg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/extensions": "3.31.3" + } + }, + "node_modules/@tiptap/extension-floating-menu": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-floating-menu/-/extension-floating-menu-3.31.3.tgz", + "integrity": "sha512-rd4VJ9PGSP9Eop8ZTEwaLZcMzMXLuJKe3hUNf58rq+zANpwM+9fI+vB7g9MAc3eXwUNDxNDVACFIL2oeBqpQ3A==", + "dev": true, + "license": "MIT", + "optional": true, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@floating-ui/dom": "^1.0.0", + "@tiptap/core": "3.31.3", + "@tiptap/pm": "3.31.3" + } + }, + "node_modules/@tiptap/extension-gapcursor": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-gapcursor/-/extension-gapcursor-3.31.3.tgz", + "integrity": "sha512-EBXKb1FrVStsNYCcRGtd9jmzveCvR+eqgg1rVqoONrqFK6U7bga6LN+1dMKroP1kliDVgveYkP3vRYxqw+rFqg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/extensions": "3.31.3" + } + }, + "node_modules/@tiptap/extension-hard-break": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-hard-break/-/extension-hard-break-3.31.3.tgz", + "integrity": "sha512-QAdCvNO4+yW9ATwsrej11NTkDYFqPLIEQr3ARNrKOK1qaiS7A0fia2SEukb/hrkP3A6mbozhoQt2r2RGUf/DpQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3" + } + }, + "node_modules/@tiptap/extension-heading": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-heading/-/extension-heading-3.31.3.tgz", + "integrity": "sha512-rk5VHMAeQcg06SLauN6EGdD2jc0O2qY8QkZYPd0LxNvLblw2BxBx+lxUQSYwLAT9Ie5914gKIK2YbRyO2Ts3ig==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3" + } + }, + "node_modules/@tiptap/extension-horizontal-rule": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-horizontal-rule/-/extension-horizontal-rule-3.31.3.tgz", + "integrity": "sha512-YnHGy2KShRwvCseAmmxl9VP7R0qaj8QMp3DA6DJWZqp7r5gLGvDkAqhedxqqefqsE4Y43hjkBdjtB9Ce78LkIw==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3", + "@tiptap/pm": "3.31.3" + } + }, + "node_modules/@tiptap/extension-image": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-image/-/extension-image-3.31.3.tgz", + "integrity": "sha512-wWNG9BOtx2Cg4vwxPVGDIJ5DGX+ETkldeoaFJLB1NXUL4OPUiVTf8cHZ+hdYgJWP704BEB7jQgjlpvdi6VigTg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3" + } + }, + "node_modules/@tiptap/extension-italic": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-italic/-/extension-italic-3.31.3.tgz", + "integrity": "sha512-ibGvdvAPyfxBMUVNRI43eb9h2/Jka1MRG5GtnGqbcCX/2+Y/y0EOfFrPQPkuYphiWQYyu9+FzPKMB/pjuaLuKQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3" + } + }, + "node_modules/@tiptap/extension-link": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-link/-/extension-link-3.31.3.tgz", + "integrity": "sha512-986wOQzTL9Zr5lf84LCLpm+YOms8A0K39/8DVoqRfebqcOe0/eq4bnztmAlfabOd+kJY92g3AgZERFUx/w+dcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "linkifyjs": "^4.3.3" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3", + "@tiptap/pm": "3.31.3" + } + }, + "node_modules/@tiptap/extension-list": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-list/-/extension-list-3.31.3.tgz", + "integrity": "sha512-LoveGnC0FVdCV4jUNBaG1ZA+KWE07+adzV3kGy6uUYFcJEjbVUHTnPDrBOob3IwOSO3sCwIkvQb6EVYeXn/4yg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3", + "@tiptap/pm": "3.31.3" + } + }, + "node_modules/@tiptap/extension-list-item": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-list-item/-/extension-list-item-3.31.3.tgz", + "integrity": "sha512-4QlKOriJJMvg95QJTEsy9BUYPBQ6UvJyb8WURRwdUtQUkkqb8h32lg/eyQUv2FzW9IT1AdUyNZfVaxH64kRfQA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/extension-list": "3.31.3" + } + }, + "node_modules/@tiptap/extension-list-keymap": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-list-keymap/-/extension-list-keymap-3.31.3.tgz", + "integrity": "sha512-If8UOEdDZbPJU6iYTvLtH6DOp2KBy6BKxg9UELL1AevVetGHEF/7lW8hP50Gn1tHMVpPRqmhSzVrJRpEJJgb/Q==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/extension-list": "3.31.3" + } + }, + "node_modules/@tiptap/extension-ordered-list": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-ordered-list/-/extension-ordered-list-3.31.3.tgz", + "integrity": "sha512-mp3g11NgA/PYu8rj7J7Ez3l4qBy6WfTSmHIG4PZvEGG5w2oUAIkgb9DU7nPPzjmeme27oazFYZw+AtZA0+u4tw==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/extension-list": "3.31.3" + } + }, + "node_modules/@tiptap/extension-paragraph": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-paragraph/-/extension-paragraph-3.31.3.tgz", + "integrity": "sha512-+iPku7wJfy5hbNDNLX8dveFtYVsZMmh7vztjuq8hT3mipSC4IByDehDbU8fzUCjfXiEzmI7mQn7c8LGmHULuzA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3" + } + }, + "node_modules/@tiptap/extension-strike": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-strike/-/extension-strike-3.31.3.tgz", + "integrity": "sha512-G29bhKttYwcKHT+BI6emWVFol3RO/gUXxQVcmr/iT8LXXy7j8J6HFUnsKM+Kg5YlP1rxMRgsa65dbrQVahZi0A==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3" + } + }, + "node_modules/@tiptap/extension-text": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-text/-/extension-text-3.31.3.tgz", + "integrity": "sha512-gdsWtF+taeaCu6V+5Ct10fGo0ACUy1GnYtbb+mcathBt8OqbT+Ws60p/yEmKesBDz2Hn+B5IcWy6+2BBZl5ZTg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3" + } + }, + "node_modules/@tiptap/extension-underline": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extension-underline/-/extension-underline-3.31.3.tgz", + "integrity": "sha512-HghdJaOwRqYzsAxqSyNyb+IWyOMcdCl8IoiBETA9BZCJAqdXzFLcuWp7CqCqJPam9dgkWosSoHqTCAO4nTBfpw==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3" + } + }, + "node_modules/@tiptap/extensions": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/extensions/-/extensions-3.31.3.tgz", + "integrity": "sha512-8sJNPGGUe8f3aDojcOW5cfVL7I5NrBbE0UWxG08qoi9Tea6qWbvQJsCR9tsrOapr/DaLr3kpbGZ9s1gEEfcNcA==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.31.3", + "@tiptap/pm": "3.31.3" + } + }, + "node_modules/@tiptap/pm": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/pm/-/pm-3.31.3.tgz", + "integrity": "sha512-sZime0SWsz/k62W2WvHx5Ig7G2h7kVhrrmnqy+wEgIHfDwEfOlelRjaWCiBCFlF7dxGUntJusCh9FxlLhni0Ag==", + "dev": true, + "license": "MIT", + "dependencies": { + "prosemirror-changeset": "^2.4.1", + "prosemirror-commands": "^1.7.1", + "prosemirror-dropcursor": "^1.8.2", + "prosemirror-gapcursor": "^1.4.1", + "prosemirror-history": "^1.5.0", + "prosemirror-inputrules": "^1.5.1", + "prosemirror-keymap": "^1.2.3", + "prosemirror-model": "^1.25.11", + "prosemirror-schema-list": "^1.5.1", + "prosemirror-state": "^1.4.4", + "prosemirror-tables": "^1.8.5", + "prosemirror-transform": "^1.12.0", + "prosemirror-view": "^1.42.3" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + } + }, + "node_modules/@tiptap/starter-kit": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/starter-kit/-/starter-kit-3.31.3.tgz", + "integrity": "sha512-WKof9RewdmGHvWJ1wn0/HVNG2mV+HOgVRyJkKekuM9fgr6BZAAH/xZsWE1eon+94JnQ+KtK2ThydXQM/qc6b2A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tiptap/core": "3.31.3", + "@tiptap/extension-blockquote": "3.31.3", + "@tiptap/extension-bold": "3.31.3", + "@tiptap/extension-bullet-list": "3.31.3", + "@tiptap/extension-code": "3.31.3", + "@tiptap/extension-code-block": "3.31.3", + "@tiptap/extension-document": "3.31.3", + "@tiptap/extension-dropcursor": "3.31.3", + "@tiptap/extension-gapcursor": "3.31.3", + "@tiptap/extension-hard-break": "3.31.3", + "@tiptap/extension-heading": "3.31.3", + "@tiptap/extension-horizontal-rule": "3.31.3", + "@tiptap/extension-italic": "3.31.3", + "@tiptap/extension-link": "3.31.3", + "@tiptap/extension-list": "3.31.3", + "@tiptap/extension-list-item": "3.31.3", + "@tiptap/extension-list-keymap": "3.31.3", + "@tiptap/extension-ordered-list": "3.31.3", + "@tiptap/extension-paragraph": "3.31.3", + "@tiptap/extension-strike": "3.31.3", + "@tiptap/extension-text": "3.31.3", + "@tiptap/extension-underline": "3.31.3", + "@tiptap/extensions": "3.31.3", + "@tiptap/pm": "3.31.3" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + } + }, + "node_modules/@tiptap/vue-3": { + "version": "3.31.3", + "resolved": "https://registry.npmjs.org/@tiptap/vue-3/-/vue-3-3.31.3.tgz", + "integrity": "sha512-PNt0+rm7BXzhe/U+xlNnXBeJ6t9x2mE3902VXeIeEBxu5CrYLCJ0a5yHrof1jU3KwJrLOe/BtlGWjbq4qnTTfQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "optionalDependencies": { + "@tiptap/extension-bubble-menu": "^3.31.3", + "@tiptap/extension-floating-menu": "^3.31.3" + }, + "peerDependencies": { + "@floating-ui/dom": "^1.0.0", + "@tiptap/core": "3.31.3", + "@tiptap/pm": "3.31.3", + "vue": "^3.0.0" + } + }, + "node_modules/@types/sortablejs": { + "version": "1.15.9", + "resolved": "https://registry.npmjs.org/@types/sortablejs/-/sortablejs-1.15.9.tgz", + "integrity": "sha512-7HP+rZGE2p886PKV9c9OJzLBI6BBJu1O7lJGYnPyG3fS4/duUCcngkNCjsLwIMV+WMqANe3tt4irrXHSIe68OQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/web-bluetooth": { "version": "0.0.21", "resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz", @@ -1834,6 +2422,13 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/linkifyjs": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.3.3.tgz", + "integrity": "sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==", + "dev": true, + "license": "MIT" + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -1870,6 +2465,13 @@ "dev": true, "license": "MIT" }, + "node_modules/orderedmap": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/orderedmap/-/orderedmap-2.1.1.tgz", + "integrity": "sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==", + "dev": true, + "license": "MIT" + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -1933,6 +2535,158 @@ "node": ">=4" } }, + "node_modules/prosemirror-changeset": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/prosemirror-changeset/-/prosemirror-changeset-2.4.4.tgz", + "integrity": "sha512-Gyuz9jYdrAeA9I7AholyOes9KUmv/lEwsC5O9s5xF5VB3EgTPsXMGUxz4+H1B+wKVPdZbvRcg1Cp3x8qX+8ofA==", + "dev": true, + "license": "MIT", + "dependencies": { + "prosemirror-transform": "^1.0.0" + } + }, + "node_modules/prosemirror-commands": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/prosemirror-commands/-/prosemirror-commands-1.7.2.tgz", + "integrity": "sha512-q6Q6szxqdu9Xd6EcdKsqXghu5nQdZTpB4Q9yd04WRc7/jt763e/rT60Owh0L1GYY+T46o5rD+9lEN36dZS43tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "prosemirror-model": "^1.0.0", + "prosemirror-state": "^1.0.0", + "prosemirror-transform": "^1.10.2" + } + }, + "node_modules/prosemirror-dropcursor": { + "version": "1.8.4", + "resolved": "https://registry.npmjs.org/prosemirror-dropcursor/-/prosemirror-dropcursor-1.8.4.tgz", + "integrity": "sha512-VmKxhcA6a+h5oPSYmfF1ZNeQqPbyYaIxqZsKqeYCyTlPtrjUgNaHL3P8vVaO19oqAV0zuaM/axkowZHrB1P3Tg==", + "dev": true, + "license": "MIT", + "dependencies": { + "prosemirror-state": "^1.0.0", + "prosemirror-transform": "^1.1.0", + "prosemirror-view": "^1.1.0" + } + }, + "node_modules/prosemirror-gapcursor": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/prosemirror-gapcursor/-/prosemirror-gapcursor-1.4.1.tgz", + "integrity": "sha512-pMdYaEnjNMSwl11yjEGtgTmLkR08m/Vl+Jj443167p9eB3HVQKhYCc4gmHVDsLPODfZfjr/MmirsdyZziXbQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "prosemirror-keymap": "^1.0.0", + "prosemirror-model": "^1.0.0", + "prosemirror-state": "^1.0.0", + "prosemirror-view": "^1.0.0" + } + }, + "node_modules/prosemirror-history": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/prosemirror-history/-/prosemirror-history-1.5.0.tgz", + "integrity": "sha512-zlzTiH01eKA55UAf1MEjtssJeHnGxO0j4K4Dpx+gnmX9n+SHNlDqI2oO1Kv1iPN5B1dm5fsljCfqKF9nFL6HRg==", + "dev": true, + "license": "MIT", + "dependencies": { + "prosemirror-state": "^1.2.2", + "prosemirror-transform": "^1.0.0", + "prosemirror-view": "^1.31.0", + "rope-sequence": "^1.3.0" + } + }, + "node_modules/prosemirror-inputrules": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/prosemirror-inputrules/-/prosemirror-inputrules-1.5.1.tgz", + "integrity": "sha512-7wj4uMjKaXWAQ1CDgxNzNtR9AlsuwzHfdFH1ygEHA2KHF2DOEaXl1CJfNPAKCg9qNEh4rum975QLaCiQPyY6Fw==", + "dev": true, + "license": "MIT", + "dependencies": { + "prosemirror-state": "^1.0.0", + "prosemirror-transform": "^1.0.0" + } + }, + "node_modules/prosemirror-keymap": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/prosemirror-keymap/-/prosemirror-keymap-1.2.3.tgz", + "integrity": "sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "prosemirror-state": "^1.0.0", + "w3c-keyname": "^2.2.0" + } + }, + "node_modules/prosemirror-model": { + "version": "1.25.12", + "resolved": "https://registry.npmjs.org/prosemirror-model/-/prosemirror-model-1.25.12.tgz", + "integrity": "sha512-Ue2gTmXMa7EhpLNhC7J+h4+ykD8ha12K6rrZFFKKJHBForfIStw5gJ6Zrf1mqqAa9NmpmEB4wp9bKmA4eUVjWg==", + "dev": true, + "license": "MIT", + "dependencies": { + "orderedmap": "^2.0.0" + } + }, + "node_modules/prosemirror-schema-list": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/prosemirror-schema-list/-/prosemirror-schema-list-1.5.1.tgz", + "integrity": "sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "prosemirror-model": "^1.0.0", + "prosemirror-state": "^1.0.0", + "prosemirror-transform": "^1.7.3" + } + }, + "node_modules/prosemirror-state": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/prosemirror-state/-/prosemirror-state-1.4.4.tgz", + "integrity": "sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw==", + "dev": true, + "license": "MIT", + "dependencies": { + "prosemirror-model": "^1.0.0", + "prosemirror-transform": "^1.0.0", + "prosemirror-view": "^1.27.0" + } + }, + "node_modules/prosemirror-tables": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/prosemirror-tables/-/prosemirror-tables-1.8.5.tgz", + "integrity": "sha512-V/0cDCsHKHe/tfWkeCmthNUcEp1IVO3p6vwN8XtwE9PZQLAZJigbw3QoraAdfJPir4NKJtNvOB8oYGKRl+t0Dw==", + "dev": true, + "license": "MIT", + "dependencies": { + "prosemirror-keymap": "^1.2.3", + "prosemirror-model": "^1.25.4", + "prosemirror-state": "^1.4.4", + "prosemirror-transform": "^1.10.5", + "prosemirror-view": "^1.41.4" + } + }, + "node_modules/prosemirror-transform": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/prosemirror-transform/-/prosemirror-transform-1.12.2.tgz", + "integrity": "sha512-PE/aY0HEY4zczvmqrilgkUK/WautF0chvMqkmM/iN5/aPHvwrCWaQZjS6CIZp+K84YrvPFqrL+YArrfJX8xX7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "prosemirror-model": "^1.21.0" + } + }, + "node_modules/prosemirror-view": { + "version": "1.42.6", + "resolved": "https://registry.npmjs.org/prosemirror-view/-/prosemirror-view-1.42.6.tgz", + "integrity": "sha512-3g25f6hKV2bBxo3puH3EcYWmmVNSH0iWmNsMVT7sugDSpA025jgpOLarcDWr39SdzPjYMaiYtRdNtXialPSjEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prosemirror-model": "^1.25.12", + "prosemirror-state": "^1.0.0", + "prosemirror-transform": "^1.1.0" + } + }, "node_modules/reka-ui": { "version": "2.10.5", "resolved": "https://registry.npmjs.org/reka-ui/-/reka-ui-2.10.5.tgz", @@ -2034,6 +2788,13 @@ "@rolldown/binding-win32-x64-msvc": "1.2.11" } }, + "node_modules/rope-sequence": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/rope-sequence/-/rope-sequence-1.3.4.tgz", + "integrity": "sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==", + "dev": true, + "license": "MIT" + }, "node_modules/source-map-js": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", @@ -2255,6 +3016,24 @@ } } }, + "node_modules/vue-draggable-plus": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/vue-draggable-plus/-/vue-draggable-plus-0.6.1.tgz", + "integrity": "sha512-FbtQ/fuoixiOfTZzG3yoPl4JAo9HJXRHmBQZFB9x2NYCh6pq0TomHf7g5MUmpaDYv+LU2n6BPq2YN9sBO+FbIg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/sortablejs": "^1.15.8" + }, + "peerDependencies": { + "@types/sortablejs": "^1.15.0" + }, + "peerDependenciesMeta": { + "@vue/composition-api": { + "optional": true + } + } + }, "node_modules/vue-sonner": { "version": "2.0.9", "resolved": "https://registry.npmjs.org/vue-sonner/-/vue-sonner-2.0.9.tgz", @@ -2277,6 +3056,13 @@ "optional": true } } + }, + "node_modules/w3c-keyname": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", + "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==", + "dev": true, + "license": "MIT" } } } diff --git a/package.json b/package.json index bbc24154..ba02e2d2 100644 --- a/package.json +++ b/package.json @@ -7,11 +7,26 @@ "dev": "vite" }, "devDependencies": { + "@fontsource-variable/figtree": "^5.3.0", + "@fontsource-variable/ibm-plex-sans": "^5.3.0", "@fontsource-variable/inter": "^5.3.0", + "@fontsource-variable/lora": "^5.3.0", + "@fontsource-variable/merriweather": "^5.3.0", + "@fontsource-variable/nunito-sans": "^5.3.0", + "@fontsource-variable/open-sans": "^5.3.0", + "@fontsource-variable/roboto": "^5.3.0", + "@fontsource-variable/source-sans-3": "^5.3.0", + "@fontsource-variable/source-serif-4": "^5.3.0", + "@fontsource/atkinson-hyperlegible": "^5.3.0", "@inertiajs/vue3": "^3.7.1", "@lucide/vue": "^1.48.0", "@tailwindcss/typography": "^0.5.20", "@tailwindcss/vite": "^4.3.3", + "@tiptap/extension-image": "^3.31.3", + "@tiptap/extensions": "^3.31.3", + "@tiptap/pm": "^3.31.3", + "@tiptap/starter-kit": "^3.31.3", + "@tiptap/vue-3": "^3.31.3", "@vitejs/plugin-vue": "^6.0.9", "@vueuse/core": "^15.0.0", "class-variance-authority": "^0.7.1", @@ -24,6 +39,7 @@ "typescript": "^5.9.3", "vite": "^8.3.1", "vue": "^3.5.43", + "vue-draggable-plus": "^0.6.1", "vue-sonner": "^2.0.9" } } diff --git a/phpunit.xml b/phpunit.xml index 1e358afa..a05fc308 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -19,6 +19,7 @@ + diff --git a/plugins-core/birthdays/database/migrations/2026_09_28_000004_create_birthdays_table.php b/plugins-core/birthdays/database/migrations/2026_09_28_000004_create_birthdays_table.php new file mode 100644 index 00000000..2c23dbee --- /dev/null +++ b/plugins-core/birthdays/database/migrations/2026_09_28_000004_create_birthdays_table.php @@ -0,0 +1,29 @@ +id(); + $table->foreignId('user_id')->unique()->constrained('users')->cascadeOnDelete(); + $table->unsignedTinyInteger('month'); + $table->unsignedTinyInteger('day'); + $table->timestamps(); + + $table->index(['month', 'day']); + }); + } + + public function down(): void + { + Schema::dropIfExists('birthdays'); + } +}; diff --git a/plugins-core/birthdays/plugin.json b/plugins-core/birthdays/plugin.json new file mode 100644 index 00000000..acca40b7 --- /dev/null +++ b/plugins-core/birthdays/plugin.json @@ -0,0 +1,14 @@ +{ + "slug": "birthdays", + "name": "Geburtstage", + "version": "1.0.0", + "description": "Geburtstagsliste zum Mitmachen: Wer möchte, trägt Tag und Monat im Profil ein. Mit Kachel auf der Startseite und Glückwunsch am eigenen Geburtstag.", + "author": "Inhaus", + "namespace": "Inhaus\\Plugins\\Birthdays\\", + "class": "Inhaus\\Plugins\\Birthdays\\BirthdaysPlugin", + "enabled_by_default": false, + "requires": { + "core": ">=0.6.0", + "php": ">=8.3" + } +} diff --git a/plugins-core/birthdays/resources/js/blocks/BirthdaysBlock.vue b/plugins-core/birthdays/resources/js/blocks/BirthdaysBlock.vue new file mode 100644 index 00000000..75c21b30 --- /dev/null +++ b/plugins-core/birthdays/resources/js/blocks/BirthdaysBlock.vue @@ -0,0 +1,15 @@ + + + diff --git a/plugins-core/birthdays/resources/js/components/BirthdayItem.vue b/plugins-core/birthdays/resources/js/components/BirthdayItem.vue new file mode 100644 index 00000000..8b233a29 --- /dev/null +++ b/plugins-core/birthdays/resources/js/components/BirthdayItem.vue @@ -0,0 +1,28 @@ + + + diff --git a/plugins-core/birthdays/resources/js/pages/Index.vue b/plugins-core/birthdays/resources/js/pages/Index.vue new file mode 100644 index 00000000..925c9ef8 --- /dev/null +++ b/plugins-core/birthdays/resources/js/pages/Index.vue @@ -0,0 +1,52 @@ + + + diff --git a/plugins-core/birthdays/resources/js/profile/ProfileBirthday.vue b/plugins-core/birthdays/resources/js/profile/ProfileBirthday.vue new file mode 100644 index 00000000..ddfdfb66 --- /dev/null +++ b/plugins-core/birthdays/resources/js/profile/ProfileBirthday.vue @@ -0,0 +1,69 @@ + + + diff --git a/plugins-core/birthdays/resources/js/widgets/Greeting.vue b/plugins-core/birthdays/resources/js/widgets/Greeting.vue new file mode 100644 index 00000000..412b0eb4 --- /dev/null +++ b/plugins-core/birthdays/resources/js/widgets/Greeting.vue @@ -0,0 +1,55 @@ + + + diff --git a/plugins-core/birthdays/resources/js/widgets/Upcoming.vue b/plugins-core/birthdays/resources/js/widgets/Upcoming.vue new file mode 100644 index 00000000..b48f8b56 --- /dev/null +++ b/plugins-core/birthdays/resources/js/widgets/Upcoming.vue @@ -0,0 +1,17 @@ + + + diff --git a/plugins-core/birthdays/routes/web.php b/plugins-core/birthdays/routes/web.php new file mode 100644 index 00000000..bc970cba --- /dev/null +++ b/plugins-core/birthdays/routes/web.php @@ -0,0 +1,10 @@ +group(function () { + Route::get('/geburtstage', [BirthdayController::class, 'index'])->name('birthdays.index'); + Route::put('/profil/geburtstag', [BirthdayController::class, 'update'])->name('birthdays.update'); + Route::delete('/profil/geburtstag', [BirthdayController::class, 'destroy'])->name('birthdays.destroy'); +}); diff --git a/plugins-core/birthdays/src/BirthdayList.php b/plugins-core/birthdays/src/BirthdayList.php new file mode 100644 index 00000000..dbf0547c --- /dev/null +++ b/plugins-core/birthdays/src/BirthdayList.php @@ -0,0 +1,95 @@ + 'Alle Mitarbeitenden', + 'department' => 'Nur die eigene Abteilung', + 'location' => 'Nur der eigene Standort', + ]; + + public function __construct(private readonly Settings $settings) {} + + public function scope(): string + { + return array_key_exists($s = (string) $this->settings->get('birthdays.scope', 'all'), self::SCOPES) ? $s : 'all'; + } + + public function daysAhead(): int + { + return max(0, min(60, (int) $this->settings->get('birthdays.days', 7))); + } + + public function greetingEnabled(): bool + { + return (bool) $this->settings->get('birthdays.greeting', true); + } + + /** + * @return list}> + */ + public function upcoming(User $viewer, ?int $days = null, ?string $scope = null, int $limit = 200): array + { + $days ??= $this->daysAhead(); + $scope ??= $this->scope(); + $today = Carbon::today(); + $end = $today->copy()->addDays($days); + + // Nur die betroffenen Monate laden (höchstens drei), dann genau filtern. + $months = collect(range(0, (int) $today->copy()->startOfMonth()->diffInMonths($end->copy()->startOfMonth()))) + ->map(fn ($i) => $today->copy()->startOfMonth()->addMonths($i)->month)->unique()->values()->all(); + + $birthdays = Birthday::query() + ->whereIn('month', $months) + ->whereHas('user', function ($q) use ($viewer, $scope) { + $q->where('is_active', true); + + if ($scope === 'department') { + $viewer->department ? $q->where('department', $viewer->department) : $q->whereKey($viewer->id); + } elseif ($scope === 'location') { + $viewer->location ? $q->where('location', $viewer->location) : $q->whereKey($viewer->id); + } + }) + ->with('user') + ->get(); + + return $birthdays + ->map(fn (Birthday $b) => ['birthday' => $b, 'date' => $b->nextOccurrence($today)]) + ->filter(fn ($row) => $row['date']->lte($end)) + ->sortBy(fn ($row) => $row['date']->format('Ymd').mb_strtolower($row['birthday']->user->last_name.' '.$row['birthday']->user->first_name)) + ->take($limit) + ->map(fn ($row) => [ + 'date' => $row['date']->toDateString(), + 'today' => $row['date']->isSameDay($today), + 'person' => (new PersonResource($row['birthday']->user))->resolve(), + ]) + ->values() + ->all(); + } + + public function isBirthdayToday(User $user): bool + { + return (bool) Birthday::query()->where('user_id', $user->id)->first()?->isOn(Carbon::today()); + } + + /** + * @return Collection + */ + public static function months(): Collection + { + return collect(range(1, 12))->mapWithKeys(fn ($m) => [$m => Carbon::create(2000, $m, 1)->locale('de')->translatedFormat('F')]); + } +} diff --git a/plugins-core/birthdays/src/BirthdaysPlugin.php b/plugins-core/birthdays/src/BirthdaysPlugin.php new file mode 100644 index 00000000..7659a79d --- /dev/null +++ b/plugins-core/birthdays/src/BirthdaysPlugin.php @@ -0,0 +1,60 @@ +app->singleton(BirthdayList::class); + + $this->app->make(ProfileSections::class)->add('birthday', 'birthdays::ProfileBirthday', 10, function (User $user) { + $birthday = Birthday::query()->where('user_id', $user->id)->first(); + + return [ + 'birthday' => $birthday ? ['day' => $birthday->day, 'month' => $birthday->month] : null, + 'months' => BirthdayList::months()->map(fn ($label, $value) => ['value' => $value, 'label' => $label])->values(), + 'scope' => app(BirthdayList::class)->scope(), + ]; + }); + + $widgets = $this->app->make(Widgets::class); + + // Glückwunsch oben auf der Startseite – nur am eigenen Geburtstag. + $widgets->add('birthdays.greeting', 'birthdays::Greeting', 'top', sort: 0, props: function (User $user) { + $list = app(BirthdayList::class); + + return $list->greetingEnabled() && $list->isBirthdayToday($user) ? ['name' => $user->first_name ?: $user->name] : null; + }, label: 'Geburtstagsgruß (am eigenen Geburtstag)', mobileSort: -100); + + $widgets->add('birthdays.upcoming', 'birthdays::Upcoming', 'aside', sort: 30, props: function (User $user) { + $list = app(BirthdayList::class); + $upcoming = $list->upcoming($user, limit: 8); + + return $upcoming === [] ? null : ['birthdays' => $upcoming, 'days' => $list->daysAhead()]; + }, label: 'Geburtstage', mobileSort: 35); + + $this->app->make(Blocks::class)->add(BlockType::make('birthdays.list', 'Geburtstage', 'cake', 'dynamic', 'birthdays::BirthdaysBlock') + ->description('Anstehende Geburtstage – z. B. auf der Seite einer Abteilung.') + ->fields([ + Field::text('title', 'Überschrift', 150, 'Geburtstage'), + Field::select('scope', 'Wessen Geburtstage', ['' => 'Wie in den Einstellungen'] + BirthdayList::SCOPES, ''), + Field::number('days', 'Tage im Voraus', 0, 60, 14), + ]) + ->resolveUsing(fn (array $data, ?User $user) => $user ? [ + 'birthdays' => app(BirthdayList::class)->upcoming($user, $data['days'], $data['scope'] ?: null, 30), + ] : null)); + } +} diff --git a/plugins-core/birthdays/src/Filament/Pages/BirthdaySettings.php b/plugins-core/birthdays/src/Filament/Pages/BirthdaySettings.php new file mode 100644 index 00000000..0913c457 --- /dev/null +++ b/plugins-core/birthdays/src/Filament/Pages/BirthdaySettings.php @@ -0,0 +1,69 @@ +|null */ + public ?array $data = []; + + public static function canAccess(): bool + { + return auth()->user()?->can('appearance.manage') ?? false; + } + + public function mount(BirthdayList $list): void + { + $this->form->fill(['scope' => $list->scope(), 'days' => $list->daysAhead(), 'greeting' => $list->greetingEnabled()]); + } + + public function form(Schema $schema): Schema + { + return $schema->statePath('data')->components([ + Section::make('Geburtstagsliste') + ->description(fn () => 'Mitarbeitende tragen sich freiwillig im Profil ein (nur Tag und Monat). Derzeit eingetragen: '.Birthday::query()->count().'.') + ->columns(2) + ->schema([ + Select::make('scope')->label('Wer sieht wessen Geburtstag')->options(BirthdayList::SCOPES)->required()->native(false), + TextInput::make('days')->label('Tage im Voraus auf der Startseite')->numeric()->minValue(0)->maxValue(60)->required(), + Toggle::make('greeting')->label('Am eigenen Geburtstag auf der Startseite gratulieren')->columnSpanFull(), + ]), + ]); + } + + public function save(Settings $settings): void + { + $state = $this->form->getState(); + $settings->setMany(['birthdays.scope' => $state['scope'], 'birthdays.days' => (int) $state['days'], 'birthdays.greeting' => (bool) $state['greeting']]); + + Notification::make()->success()->title('Gespeichert')->send(); + } +} diff --git a/plugins-core/birthdays/src/Http/Controllers/BirthdayController.php b/plugins-core/birthdays/src/Http/Controllers/BirthdayController.php new file mode 100644 index 00000000..956304a0 --- /dev/null +++ b/plugins-core/birthdays/src/Http/Controllers/BirthdayController.php @@ -0,0 +1,48 @@ + $list->upcoming($request->user(), 30), + 'scope' => BirthdayList::SCOPES[$list->scope()], + 'registered' => Birthday::query()->where('user_id', $request->user()->id)->exists(), + ]); + } + + public function update(Request $request): RedirectResponse + { + $data = $request->validate([ + 'day' => ['required', 'integer', 'between:1,31'], + 'month' => ['required', 'integer', 'between:1,12'], + ], [], ['day' => 'Tag', 'month' => 'Monat']); + + // Gültiger Tag im Monat (29. Februar erlaubt). + if (! checkdate($data['month'], $data['day'], 2000)) { + throw ValidationException::withMessages(['day' => 'Diesen Tag gibt es im gewählten Monat nicht.']); + } + + Birthday::query()->updateOrCreate(['user_id' => $request->user()->id], $data); + + return back()->with('status', 'birthday-saved'); + } + + public function destroy(Request $request): RedirectResponse + { + Birthday::query()->where('user_id', $request->user()->id)->delete(); + + return back()->with('status', 'birthday-removed'); + } +} diff --git a/plugins-core/birthdays/src/Models/Birthday.php b/plugins-core/birthdays/src/Models/Birthday.php new file mode 100644 index 00000000..237f39cc --- /dev/null +++ b/plugins-core/birthdays/src/Models/Birthday.php @@ -0,0 +1,46 @@ + + */ + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } + + /** + * Nächster Geburtstag ab $from (heute eingeschlossen). Der 29. Februar + * wird in Nicht-Schaltjahren am 28. Februar gefeiert. + */ + public function nextOccurrence(Carbon $from): Carbon + { + $date = self::inYear($from->year, $this->month, $this->day); + + return $date->lt($from->copy()->startOfDay()) ? self::inYear($from->year + 1, $this->month, $this->day) : $date; + } + + public function isOn(Carbon $date): bool + { + return self::inYear($date->year, $this->month, $this->day)->isSameDay($date); + } + + private static function inYear(int $year, int $month, int $day): Carbon + { + if ($month === 2 && $day === 29 && ! Carbon::create($year)->isLeapYear()) { + $day = 28; + } + + return Carbon::create($year, $month, $day)->startOfDay(); + } +} diff --git a/database/migrations/2026_09_26_000002_create_events_table.php b/plugins-core/events/database/migrations/2026_09_26_000002_create_events_table.php similarity index 100% rename from database/migrations/2026_09_26_000002_create_events_table.php rename to plugins-core/events/database/migrations/2026_09_26_000002_create_events_table.php diff --git a/plugins-core/events/plugin.json b/plugins-core/events/plugin.json new file mode 100644 index 00000000..6bd9211d --- /dev/null +++ b/plugins-core/events/plugin.json @@ -0,0 +1,13 @@ +{ + "slug": "events", + "name": "Termine", + "version": "1.1.0", + "description": "Veranstaltungen und Fortbildungen mit Kalender-Export.", + "author": "Inhaus", + "namespace": "Inhaus\\Plugins\\Events\\", + "class": "Inhaus\\Plugins\\Events\\EventsPlugin", + "requires": { + "core": ">=0.5.0", + "php": ">=8.3" + } +} diff --git a/plugins-core/events/resources/js/blocks/UpcomingEvents.vue b/plugins-core/events/resources/js/blocks/UpcomingEvents.vue new file mode 100644 index 00000000..9bafd54c --- /dev/null +++ b/plugins-core/events/resources/js/blocks/UpcomingEvents.vue @@ -0,0 +1,20 @@ + + + diff --git a/resources/js/components/EventDateBlock.vue b/plugins-core/events/resources/js/components/EventDateBlock.vue similarity index 90% rename from resources/js/components/EventDateBlock.vue rename to plugins-core/events/resources/js/components/EventDateBlock.vue index 75cf3336..1bfdb474 100644 --- a/resources/js/components/EventDateBlock.vue +++ b/plugins-core/events/resources/js/components/EventDateBlock.vue @@ -12,6 +12,6 @@ const block = computed(() => dateBlock(props.date)); diff --git a/resources/js/components/EventListItem.vue b/plugins-core/events/resources/js/components/EventListItem.vue similarity index 92% rename from resources/js/components/EventListItem.vue rename to plugins-core/events/resources/js/components/EventListItem.vue index 592270c4..bba94b72 100644 --- a/resources/js/components/EventListItem.vue +++ b/plugins-core/events/resources/js/components/EventListItem.vue @@ -1,6 +1,6 @@ + + diff --git a/plugins-core/events/routes/web.php b/plugins-core/events/routes/web.php new file mode 100644 index 00000000..bbcbcd31 --- /dev/null +++ b/plugins-core/events/routes/web.php @@ -0,0 +1,10 @@ +group(function () { + Route::get('/termine', [EventController::class, 'index'])->name('events.index'); + Route::get('/termine/{event}', [EventController::class, 'show'])->name('events.show'); + Route::get('/termine/{event}/kalender.ics', [EventController::class, 'ics'])->name('events.ics'); +}); diff --git a/app/Support/Calendar.php b/plugins-core/events/src/Calendar.php similarity index 97% rename from app/Support/Calendar.php rename to plugins-core/events/src/Calendar.php index edc587fb..8ea98893 100644 --- a/app/Support/Calendar.php +++ b/plugins-core/events/src/Calendar.php @@ -1,9 +1,9 @@ */ class EventFactory extends Factory { + protected $model = Event::class; + public function definition(): array { $start = now()->addDays(fake()->numberBetween(1, 30))->setTime(10, 0); diff --git a/plugins-core/events/src/EventsPlugin.php b/plugins-core/events/src/EventsPlugin.php new file mode 100644 index 00000000..99093a8a --- /dev/null +++ b/plugins-core/events/src/EventsPlugin.php @@ -0,0 +1,40 @@ +app->make(Navigation::class)->add('events', 'Termine', '/termine', active: 'events.*', sort: 30); + $this->app->make(Abilities::class)->define('events.manage', 'Termine verwalten', 'Termine'); + Gate::policy(Event::class, EventPolicy::class); + + $this->app->make(Widgets::class)->add('events.upcoming', 'events::Upcoming', 'aside', sort: 20, props: fn (User $user) => [ + 'events' => EventResource::collection(Event::query()->upcoming()->visibleTo($user)->limit(4)->get())->resolve(), + ], label: 'Termine', mobileSort: 30); + + $this->app->make(Blocks::class)->add(BlockType::make('events.upcoming', 'Termine', 'calendar-days', 'dynamic', 'events::UpcomingEvents') + ->description('Die nächsten Termine.') + ->fields([ + Field::text('title', 'Überschrift', 150, 'Termine'), + Field::number('count', 'Anzahl', 1, 12, 4), + ]) + ->resolveUsing(fn (array $data, ?User $user) => [ + 'events' => EventResource::collection(Event::query()->upcoming()->visibleTo($user)->limit($data['count'])->get())->resolve(), + ])); + } +} diff --git a/app/Filament/Resources/Events/EventResource.php b/plugins-core/events/src/Filament/Resources/Events/EventResource.php similarity index 92% rename from app/Filament/Resources/Events/EventResource.php rename to plugins-core/events/src/Filament/Resources/Events/EventResource.php index 833860e2..f74d3349 100644 --- a/app/Filament/Resources/Events/EventResource.php +++ b/plugins-core/events/src/Filament/Resources/Events/EventResource.php @@ -1,11 +1,8 @@ columnSpan(1) ->schema([ + AudienceSection::make('event', 'Wer den Termin sieht. Leer lassen = alle.'), Toggle::make('is_published')->label('Veröffentlicht')->default(true), FileUpload::make('image_path') ->label('Bild') diff --git a/app/Filament/Resources/Events/Pages/CreateEvent.php b/plugins-core/events/src/Filament/Resources/Events/Pages/CreateEvent.php similarity index 69% rename from app/Filament/Resources/Events/Pages/CreateEvent.php rename to plugins-core/events/src/Filament/Resources/Events/Pages/CreateEvent.php index 84793412..75b17248 100644 --- a/app/Filament/Resources/Events/Pages/CreateEvent.php +++ b/plugins-core/events/src/Filament/Resources/Events/Pages/CreateEvent.php @@ -1,9 +1,9 @@ EventResource::collection( - Event::query()->upcoming()->limit(200)->get() + Event::query()->upcoming()->visibleTo(request()->user())->limit(200)->get() ), ]); } public function show(Event $event): Response { - abort_unless($event->is_published, 404); + abort_unless($event->is_published && $event->isVisibleTo(request()->user()), 404); - return Inertia::render('Events/Show', [ + return Inertia::render('events::Show', [ 'event' => [ ...(new EventResource($event))->resolve(), 'description_html' => $event->description_html, @@ -35,7 +36,7 @@ class EventController extends Controller public function ics(Event $event, Calendar $calendar, Branding $branding): HttpResponse { - abort_unless($event->is_published, 404); + abort_unless($event->is_published && $event->isVisibleTo(request()->user()), 404); return response($calendar->toIcs($event, $branding->portalName()), 200, [ 'Content-Type' => 'text/calendar; charset=utf-8', diff --git a/app/Http/Resources/EventResource.php b/plugins-core/events/src/Http/Resources/EventResource.php similarity index 89% rename from app/Http/Resources/EventResource.php rename to plugins-core/events/src/Http/Resources/EventResource.php index 34ed0f6b..2fd1b7c0 100644 --- a/app/Http/Resources/EventResource.php +++ b/plugins-core/events/src/Http/Resources/EventResource.php @@ -1,10 +1,10 @@ url($this->image_path, $variant); } + + /** + * Nur Termine, die diese Person sehen darf (Zielgruppe des Termins). + * + * @param Builder $query + */ + public function scopeVisibleTo(Builder $query, ?User $user): void + { + if ($user?->can('events.manage')) { + return; + } + + Audiences::constrain($query, 'event', 'events.id', $user); + } + + public function isVisibleTo(?User $user): bool + { + return (bool) $user?->can('events.manage') || Audiences::allows('event', $this->id, $user); + } } diff --git a/plugins-core/events/src/Policies/EventPolicy.php b/plugins-core/events/src/Policies/EventPolicy.php new file mode 100644 index 00000000..ee2148b3 --- /dev/null +++ b/plugins-core/events/src/Policies/EventPolicy.php @@ -0,0 +1,29 @@ +can('events.manage'); + } + + public function create(User $user): bool + { + return $user->can('events.manage'); + } + + public function update(User $user, Event $event): bool + { + return $user->can('events.manage'); + } + + public function delete(User $user, Event $event): bool + { + return $user->can('events.manage'); + } +} diff --git a/plugins-core/forms/database/migrations/2026_09_28_000002_create_forms_tables.php b/plugins-core/forms/database/migrations/2026_09_28_000002_create_forms_tables.php new file mode 100644 index 00000000..7ae396dc --- /dev/null +++ b/plugins-core/forms/database/migrations/2026_09_28_000002_create_forms_tables.php @@ -0,0 +1,57 @@ +id(); + $table->string('title'); + $table->string('slug', 120)->unique(); + $table->text('description')->nullable(); + $table->json('fields'); + $table->json('settings')->nullable(); + $table->boolean('is_open')->default(true); + $table->timestamp('closes_at')->nullable(); + $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete(); + $table->timestamps(); + }); + + Schema::create('form_submissions', function (Blueprint $table) { + $table->id(); + $table->foreignId('form_id')->constrained('forms')->cascadeOnDelete(); + // Bei anonymen Formularen leer; „nur einmal ausfüllen“ prüft dann user_hash. + $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete(); + $table->string('user_hash', 64)->nullable(); + $table->json('data'); + $table->timestamp('read_at')->nullable(); + $table->timestamps(); + + $table->index(['form_id', 'created_at']); + $table->index(['form_id', 'user_hash']); + $table->index(['form_id', 'user_id']); + }); + + Schema::create('form_files', function (Blueprint $table) { + $table->id(); + $table->foreignId('submission_id')->constrained('form_submissions')->cascadeOnDelete(); + $table->string('field', 80); + $table->string('name'); + $table->string('path'); + $table->string('mime', 150)->nullable(); + $table->unsignedBigInteger('size')->default(0); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('form_files'); + Schema::dropIfExists('form_submissions'); + Schema::dropIfExists('forms'); + } +}; diff --git a/plugins-core/forms/plugin.json b/plugins-core/forms/plugin.json new file mode 100644 index 00000000..0d1c1f80 --- /dev/null +++ b/plugins-core/forms/plugin.json @@ -0,0 +1,13 @@ +{ + "slug": "forms", + "name": "Formulare", + "version": "1.0.0", + "description": "Formulare zusammenstellen – Anträge, Anmeldungen, Umfragen, Meldungen. Ergebnisse per E-Mail und im Backend, Zugriff je Formular und Rolle.", + "author": "Inhaus", + "namespace": "Inhaus\\Plugins\\Forms\\", + "class": "Inhaus\\Plugins\\Forms\\FormsPlugin", + "requires": { + "core": ">=0.6.0", + "php": ">=8.3" + } +} diff --git a/plugins-core/forms/resources/js/blocks/FormBlock.vue b/plugins-core/forms/resources/js/blocks/FormBlock.vue new file mode 100644 index 00000000..4436a8ec --- /dev/null +++ b/plugins-core/forms/resources/js/blocks/FormBlock.vue @@ -0,0 +1,21 @@ + + + diff --git a/plugins-core/forms/resources/js/components/FormRenderer.vue b/plugins-core/forms/resources/js/components/FormRenderer.vue new file mode 100644 index 00000000..d78b10e0 --- /dev/null +++ b/plugins-core/forms/resources/js/components/FormRenderer.vue @@ -0,0 +1,218 @@ + + +