Loheide-eu-mitarbeiterplatt.../app/Plugins/PluginManager.php
Friederich Loheide c275db4dce
Some checks failed
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 11m34s
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 12m8s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 15m14s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 15m47s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 13m48s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 14m15s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 16m38s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 17m2s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 1m16s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m53s
Menüleiste am Handy, Updater in zwei Schritten, Absturzerkennung ohne Merkdateien (0.62.0)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 17:03:05 +00:00

554 lines
19 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Plugins;
use App\Http\Middleware\EnsurePluginAccess;
use App\Support\Audit;
use App\Support\Update\Filesystem;
use App\Support\Update\MaintenanceFlag;
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: Ausnahmen beim Laden schalten ein Plugin sofort ab.
* Schwere Fehler (Fatal Error), die PHP beendet, fängt eine Shutdown-Funktion ab:
* Sie weiß, welches Plugin gerade geladen wurde, und vermerkt den Absturz in
* plugins.json. Zweimal binnen einer Stunde → abgeschaltet, das Portal bleibt
* erreichbar. Ohne Merkdateien: Ein von außen beendeter Prozess (Speicher,
* Hoster) hinterlässt nichts und kann kein gesundes Plugin mehr abschalten.
*/
class PluginManager
{
/** Fehlerarten, bei denen PHP abbricht und kein catch mehr greift */
private const FATAL_ERRORS = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR];
/** Zwei Abbrüche innerhalb dieser Zeit schalten ein Plugin ab */
private const STRIKE_WINDOW_SECONDS = 3600;
private ?MaintenanceFlag $updateWindow = null;
/** @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 = [];
/** Plugin, das gerade geladen wird – für die Shutdown-Funktion */
private ?string $booting = null;
private bool $shutdownHandlerRegistered = false;
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;
}
}
// Der Updater löscht nie (docs/specs/self-updater.md): Der Ordner eines
// umbenannten mitgelieferten Plugins bleibt liegen und wird hier ignoriert.
foreach ($this->manifests as $manifest) {
foreach ($manifest->core ? $manifest->replaces : [] as $old) {
if (($this->manifests[$old] ?? null)?->core) {
unset($this->manifests[$old]);
}
}
}
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->removeLegacyMarkers();
$this->reenableAfterIncompleteUpload();
$this->reenableAfterUpdate();
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', EnsurePluginAccess::class.':'.$manifest->slug])->group($manifest->path.'/routes/web.php');
}
// REST-API des Plugins: /api/v1/…, nur mit gültigem Token
if (is_file($manifest->path.'/routes/api.php') && ! $this->app->routesAreCached()) {
Route::prefix('api/v1')->middleware(['api', 'auth:sanctum', EnsurePluginAccess::class.':'.$manifest->slug])->group($manifest->path.'/routes/api.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);
PluginAssets::unpublish($slug);
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);
PluginAssets::unpublish($slug);
$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 PluginClassMissing(PluginClassMissing::PREFIX."{$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
{
// Während eines Updates tauscht das Portal gerade Dateien aus: Fehler beim Laden sind dann
// meist nur ein Zwischenstand – das Plugin fehlt in dieser Anfrage, wird aber nicht abgeschaltet.
$updating = $this->updateWindow()->isUpdating();
if (! $this->shutdownHandlerRegistered) {
$this->shutdownHandlerRegistered = true;
register_shutdown_function(function () {
$error = error_get_last();
if ($this->booting !== null && is_array($error)) {
$this->handleFatalError($error);
}
});
}
$this->booting = $manifest->slug;
try {
$callback();
} catch (PluginClassMissing $e) {
// Vorübergehend (z. B. während ein Update Dateien kopiert): nur diesen
// Aufruf ohne das Plugin laufen lassen, nicht dauerhaft deaktivieren.
unset($this->loaded[$manifest->slug]);
$this->problems[$manifest->slug] = $e->getMessage();
Log::warning("Plugin {$manifest->slug} konnte nicht geladen werden: ".$e->getMessage());
} catch (Throwable $e) {
unset($this->loaded[$manifest->slug]);
$this->problems[$manifest->slug] = $e->getMessage();
if ($updating) {
Log::warning("Plugin {$manifest->slug} konnte während eines Updates nicht geladen werden (nicht deaktiviert): ".$e->getMessage());
return;
}
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 {
$this->booting = null;
}
}
/**
* Aus der Shutdown-Funktion: PHP ist mit einem schweren Fehler abgebrochen, während
* ein Plugin geladen wurde. Erster Abbruch: nur vermerken (kann z. B. eine überschrittene
* Laufzeit auf einem überlasteten Server sein). Ein wirklich defektes Plugin bricht bei
* jeder Anfrage ab und fällt binnen Sekunden ein zweites Mal auf – dann wird es abgeschaltet.
*
* @param array{type: int, message: string, file?: string, line?: int} $error
*/
public function handleFatalError(array $error): void
{
$slug = $this->booting;
if ($slug === null || ! in_array($error['type'], self::FATAL_ERRORS, true)) {
return;
}
$this->booting = null;
$message = mb_substr(trim(strtok($error['message'], "\n") ?: ''), 0, 300);
try {
if ($this->updateWindow()->isUpdating()) {
Log::warning("Plugin {$slug} ist während eines Updates beim Laden abgebrochen – es bleibt aktiv: {$message}");
return;
}
$previous = $this->state->crashedAt($slug);
if ($previous === null || time() - $previous > self::STRIKE_WINDOW_SECONDS) {
$this->state->recordCrash($slug);
Log::warning("Plugin {$slug} ist beim Laden abgebrochen ({$message}) – es bleibt vorerst aktiv. Bricht es binnen einer Stunde erneut ab, wird es deaktiviert.");
return;
}
Log::critical("Plugin {$slug} hat beim Laden einen schweren Fehler verursacht und wurde deaktiviert: {$message}");
$this->state->setEnabled($slug, false, 'Schwerer Fehler beim Laden: '.$message);
} catch (Throwable) {
// Im Shutdown darf nichts mehr werfen.
}
}
/**
* Frühere Versionen haben ein Plugin dauerhaft deaktiviert, wenn seine Klasse
* fehlte – typischerweise nur für einen Augenblick während des Aufspielens.
* Ist die Datei inzwischen da, wird es wieder aktiviert.
*/
private function reenableAfterIncompleteUpload(): void
{
foreach ($this->all() as $manifest) {
$reason = $this->state->disabledReason($manifest->slug);
if ($reason === null || ! str_starts_with($reason, 'Fehler beim Laden: '.PluginClassMissing::PREFIX)) {
continue;
}
$file = $manifest->path.'/src/'.str_replace('\\', '/', substr($manifest->class, strlen($manifest->namespace))).'.php';
if (is_file($file)) {
$this->state->setEnabled($manifest->slug, true);
Log::info("Plugin {$manifest->slug} wieder aktiviert (Klasse fehlte beim Aufspielen nur vorübergehend).");
}
}
}
/**
* Plugins, die während eines Updates wegen eines Ladefehlers abgeschaltet wurden (ältere
* Portal-Versionen taten das), wieder einschalten – der Fehler war nur ein Zwischenstand.
* Ist das Plugin wirklich defekt, fällt es beim nächsten Laden außerhalb des Updates erneut auf.
*/
private function reenableAfterUpdate(): void
{
foreach ($this->state->all() as $slug => $entry) {
$reason = (string) ($entry['disabled_reason'] ?? '');
$at = $this->state->disabledAt($slug);
$crash = str_starts_with($reason, 'Fehler beim Laden') || str_starts_with($reason, 'Schwerer Fehler beim Laden');
if (($entry['enabled'] ?? true) === false && $crash && $at !== null && $this->updateWindow()->covers($at)) {
$this->state->setEnabled($slug, true);
Log::info("Plugin {$slug} wieder aktiviert (Ladefehler während eines Updates).");
}
}
}
private function updateWindow(): MaintenanceFlag
{
return $this->updateWindow ??= $this->app->make(MaintenanceFlag::class);
}
/**
* Merkdateien früherer Versionen (storage/framework/plugins) aufräumen – sie würden
* sonst nie mehr gelesen. Danach kostet die Prüfung nur noch ein is_dir().
*/
private function removeLegacyMarkers(): void
{
$dir = storage_path('framework/plugins');
if (! is_dir($dir)) {
return;
}
foreach (array_merge(glob($dir.'/booting-*') ?: [], glob($dir.'/strike-*') ?: []) as $file) {
@unlink($file);
}
@rmdir($dir);
}
}