Loheide-eu-mitarbeiterplatt.../app/Plugins/PluginManager.php
Friederich Loheide 293d7f86a4
Some checks failed
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 3m4s
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 3m8s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 3m32s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 3m35s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 5m7s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 5m1s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 5m30s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 5m31s
CI / Build-Artefakte aktuell (pull_request) Failing after 1m26s
Plugins bei fehlender Klasse nicht dauerhaft deaktivieren, Speichern-Abstand im Admin, Profilbild-Fehlermeldung
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 18:28:03 +00:00

441 lines
14 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\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();
$this->reenableAfterIncompleteUpload();
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 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
{
$marker = $this->markerPath($manifest->slug);
@file_put_contents($marker, (string) time());
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();
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);
}
}
/**
* 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).");
}
}
}
private function markerPath(string $slug): string
{
$dir = storage_path('framework/plugins');
if (! is_dir($dir)) {
@mkdir($dir, 0775, true);
}
return $dir.'/booting-'.$slug;
}
}