Rückmeldungen, Hintergrundaufgaben, Systemzustand und Web-Installer

- Rückmeldungen an den Hersteller (docs/specs/feedback.md): Fehlerbericht und
  Funktionswunsch, nur freigeschaltete Wege, Idempotency-Key je Meldung,
  Warteschlange mit höchstens fünf Versuchen, 422 am Feld, 429 mit Wartezeit,
  404 blendet den Weg aus, Referenznummer und „Meine Rückmeldungen“,
  sichtbare technische Angaben und Datenschutzhinweis über dem Absendeknopf
- Hintergrundaufgaben ohne Dauerprozess: Cron, Web-Cron (/cron/{token}) oder
  Pseudo-Cron nach dem Seitenaufruf; Queue in kurzen Häppchen
- Seite „Systemzustand“ mit Voraussetzungen, Grenzen, Betrieb, Sicherheit und
  Anleitung für den Cronjob
- Web-Installer (Systemprüfung → Datenbank → Administrator), legt .env und
  Anwendungsschlüssel selbst an, arbeitet vor der Einrichtung ohne Datenbank
- Datenbank-Benachrichtigungen im Admin-Bereich

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 06:11:09 +00:00
parent 43244d751a
commit 029dbd243d
38 changed files with 2274 additions and 12 deletions

View file

@ -0,0 +1,137 @@
<?php
namespace App\Filament\Pages;
use App\Models\VendorFeedback;
use App\Support\Audit;
use App\Support\Feedback\FeedbackChannels;
use App\Support\Feedback\FeedbackOutbox;
use App\Support\Feedback\FeedbackResult;
use App\Support\Feedback\TechnicalInfo;
use App\Support\License\LicenseStore;
use BackedEnum;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon;
use UnitEnum;
/**
* „Hilfe → Rückmeldung geben“: Fehlerbericht oder Funktionswunsch an den
* Hersteller (docs/specs/feedback.md).
*/
class Feedback extends Page
{
protected string $view = 'filament.pages.feedback';
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedChatBubbleLeftEllipsis;
protected static string|UnitEnum|null $navigationGroup = 'Hilfe';
protected static ?string $navigationLabel = 'Rückmeldung geben';
protected static ?string $title = 'Rückmeldung geben';
protected static ?string $slug = 'rueckmeldung';
public string $type = '';
public string $subject = '';
public string $body = '';
public string $severity = 'normal';
public string $email = '';
public string $name = '';
public ?string $lastReference = null;
public ?string $notice = null;
public function mount(FeedbackChannels $channels): void
{
$this->type = (string) array_key_first($channels->available());
}
public function submit(FeedbackChannels $channels, FeedbackOutbox $outbox, TechnicalInfo $info): void
{
$available = $channels->available();
$this->validate([
'type' => ['required', 'in:'.implode(',', array_keys($available))],
'subject' => ['required', 'string', 'max:255'],
'body' => ['required', 'string', 'min:10', 'max:20000'],
'severity' => ['required', 'in:low,normal,high,critical'],
'email' => ['nullable', 'email', 'max:255'],
'name' => ['nullable', 'string', 'max:255'],
], attributes: [
'type' => 'Art der Meldung', 'subject' => 'Betreff', 'body' => 'Beschreibung',
'email' => 'E-Mail-Adresse', 'name' => 'Name',
]);
$this->notice = null;
$this->lastReference = null;
$payload = array_filter([
'title' => $this->subject,
'body' => $this->body,
'email' => $this->email ?: null,
'name' => $this->name ?: null,
'severity' => $this->type === 'bugreport' ? $this->severity : null,
...$info->collect(),
], fn ($value) => $value !== null);
$result = $outbox->submit(auth()->user(), $this->type, $payload);
switch ($result->status) {
case FeedbackResult::SENT:
Audit::log('feedback.sent', ['type' => $this->type, 'reference' => $result->reference]);
$this->lastReference = $result->reference;
$this->reset(['subject', 'body', 'severity']);
Notification::make()->success()->title('Vielen Dank – Ihre Meldung ist eingegangen')->body("Referenznummer: {$result->reference}")->persistent()->send();
break;
case FeedbackResult::RETRY:
$this->reset(['subject', 'body', 'severity']);
$this->notice = 'Der Server ist gerade nicht erreichbar. Ihre Meldung ist gespeichert und wird automatisch gesendet, sobald es wieder geht. Die Referenznummer erscheint dann unten in der Liste.';
break;
case FeedbackResult::INVALID:
// Fehler direkt am betroffenen Feld anzeigen (API-Feld „title“ = Formularfeld „subject“).
foreach ($result->errors as $field => $message) {
$field = $field === 'title' ? 'subject' : $field;
$this->addError(in_array($field, ['subject', 'body', 'email', 'name', 'severity'], true) ? $field : 'body', $message);
}
if ($result->errors === []) {
$this->addError('body', $result->message ?? 'Die Eingabe ist unvollständig.');
}
break;
case FeedbackResult::RATE_LIMITED:
$minutes = $result->retryAfter ? max(1, (int) ceil($result->retryAfter / 60)) : null;
$this->notice = 'Es wurden zu viele Meldungen in kurzer Zeit gesendet. Bitte versuchen Sie es '.($minutes ? "in etwa {$minutes} Minute(n)" : 'später').' noch einmal – Ihre Eingabe bleibt erhalten.';
break;
case FeedbackResult::DISABLED:
$channels->disable($this->type);
$this->notice = 'Dieser Meldeweg steht nicht mehr zur Verfügung. Ihre Eingabe bleibt erhalten'.(count($channels->available()) ? ' – bitte wählen Sie eine andere Art der Meldung.' : '.');
$this->type = (string) array_key_first($channels->available());
break;
}
}
/**
* @return array<string, mixed>
*/
protected function getViewData(): array
{
return [
'types' => app(FeedbackChannels::class)->available(),
'technical' => app(TechnicalInfo::class)->collect(),
'hasLicense' => app(LicenseStore::class)->hasLicense(),
'history' => VendorFeedback::query()->where('user_id', auth()->id())->latest()->limit(20)->get(),
];
}
}

View file

@ -0,0 +1,39 @@
<?php
namespace App\Filament\Pages;
use App\Support\BackgroundTasks;
use App\Support\SiteHealth;
use BackedEnum;
use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon;
use UnitEnum;
class SystemHealth extends Page
{
protected string $view = 'filament.pages.system-health';
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedHeart;
protected static string|UnitEnum|null $navigationGroup = 'System';
protected static ?int $navigationSort = 20;
protected static ?string $navigationLabel = 'Systemzustand';
protected static ?string $title = 'Systemzustand';
protected static ?string $slug = 'systemzustand';
/**
* @return array<string, mixed>
*/
protected function getViewData(): array
{
return [
'groups' => app(SiteHealth::class)->all(),
'cronLine' => '* * * * * cd '.base_path().' && php artisan schedule:run >> /dev/null 2>&1',
'webCronUrl' => url('/cron/'.app(BackgroundTasks::class)->webCronToken()),
];
}
}

View file

@ -0,0 +1,23 @@
<?php
namespace App\Http\Controllers;
use App\Support\BackgroundTasks;
use Illuminate\Http\Response;
/**
* Web-Cron für Hoster ohne Cron: ein externer Dienst ruft minütlich
* /cron/{token} auf.
*/
class CronController extends Controller
{
public function __invoke(string $token, BackgroundTasks $tasks): Response
{
abort_unless(hash_equals($tasks->webCronToken(), $token), 404);
@ignore_user_abort(true);
$tasks->run('webcron');
return response()->noContent();
}
}

View file

@ -0,0 +1,160 @@
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Support\Audit;
use App\Support\EnvFile;
use App\Support\Installation;
use App\Support\License\LicenseStore;
use App\Support\Settings;
use App\Support\SiteHealth;
use App\Support\Update\Migrations;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Validation\Rules\Password;
use Illuminate\View\View;
use PDO;
use Throwable;
/**
* Web-Installer: Systemprüfung → Datenbank → Administrator. Nur erreichbar,
* solange die Installation nicht eingerichtet ist.
*/
class InstallController extends Controller
{
public function __construct()
{
abort_if(Installation::isInstalled(), 404);
}
public function requirements(SiteHealth $health): View
{
$checks = $health->requirements();
return view('install.requirements', [
'checks' => $checks,
'canContinue' => collect($checks)->doesntContain('status', SiteHealth::ERROR) && is_file(app()->environmentFilePath()),
'envWritable' => is_file(app()->environmentFilePath()) && is_writable(app()->environmentFilePath()),
]);
}
public function database(): View
{
return view('install.database', [
'values' => [
'host' => config('database.connections.mysql.host', 'localhost'),
'port' => config('database.connections.mysql.port', 3306),
'database' => config('database.connections.mysql.database'),
'username' => config('database.connections.mysql.username'),
],
]);
}
public function saveDatabase(Request $request): RedirectResponse
{
$data = $request->validate([
'host' => ['required', 'string', 'max:255'],
'port' => ['required', 'integer', 'between:1,65535'],
'database' => ['required', 'string', 'max:64'],
'username' => ['required', 'string', 'max:255'],
'password' => ['nullable', 'string', 'max:255'],
], attributes: ['host' => 'Server', 'port' => 'Port', 'database' => 'Datenbank', 'username' => 'Benutzer', 'password' => 'Passwort']);
try {
$pdo = new PDO(
"mysql:host={$data['host']};port={$data['port']};dbname={$data['database']};charset=utf8mb4",
$data['username'],
$data['password'] ?? '',
[PDO::ATTR_TIMEOUT => 5, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION],
);
$version = (string) $pdo->query('select version()')->fetchColumn();
} catch (Throwable $e) {
return back()->withInput($request->except('password'))
->withErrors(['host' => 'Verbindung fehlgeschlagen: '.$this->pdoMessage($e->getMessage())]);
}
$mariadb = str_contains(strtolower($version), 'mariadb');
$number = preg_replace('/^(\d+\.\d+\.\d+).*$/', '$1', $version);
if (! version_compare($number, $mariadb ? '10.6.0' : '8.0.0', '>=')) {
return back()->withInput($request->except('password'))
->withErrors(['host' => ($mariadb ? 'MariaDB ' : 'MySQL ').$number.' wird nicht unterstützt. Benötigt wird MySQL ab 8.0 oder MariaDB ab 10.6.']);
}
EnvFile::set(app()->environmentFilePath(), [
'APP_URL' => $request->getSchemeAndHttpHost().$request->getBaseUrl(),
'DB_CONNECTION' => 'mysql',
'DB_HOST' => $data['host'],
'DB_PORT' => (string) $data['port'],
'DB_DATABASE' => $data['database'],
'DB_USERNAME' => $data['username'],
'DB_PASSWORD' => $data['password'] ?? '',
]);
return redirect('/install/konto');
}
public function account(): View|RedirectResponse
{
return view('install.account');
}
public function saveAccount(Request $request, Settings $settings, LicenseStore $license, Migrations $migrations): RedirectResponse
{
$data = $request->validate([
'portal_name' => ['required', 'string', 'max:60'],
'first_name' => ['required', 'string', 'max:100'],
'last_name' => ['required', 'string', 'max:100'],
'email' => ['required', 'email', 'max:255'],
'password' => ['required', 'confirmed', Password::min(10)->letters()->numbers()],
'license_email' => ['nullable', 'email', 'max:255', 'required_with:license_key'],
'license_key' => ['nullable', 'string', 'max:500', 'required_with:license_email'],
], attributes: [
'portal_name' => 'Name des Portals', 'first_name' => 'Vorname', 'last_name' => 'Nachname',
'email' => 'E-Mail-Adresse', 'password' => 'Passwort',
'license_email' => 'Lizenz-E-Mail', 'license_key' => 'Lizenzschlüssel',
]);
@set_time_limit(300);
try {
Artisan::call('migrate', ['--force' => true]);
} catch (Throwable $e) {
return back()->withInput($request->except('password', 'password_confirmation', 'license_key'))
->withErrors(['portal_name' => 'Die Datenbank konnte nicht eingerichtet werden: '.$e->getMessage()]);
}
$admin = User::query()->updateOrCreate(['email' => strtolower($data['email'])], [
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'password' => $data['password'],
'is_admin' => true,
'is_active' => true,
]);
$settings->set('branding.portal_name', $data['portal_name']);
if (filled($data['license_email'] ?? null)) {
$license->setLicense($data['license_email'], $data['license_key']);
}
$license->deviceId();
file_put_contents(storage_path('.migrations-fingerprint'), $migrations->fingerprint());
Installation::markInstalled();
Audit::log('install.completed', ['portal_name' => $data['portal_name']], $admin->id);
return redirect('/login')->with('status', 'Die Einrichtung ist abgeschlossen. Sie können sich jetzt anmelden.');
}
private function pdoMessage(string $message): string
{
return match (true) {
str_contains($message, 'Access denied') => 'Benutzername oder Passwort sind falsch, oder der Benutzer hat keinen Zugriff auf diese Datenbank.',
str_contains($message, 'Unknown database') => 'Die Datenbank existiert nicht. Bitte zuerst beim Hoster anlegen.',
str_contains($message, 'getaddrinfo'), str_contains($message, 'Connection refused'), str_contains($message, 'timed out') => 'Der Datenbankserver ist nicht erreichbar. Bitte Server und Port prüfen.',
default => $message,
};
}
}

View file

@ -0,0 +1,23 @@
<?php
namespace App\Http\Middleware;
use App\Support\Installation;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Solange nicht eingerichtet, führt jede Seite zum Web-Installer.
*/
class RedirectToInstaller
{
public function handle(Request $request, Closure $next): Response
{
if (! Installation::isInstalled() && ! $request->is('install', 'install/*', 'up')) {
return redirect('/install');
}
return $next($request);
}
}

View file

@ -0,0 +1,33 @@
<?php
namespace App\Http\Middleware;
use App\Support\BackgroundTasks;
use App\Support\Installation;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Pseudo-Cron: Läuft weder echter Cron noch Web-Cron, werden fällige
* Hintergrundaufgaben nach dem Ausliefern einer Seite erledigt – höchstens
* einmal pro Minute.
*/
class RunPseudoCron
{
public function __construct(private readonly BackgroundTasks $tasks) {}
public function handle(Request $request, Closure $next): Response
{
return $next($request);
}
public function terminate(Request $request, Response $response): void
{
if (app()->runningUnitTests() || ! Installation::isInstalled() || ! $this->tasks->pseudoCronDue()) {
return;
}
$this->tasks->run('pseudo');
}
}

View file

@ -0,0 +1,40 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable(['user_id', 'type', 'payload', 'idempotency_key', 'status', 'attempts', 'next_attempt_at', 'reference', 'last_error'])]
class VendorFeedback extends Model
{
public const PENDING = 'pending';
public const SENT = 'sent';
public const DISCARDED = 'discarded';
public const TYPES = [
'bugreport' => 'Fehlerbericht',
'featurerequest' => 'Funktionswunsch',
];
protected $table = 'vendor_feedback';
protected function casts(): array
{
return [
'payload' => 'array',
'next_attempt_at' => 'datetime',
];
}
/**
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}

View file

@ -4,7 +4,9 @@ namespace App\Providers;
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;
@ -21,12 +23,23 @@ class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
// Frisch hochgeladen: .env und Schlüssel anlegen; bis zur Einrichtung ohne Datenbank
// für Sitzungen, Cache und Queue auskommen (der Web-Installer braucht das).
if (! $this->app->runningUnitTests()) {
Installation::prepareEnvironment();
}
if (! Installation::isInstalled()) {
config(['session.driver' => 'file', 'cache.default' => 'file', 'queue.default' => 'sync']);
}
$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);
$this->app->singleton(InstalledVersion::class);
$this->app->singleton(UpdateProgress::class);
$this->app->singleton(MaintenanceFlag::class);

View file

@ -3,7 +3,9 @@
namespace App\Providers\Filament;
use App\Filament\AvatarProviders\InitialsAvatarProvider;
use App\Filament\Pages\Feedback;
use App\Support\Branding;
use Filament\Actions\Action;
use Filament\Http\Middleware\Authenticate;
use Filament\Http\Middleware\AuthenticateSession;
use Filament\Http\Middleware\DisableBladeIconComponents;
@ -37,7 +39,14 @@ class AdminPanelProvider extends PanelProvider
->colors(fn () => [
'primary' => app(Branding::class)->palette(),
])
->navigationGroups(['Inhalte', 'Portal', 'System'])
->navigationGroups(['Inhalte', 'Portal', 'System', 'Hilfe'])
->databaseNotifications()
->userMenuItems([
Action::make('feedback')
->label('Rückmeldung geben')
->icon(Heroicon::OutlinedChatBubbleLeftEllipsis)
->url(fn () => Feedback::getUrl()),
])
->navigationItems([
NavigationItem::make('Zum Portal')
->url('/')

View file

@ -0,0 +1,80 @@
<?php
namespace App\Support;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Throwable;
/**
* Hintergrundaufgaben ohne Dauerprozess (Shared Hosting):
* 1. echter Cron: * * * * * php artisan schedule:run
* 2. Web-Cron: externer Dienst ruft /cron/{token} auf
* 3. Pseudo-Cron: nach Auslieferung einer Seite, wenn 1 und 2 fehlen (wie WP-Cron)
* Jeder Lauf hinterlässt ein Lebenszeichen, das „Systemzustand“ anzeigt.
*/
class BackgroundTasks
{
/** Ohne Lebenszeichen von Cron/Web-Cron springt der Pseudo-Cron ein. */
public const PSEUDO_CRON_AFTER_SECONDS = 300;
public function __construct(private readonly Settings $settings) {}
public function run(string $source): void
{
$lock = @fopen(storage_path('.background.lock'), 'c');
if ($lock === false || ! flock($lock, LOCK_EX | LOCK_NB)) {
return;
}
try {
@set_time_limit(55);
$this->heartbeat($source);
Artisan::call('schedule:run');
} catch (Throwable $e) {
Log::error('Hintergrundaufgaben fehlgeschlagen: '.$e->getMessage(), ['exception' => $e]);
} finally {
flock($lock, LOCK_UN);
fclose($lock);
}
}
public function heartbeat(string $source): void
{
$beats = $this->heartbeats();
$beats[$source] = now()->getTimestamp();
@file_put_contents(storage_path('.background-heartbeat'), json_encode($beats));
}
/**
* @return array<string, int> Quelle (cron, webcron, pseudo) => Zeitpunkt
*/
public function heartbeats(): array
{
$data = json_decode((string) @file_get_contents(storage_path('.background-heartbeat')), true);
return is_array($data) ? array_map('intval', $data) : [];
}
public function pseudoCronDue(): bool
{
$beats = $this->heartbeats();
$external = max($beats['cron'] ?? 0, $beats['webcron'] ?? 0);
return now()->getTimestamp() - $external > self::PSEUDO_CRON_AFTER_SECONDS
&& now()->getTimestamp() - ($beats['pseudo'] ?? 0) >= 60;
}
public function webCronToken(): string
{
$token = $this->settings->get('system.cron_token');
if (! is_string($token) || strlen($token) < 32) {
$token = bin2hex(random_bytes(20));
$this->settings->set('system.cron_token', $token);
}
return $token;
}
}

49
app/Support/EnvFile.php Normal file
View file

@ -0,0 +1,49 @@
<?php
namespace App\Support;
use App\Support\Update\AtomicFile;
/**
* Setzt Werte in einer .env-Datei (vorhandene Zeilen ersetzen, neue anhängen).
*/
class EnvFile
{
/**
* @param array<string, string|int|bool|null> $values
*/
public static function set(string $path, array $values): void
{
$content = is_file($path) ? (string) file_get_contents($path) : '';
foreach ($values as $key => $value) {
$line = $key.'='.self::format($value);
$pattern = '/^#?\s*'.preg_quote($key, '/').'=.*$/m';
$content = preg_match($pattern, $content)
? preg_replace($pattern, str_replace(['\\', '$'], ['\\\\', '\\$'], $line), $content, 1)
: rtrim($content, "\n")."\n".$line."\n";
}
AtomicFile::write($path, $content);
}
private static function format(string|int|bool|null $value): string
{
if ($value === null) {
return '';
}
if (is_bool($value)) {
return $value ? 'true' : 'false';
}
$value = (string) $value;
if ($value === '' || preg_match('/^[A-Za-z0-9_.:\/@+=-]+$/', $value)) {
return $value;
}
return '"'.str_replace(['\\', '"', '$'], ['\\\\', '\\"', '\\$'], $value).'"';
}
}

View file

@ -0,0 +1,58 @@
<?php
namespace App\Support\Feedback;
use App\Models\VendorFeedback;
use App\Support\Settings;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Throwable;
/**
* Welche Meldewege für dieses Programm freigeschaltet sind – einmal täglich über
* GET /v1/software ermittelt. Ein 404 beim Senden blendet den Weg dauerhaft aus.
*/
class FeedbackChannels
{
public function __construct(private readonly Settings $settings) {}
/**
* @return array<string, string> Schlüssel => Bezeichnung
*/
public function available(): array
{
$enabled = Cache::remember('feedback.endpoints', now()->addDay(), fn () => $this->fetch());
$disabled = (array) $this->settings->get('feedback.disabled', []);
return collect(VendorFeedback::TYPES)
->only($enabled ?? array_keys(VendorFeedback::TYPES))
->except($disabled)
->all();
}
public function disable(string $type): void
{
$disabled = (array) $this->settings->get('feedback.disabled', []);
$this->settings->set('feedback.disabled', array_values(array_unique([...$disabled, $type])));
}
/**
* @return list<string>|null null = unbekannt (Server nicht erreichbar) – dann alle anbieten
*/
private function fetch(): ?array
{
try {
$software = Http::timeout(5)->acceptJson()->get(rtrim(config('updater.api_url'), '/').'/software')->json('software');
foreach ((array) $software as $entry) {
if (($entry['slug'] ?? null) === config('updater.software')) {
return array_values(array_filter((array) ($entry['endpoints'] ?? []), 'is_string'));
}
}
return [];
} catch (Throwable) {
return null;
}
}
}

View file

@ -0,0 +1,80 @@
<?php
namespace App\Support\Feedback;
use App\Support\License\ServerError;
use App\Support\License\VendorHttp;
/**
* Sendet Rückmeldungen an api.loheide.cloud (docs/specs/feedback.md).
* Lizenz-Kopfzeilen nur, wenn eine Lizenz hinterlegt ist; eine ungültige oder
* abgelaufene Lizenz verhindert das Senden nicht.
*/
class FeedbackClient
{
public function __construct(private readonly VendorHttp $http) {}
/**
* @param array<string, mixed> $payload
*/
public function send(string $type, array $payload, string $idempotencyKey, int $timeout = 10): FeedbackResult
{
try {
$response = VendorHttp::guard(fn () => $this->http->request($timeout, identifyDevice: false)
->withHeaders(['Idempotency-Key' => $idempotencyKey])
->post($this->url($type), $payload));
} catch (ServerError $e) {
return FeedbackResult::retry('Der Server ist nicht erreichbar.');
}
$data = $response->json() ?? [];
return match (true) {
$response->status() === 201 || ($response->successful() && isset($data['reference'])) => FeedbackResult::sent((string) ($data['reference'] ?? '')),
$response->status() === 404 => FeedbackResult::disabled(),
$response->status() === 422 => FeedbackResult::invalid($this->fieldErrors($data), $data['error'] ?? $data['message'] ?? null),
$response->status() === 429 => FeedbackResult::rateLimited($this->retryAfter($response->header('Retry-After'), $data)),
// 409: dieselbe Meldung wird gerade verarbeitet – kurz warten, dann erneut (kein Fehler).
$response->status() === 409 => FeedbackResult::retry('Wird bereits verarbeitet.', 30),
default => FeedbackResult::retry('Server antwortet mit HTTP '.$response->status().'.', $this->retryAfter($response->header('Retry-After'), $data)),
};
}
private function url(string $type): string
{
return rtrim(config('updater.api_url'), '/').'/software/'.config('updater.software').'/'.$type;
}
/**
* Unterstützt {"errors": {"feld": ["Grund"]}} und {"field": "feld", "error": "Grund"}.
*
* @param array<string, mixed> $data
* @return array<string, string>
*/
private function fieldErrors(array $data): array
{
$errors = [];
if (is_array($data['errors'] ?? null)) {
foreach ($data['errors'] as $field => $messages) {
$errors[(string) $field] = is_array($messages) ? (string) reset($messages) : (string) $messages;
}
}
if (is_string($data['field'] ?? null)) {
$errors[$data['field']] = (string) ($data['error'] ?? $data['message'] ?? 'Ungültige Eingabe.');
}
return $errors;
}
/**
* @param array<string, mixed> $data
*/
private function retryAfter(?string $header, array $data): ?int
{
$value = $data['retry_after'] ?? $header;
return is_numeric($value) ? (int) $value : null;
}
}

View file

@ -0,0 +1,137 @@
<?php
namespace App\Support\Feedback;
use App\Models\User;
use App\Models\VendorFeedback;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Log;
/**
* Warteschlange für Rückmeldungen: Die Meldung wird sofort gespeichert (samt
* Idempotency-Key) und dann zugestellt. Klappt das nicht, versucht es der
* Hintergrundlauf erneut – höchstens fünfmal, danach wird verworfen und die
* Person informiert.
*/
class FeedbackOutbox
{
public const MAX_ATTEMPTS = 5;
public function __construct(
private readonly FeedbackClient $client,
private readonly FeedbackChannels $channels,
) {}
/**
* Neue Meldung speichern und direkt einen ersten Zustellversuch machen.
*
* @param array<string, mixed> $payload
*/
public function submit(?User $user, string $type, array $payload): FeedbackResult
{
$feedback = VendorFeedback::query()->create([
'user_id' => $user?->id,
'type' => $type,
'payload' => $payload,
// Je Meldung EINMAL erzeugt und bei jedem Wiederholungsversuch mitgeschickt.
'idempotency_key' => bin2hex(random_bytes(16)),
'status' => VendorFeedback::PENDING,
'next_attempt_at' => now(),
]);
$result = $this->attempt($feedback, timeout: 8);
// Eingabe- und Mengenfehler klärt die Person im Formular – nicht die Warteschlange.
// Die Eingabe bleibt im Formular erhalten; eine neue Meldung bekommt einen neuen Schlüssel.
if (in_array($result->status, [FeedbackResult::INVALID, FeedbackResult::RATE_LIMITED, FeedbackResult::DISABLED], true)) {
$feedback->delete();
}
return $result;
}
/**
* Fällige Meldungen erneut senden (Hintergrundlauf). Nacheinander, damit das
* Gerätetoken zwischen den Anfragen nachgeführt wird.
*/
public function processDue(): int
{
$processed = 0;
VendorFeedback::query()
->where('status', VendorFeedback::PENDING)
->where('next_attempt_at', '<=', now())
->orderBy('id')
->limit(20)
->get()
->each(function (VendorFeedback $feedback) use (&$processed) {
$this->attempt($feedback);
$processed++;
});
return $processed;
}
private function attempt(VendorFeedback $feedback, int $timeout = 15): FeedbackResult
{
$result = $this->client->send($feedback->type, $feedback->payload, $feedback->idempotency_key, $timeout);
$attempts = $feedback->attempts + 1;
switch ($result->status) {
case FeedbackResult::SENT:
$feedback->update(['status' => VendorFeedback::SENT, 'attempts' => $attempts, 'reference' => $result->reference, 'last_error' => null]);
Log::info("Rückmeldung zugestellt: {$result->reference}");
break;
case FeedbackResult::DISABLED:
$this->channels->disable($feedback->type);
$this->discard($feedback, $attempts, 'Dieser Meldeweg ist für das Programm nicht freigeschaltet.');
break;
case FeedbackResult::INVALID:
case FeedbackResult::RATE_LIMITED:
if ($feedback->attempts > 0) {
// Nur im Hintergrund möglich (z. B. 429 bei Wiederholung): später erneut.
$this->reschedule($feedback, $attempts, $result->message ?? 'Später erneut versuchen.', $result->retryAfter);
}
break;
default:
$this->reschedule($feedback, $attempts, $result->message ?? 'Nicht zugestellt.', $result->retryAfter);
}
return $result;
}
private function reschedule(VendorFeedback $feedback, int $attempts, string $error, ?int $retryAfter): void
{
if ($attempts >= self::MAX_ATTEMPTS) {
$this->discard($feedback, $attempts, $error);
return;
}
// 1, 5, 15, 60 Minuten – oder so lange, wie der Server es verlangt.
$delay = $retryAfter ?? [60, 300, 900, 3600][min($attempts - 1, 3)];
$feedback->update([
'attempts' => $attempts,
'next_attempt_at' => now()->addSeconds(max(30, $delay)),
'last_error' => mb_substr($error, 0, 500),
]);
}
private function discard(VendorFeedback $feedback, int $attempts, string $error): void
{
$feedback->update(['status' => VendorFeedback::DISCARDED, 'attempts' => $attempts, 'last_error' => mb_substr($error, 0, 500)]);
Log::warning("Rückmeldung verworfen nach {$attempts} Versuchen: {$error}");
if ($feedback->user) {
Notification::make()
->danger()
->title('Rückmeldung konnte nicht zugestellt werden')
->body('„'.($feedback->payload['title'] ?? '').'“ wurde nach '.$attempts.' Versuchen verworfen. Bitte senden Sie die Meldung später erneut.')
->sendToDatabase($feedback->user);
}
}
}

View file

@ -0,0 +1,58 @@
<?php
namespace App\Support\Feedback;
/**
* Ergebnis eines Zustellversuchs.
*/
final class FeedbackResult
{
public const SENT = 'sent';
public const INVALID = 'invalid';
public const RATE_LIMITED = 'rate_limited';
public const DISABLED = 'disabled';
public const RETRY = 'retry';
/**
* @param array<string, string> $errors Feld => Meldung (bei 422)
*/
private function __construct(
public readonly string $status,
public readonly ?string $reference = null,
public readonly array $errors = [],
public readonly ?int $retryAfter = null,
public readonly ?string $message = null,
) {}
public static function sent(string $reference): self
{
return new self(self::SENT, reference: $reference);
}
/**
* @param array<string, string> $errors
*/
public static function invalid(array $errors, ?string $message = null): self
{
return new self(self::INVALID, errors: $errors, message: $message);
}
public static function rateLimited(?int $retryAfter): self
{
return new self(self::RATE_LIMITED, retryAfter: $retryAfter);
}
public static function disabled(): self
{
return new self(self::DISABLED);
}
public static function retry(string $message, ?int $retryAfter = null): self
{
return new self(self::RETRY, retryAfter: $retryAfter, message: $message);
}
}

View file

@ -0,0 +1,64 @@
<?php
namespace App\Support\Feedback;
use App\Support\License\VendorHttp;
use App\Support\Update\Channels;
use App\Support\Update\InstalledVersion;
use App\Version;
use Illuminate\Support\Facades\DB;
use Throwable;
/**
* Technische Angaben, die jede Meldung automatisch mitschickt – und die vor dem
* Absenden sichtbar sind. Keine personenbezogenen Daten, keine Dateipfade,
* keine Inhalte.
*/
class TechnicalInfo
{
public function __construct(
private readonly InstalledVersion $version,
private readonly Channels $channels,
) {}
/**
* @return array{app_version: string, current_sha: string|null, os: string, metadata: array<string, string|int>}
*/
public function collect(): array
{
return [
'app_version' => Version::VERSION,
'current_sha' => $this->version->current(),
'os' => VendorHttp::operatingSystem(),
'metadata' => array_filter([
'php' => PHP_VERSION,
'datenbank' => $this->database(),
'webserver' => $this->webserver(),
'update_kanal' => $this->channels->active(),
'cache' => (string) config('cache.default'),
'queue' => (string) config('queue.default'),
'sprache' => app()->getLocale(),
'opcache' => function_exists('opcache_get_status') && @opcache_get_status(false) ? 'an' : 'aus',
], fn ($value) => $value !== null && $value !== ''),
];
}
private function database(): ?string
{
try {
$version = (string) DB::selectOne('select version() as v')->v;
return (str_contains(strtolower($version), 'mariadb') ? 'MariaDB ' : 'MySQL ').preg_replace('/-.*$/', '', $version);
} catch (Throwable) {
return null;
}
}
private function webserver(): ?string
{
$software = (string) ($_SERVER['SERVER_SOFTWARE'] ?? '');
// Nur Produkt und Version, keine Modul-Liste.
return $software !== '' ? strtok($software, ' ') : PHP_SAPI;
}
}

View file

@ -2,14 +2,21 @@
namespace App\Support;
use Illuminate\Encryption\Encrypter;
/**
* Ob diese Installation eingerichtet ist. Der Web-Installer legt die Markierung
* storage/.installed an; lokale Entwicklungsumgebungen gelten immer als eingerichtet.
* Installationsstatus und Vorbereitung für den Web-Installer.
*/
class Installation
{
public static function isInstalled(): bool
{
$forced = config('inhaus.installed');
if ($forced !== null && $forced !== '') {
return filter_var($forced, FILTER_VALIDATE_BOOL);
}
return is_file(storage_path('.installed')) || app()->environment('local');
}
@ -17,4 +24,27 @@ class Installation
{
file_put_contents(storage_path('.installed'), date(DATE_ATOM));
}
/**
* Frisch hochgeladene Installation: .env aus der Vorlage anlegen und einen
* Anwendungsschlüssel erzeugen – ohne Schlüssel funktionieren weder Sitzungen
* noch Cookies, also auch der Installer nicht.
*/
public static function prepareEnvironment(): void
{
$env = app()->environmentFilePath();
if (! is_file($env) && is_file(base_path('.env.example')) && is_writable(base_path())) {
$key = 'base64:'.base64_encode(Encrypter::generateKey(config('app.cipher', 'AES-256-CBC')));
copy(base_path('.env.example'), $env);
EnvFile::set($env, [
'APP_KEY' => $key,
'APP_ENV' => 'production',
'APP_DEBUG' => 'false',
]);
config(['app.key' => $key, 'app.env' => 'production', 'app.debug' => false]);
}
}
}

View file

@ -4,6 +4,7 @@ namespace App\Support;
use App\Models\Setting;
use Illuminate\Support\Facades\Cache;
use Throwable;
/**
* Systemweite Einstellungen als Schlüssel/Wert-Paare.
@ -47,10 +48,15 @@ class Settings
*/
public function all(): array
{
return $this->values ??= Cache::rememberForever(
self::CACHE_KEY,
fn () => Setting::query()->pluck('value', 'key')->all(),
);
try {
return $this->values ??= Cache::rememberForever(
self::CACHE_KEY,
fn () => Setting::query()->pluck('value', 'key')->all(),
);
} catch (Throwable) {
// Noch keine Datenbank (Web-Installer) oder vorübergehend nicht erreichbar.
return [];
}
}
public function flush(): void

262
app/Support/SiteHealth.php Normal file
View file

@ -0,0 +1,262 @@
<?php
namespace App\Support;
use App\Support\License\LicenseStore;
use App\Support\License\ServerError;
use App\Support\License\ServerMessages;
use App\Support\Update\MaintenanceFlag;
use App\Support\Update\Migrations;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Throwable;
/**
* Systemzustand: prüft Voraussetzungen und Betrieb. Wird im Admin-Bereich
* angezeigt und vom Web-Installer für die Systemprüfung genutzt.
*/
class SiteHealth
{
public const OK = 'ok';
public const WARNING = 'warning';
public const ERROR = 'error';
public const MIN_PHP = '8.3.0';
public const REQUIRED_EXTENSIONS = ['pdo_mysql', 'mbstring', 'openssl', 'intl', 'gd', 'zip', 'fileinfo', 'tokenizer', 'ctype', 'xml', 'dom'];
/**
* Voraussetzungen, die schon vor der Installation erfüllt sein müssen.
*
* @return list<array{label: string, status: string, message: string}>
*/
public function requirements(): array
{
$checks = [];
$checks[] = $this->check(
'PHP-Version',
version_compare(PHP_VERSION, self::MIN_PHP, '>='),
'PHP '.PHP_VERSION,
'Benötigt wird mindestens PHP '.self::MIN_PHP.'. Die Version lässt sich meist in der Verwaltung des Hosters umstellen.',
);
$missing = array_values(array_filter(self::REQUIRED_EXTENSIONS, fn (string $ext) => ! extension_loaded($ext)));
$checks[] = $this->check(
'PHP-Erweiterungen',
$missing === [],
'Alle vorhanden',
'Es fehlen: '.implode(', ', $missing).'. Bitte beim Hoster aktivieren.',
);
$checks[] = [
'label' => 'Ausgehende Verbindungen',
'status' => function_exists('curl_init') || ini_get('allow_url_fopen') ? self::OK : self::WARNING,
'message' => function_exists('curl_init') ? 'cURL verfügbar' : 'Weder cURL noch allow_url_fopen – Updates sind so nicht möglich.',
];
foreach (['storage' => storage_path(), 'bootstrap/cache' => base_path('bootstrap/cache'), 'public/uploads' => public_path('uploads')] as $label => $path) {
$checks[] = $this->check(
"Schreibrechte: {$label}",
$this->writable($path),
'Beschreibbar',
"Das Verzeichnis {$label} muss für den Webserver beschreibbar sein.",
);
}
$checks[] = [
'label' => 'Schreibrechte für Updates',
'status' => $this->writable(base_path('app')) && $this->writable(base_path('vendor')) && $this->writable(public_path('build')) ? self::OK : self::WARNING,
'message' => $this->writable(base_path('app'))
? 'Programmdateien sind beschreibbar – Aktualisierungen per Klick funktionieren.'
: 'Programmdateien sind nicht beschreibbar – Aktualisierungen per Klick sind so nicht möglich.',
];
return $checks;
}
/**
* Alle Prüfungen für die Seite „Systemzustand“.
*
* @return array<string, list<array{label: string, status: string, message: string}>>
*/
public function all(): array
{
return [
'Voraussetzungen' => $this->requirements(),
'Leistung und Grenzen' => $this->performance(),
'Betrieb' => $this->operations(),
'Sicherheit' => $this->security(),
];
}
/**
* @return list<array{label: string, status: string, message: string}>
*/
private function performance(): array
{
$opcache = function_exists('opcache_get_status') && @opcache_get_status(false);
$memory = self::bytes((string) ini_get('memory_limit'));
$upload = min(self::bytes((string) ini_get('upload_max_filesize')), self::bytes((string) ini_get('post_max_size')));
return [
[
'label' => 'OPcache',
'status' => $opcache ? self::OK : self::WARNING,
'message' => $opcache ? 'Aktiv' : 'Nicht aktiv – das Portal läuft deutlich langsamer. Bitte beim Hoster aktivieren.',
],
[
'label' => 'Arbeitsspeicher (memory_limit)',
'status' => $memory === -1 || $memory >= 128 * 1024 ** 2 ? self::OK : self::WARNING,
'message' => ini_get('memory_limit').($memory !== -1 && $memory < 128 * 1024 ** 2 ? ' – empfohlen sind mindestens 128M.' : ''),
],
[
'label' => 'Maximale Upload-Größe',
'status' => $upload === -1 || $upload >= 8 * 1024 ** 2 ? self::OK : self::WARNING,
'message' => ini_get('upload_max_filesize').' / '.ini_get('post_max_size').($upload !== -1 && $upload < 8 * 1024 ** 2 ? ' – für Fotos sind mindestens 8M empfohlen.' : ''),
],
$this->databaseCheck(),
];
}
/**
* @return list<array{label: string, status: string, message: string}>
*/
private function operations(): array
{
$beats = app(BackgroundTasks::class)->heartbeats();
$cron = max($beats['cron'] ?? 0, $beats['webcron'] ?? 0);
$pseudo = $beats['pseudo'] ?? 0;
$background = match (true) {
now()->getTimestamp() - $cron < 600 => ['status' => self::OK, 'message' => 'Läuft per '.(($beats['cron'] ?? 0) >= ($beats['webcron'] ?? 0) ? 'Cron' : 'Web-Cron').', zuletzt '.$this->ago($cron).'.'],
$pseudo > 0 => ['status' => self::WARNING, 'message' => 'Läuft nur beim Seitenaufruf (Pseudo-Cron), zuletzt '.$this->ago($pseudo).'. Zuverlässiger ist ein Cronjob.'],
default => ['status' => self::WARNING, 'message' => 'Noch kein Lauf erkannt. Bitte einen Cronjob einrichten (siehe unten).'],
};
try {
$pending = count(app(Migrations::class)->pending());
} catch (Throwable) {
$pending = null;
}
$license = app(LicenseStore::class);
$code = $license->lastStatus()['error_code'] ?? null;
return [
['label' => 'Hintergrundaufgaben', ...$background],
[
'label' => 'Datenbank-Migrationen',
'status' => $pending === 0 ? self::OK : ($pending === null ? self::ERROR : self::WARNING),
'message' => match (true) {
$pending === null => 'Status kann nicht gelesen werden.',
$pending === 0 => 'Alle angewendet.',
default => "{$pending} ausstehend – unter „Aktualisierung“ ausführen.",
},
],
[
'label' => 'Lizenz',
'status' => ! $license->hasLicense() || $code ? self::WARNING : self::OK,
'message' => match (true) {
! $license->hasLicense() => 'Keine Lizenz hinterlegt – Updates sind nicht möglich.',
$code !== null => ServerMessages::for(new ServerError($code, 0, $code)),
default => 'Hinterlegt.',
},
],
[
'label' => 'Wartungsmodus',
'status' => app(MaintenanceFlag::class)->isActive() ? self::WARNING : self::OK,
'message' => app(MaintenanceFlag::class)->isActive() ? 'Aktiv – es läuft gerade eine Aktualisierung.' : 'Aus',
],
];
}
/**
* @return list<array{label: string, status: string, message: string}>
*/
private function security(): array
{
$https = str_starts_with((string) config('app.url'), 'https://');
return [
[
'label' => 'Fehlerdetails (APP_DEBUG)',
'status' => match (true) {
config('app.debug') && app()->isProduction() => self::ERROR,
(bool) config('app.debug') => self::WARNING,
default => self::OK,
},
'message' => config('app.debug') ? 'Eingeschaltet – im Betrieb unbedingt ausschalten, sonst werden interne Details angezeigt.' : 'Ausgeschaltet',
],
[
'label' => 'Verschlüsselte Verbindung',
'status' => $https ? self::OK : self::WARNING,
'message' => $https ? 'Das Portal läuft über HTTPS.' : 'APP_URL beginnt nicht mit https:// – Anmeldedaten würden unverschlüsselt übertragen.',
],
[
'label' => 'Anwendungsschlüssel',
'status' => filled(config('app.key')) ? self::OK : self::ERROR,
'message' => filled(config('app.key')) ? 'Gesetzt' : 'APP_KEY fehlt.',
],
];
}
/**
* @return array{label: string, status: string, message: string}
*/
private function databaseCheck(): array
{
try {
$version = (string) DB::selectOne('select version() as v')->v;
$mariadb = str_contains(strtolower($version), 'mariadb');
$number = preg_replace('/^(\d+\.\d+\.\d+).*$/', '$1', $version);
$ok = version_compare($number, $mariadb ? '10.6.0' : '8.0.0', '>=');
return [
'label' => 'Datenbank',
'status' => $ok ? self::OK : self::WARNING,
'message' => ($mariadb ? 'MariaDB ' : 'MySQL ').$number.($ok ? '' : ' – unterstützt werden MySQL ab 8.0 und MariaDB ab 10.6.'),
];
} catch (Throwable) {
return ['label' => 'Datenbank', 'status' => self::ERROR, 'message' => 'Keine Verbindung.'];
}
}
/**
* @return array{label: string, status: string, message: string}
*/
private function check(string $label, bool $ok, string $okMessage, string $errorMessage): array
{
return ['label' => $label, 'status' => $ok ? self::OK : self::ERROR, 'message' => $ok ? $okMessage : $errorMessage];
}
private function writable(string $path): bool
{
return is_dir($path) ? is_writable($path) : is_writable(dirname($path));
}
private function ago(int $timestamp): string
{
return Carbon::createFromTimestamp($timestamp)->locale('de')->diffForHumans();
}
public static function bytes(string $value): int
{
$value = trim($value);
if ($value === '' || $value === '-1') {
return -1;
}
$number = (int) $value;
return match (strtolower(substr($value, -1))) {
'g' => $number * 1024 ** 3,
'm' => $number * 1024 ** 2,
'k' => $number * 1024,
default => $number,
};
}
}