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
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));
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue