Plugin-System; Neuigkeiten und Termine als mitgelieferte Plugins
- Plugins nach WordPress-Prinzip: plugin.json-Manifest mit Versions- und Abhängigkeitsprüfung, eigenes PSR-4-Autoloading, register()/boot(), activate()/deactivate()/uninstall(), Migrationen, Routen und Views je Plugin - plugins-core/ (mitgeliefert, aktiv bis zur Deaktivierung) und plugins/ (Kunden-Plugins, geschützt vor Updates, inaktiv bis zur Aktivierung) - Zustand in storage/app/plugins.json – Laden ohne Datenbankabfrage - Wiederherstellungsmodus: Ausnahmen und Fatal Errors beim Laden deaktivieren das Plugin, das Portal bleibt erreichbar - Hooks (Actions/Filter mit Prioritäten) und Registries für Navigation, Startseiten-Kacheln, Rechte und Admin-Seiten (Filament-Discovery) - Admin-Seite „Plugins“: aktivieren, deaktivieren, per ZIP installieren (ZIP-Slip-Schutz), löschen mit oder ohne Daten; abschaltbar per INHAUS_DISALLOW_FILE_MODS - Startseite komplett aus Kacheln; Plugin-Seiten als „slug::Seite“ - Version 0.3.0 Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
cc0020458f
commit
28ef1e4a20
155 changed files with 2762 additions and 573 deletions
47
app/Dashboard/CoreWidgets.php
Normal file
47
app/Dashboard/CoreWidgets.php
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
<?php
|
||||
|
||||
namespace App\Dashboard;
|
||||
|
||||
use App\Http\Resources\PersonResource;
|
||||
use App\Models\User;
|
||||
use App\Support\QuickLinks;
|
||||
|
||||
/**
|
||||
* Kacheln des Kerns. Plugins ergänzen weitere über App\Dashboard\Widgets.
|
||||
*/
|
||||
class CoreWidgets
|
||||
{
|
||||
public static function register(Widgets $widgets): void
|
||||
{
|
||||
$widgets->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),
|
||||
],
|
||||
], mobileSort: 0);
|
||||
|
||||
$widgets->add('core.quick-links', 'core::QuickLinks', 'main', sort: 10, props: fn () => [
|
||||
'links' => app(QuickLinks::class)->all(),
|
||||
], 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()];
|
||||
}, mobileSort: 60);
|
||||
|
||||
$widgets->add('core.profile-incomplete', 'core::ProfileIncomplete', 'aside', sort: 50, props: fn (User $user) => $user->avatar_path && $user->job_title ? null : [], mobileSort: 70);
|
||||
|
||||
$widgets->add('core.people-search', 'core::PeopleSearch', 'aside', sort: 60, props: fn () => [
|
||||
'count' => User::query()->active()->count(),
|
||||
], mobileSort: 80);
|
||||
}
|
||||
}
|
||||
72
app/Dashboard/Widgets.php
Normal file
72
app/Dashboard/Widgets.php
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
<?php
|
||||
|
||||
namespace App\Dashboard;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Kacheln der Startseite als Registry.
|
||||
*
|
||||
* Bereiche (siehe resources/js/pages/Dashboard.vue):
|
||||
* hero – groß links oben (z. B. Slider) feed – neben hero
|
||||
* main – volle Breite der linken Spalte aside – rechte Spalte
|
||||
*
|
||||
* Die Props-Funktion liefert die Daten der Kachel oder null, wenn sie für
|
||||
* diese Person nichts anzuzeigen hat.
|
||||
*/
|
||||
class Widgets
|
||||
{
|
||||
public const AREAS = ['hero', 'feed', 'main', 'aside'];
|
||||
|
||||
/** @var array<string, array{component: string, area: string, sort: int, mobileSort: int, props: callable}> */
|
||||
private array $widgets = [];
|
||||
|
||||
/**
|
||||
* @param string $component Vue-Komponente, z. B. „core::QuickLinks“ oder „news::Hero“
|
||||
* @param callable(User, Request): (array<string, mixed>|null) $props
|
||||
* @param int|null $mobileSort Reihenfolge in der einspaltigen Mobilansicht (Standard: nach Bereich)
|
||||
*/
|
||||
public function add(string $key, string $component, string $area, int $sort, callable $props, ?int $mobileSort = null): void
|
||||
{
|
||||
if (! in_array($area, self::AREAS, true)) {
|
||||
throw new \InvalidArgumentException("Unbekannter Bereich „{$area}“ für Kachel {$key}.");
|
||||
}
|
||||
|
||||
$mobileSort ??= ['hero' => 10, 'feed' => 20, 'aside' => 30, 'main' => 50][$area] + $sort;
|
||||
|
||||
$this->widgets[$key] = compact('component', 'area', 'sort', 'mobileSort', 'props');
|
||||
}
|
||||
|
||||
public function remove(string $key): void
|
||||
{
|
||||
unset($this->widgets[$key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{key: string, component: string, area: string, mobileSort: int, props: array<string, mixed>}>
|
||||
*/
|
||||
public function resolve(User $user, Request $request): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach (collect($this->widgets)->sortBy('sort') as $key => $widget) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
102
app/Filament/Pages/Plugins.php
Normal file
102
app/Filament/Pages/Plugins.php
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Plugins\PluginInstaller;
|
||||
use App\Plugins\PluginManager;
|
||||
use App\Plugins\PluginManifest;
|
||||
use BackedEnum;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
|
||||
use Livewire\WithFileUploads;
|
||||
use Throwable;
|
||||
use UnitEnum;
|
||||
|
||||
class Plugins extends Page
|
||||
{
|
||||
use WithFileUploads;
|
||||
|
||||
protected string $view = 'filament.pages.plugins';
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedPuzzlePiece;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'System';
|
||||
|
||||
protected static ?int $navigationSort = 5;
|
||||
|
||||
protected static ?string $title = 'Plugins';
|
||||
|
||||
protected static ?string $slug = 'plugins';
|
||||
|
||||
/** @var TemporaryUploadedFile|null */
|
||||
public $archive = null;
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return auth()->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<string, mixed>
|
||||
*/
|
||||
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(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,140 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Events;
|
||||
|
||||
use App\Filament\Resources\Events\Pages\CreateEvent;
|
||||
use App\Filament\Resources\Events\Pages\EditEvent;
|
||||
use App\Filament\Resources\Events\Pages\ListEvents;
|
||||
use App\Models\Event;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\DateTimePicker;
|
||||
use Filament\Forms\Components\FileUpload;
|
||||
use Filament\Forms\Components\RichEditor;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\IconColumn;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\TernaryFilter;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use UnitEnum;
|
||||
|
||||
class EventResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Event::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCalendarDays;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Inhalte';
|
||||
|
||||
protected static ?int $navigationSort = 3;
|
||||
|
||||
protected static ?string $modelLabel = 'Termin';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Termine';
|
||||
|
||||
protected static ?string $slug = 'termine';
|
||||
|
||||
protected static ?string $recordTitleAttribute = 'title';
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->columns(3)
|
||||
->components([
|
||||
Section::make('Termin')
|
||||
->columnSpan(2)
|
||||
->columns(2)
|
||||
->schema([
|
||||
TextInput::make('title')->label('Titel')->required()->maxLength(160)->columnSpanFull(),
|
||||
Toggle::make('all_day')->label('Ganztägig')->live()->columnSpanFull(),
|
||||
DateTimePicker::make('starts_at')
|
||||
->label('Beginn')
|
||||
->required()
|
||||
->seconds(false)
|
||||
->native(false)
|
||||
->time(fn (Get $get) => ! $get('all_day'))
|
||||
->displayFormat(fn (Get $get) => $get('all_day') ? 'd.m.Y' : 'd.m.Y H:i'),
|
||||
DateTimePicker::make('ends_at')
|
||||
->label('Ende')
|
||||
->seconds(false)
|
||||
->native(false)
|
||||
->time(fn (Get $get) => ! $get('all_day'))
|
||||
->displayFormat(fn (Get $get) => $get('all_day') ? 'd.m.Y' : 'd.m.Y H:i')
|
||||
->afterOrEqual('starts_at'),
|
||||
TextInput::make('location')->label('Ort')->maxLength(255),
|
||||
TextInput::make('online_url')->label('Online-Link')->url()->maxLength(500)->placeholder('https://…'),
|
||||
RichEditor::make('description')
|
||||
->label('Beschreibung')
|
||||
->toolbarButtons([
|
||||
['bold', 'italic', 'link'],
|
||||
['bulletList', 'orderedList'],
|
||||
['undo', 'redo'],
|
||||
])
|
||||
->columnSpanFull(),
|
||||
]),
|
||||
Section::make('Anzeige')
|
||||
->columnSpan(1)
|
||||
->schema([
|
||||
Toggle::make('is_published')->label('Veröffentlicht')->default(true),
|
||||
FileUpload::make('image_path')
|
||||
->label('Bild')
|
||||
->helperText('Optional, Querformat.')
|
||||
->image()
|
||||
->disk('uploads')
|
||||
->directory('events')
|
||||
->visibility('public')
|
||||
->imageAspectRatio('16:9')
|
||||
->automaticallyCropImagesToAspectRatio()
|
||||
->maxSize(10 * 1024),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('starts_at')
|
||||
->columns([
|
||||
TextColumn::make('starts_at')
|
||||
->label('Datum')
|
||||
->formatStateUsing(fn (Event $record) => $record->starts_at->format($record->all_day ? 'd.m.Y' : 'd.m.Y H:i'))
|
||||
->sortable(),
|
||||
TextColumn::make('title')->label('Titel')->searchable()->limit(60)->weight('medium'),
|
||||
TextColumn::make('location')->label('Ort')->limit(40)->toggleable(),
|
||||
IconColumn::make('is_published')->label('Veröffentlicht')->boolean(),
|
||||
])
|
||||
->filters([
|
||||
TernaryFilter::make('upcoming')
|
||||
->label('Zeitraum')
|
||||
->placeholder('Alle')
|
||||
->trueLabel('Anstehende')
|
||||
->falseLabel('Vergangene')
|
||||
->default(true)
|
||||
->queries(
|
||||
true: fn (Builder $query) => $query->where(fn ($q) => $q->where('ends_at', '>=', now())->orWhere(fn ($q) => $q->whereNull('ends_at')->where('starts_at', '>=', now()->startOfDay()))),
|
||||
false: fn (Builder $query) => $query->where(fn ($q) => $q->where('ends_at', '<', now())->orWhere(fn ($q) => $q->whereNull('ends_at')->where('starts_at', '<', now()->startOfDay()))),
|
||||
),
|
||||
])
|
||||
->recordActions([
|
||||
EditAction::make(),
|
||||
DeleteAction::make(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListEvents::route('/'),
|
||||
'create' => CreateEvent::route('/neu'),
|
||||
'edit' => EditEvent::route('/{record}/bearbeiten'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Events\Pages;
|
||||
|
||||
use App\Filament\Resources\Events\EventResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateEvent extends CreateRecord
|
||||
{
|
||||
protected static string $resource = EventResource::class;
|
||||
|
||||
protected function mutateFormDataBeforeCreate(array $data): array
|
||||
{
|
||||
$data['author_id'] = auth()->id();
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Events\Pages;
|
||||
|
||||
use App\Filament\Resources\Events\EventResource;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditEvent extends EditRecord
|
||||
{
|
||||
protected static string $resource = EventResource::class;
|
||||
}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Events\Pages;
|
||||
|
||||
use App\Filament\Resources\Events\EventResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListEvents extends ListRecords
|
||||
{
|
||||
protected static string $resource = EventResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make()->label('Neuer Termin'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\NewsCategories;
|
||||
|
||||
use App\Filament\Resources\NewsCategories\Pages\ManageNewsCategories;
|
||||
use App\Models\NewsCategory;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Utilities\Set;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Support\Str;
|
||||
use UnitEnum;
|
||||
|
||||
class NewsCategoryResource extends Resource
|
||||
{
|
||||
protected static ?string $model = NewsCategory::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedTag;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Inhalte';
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
|
||||
protected static ?string $modelLabel = 'Kategorie';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Kategorien';
|
||||
|
||||
protected static ?string $slug = 'kategorien';
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components([
|
||||
TextInput::make('name')
|
||||
->label('Name')
|
||||
->required()
|
||||
->maxLength(60)
|
||||
->live(onBlur: true)
|
||||
->afterStateUpdated(fn (?string $state, Set $set, string $operation) => $operation === 'create' ? $set('slug', Str::slug((string) $state, language: 'de')) : null),
|
||||
TextInput::make('slug')
|
||||
->label('Kürzel in der Adresse')
|
||||
->required()
|
||||
->maxLength(80)
|
||||
->alphaDash()
|
||||
->unique(ignoreRecord: true),
|
||||
TextInput::make('description')->label('Beschreibung')->maxLength(500)->columnSpanFull(),
|
||||
TextInput::make('sort')->label('Reihenfolge')->numeric()->default(0),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('sort')
|
||||
->reorderable('sort')
|
||||
->columns([
|
||||
TextColumn::make('name')->label('Name')->searchable(),
|
||||
TextColumn::make('slug')->label('Kürzel')->color('gray'),
|
||||
TextColumn::make('posts_count')->label('Beiträge')->counts('posts'),
|
||||
])
|
||||
->recordActions([
|
||||
EditAction::make(),
|
||||
DeleteAction::make(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ManageNewsCategories::route('/'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\NewsCategories\Pages;
|
||||
|
||||
use App\Filament\Resources\NewsCategories\NewsCategoryResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ManageRecords;
|
||||
|
||||
class ManageNewsCategories extends ManageRecords
|
||||
{
|
||||
protected static string $resource = NewsCategoryResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,156 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\NewsPosts;
|
||||
|
||||
use App\Filament\Resources\NewsPosts\Pages\CreateNewsPost;
|
||||
use App\Filament\Resources\NewsPosts\Pages\EditNewsPost;
|
||||
use App\Filament\Resources\NewsPosts\Pages\ListNewsPosts;
|
||||
use App\Models\NewsPost;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\DateTimePicker;
|
||||
use Filament\Forms\Components\FileUpload;
|
||||
use Filament\Forms\Components\RichEditor;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\IconColumn;
|
||||
use Filament\Tables\Columns\ImageColumn;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Filament\Tables\Table;
|
||||
use UnitEnum;
|
||||
|
||||
class NewsPostResource extends Resource
|
||||
{
|
||||
protected static ?string $model = NewsPost::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedNewspaper;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Inhalte';
|
||||
|
||||
protected static ?int $navigationSort = 1;
|
||||
|
||||
protected static ?string $modelLabel = 'Beitrag';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Neuigkeiten';
|
||||
|
||||
protected static ?string $slug = 'neuigkeiten';
|
||||
|
||||
protected static ?string $recordTitleAttribute = 'title';
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->columns(3)
|
||||
->components([
|
||||
Section::make('Beitrag')
|
||||
->columnSpan(2)
|
||||
->schema([
|
||||
TextInput::make('title')->label('Titel')->required()->maxLength(160),
|
||||
Textarea::make('teaser')
|
||||
->label('Kurztext')
|
||||
->helperText('Erscheint in Listen und auf der Startseite. 1–2 Sätze.')
|
||||
->rows(2)
|
||||
->maxLength(300),
|
||||
RichEditor::make('body')
|
||||
->label('Text')
|
||||
->toolbarButtons([
|
||||
['bold', 'italic', 'underline', 'link'],
|
||||
['h2', 'h3'],
|
||||
['bulletList', 'orderedList', 'blockquote'],
|
||||
['attachFiles', 'table'],
|
||||
['undo', 'redo'],
|
||||
])
|
||||
->fileAttachmentsDisk('uploads')
|
||||
->fileAttachmentsDirectory('news/inline')
|
||||
->fileAttachmentsVisibility('public')
|
||||
->fileAttachmentsAcceptedFileTypes(['image/jpeg', 'image/png', 'image/webp'])
|
||||
->fileAttachmentsMaxSize(8 * 1024),
|
||||
]),
|
||||
Section::make('Veröffentlichung')
|
||||
->columnSpan(1)
|
||||
->schema([
|
||||
Select::make('category_id')
|
||||
->label('Kategorie')
|
||||
->relationship('category', 'name')
|
||||
->preload()
|
||||
->searchable(),
|
||||
DateTimePicker::make('published_at')
|
||||
->label('Veröffentlichen am')
|
||||
->helperText('Leer lassen = Entwurf. Ein Datum in der Zukunft plant den Beitrag.')
|
||||
->seconds(false)
|
||||
->native(false)
|
||||
->displayFormat('d.m.Y H:i'),
|
||||
Toggle::make('is_featured')
|
||||
->label('Auf der Startseite hervorheben')
|
||||
->helperText('Hervorgehobene Beiträge mit Titelbild erscheinen groß im Slider.'),
|
||||
FileUpload::make('cover_path')
|
||||
->label('Titelbild')
|
||||
->helperText('Querformat, mindestens 1600 × 900 Pixel.')
|
||||
->image()
|
||||
->disk('uploads')
|
||||
->directory('news')
|
||||
->visibility('public')
|
||||
->imageAspectRatio('16:9')
|
||||
->automaticallyCropImagesToAspectRatio()
|
||||
->maxSize(10 * 1024),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('created_at', 'desc')
|
||||
->columns([
|
||||
ImageColumn::make('cover_path')->label('')->disk('uploads')->width(80)->height(45),
|
||||
TextColumn::make('title')->label('Titel')->searchable()->limit(60)->weight('medium'),
|
||||
TextColumn::make('category.name')->label('Kategorie')->badge()->color('gray'),
|
||||
TextColumn::make('status')
|
||||
->label('Status')
|
||||
->badge()
|
||||
->state(fn (NewsPost $record) => match (true) {
|
||||
$record->published_at === null => 'Entwurf',
|
||||
$record->published_at->isFuture() => 'Geplant',
|
||||
default => 'Veröffentlicht',
|
||||
})
|
||||
->color(fn (string $state) => match ($state) {
|
||||
'Veröffentlicht' => 'success',
|
||||
'Geplant' => 'warning',
|
||||
default => 'gray',
|
||||
}),
|
||||
IconColumn::make('is_featured')->label('Hervorgehoben')->boolean()->trueIcon(Heroicon::Star)->falseIcon(false)->trueColor('warning'),
|
||||
TextColumn::make('published_at')->label('Veröffentlicht')->dateTime('d.m.Y H:i')->sortable(),
|
||||
])
|
||||
->filters([
|
||||
SelectFilter::make('category_id')->label('Kategorie')->relationship('category', 'name'),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('view')
|
||||
->label('Ansehen')
|
||||
->icon(Heroicon::OutlinedEye)
|
||||
->url(fn (NewsPost $record) => route('news.show', $record))
|
||||
->openUrlInNewTab()
|
||||
->visible(fn (NewsPost $record) => $record->isPublished()),
|
||||
EditAction::make(),
|
||||
DeleteAction::make(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListNewsPosts::route('/'),
|
||||
'create' => CreateNewsPost::route('/neu'),
|
||||
'edit' => EditNewsPost::route('/{record}/bearbeiten'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\NewsPosts\Pages;
|
||||
|
||||
use App\Filament\Resources\NewsPosts\NewsPostResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateNewsPost extends CreateRecord
|
||||
{
|
||||
protected static string $resource = NewsPostResource::class;
|
||||
|
||||
protected function mutateFormDataBeforeCreate(array $data): array
|
||||
{
|
||||
$data['author_id'] = auth()->id();
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\NewsPosts\Pages;
|
||||
|
||||
use App\Filament\Resources\NewsPosts\NewsPostResource;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditNewsPost extends EditRecord
|
||||
{
|
||||
protected static string $resource = NewsPostResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
DeleteAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Filament\Resources\NewsPosts\Pages;
|
||||
|
||||
use App\Filament\Resources\NewsPosts\NewsPostResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListNewsPosts extends ListRecords
|
||||
{
|
||||
protected static string $resource = NewsPostResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make()->label('Neuer Beitrag'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -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),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,45 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Http\Resources\EventResource;
|
||||
use App\Models\Event;
|
||||
use App\Support\Branding;
|
||||
use App\Support\Calendar;
|
||||
use Illuminate\Http\Response as HttpResponse;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class EventController extends Controller
|
||||
{
|
||||
public function index(): Response
|
||||
{
|
||||
return Inertia::render('Events/Index', [
|
||||
'events' => EventResource::collection(
|
||||
Event::query()->upcoming()->limit(200)->get()
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
public function show(Event $event): Response
|
||||
{
|
||||
abort_unless($event->is_published, 404);
|
||||
|
||||
return Inertia::render('Events/Show', [
|
||||
'event' => [
|
||||
...(new EventResource($event))->resolve(),
|
||||
'description_html' => $event->description_html,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function ics(Event $event, Calendar $calendar, Branding $branding): HttpResponse
|
||||
{
|
||||
abort_unless($event->is_published, 404);
|
||||
|
||||
return response($calendar->toIcs($event, $branding->portalName()), 200, [
|
||||
'Content-Type' => 'text/calendar; charset=utf-8',
|
||||
'Content-Disposition' => 'attachment; filename="termin-'.$event->id.'.ics"',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Http\Resources\NewsPostResource;
|
||||
use App\Models\NewsCategory;
|
||||
use App\Models\NewsPost;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class NewsController extends Controller
|
||||
{
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$categories = NewsCategory::query()->orderBy('sort')->orderBy('name')->get(['id', 'name', 'slug']);
|
||||
$category = $categories->firstWhere('slug', $request->query('kategorie'));
|
||||
|
||||
$posts = NewsPost::query()
|
||||
->published()
|
||||
->with('category')
|
||||
->when($category, fn ($query) => $query->where('category_id', $category->id))
|
||||
->latest('published_at')
|
||||
->paginate(12)
|
||||
->withQueryString();
|
||||
|
||||
return Inertia::render('News/Index', [
|
||||
'posts' => NewsPostResource::collection($posts),
|
||||
'categories' => $categories->map(fn (NewsCategory $c) => ['name' => $c->name, 'slug' => $c->slug]),
|
||||
'activeCategory' => $category?->slug,
|
||||
]);
|
||||
}
|
||||
|
||||
public function show(NewsPost $post): Response
|
||||
{
|
||||
abort_unless($post->isPublished(), 404);
|
||||
|
||||
$post->load(['category', 'author']);
|
||||
|
||||
return Inertia::render('News/Show', [
|
||||
'post' => [
|
||||
...(new NewsPostResource($post))->resolve(),
|
||||
'body_html' => $post->body_html,
|
||||
'author' => $post->author ? [
|
||||
'id' => $post->author->id,
|
||||
'name' => $post->author->name,
|
||||
'initials' => $post->author->initials,
|
||||
'job_title' => $post->author->job_title,
|
||||
'avatar_url' => $post->author->avatarUrl(96),
|
||||
] : null,
|
||||
],
|
||||
'related' => NewsPostResource::collection(
|
||||
NewsPost::query()
|
||||
->published()
|
||||
->with('category')
|
||||
->whereKeyNot($post->id)
|
||||
->when($post->category_id, fn ($query) => $query->where('category_id', $post->category_id))
|
||||
->latest('published_at')
|
||||
->limit(3)
|
||||
->get()
|
||||
),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Models\Event;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @mixin Event
|
||||
*/
|
||||
class EventResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'title' => $this->title,
|
||||
'location' => $this->location,
|
||||
'online_url' => $this->online_url,
|
||||
'starts_at' => $this->starts_at->toIso8601String(),
|
||||
'ends_at' => $this->ends_at?->toIso8601String(),
|
||||
'all_day' => $this->all_day,
|
||||
'image_url' => $this->imageUrl('large'),
|
||||
'thumb_url' => $this->imageUrl('thumb'),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Resources;
|
||||
|
||||
use App\Models\NewsPost;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @mixin NewsPost
|
||||
*/
|
||||
class NewsPostResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'title' => $this->title,
|
||||
'slug' => $this->slug,
|
||||
'teaser' => $this->teaser,
|
||||
'category' => $this->whenLoaded('category', fn () => $this->category ? [
|
||||
'name' => $this->category->name,
|
||||
'slug' => $this->category->slug,
|
||||
] : null),
|
||||
'cover_url' => $this->coverUrl('large'),
|
||||
'thumb_url' => $this->coverUrl('thumb'),
|
||||
'published_at' => $this->published_at?->toIso8601String(),
|
||||
'reading_minutes' => $this->reading_minutes,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,85 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Support\Images;
|
||||
use App\Support\RichText;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable([
|
||||
'author_id', 'title', 'description', 'location', 'online_url',
|
||||
'starts_at', 'ends_at', 'all_day', 'image_path', 'is_published',
|
||||
])]
|
||||
class Event extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::saving(function (Event $event): void {
|
||||
if ($event->isDirty('description') || $event->description_html === null) {
|
||||
$event->description_html = app(RichText::class)->toSafeHtml($event->description);
|
||||
}
|
||||
});
|
||||
|
||||
// Bildvarianten erzeugen bzw. beim Austausch die alten Dateien entfernen.
|
||||
static::saved(function (Event $event): void {
|
||||
if (! $event->wasRecentlyCreated && ! $event->wasChanged('image_path')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$previous = $event->wasRecentlyCreated ? null : $event->getOriginal('image_path');
|
||||
|
||||
if ($previous && $previous !== $event->image_path) {
|
||||
app(Images::class)->deleteWithVariants($previous);
|
||||
}
|
||||
|
||||
if ($event->image_path) {
|
||||
app(Images::class)->createVariants($event->image_path);
|
||||
}
|
||||
});
|
||||
|
||||
static::deleted(fn (Event $event) => app(Images::class)->deleteWithVariants($event->image_path));
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'starts_at' => 'datetime',
|
||||
'ends_at' => 'datetime',
|
||||
'all_day' => 'boolean',
|
||||
'is_published' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
public function author(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Veröffentlichte Termine, die noch nicht vorbei sind (laufende eingeschlossen).
|
||||
*
|
||||
* @param Builder<Event> $query
|
||||
*/
|
||||
public function scopeUpcoming(Builder $query): void
|
||||
{
|
||||
$query->where('is_published', true)
|
||||
->where(fn (Builder $q) => $q
|
||||
->where('ends_at', '>=', now())
|
||||
->orWhere(fn (Builder $q) => $q->whereNull('ends_at')->where('starts_at', '>=', now()->startOfDay())))
|
||||
->orderBy('starts_at');
|
||||
}
|
||||
|
||||
public function imageUrl(string $variant = 'large'): ?string
|
||||
{
|
||||
return app(Images::class)->url($this->image_path, $variant);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable(['name', 'slug', 'description', 'sort'])]
|
||||
class NewsCategory extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
/**
|
||||
* @return HasMany<NewsPost, $this>
|
||||
*/
|
||||
public function posts(): HasMany
|
||||
{
|
||||
return $this->hasMany(NewsPost::class, 'category_id');
|
||||
}
|
||||
}
|
||||
|
|
@ -1,111 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Support\Images;
|
||||
use App\Support\RichText;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
#[Fillable([
|
||||
'category_id', 'author_id', 'title', 'slug', 'teaser', 'body',
|
||||
'cover_path', 'is_featured', 'published_at',
|
||||
])]
|
||||
class NewsPost extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::saving(function (NewsPost $post): void {
|
||||
if (blank($post->slug)) {
|
||||
$post->slug = static::uniqueSlug($post->title, $post->getKey());
|
||||
}
|
||||
|
||||
if ($post->isDirty('body') || $post->body_html === null) {
|
||||
$richText = app(RichText::class);
|
||||
$post->body_html = $richText->toSafeHtml($post->body);
|
||||
$post->reading_minutes = $richText->readingMinutes($post->body_html);
|
||||
}
|
||||
});
|
||||
|
||||
// Bildvarianten erzeugen bzw. beim Austausch die alten Dateien entfernen.
|
||||
static::saved(function (NewsPost $post): void {
|
||||
if (! $post->wasRecentlyCreated && ! $post->wasChanged('cover_path')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$previous = $post->wasRecentlyCreated ? null : $post->getOriginal('cover_path');
|
||||
|
||||
if ($previous && $previous !== $post->cover_path) {
|
||||
app(Images::class)->deleteWithVariants($previous);
|
||||
}
|
||||
|
||||
if ($post->cover_path) {
|
||||
app(Images::class)->createVariants($post->cover_path);
|
||||
}
|
||||
});
|
||||
|
||||
static::deleted(fn (NewsPost $post) => app(Images::class)->deleteWithVariants($post->cover_path));
|
||||
}
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'is_featured' => 'boolean',
|
||||
'published_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<NewsCategory, $this>
|
||||
*/
|
||||
public function category(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(NewsCategory::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
public function author(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Veröffentlicht = Veröffentlichungsdatum gesetzt und erreicht.
|
||||
*
|
||||
* @param Builder<NewsPost> $query
|
||||
*/
|
||||
public function scopePublished(Builder $query): void
|
||||
{
|
||||
$query->whereNotNull('published_at')->where('published_at', '<=', now());
|
||||
}
|
||||
|
||||
public function isPublished(): bool
|
||||
{
|
||||
return $this->published_at !== null && $this->published_at->isPast();
|
||||
}
|
||||
|
||||
public function coverUrl(string $variant = 'large'): ?string
|
||||
{
|
||||
return app(Images::class)->url($this->cover_path, $variant);
|
||||
}
|
||||
|
||||
public static function uniqueSlug(string $title, ?int $ignoreId = null): string
|
||||
{
|
||||
$base = Str::slug($title, language: 'de') ?: 'beitrag';
|
||||
$slug = $base;
|
||||
|
||||
for ($i = 2; static::query()->where('slug', $slug)->when($ignoreId, fn ($q) => $q->whereKeyNot($ignoreId))->exists(); $i++) {
|
||||
$slug = "{$base}-{$i}";
|
||||
}
|
||||
|
||||
return $slug;
|
||||
}
|
||||
}
|
||||
67
app/Plugins/Hooks.php
Normal file
67
app/Plugins/Hooks.php
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
<?php
|
||||
|
||||
namespace App\Plugins;
|
||||
|
||||
/**
|
||||
* Actions und Filter nach WordPress-Vorbild.
|
||||
*
|
||||
* Hooks::on('post.published', fn (NewsPost $post) => …); // 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<string, array<int, list<callable>>> */
|
||||
private array $actions = [];
|
||||
|
||||
/** @var array<string, array<int, list<callable>>> */
|
||||
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<int, list<callable>> $byPriority
|
||||
* @return list<callable>
|
||||
*/
|
||||
private function sorted(array $byPriority): array
|
||||
{
|
||||
ksort($byPriority);
|
||||
|
||||
return array_merge(...array_values($byPriority) ?: [[]]);
|
||||
}
|
||||
}
|
||||
39
app/Plugins/Plugin.php
Normal file
39
app/Plugins/Plugin.php
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
<?php
|
||||
|
||||
namespace App\Plugins;
|
||||
|
||||
use Illuminate\Contracts\Foundation\Application;
|
||||
|
||||
/**
|
||||
* Basisklasse für Plugins – mitgelieferte wie vom Kunden installierte.
|
||||
*
|
||||
* register(): Dienste binden, Navigation/Kacheln/Rechte registrieren (früh, vor boot).
|
||||
* boot(): Hooks, Routen, Views – alles, was andere Dienste braucht.
|
||||
* activate()/deactivate()/uninstall(): Lebenszyklus, vom Admin ausgelöst.
|
||||
*/
|
||||
abstract class Plugin
|
||||
{
|
||||
public function __construct(
|
||||
protected readonly Application $app,
|
||||
public readonly PluginManifest $manifest,
|
||||
) {}
|
||||
|
||||
public function register(): void {}
|
||||
|
||||
public function boot(): void {}
|
||||
|
||||
public function activate(): void {}
|
||||
|
||||
public function deactivate(): void {}
|
||||
|
||||
/**
|
||||
* Beim Löschen mit „Daten entfernen“. Die Tabellen aus den Migrationen des
|
||||
* Plugins entfernt der Kern selbst.
|
||||
*/
|
||||
public function uninstall(): void {}
|
||||
|
||||
protected function path(string $path = ''): string
|
||||
{
|
||||
return $this->manifest->path.($path !== '' ? '/'.ltrim($path, '/') : '');
|
||||
}
|
||||
}
|
||||
75
app/Plugins/PluginInstaller.php
Normal file
75
app/Plugins/PluginInstaller.php
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
<?php
|
||||
|
||||
namespace App\Plugins;
|
||||
|
||||
use App\Support\Audit;
|
||||
use App\Support\Update\Filesystem;
|
||||
use App\Support\Update\ZipExtractor;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Installiert Kunden-Plugins aus einem ZIP-Archiv nach plugins/<slug>.
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
411
app/Plugins/PluginManager.php
Normal file
411
app/Plugins/PluginManager.php
Normal file
|
|
@ -0,0 +1,411 @@
|
|||
<?php
|
||||
|
||||
namespace App\Plugins;
|
||||
|
||||
use App\Support\Audit;
|
||||
use App\Support\Update\Filesystem;
|
||||
use Illuminate\Contracts\Foundation\Application;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Findet, lädt und verwaltet Plugins.
|
||||
*
|
||||
* plugins-core/<slug>/ mitgeliefert (Teil jedes Updates)
|
||||
* plugins/<slug>/ 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<string, PluginManifest>|null */
|
||||
private ?array $manifests = null;
|
||||
|
||||
/** @var array<string, Plugin> */
|
||||
private array $loaded = [];
|
||||
|
||||
/** @var array<string, string> Slug => Grund */
|
||||
private array $problems = [];
|
||||
|
||||
/** @var array<string, bool> */
|
||||
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<string, PluginManifest>
|
||||
*/
|
||||
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<string, Plugin>
|
||||
*/
|
||||
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<PluginManifest>
|
||||
*/
|
||||
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<string>
|
||||
*/
|
||||
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<array{type: string, path: string, namespace: string}>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
128
app/Plugins/PluginManifest.php
Normal file
128
app/Plugins/PluginManifest.php
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
<?php
|
||||
|
||||
namespace App\Plugins;
|
||||
|
||||
use App\Version;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Inhalt einer plugin.json.
|
||||
*
|
||||
* {
|
||||
* "slug": "mav-kalender",
|
||||
* "name": "MAV-Kalender",
|
||||
* "version": "1.0.0",
|
||||
* "description": "…",
|
||||
* "author": "…",
|
||||
* "namespace": "Acme\\MavKalender\\",
|
||||
* "class": "Acme\\MavKalender\\Plugin",
|
||||
* "requires": { "core": ">=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<string, mixed> $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 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<string, mixed> $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,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
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<string>
|
||||
*/
|
||||
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';
|
||||
}
|
||||
}
|
||||
80
app/Plugins/PluginState.php
Normal file
80
app/Plugins/PluginState.php
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
<?php
|
||||
|
||||
namespace App\Plugins;
|
||||
|
||||
use App\Support\Update\AtomicFile;
|
||||
|
||||
/**
|
||||
* Aktivierungszustand der Plugins in storage/app/plugins.json – als Datei, damit
|
||||
* das Laden der Plugins keine Datenbankabfrage kostet und auch ohne DB klappt.
|
||||
* Mitgelieferte Plugins sind aktiv, solange nichts anderes vermerkt ist.
|
||||
*/
|
||||
class PluginState
|
||||
{
|
||||
/** @var array<string, array<string, mixed>>|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;
|
||||
}
|
||||
|
||||
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<string, array<string, mixed>>
|
||||
*/
|
||||
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<string, mixed> $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<string, array<string, mixed>> $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');
|
||||
}
|
||||
}
|
||||
58
app/Plugins/VersionConstraint.php
Normal file
58
app/Plugins/VersionConstraint.php
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
<?php
|
||||
|
||||
namespace App\Plugins;
|
||||
|
||||
/**
|
||||
* Einfache Versionsbedingungen für Plugin-Manifeste: „>=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));
|
||||
}
|
||||
}
|
||||
|
|
@ -2,13 +2,14 @@
|
|||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Dashboard\CoreWidgets;
|
||||
use App\Dashboard\Widgets;
|
||||
use App\Models\User;
|
||||
use App\Support\Avatars;
|
||||
use App\Support\BackgroundTasks;
|
||||
use App\Support\Branding;
|
||||
use App\Support\Installation;
|
||||
use App\Support\License\LicenseStore;
|
||||
use App\Support\Navigation;
|
||||
use App\Support\QuickLinks;
|
||||
use App\Support\Settings;
|
||||
use App\Support\Update\InstalledVersion;
|
||||
|
|
@ -36,7 +37,6 @@ class AppServiceProvider extends ServiceProvider
|
|||
$this->app->singleton(Settings::class);
|
||||
$this->app->singleton(Branding::class);
|
||||
$this->app->singleton(Avatars::class);
|
||||
$this->app->singleton(Navigation::class);
|
||||
$this->app->singleton(QuickLinks::class);
|
||||
$this->app->singleton(LicenseStore::class);
|
||||
$this->app->singleton(BackgroundTasks::class);
|
||||
|
|
@ -47,11 +47,14 @@ class AppServiceProvider extends ServiceProvider
|
|||
|
||||
public function boot(): void
|
||||
{
|
||||
CoreWidgets::register($this->app->make(Widgets::class));
|
||||
|
||||
// N+1-Abfragen in Entwicklung und Tests sofort sichtbar machen (docs/PLAN.md, Performance).
|
||||
Model::preventLazyLoading(! $this->app->isProduction());
|
||||
|
||||
// Vorläufig: Administratoren über is_admin – wird in Phase 2 durch Rollen ersetzt.
|
||||
Gate::define('admin', fn (User $user) => $user->is_admin && $user->is_active);
|
||||
Gate::before(fn (User $user) => $user->is_admin && $user->is_active ? true : null);
|
||||
|
||||
Password::defaults(fn () => Password::min(10)->letters()->numbers());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ namespace App\Providers\Filament;
|
|||
|
||||
use App\Filament\AvatarProviders\InitialsAvatarProvider;
|
||||
use App\Filament\Pages\Feedback;
|
||||
use App\Plugins\PluginManager;
|
||||
use App\Support\Branding;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Http\Middleware\Authenticate;
|
||||
|
|
@ -29,7 +30,7 @@ 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')
|
||||
|
|
@ -76,5 +77,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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
35
app/Providers/PluginServiceProvider.php
Normal file
35
app/Providers/PluginServiceProvider.php
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Dashboard\Widgets;
|
||||
use App\Plugins\Hooks;
|
||||
use App\Plugins\PluginManager;
|
||||
use App\Plugins\PluginState;
|
||||
use App\Support\Abilities;
|
||||
use App\Support\Navigation;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
/**
|
||||
* Lädt die Plugins. Muss vor den Panel-Providern registriert sein, damit
|
||||
* Plugins ihre Admin-Seiten beitragen können.
|
||||
*/
|
||||
class PluginServiceProvider extends ServiceProvider
|
||||
{
|
||||
public function register(): void
|
||||
{
|
||||
$this->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->make(PluginManager::class)->registerAll();
|
||||
}
|
||||
|
||||
public function boot(): void
|
||||
{
|
||||
$this->app->make(PluginManager::class)->bootAll();
|
||||
}
|
||||
}
|
||||
87
app/Support/Abilities.php
Normal file
87
app/Support/Abilities.php
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
/**
|
||||
* Registry der Rechte (Abilities). Kern und Plugins melden hier an, welche
|
||||
* Rechte es gibt – das Rollen-Formular und der Rechte-Prüfer bauen darauf auf.
|
||||
*
|
||||
* Globale Rechte gelten überall („Benutzer verwalten“). Objekt-Rechte gelten für
|
||||
* einzelne Objekte eines Typs („Beiträge schreiben in Kategorie MAV-Info“).
|
||||
*/
|
||||
class Abilities
|
||||
{
|
||||
/** @var array<string, array{label: string, group: string, resource: string|null}> */
|
||||
private array $abilities = [];
|
||||
|
||||
/** @var array<string, array{label: string, options: callable}> */
|
||||
private array $resourceTypes = [];
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->define('admin.access', 'Administrationsbereich öffnen', 'System');
|
||||
$this->define('users.manage', 'Benutzer verwalten', 'System');
|
||||
$this->define('roles.manage', 'Rollen und Rechte verwalten', '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('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“).
|
||||
*
|
||||
* @param callable(): array<int|string, string> $options ID => Bezeichnung
|
||||
*/
|
||||
public function resourceType(string $type, string $label, callable $options): void
|
||||
{
|
||||
$this->resourceTypes[$type] = ['label' => $label, 'options' => $options];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{label: string, group: string, resource: string|null}>
|
||||
*/
|
||||
public function all(): array
|
||||
{
|
||||
return $this->abilities;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{label: string, group: string, resource: string|null}>
|
||||
*/
|
||||
public function global(): array
|
||||
{
|
||||
return array_filter($this->abilities, fn (array $a) => $a['resource'] === null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{label: string, group: string, resource: string|null}>
|
||||
*/
|
||||
public function forResource(string $type): array
|
||||
{
|
||||
return array_filter($this->abilities, fn (array $a) => $a['resource'] === $type);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array{label: string, options: callable}>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,86 +0,0 @@
|
|||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use App\Models\Event;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* iCalendar-Export (RFC 5545) für einzelne Termine – zum Übernehmen in Outlook & Co.
|
||||
*/
|
||||
class Calendar
|
||||
{
|
||||
public function toIcs(Event $event, string $organizer): string
|
||||
{
|
||||
$end = $event->ends_at ?? ($event->all_day ? $event->starts_at : $event->starts_at->copy()->addHour());
|
||||
|
||||
$lines = [
|
||||
'BEGIN:VCALENDAR',
|
||||
'VERSION:2.0',
|
||||
'PRODID:-//'.$this->escape($organizer).'//Inhaus//DE',
|
||||
'CALSCALE:GREGORIAN',
|
||||
'METHOD:PUBLISH',
|
||||
'BEGIN:VEVENT',
|
||||
'UID:event-'.$event->id.'@'.(parse_url(config('app.url'), PHP_URL_HOST) ?: 'inhaus'),
|
||||
'DTSTAMP:'.now()->utc()->format('Ymd\THis\Z'),
|
||||
];
|
||||
|
||||
if ($event->all_day) {
|
||||
$lines[] = 'DTSTART;VALUE=DATE:'.$event->starts_at->format('Ymd');
|
||||
// DTEND ist bei ganztägigen Terminen exklusiv: der Tag nach dem letzten Tag.
|
||||
$lines[] = 'DTEND;VALUE=DATE:'.$end->copy()->startOfDay()->addDay()->format('Ymd');
|
||||
} else {
|
||||
$lines[] = 'DTSTART:'.$event->starts_at->copy()->utc()->format('Ymd\THis\Z');
|
||||
$lines[] = 'DTEND:'.$end->copy()->utc()->format('Ymd\THis\Z');
|
||||
}
|
||||
|
||||
$lines[] = 'SUMMARY:'.$this->escape($event->title);
|
||||
|
||||
if ($event->location) {
|
||||
$lines[] = 'LOCATION:'.$this->escape($event->location);
|
||||
}
|
||||
|
||||
$description = trim(html_entity_decode(strip_tags(str_replace(['</p>', '<br>'], "\n", (string) $event->description_html))));
|
||||
|
||||
if ($description !== '') {
|
||||
$lines[] = 'DESCRIPTION:'.$this->escape(Str::limit($description, 2000));
|
||||
}
|
||||
|
||||
if ($event->online_url) {
|
||||
$lines[] = 'URL:'.$this->escape($event->online_url);
|
||||
}
|
||||
|
||||
$lines[] = 'END:VEVENT';
|
||||
$lines[] = 'END:VCALENDAR';
|
||||
|
||||
return implode("\r\n", array_map($this->fold(...), $lines))."\r\n";
|
||||
}
|
||||
|
||||
private function escape(string $value): string
|
||||
{
|
||||
return str_replace(['\\', ';', ',', "\r\n", "\n"], ['\\\\', '\;', '\\,', '\\n', '\\n'], $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zeilen nach 75 Oktetts umbrechen (Folgezeilen beginnen mit einem Leerzeichen,
|
||||
* das mitzählt), ohne UTF-8-Zeichen zu zerschneiden.
|
||||
*/
|
||||
private function fold(string $line): string
|
||||
{
|
||||
$folded = '';
|
||||
$current = '';
|
||||
$limit = 75;
|
||||
|
||||
foreach (mb_str_split($line) as $char) {
|
||||
if (strlen($current.$char) > $limit) {
|
||||
$folded .= $current."\r\n ";
|
||||
$current = '';
|
||||
$limit = 74;
|
||||
}
|
||||
|
||||
$current .= $char;
|
||||
}
|
||||
|
||||
return $folded.$current;
|
||||
}
|
||||
}
|
||||
|
|
@ -2,24 +2,56 @@
|
|||
|
||||
namespace App\Support;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Plugins\Hooks;
|
||||
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);
|
||||
*/
|
||||
class Navigation
|
||||
{
|
||||
/**
|
||||
* @return list<array{label: string, href: string, active: bool}>
|
||||
*/
|
||||
public function items(Request $request): array
|
||||
/** @var array<string, array{label: string, href: string, active: list<string>, sort: int, ability: string|null}> */
|
||||
private array $items = [];
|
||||
|
||||
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<string> $active Routennamen (mit *), bei denen der Eintrag aktiv ist
|
||||
*/
|
||||
public function add(string $key, string $label, string $href, string|array $active = [], int $sort = 50, ?string $ability = null): void
|
||||
{
|
||||
$this->items[$key] = ['label' => $label, 'href' => $href, 'active' => (array) $active, 'sort' => $sort, 'ability' => $ability];
|
||||
}
|
||||
|
||||
public function remove(string $key): void
|
||||
{
|
||||
unset($this->items[$key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{key: string, label: string, href: string, active: bool}>
|
||||
*/
|
||||
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))
|
||||
->sortBy('sort')
|
||||
->map(fn (array $item, string $key) => [
|
||||
'key' => $key,
|
||||
'label' => $item['label'],
|
||||
'href' => $item['href'],
|
||||
'active' => $item['active'] !== [] && $request->routeIs(...$item['active']),
|
||||
])
|
||||
->values()
|
||||
->all();
|
||||
|
||||
return Hooks::apply('navigation.items', $items, $request, $user);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,52 @@ use RecursiveIteratorIterator;
|
|||
|
||||
final class Filesystem
|
||||
{
|
||||
/**
|
||||
* Verzeichnis verschieben – per rename(), bei Dateisystemgrenzen per Kopie.
|
||||
*/
|
||||
public static function moveDirectory(string $from, string $to): bool
|
||||
{
|
||||
if (@rename($from, $to)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (! self::copyDirectory($from, $to)) {
|
||||
self::deleteDirectory($to);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
self::deleteDirectory($from);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static function copyDirectory(string $from, string $to): bool
|
||||
{
|
||||
if (! is_dir($to) && ! @mkdir($to, 0775, true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$items = new RecursiveIteratorIterator(
|
||||
new RecursiveDirectoryIterator($from, FilesystemIterator::SKIP_DOTS),
|
||||
RecursiveIteratorIterator::SELF_FIRST,
|
||||
);
|
||||
|
||||
foreach ($items as $item) {
|
||||
$target = $to.'/'.substr($item->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)) {
|
||||
|
|
|
|||
|
|
@ -9,5 +9,5 @@ namespace App;
|
|||
*/
|
||||
final class Version
|
||||
{
|
||||
public const VERSION = '0.2.0';
|
||||
public const VERSION = '0.3.0';
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue