Loheide-eu-mitarbeiterplatt.../app/Plugins/PluginAssets.php
Friederich Loheide 03e31f42b5
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 7m38s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 8m0s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 11m51s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 12m15s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 13m27s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 13m42s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 16m0s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 15m20s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 56s
CI / Build-Artefakte aktuell (pull_request) Successful in 1m14s
Noch schneller (0.46.0)
- Erscheinungsbild: große Fotos (Anmeldung, Titelbild) beim Speichern als WebP
  ≤ 2400 px; Migration verkleinert vorhandene einmal
- Vite: Grundgerüst und UI-Bausteine als gemeinsame Dateien (Startseite 34 statt
  58 Skripte)
- Plugin-Oberflächen: Kopie nach public/ erneuert sich bei neuem Build
  (Fingerabdruck von dist/inhaus.json), auch ohne neue Version

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 17:00:29 +00:00

190 lines
7.1 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\Update\Filesystem;
use App\Version;
use Illuminate\Support\Facades\Log;
/**
* Vorkompilierte Oberflächen separat installierter Plugins (Plugin-SDK).
*
* Ein Plugin bringt unter dist/ ES-Module und optional CSS mit und beschreibt sie in
* dist/inhaus.json:
*
* { "components": { "pages/Index": "pages/Index.js", "widgets/Verse": "widgets/Verse.js" },
* "css": ["style.css"] }
*
* Mitgelieferte Plugins brauchen das nicht – sie sind Teil des Portal-Builds.
*/
class PluginAssets
{
public const MANIFEST = 'dist/inhaus.json';
/** Dateitypen, die ausgeliefert werden */
public const TYPES = [
'js' => 'text/javascript', 'mjs' => 'text/javascript', 'css' => 'text/css', 'map' => 'application/json',
'json' => 'application/json', 'svg' => 'image/svg+xml', 'png' => 'image/png', 'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg', 'webp' => 'image/webp', 'gif' => 'image/gif', 'woff2' => 'font/woff2',
];
/** @var array<string, array{base: string, components: array<string, string>, css: list<string>}>|null */
private ?array $cache = null;
public function __construct(private readonly PluginManager $plugins) {}
/**
* Für das Frontend (window.__inhausPlugins): aktive Plugins mit Oberfläche.
*
* @return array<string, array{base: string, components: array<string, string>, css: list<string>}>
*/
public function forFrontend(): array
{
if ($this->cache !== null) {
return $this->cache;
}
$this->cache = [];
foreach ($this->plugins->loaded() as $slug => $plugin) {
$manifest = $plugin->manifest;
if ($manifest->core || ! is_file($manifest->path.'/'.self::MANIFEST)) {
continue;
}
$data = json_decode((string) file_get_contents($manifest->path.'/'.self::MANIFEST), true);
if (! is_array($data)) {
continue;
}
$clean = fn ($file) => is_string($file) && preg_match('#^[A-Za-z0-9_./-]+$#', $file) && ! str_contains($file, '..') ? $file : null;
// Einmal nach public/ kopieren – dann liefert der Webserver die Dateien ohne PHP aus
$this->publish($slug, $manifest);
$this->cache[$slug] = [
'base' => '/plugin-assets/'.rawurlencode($slug).'/'.rawurlencode($manifest->version).'/',
'components' => array_filter(array_map($clean, (array) ($data['components'] ?? [])), fn ($file, $key) => $file !== null && preg_match('#^[A-Za-z0-9_/-]+$#', (string) $key), ARRAY_FILTER_USE_BOTH),
'css' => array_values(array_filter(array_map($clean, (array) ($data['css'] ?? [])))),
];
}
return $this->cache;
}
/**
* Import Map für Plugins: dieselben Module wie im Portal.
*
* @return array{imports: array<string, string>}
*/
public static function importMap(): array
{
$v = '?v='.Version::VERSION;
return ['imports' => [
'vue' => '/sdk/vue.js'.$v,
'@inertiajs/vue3' => '/sdk/inertia.js'.$v,
'@inhaus/ui' => '/sdk/ui.js'.$v,
]];
}
/**
* dist/ eines aktiven Plugins nach public/plugin-assets/<slug>/<version>/ kopieren (gleiche
* Adresse wie die PHP-Route). Der Webserver liefert vorhandene Dateien direkt aus – schneller
* und ohne Sitzung. Geht das Kopieren nicht (public/ schreibgeschützt), springt die Route ein.
*/
public function publish(string $slug, PluginManifest $manifest): bool
{
$target = self::publicPath($slug).'/'.$manifest->version;
// Fingerabdruck des Builds: dist/inhaus.json nennt die Dateien mit Hash – ein neuer Build
// (auch bei gleicher Versionsnummer, z. B. während der Entwicklung) wird neu kopiert
$build = md5((string) @file_get_contents($manifest->path.'/'.self::MANIFEST));
if (@file_get_contents($target.'/.complete') === $build) {
return true;
}
$dist = realpath($manifest->path.'/dist');
if (! $dist || ! preg_match('#^[A-Za-z0-9.+-]+$#', $manifest->version)) {
return false;
}
$staging = self::publicPath($slug).'/.tmp-'.bin2hex(random_bytes(4));
try {
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dist, \FilesystemIterator::SKIP_DOTS));
foreach ($files as $file) {
$relative = substr($file->getPathname(), strlen($dist) + 1);
// Nur erlaubte Dateitypen und saubere Namen (wie bei der Route)
if (! $file->isFile() || ! isset(self::TYPES[strtolower($file->getExtension())]) || ! preg_match('#^[A-Za-z0-9_./-]+$#', $relative)) {
continue;
}
if (! is_dir(dirname($staging.'/'.$relative)) && ! @mkdir(dirname($staging.'/'.$relative), 0775, true)) {
throw new \RuntimeException('public/plugin-assets ist nicht beschreibbar.');
}
if (! @copy($file->getPathname(), $staging.'/'.$relative)) {
throw new \RuntimeException("{$relative} konnte nicht kopiert werden.");
}
}
@file_put_contents($staging.'/.complete', $build);
Filesystem::deleteDirectory($target);
if (! @rename($staging, $target)) {
throw new \RuntimeException('Kopie konnte nicht übernommen werden.');
}
// Ältere Versionen dieses Plugins entfernen
foreach (glob(self::publicPath($slug).'/*', GLOB_ONLYDIR) ?: [] as $dir) {
if (basename($dir) !== $manifest->version) {
Filesystem::deleteDirectory($dir);
}
}
return true;
} catch (\Throwable $e) {
Filesystem::deleteDirectory($staging);
Log::info("Plugin-Dateien von {$slug} werden über PHP ausgeliefert: ".$e->getMessage());
return false;
}
}
/** Veröffentlichte Kopie entfernen (Plugin deaktiviert oder gelöscht) */
public static function unpublish(string $slug): void
{
if (preg_match('#^[a-z0-9-]+$#', $slug)) {
Filesystem::deleteDirectory(self::publicPath($slug));
}
}
private static function publicPath(string $slug): string
{
return rtrim((string) (config('inhaus.plugin_assets_path') ?: public_path('plugin-assets')), '/').'/'.$slug;
}
/**
* Pfad einer ausgelieferten Datei – nur aus dist/ eines aktiven Kunden-Plugins.
*/
public function file(string $slug, string $path): ?string
{
$plugin = $this->plugins->loaded()[$slug] ?? null;
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
if (! $plugin || $plugin->manifest->core || ! isset(self::TYPES[$extension]) || str_contains($path, '..')) {
return null;
}
$dist = realpath($plugin->manifest->path.'/dist');
$file = realpath($plugin->manifest->path.'/dist/'.$path);
return $dist && $file && str_starts_with($file, $dist.DIRECTORY_SEPARATOR) && is_file($file) ? $file : null;
}
}