diff --git a/app/Filament/Pages/Feedback.php b/app/Filament/Pages/Feedback.php new file mode 100644 index 00000000..ab0b04ba --- /dev/null +++ b/app/Filament/Pages/Feedback.php @@ -0,0 +1,137 @@ +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 + */ + 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(), + ]; + } +} diff --git a/app/Filament/Pages/SystemHealth.php b/app/Filament/Pages/SystemHealth.php new file mode 100644 index 00000000..84bd74ce --- /dev/null +++ b/app/Filament/Pages/SystemHealth.php @@ -0,0 +1,39 @@ + + */ + 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()), + ]; + } +} diff --git a/app/Http/Controllers/CronController.php b/app/Http/Controllers/CronController.php new file mode 100644 index 00000000..e134a597 --- /dev/null +++ b/app/Http/Controllers/CronController.php @@ -0,0 +1,23 @@ +webCronToken(), $token), 404); + + @ignore_user_abort(true); + $tasks->run('webcron'); + + return response()->noContent(); + } +} diff --git a/app/Http/Controllers/InstallController.php b/app/Http/Controllers/InstallController.php new file mode 100644 index 00000000..81cf53bf --- /dev/null +++ b/app/Http/Controllers/InstallController.php @@ -0,0 +1,160 @@ +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, + }; + } +} diff --git a/app/Http/Middleware/RedirectToInstaller.php b/app/Http/Middleware/RedirectToInstaller.php new file mode 100644 index 00000000..af19b9e3 --- /dev/null +++ b/app/Http/Middleware/RedirectToInstaller.php @@ -0,0 +1,23 @@ +is('install', 'install/*', 'up')) { + return redirect('/install'); + } + + return $next($request); + } +} diff --git a/app/Http/Middleware/RunPseudoCron.php b/app/Http/Middleware/RunPseudoCron.php new file mode 100644 index 00000000..8b3fd235 --- /dev/null +++ b/app/Http/Middleware/RunPseudoCron.php @@ -0,0 +1,33 @@ +runningUnitTests() || ! Installation::isInstalled() || ! $this->tasks->pseudoCronDue()) { + return; + } + + $this->tasks->run('pseudo'); + } +} diff --git a/app/Models/VendorFeedback.php b/app/Models/VendorFeedback.php new file mode 100644 index 00000000..1db7e9ba --- /dev/null +++ b/app/Models/VendorFeedback.php @@ -0,0 +1,40 @@ + 'Fehlerbericht', + 'featurerequest' => 'Funktionswunsch', + ]; + + protected $table = 'vendor_feedback'; + + protected function casts(): array + { + return [ + 'payload' => 'array', + 'next_attempt_at' => 'datetime', + ]; + } + + /** + * @return BelongsTo + */ + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index fe18b4d1..c553bee8 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -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); diff --git a/app/Providers/Filament/AdminPanelProvider.php b/app/Providers/Filament/AdminPanelProvider.php index cfd8aa47..df6bfb96 100644 --- a/app/Providers/Filament/AdminPanelProvider.php +++ b/app/Providers/Filament/AdminPanelProvider.php @@ -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('/') diff --git a/app/Support/BackgroundTasks.php b/app/Support/BackgroundTasks.php new file mode 100644 index 00000000..f25a6965 --- /dev/null +++ b/app/Support/BackgroundTasks.php @@ -0,0 +1,80 @@ +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 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; + } +} diff --git a/app/Support/EnvFile.php b/app/Support/EnvFile.php new file mode 100644 index 00000000..e1b9ddbb --- /dev/null +++ b/app/Support/EnvFile.php @@ -0,0 +1,49 @@ + $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).'"'; + } +} diff --git a/app/Support/Feedback/FeedbackChannels.php b/app/Support/Feedback/FeedbackChannels.php new file mode 100644 index 00000000..3c755ed9 --- /dev/null +++ b/app/Support/Feedback/FeedbackChannels.php @@ -0,0 +1,58 @@ + 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|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; + } + } +} diff --git a/app/Support/Feedback/FeedbackClient.php b/app/Support/Feedback/FeedbackClient.php new file mode 100644 index 00000000..901d5551 --- /dev/null +++ b/app/Support/Feedback/FeedbackClient.php @@ -0,0 +1,80 @@ + $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 $data + * @return array + */ + 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 $data + */ + private function retryAfter(?string $header, array $data): ?int + { + $value = $data['retry_after'] ?? $header; + + return is_numeric($value) ? (int) $value : null; + } +} diff --git a/app/Support/Feedback/FeedbackOutbox.php b/app/Support/Feedback/FeedbackOutbox.php new file mode 100644 index 00000000..69cf705e --- /dev/null +++ b/app/Support/Feedback/FeedbackOutbox.php @@ -0,0 +1,137 @@ + $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); + } + } +} diff --git a/app/Support/Feedback/FeedbackResult.php b/app/Support/Feedback/FeedbackResult.php new file mode 100644 index 00000000..e5f31c4f --- /dev/null +++ b/app/Support/Feedback/FeedbackResult.php @@ -0,0 +1,58 @@ + $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 $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); + } +} diff --git a/app/Support/Feedback/TechnicalInfo.php b/app/Support/Feedback/TechnicalInfo.php new file mode 100644 index 00000000..e45efdf4 --- /dev/null +++ b/app/Support/Feedback/TechnicalInfo.php @@ -0,0 +1,64 @@ +} + */ + 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; + } +} diff --git a/app/Support/Installation.php b/app/Support/Installation.php index 90ebbdd1..26645f72 100644 --- a/app/Support/Installation.php +++ b/app/Support/Installation.php @@ -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]); + } + } } diff --git a/app/Support/Settings.php b/app/Support/Settings.php index 9e283a0f..aaf21fa9 100644 --- a/app/Support/Settings.php +++ b/app/Support/Settings.php @@ -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 diff --git a/app/Support/SiteHealth.php b/app/Support/SiteHealth.php new file mode 100644 index 00000000..ea922d44 --- /dev/null +++ b/app/Support/SiteHealth.php @@ -0,0 +1,262 @@ + + */ + 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> + */ + public function all(): array + { + return [ + 'Voraussetzungen' => $this->requirements(), + 'Leistung und Grenzen' => $this->performance(), + 'Betrieb' => $this->operations(), + 'Sicherheit' => $this->security(), + ]; + } + + /** + * @return list + */ + 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 + */ + 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 + */ + 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, + }; + } +} diff --git a/bootstrap/app.php b/bootstrap/app.php index 836b7514..0c5f90d0 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -2,7 +2,9 @@ use App\Http\Middleware\EnsureNotInMaintenance; use App\Http\Middleware\HandleInertiaRequests; +use App\Http\Middleware\RedirectToInstaller; use App\Http\Middleware\RunPendingMigrations; +use App\Http\Middleware\RunPseudoCron; use Illuminate\Foundation\Application; use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Middleware; @@ -17,9 +19,11 @@ return Application::configure(basePath: dirname(__DIR__)) ->withMiddleware(function (Middleware $middleware): void { $middleware->web(prepend: [ EnsureNotInMaintenance::class, + RedirectToInstaller::class, ], append: [ RunPendingMigrations::class, HandleInertiaRequests::class, + RunPseudoCron::class, ]); }) ->withExceptions(function (Exceptions $exceptions): void { diff --git a/config/inhaus.php b/config/inhaus.php new file mode 100644 index 00000000..f9e0b5db --- /dev/null +++ b/config/inhaus.php @@ -0,0 +1,9 @@ + env('INHAUS_INSTALLED'), + +]; diff --git a/database/migrations/2026_09_26_000004_create_vendor_feedback_table.php b/database/migrations/2026_09_26_000004_create_vendor_feedback_table.php new file mode 100644 index 00000000..4e0c16ba --- /dev/null +++ b/database/migrations/2026_09_26_000004_create_vendor_feedback_table.php @@ -0,0 +1,37 @@ +id(); + $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete(); + $table->string('type', 30); + $table->json('payload'); + $table->char('idempotency_key', 32)->unique(); + $table->string('status', 20)->default('pending'); + $table->unsignedTinyInteger('attempts')->default(0); + $table->timestamp('next_attempt_at')->nullable(); + $table->string('reference', 50)->nullable(); + $table->string('last_error', 500)->nullable(); + $table->timestamps(); + + $table->index(['status', 'next_attempt_at']); + }); + } + + public function down(): void + { + Schema::dropIfExists('vendor_feedback'); + } +}; diff --git a/database/migrations/2026_09_26_060321_create_notifications_table.php b/database/migrations/2026_09_26_060321_create_notifications_table.php new file mode 100644 index 00000000..d7380322 --- /dev/null +++ b/database/migrations/2026_09_26_060321_create_notifications_table.php @@ -0,0 +1,31 @@ +uuid('id')->primary(); + $table->string('type'); + $table->morphs('notifiable'); + $table->text('data'); + $table->timestamp('read_at')->nullable(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('notifications'); + } +}; diff --git a/phpunit.xml b/phpunit.xml index 1e358afa..a05fc308 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -19,6 +19,7 @@ + diff --git a/resources/views/filament/pages/feedback.blade.php b/resources/views/filament/pages/feedback.blade.php new file mode 100644 index 00000000..5e58db89 --- /dev/null +++ b/resources/views/filament/pages/feedback.blade.php @@ -0,0 +1,161 @@ + + + + @if ($lastReference) + + Referenznummer für Rückfragen: {{ $lastReference }} + + @endif + + @if ($notice) + + @endif + + @if (count($types) === 0) + +

Rückmeldungen an den Hersteller sind für dieses Programm derzeit nicht freigeschaltet.

+
+ @else + +
+
+ Art der Meldung +
+ @foreach ($types as $key => $label) + + @endforeach +
+
+ + + + + + @if ($type === 'bugreport') + + @endif + +
+ + +
+ +
+ Diese technischen Angaben werden mitgesendet +
+
app_version
{{ $technical['app_version'] }}
+
current_sha
{{ $technical['current_sha'] ?? '–' }}
+
os
{{ $technical['os'] }}
+ @foreach ($technical['metadata'] as $key => $value) +
metadata.{{ $key }}
{{ $value }}
+ @endforeach +
+
+ + {{-- Datenschutzhinweis über dem Absendeknopf (docs/specs/feedback.md). Zeilen für nicht + gesendete Angaben sind gestrichen: Anhänge gibt es nicht, Lizenzdaten nur mit Lizenz. --}} +
+

Mit dem Absenden werden Daten an api.loheide.cloud übertragen. Übermittelt werden:

+
    +
  • Ihr Text: Betreff und Beschreibung
  • +
  • Name und E-Mail-Adresse, soweit Sie sie angeben – für Rückfragen
  • + @if ($hasLicense) +
  • Ihre Lizenzdaten, damit die Meldung Ihrem Konto zugeordnet werden kann
  • + @endif +
  • Programmversion, installierter Stand und Betriebssystem
  • +
  • technisch bedingt: Ihre IP-Adresse, Datum und Uhrzeit
  • +
+

Bitte beachten: Was Sie in die Beschreibung schreiben, wird mit übertragen. Enthält es Namen, Adressen oder Vorgänge anderer Personen, entfernen Sie diese bitte vorher.

+

Zweck: Bearbeitung Ihrer Meldung und Rückfragen dazu. Das Senden ist freiwillig; es geschieht nur, wenn Sie es hier auslösen.

+
+ +
+ Absenden +
+
+
+ @endif + + @if ($history->isNotEmpty()) + + + + + @foreach ($history as $item) + + + + + + + @endforeach + +
DatumArtBetreffReferenz / Status
{{ $item->created_at->format('d.m.Y H:i') }}{{ \App\Models\VendorFeedback::TYPES[$item->type] ?? $item->type }}{{ $item->payload['title'] ?? '' }} + @if ($item->status === 'sent') + {{ $item->reference }} + @elseif ($item->status === 'pending') + wird gesendet ({{ $item->attempts }}. Versuch) + @else + nicht zugestellt + @endif +
+
+ @endif +
diff --git a/resources/views/filament/pages/system-health.blade.php b/resources/views/filament/pages/system-health.blade.php new file mode 100644 index 00000000..b916aea3 --- /dev/null +++ b/resources/views/filament/pages/system-health.blade.php @@ -0,0 +1,39 @@ + + + + @foreach ($groups as $heading => $checks) + +
+ @foreach ($checks as $check) +
+ + {{ $check['label'] }} + {{ $check['message'] }} +
+ @endforeach +
+
+ @endforeach + + +

Am besten: ein Cronjob beim Hoster, der jede Minute läuft:

+
{{ $cronLine }}
+

Ohne Cron-Zugang: diese Adresse jede Minute von einem Cron-Dienst aufrufen lassen (geheim halten):

+
{{ $webCronUrl }}
+
+
diff --git a/resources/views/install/account.blade.php b/resources/views/install/account.blade.php new file mode 100644 index 00000000..fd1c4126 --- /dev/null +++ b/resources/views/install/account.blade.php @@ -0,0 +1,55 @@ +@extends('install.layout', ['step' => 3]) + +@section('content') +

Portal und Administrator

+

Mit diesem Konto verwalten Sie das Portal. Weitere Personen legen Sie später im Admin-Bereich an oder binden Ihren Identity Provider an.

+ +
+ @csrf + + + @error('portal_name')
{{ $message }}
@enderror + +
+
+ + + @error('first_name')
{{ $message }}
@enderror +
+
+ + + @error('last_name')
{{ $message }}
@enderror +
+
+ + + + @error('email')
{{ $message }}
@enderror + +
+
+ + +
+
+ + +
+
+ @error('password')
{{ $message }}
@else
Mindestens 10 Zeichen, mit Buchstaben und Ziffern.
@enderror + +
+ Lizenz (optional, für Updates) + + + @error('license_email')
{{ $message }}
@enderror + + + @error('license_key')
{{ $message }}
@enderror +
Kann auch später unter „Aktualisierung“ hinterlegt werden.
+
+ + +
+@endsection diff --git a/resources/views/install/database.blade.php b/resources/views/install/database.blade.php new file mode 100644 index 00000000..7cb01d7a --- /dev/null +++ b/resources/views/install/database.blade.php @@ -0,0 +1,38 @@ +@extends('install.layout', ['step' => 2]) + +@section('content') +

Datenbank

+

Die Zugangsdaten finden Sie in der Verwaltung Ihres Hosters. Die Datenbank muss dort bereits angelegt sein (MySQL ab 8.0 oder MariaDB ab 10.6).

+ +
+ @csrf +
+
+ + +
+
+ + +
+
+ @error('host')
{{ $message }}
@enderror + + + + @error('database')
{{ $message }}
@enderror + +
+
+ + +
+
+ + +
+
+ + +
+@endsection diff --git a/resources/views/install/layout.blade.php b/resources/views/install/layout.blade.php new file mode 100644 index 00000000..4a12a3ae --- /dev/null +++ b/resources/views/install/layout.blade.php @@ -0,0 +1,48 @@ + + + + + + + Einrichtung + + + +
+
+ $step === 1])>1 Systemprüfung + $step === 2])>2 Datenbank + $step === 3])>3 Administrator +
+
+ @yield('content') +
+
+ + diff --git a/resources/views/install/requirements.blade.php b/resources/views/install/requirements.blade.php new file mode 100644 index 00000000..321aa48d --- /dev/null +++ b/resources/views/install/requirements.blade.php @@ -0,0 +1,21 @@ +@extends('install.layout', ['step' => 1]) + +@section('content') +

Willkommen

+

In drei Schritten ist Ihr Mitarbeiterportal eingerichtet. Zuerst prüfen wir, ob der Server alles Nötige mitbringt.

+ + @foreach ($checks as $check) +
+ $check['status'] === 'ok', 'warning' => $check['status'] === 'warning', 'error-dot' => $check['status'] === 'error'])> +
{{ $check['label'] }}
{{ $check['message'] }}
+
+ @endforeach + + @unless ($envWritable) +

Die Konfigurationsdatei .env fehlt oder ist nicht beschreibbar. Bitte Schreibrechte für das Installationsverzeichnis vergeben.

+ @endunless + +
+ +
+@endsection diff --git a/routes/console.php b/routes/console.php index 3c9adf1a..c6ffc302 100644 --- a/routes/console.php +++ b/routes/console.php @@ -1,8 +1,26 @@ comment(Inspiring::quote()); -})->purpose('Display an inspiring quote'); +/* +| Geplante Aufgaben. Ausgelöst per Cron, Web-Cron oder Pseudo-Cron (App\Support\BackgroundTasks). +*/ + +// Lebenszeichen des echten Crons. Web-Cron und Pseudo-Cron vermerken sich selbst. +Schedule::call(fn () => app(BackgroundTasks::class)->heartbeat('cron')) + ->everyMinute() + ->name('heartbeat') + ->when(fn () => app()->runningInConsole()); + +Schedule::call(fn () => app(FeedbackOutbox::class)->processDue()) + ->everyMinute() + ->name('feedback-outbox') + ->withoutOverlapping(10); + +// Aufträge der Datenbank-Queue in kurzen Häppchen abarbeiten (kein Dauerprozess nötig). +Schedule::command('queue:work --stop-when-empty --max-time=40 --tries=3') + ->everyMinute() + ->name('queue') + ->withoutOverlapping(5); diff --git a/routes/web.php b/routes/web.php index 9ecfe000..8ace813c 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,13 +1,27 @@ middleware('throttle:30,1')->group(function () { + Route::get('/', [InstallController::class, 'requirements']); + Route::get('/datenbank', [InstallController::class, 'database']); + Route::post('/datenbank', [InstallController::class, 'saveDatabase']); + Route::get('/konto', [InstallController::class, 'account']); + Route::post('/konto', [InstallController::class, 'saveAccount']); +}); + +// Web-Cron für Hoster ohne Cron (siehe App\Support\BackgroundTasks). +Route::get('/cron/{token}', CronController::class)->middleware('throttle:10,1')->name('cron'); + // Login, Logout und Passwort-Reset stellt Laravel Fortify bereit (FortifyServiceProvider). Route::middleware('auth')->group(function () { diff --git a/storage/.background.lock b/storage/.background.lock new file mode 100644 index 00000000..e69de29b diff --git a/storage/.migrations-fingerprint b/storage/.migrations-fingerprint new file mode 100644 index 00000000..87e60f11 --- /dev/null +++ b/storage/.migrations-fingerprint @@ -0,0 +1 @@ +e880d7878d8f731b6539839a9721d2bff91c425b \ No newline at end of file diff --git a/tests/Feature/BackgroundTasksTest.php b/tests/Feature/BackgroundTasksTest.php new file mode 100644 index 00000000..d9891d38 --- /dev/null +++ b/tests/Feature/BackgroundTasksTest.php @@ -0,0 +1,53 @@ +webCronToken(); + + $this->assertSame(40, strlen($token)); + $this->get('/cron/falsch')->assertNotFound(); + $this->get("/cron/{$token}")->assertNoContent(); + + $this->assertArrayHasKey('webcron', app(BackgroundTasks::class)->heartbeats()); + } + + public function test_pseudo_cron_only_steps_in_without_external_cron(): void + { + $tasks = app(BackgroundTasks::class); + + $this->assertTrue($tasks->pseudoCronDue()); + + $tasks->heartbeat('cron'); + $this->assertFalse($tasks->pseudoCronDue()); + + $this->travel(BackgroundTasks::PSEUDO_CRON_AFTER_SECONDS + 5)->seconds(); + $this->assertTrue($tasks->pseudoCronDue()); + + $tasks->heartbeat('pseudo'); + $this->assertFalse($tasks->pseudoCronDue(), 'Höchstens einmal pro Minute.'); + } +} diff --git a/tests/Feature/Feedback/FeedbackTest.php b/tests/Feature/Feedback/FeedbackTest.php new file mode 100644 index 00000000..fc1d4c75 --- /dev/null +++ b/tests/Feature/Feedback/FeedbackTest.php @@ -0,0 +1,274 @@ +dir = sys_get_temp_dir().'/inhaus-fb-'.bin2hex(random_bytes(4)); + mkdir($this->dir); + $this->app->instance(LicenseStore::class, new LicenseStore($this->dir.'/license.json')); + $this->app->instance(InstalledVersion::class, new InstalledVersion($this->dir.'/.version')); + app(InstalledVersion::class)->save(str_repeat('9', 40)); + Cache::put('feedback.endpoints', ['bugreport', 'featurerequest', 'telemetry'], 60); + } + + protected function tearDown(): void + { + Filesystem::deleteDirectory($this->dir); + + parent::tearDown(); + } + + /** + * @return array + */ + private function payload(): array + { + return ['title' => 'Export bricht ab', 'body' => 'Ab etwa 5000 Zeilen passiert nichts mehr.', 'severity' => 'high']; + } + + public function test_request_body_and_headers_with_license(): void + { + app(LicenseStore::class)->setLicense('lizenz@firma.de', 'KEY-1'); + Http::fake([self::URL => Http::response(['ok' => true, 'reference' => 'BUG-8F3K2Q', 'id' => 'x'], 201)]); + $user = User::factory()->admin()->create(); + $this->actingAs($user); + + Livewire::test(Feedback::class) + ->set('type', 'bugreport') + ->set('subject', 'Export bricht ab') + ->set('body', 'Ab etwa 5000 Zeilen passiert nichts mehr.') + ->set('severity', 'high') + ->set('email', 'rueckfrage@firma.de') + ->call('submit') + ->assertHasNoErrors() + ->assertSet('lastReference', 'BUG-8F3K2Q') + ->assertSet('subject', '') + ->assertSee('BUG-8F3K2Q'); + + Http::assertSent(function (Request $request) { + $data = $request->data(); + + return $request->url() === self::URL + && $request->method() === 'POST' + && $request->hasHeader('X-License-Email', 'lizenz@firma.de') + && $request->hasHeader('Authorization', 'Bearer KEY-1') + && strlen($request->header('Idempotency-Key')[0]) === 32 + && $data['title'] === 'Export bricht ab' + && $data['email'] === 'rueckfrage@firma.de' + && $data['severity'] === 'high' + && $data['app_version'] === Version::VERSION + && $data['current_sha'] === str_repeat('9', 40) + && $data['os'] !== '' + && isset($data['metadata']['php']) + && ! isset($data['name']); + }); + + $feedback = VendorFeedback::query()->sole(); + $this->assertSame('sent', $feedback->status); + $this->assertSame('BUG-8F3K2Q', $feedback->reference); + } + + public function test_no_license_headers_without_license(): void + { + Http::fake([self::URL => Http::response(['ok' => true, 'reference' => 'BUG-1'], 201)]); + + app(FeedbackOutbox::class)->submit(null, 'bugreport', $this->payload()); + + Http::assertSent(fn (Request $request) => ! $request->hasHeader('X-License-Email') + && ! $request->hasHeader('Authorization') + && ! $request->hasHeader('X-Device-Id')); + } + + public function test_expired_license_does_not_prevent_sending(): void + { + app(LicenseStore::class)->setLicense('lizenz@firma.de', 'ABGELAUFEN'); + app(LicenseStore::class)->rememberStatus(null, 'license_expired'); + Http::fake([self::URL => Http::response(['ok' => true, 'reference' => 'BUG-2'], 201)]); + + $result = app(FeedbackOutbox::class)->submit(null, 'bugreport', $this->payload()); + + $this->assertSame(FeedbackResult::SENT, $result->status); + Http::assertSentCount(1); + } + + public function test_422_shows_error_on_field_and_keeps_input(): void + { + Http::fake([self::URL => Http::response(['code' => 'validation_failed', 'errors' => ['title' => ['Der Betreff ist zu lang.']]], 422)]); + $this->actingAs(User::factory()->admin()->create()); + + Livewire::test(Feedback::class) + ->set('type', 'bugreport') + ->set('subject', 'Betreff') + ->set('body', 'Eine ausreichend lange Beschreibung.') + ->call('submit') + ->assertHasErrors(['subject']) + ->assertSet('subject', 'Betreff') + ->assertSet('body', 'Eine ausreichend lange Beschreibung.'); + + $this->assertSame(0, VendorFeedback::query()->count()); + } + + public function test_429_names_the_waiting_time_and_keeps_input(): void + { + Http::fake([self::URL => Http::response(['code' => 'rate_limited'], 429, ['Retry-After' => '600'])]); + $this->actingAs(User::factory()->admin()->create()); + + Livewire::test(Feedback::class) + ->set('type', 'bugreport') + ->set('subject', 'Betreff') + ->set('body', 'Eine ausreichend lange Beschreibung.') + ->call('submit') + ->assertSet('notice', fn (string $notice) => str_contains($notice, 'in etwa 10 Minute(n)')) + ->assertSet('body', 'Eine ausreichend lange Beschreibung.'); + + Http::assertSentCount(1); + $this->assertSame(0, VendorFeedback::query()->count()); + } + + public function test_404_hides_the_channel_permanently(): void + { + Http::fake([self::URL => Http::response(['code' => 'not_found'], 404)]); + $this->actingAs(User::factory()->admin()->create()); + + Livewire::test(Feedback::class) + ->set('type', 'bugreport') + ->set('subject', 'Betreff') + ->set('body', 'Eine ausreichend lange Beschreibung.') + ->call('submit') + ->assertSet('type', 'featurerequest') + ->assertSet('body', 'Eine ausreichend lange Beschreibung.'); + + $this->assertSame(['featurerequest' => 'Funktionswunsch'], app(FeedbackChannels::class)->available()); + } + + public function test_only_enabled_channels_are_offered(): void + { + Cache::put('feedback.endpoints', ['featurerequest', 'telemetry'], 60); + + $this->assertSame(['featurerequest' => 'Funktionswunsch'], app(FeedbackChannels::class)->available()); + } + + public function test_channels_are_read_from_software_list(): void + { + Cache::forget('feedback.endpoints'); + Http::fake(['api.loheide.cloud/v1/software' => Http::response(['software' => [ + ['slug' => 'andere', 'endpoints' => ['bugreport']], + ['slug' => 'mitarbeiterportal', 'endpoints' => ['bugreport', 'telemetry']], + ]])]); + + $this->assertSame(['bugreport' => 'Fehlerbericht'], app(FeedbackChannels::class)->available()); + } + + public function test_503_queues_and_retries_with_same_idempotency_key(): void + { + Http::fakeSequence(self::URL) + ->push(['code' => 'maintenance'], 503) + ->push(['code' => 'maintenance'], 503) + ->push(['ok' => true, 'reference' => 'BUG-SPAET'], 201); + + $result = app(FeedbackOutbox::class)->submit(null, 'bugreport', $this->payload()); + $this->assertSame(FeedbackResult::RETRY, $result->status); + + $feedback = VendorFeedback::query()->sole(); + $this->assertSame('pending', $feedback->status); + $this->assertSame(1, $feedback->attempts); + + // Noch nicht fällig. + $this->assertSame(0, app(FeedbackOutbox::class)->processDue()); + + $this->travel(2)->minutes(); + app(FeedbackOutbox::class)->processDue(); + $this->travel(10)->minutes(); + app(FeedbackOutbox::class)->processDue(); + + $feedback->refresh(); + $this->assertSame('sent', $feedback->status); + $this->assertSame('BUG-SPAET', $feedback->reference); + + $keys = collect(Http::recorded())->map(fn ($pair) => $pair[0]->header('Idempotency-Key')[0])->unique(); + $this->assertCount(1, $keys, 'Wiederholungen müssen denselben Idempotency-Key senden.'); + } + + public function test_gives_up_after_five_attempts_and_informs_the_user(): void + { + Http::fake([self::URL => Http::response('', 503)]); + $user = User::factory()->admin()->create(); + + app(FeedbackOutbox::class)->submit($user, 'bugreport', $this->payload()); + + for ($i = 0; $i < 6; $i++) { + $this->travel(2)->hours(); + app(FeedbackOutbox::class)->processDue(); + } + + $feedback = VendorFeedback::query()->sole(); + $this->assertSame('discarded', $feedback->status); + $this->assertSame(5, $feedback->attempts); + Http::assertSentCount(5); + $this->assertSame(1, $user->notifications()->count()); + } + + public function test_network_failure_is_queued(): void + { + Http::fake([self::URL => fn () => throw new ConnectionException('offline')]); + + $result = app(FeedbackOutbox::class)->submit(null, 'bugreport', $this->payload()); + + $this->assertSame(FeedbackResult::RETRY, $result->status); + $this->assertSame('pending', VendorFeedback::query()->sole()->status); + } + + public function test_409_is_not_shown_as_error_but_retried(): void + { + Http::fake([self::URL => Http::response(['code' => 'in_progress'], 409)]); + + $result = app(FeedbackOutbox::class)->submit(null, 'bugreport', $this->payload()); + + $this->assertSame(FeedbackResult::RETRY, $result->status); + $this->assertTrue(VendorFeedback::query()->sole()->next_attempt_at->isFuture()); + } + + public function test_page_shows_technical_info_and_privacy_notice_and_is_admin_only(): void + { + $this->actingAs(User::factory()->create())->get('/admin/rueckmeldung')->assertForbidden(); + + $this->actingAs(User::factory()->admin()->create()) + ->get('/admin/rueckmeldung') + ->assertOk() + ->assertSee('Diese technischen Angaben werden mitgesendet') + ->assertSee(Version::VERSION) + ->assertSee(str_repeat('9', 40)) + ->assertSee('Mit dem Absenden werden Daten an api.loheide.cloud übertragen.') + ->assertDontSee('die von Ihnen angehängten Dateien') + ->assertDontSee('Ihre Lizenzdaten, damit die Meldung'); + } +} diff --git a/tests/Feature/InstallerTest.php b/tests/Feature/InstallerTest.php new file mode 100644 index 00000000..372c6e0c --- /dev/null +++ b/tests/Feature/InstallerTest.php @@ -0,0 +1,115 @@ +dir = sys_get_temp_dir().'/inhaus-inst-'.bin2hex(random_bytes(4)); + mkdir($this->dir); + copy(base_path('.env.example'), $this->dir.'/.env'); + $this->app->useEnvironmentPath($this->dir); + $this->app->instance(LicenseStore::class, new LicenseStore($this->dir.'/license.json')); + config(['inhaus.installed' => false]); + } + + protected function tearDown(): void + { + @unlink(storage_path('.installed')); + Filesystem::deleteDirectory($this->dir); + + parent::tearDown(); + } + + public function test_every_page_leads_to_the_installer(): void + { + $this->get('/')->assertRedirect('/install'); + $this->get('/login')->assertRedirect('/install'); + $this->get('/install')->assertOk()->assertSee('Systemprüfung')->assertSee('PHP-Version'); + } + + public function test_wrong_database_credentials_are_explained(): void + { + $this->post('/install/datenbank', [ + 'host' => config('database.connections.mysql.host'), + 'port' => config('database.connections.mysql.port'), + 'database' => config('database.connections.mysql.database'), + 'username' => 'gibtesnicht', + 'password' => 'falsch', + ])->assertSessionHasErrors(['host' => 'Verbindung fehlgeschlagen: Benutzername oder Passwort sind falsch, oder der Benutzer hat keinen Zugriff auf diese Datenbank.']); + } + + public function test_database_settings_are_written_to_env(): void + { + $this->post('/install/datenbank', [ + 'host' => config('database.connections.mysql.host'), + 'port' => config('database.connections.mysql.port'), + 'database' => config('database.connections.mysql.database'), + 'username' => config('database.connections.mysql.username'), + 'password' => config('database.connections.mysql.password'), + ])->assertRedirect('/install/konto'); + + $env = file_get_contents($this->dir.'/.env'); + $this->assertStringContainsString('DB_DATABASE='.config('database.connections.mysql.database'), $env); + $this->assertStringContainsString('DB_USERNAME='.config('database.connections.mysql.username'), $env); + $this->assertStringContainsString('APP_URL='.url('/'), $env); + } + + public function test_account_step_completes_the_installation(): void + { + $this->post('/install/konto', [ + 'portal_name' => 'Caritas-Netz', + 'first_name' => 'Ada', + 'last_name' => 'Admin', + 'email' => 'Ada@Example.com', + 'password' => 'SicheresPasswort1', + 'password_confirmation' => 'SicheresPasswort1', + 'license_email' => 'lizenz@example.com', + 'license_key' => 'KEY-123', + ])->assertRedirect('/login'); + + $admin = User::query()->where('email', 'ada@example.com')->sole(); + $this->assertTrue($admin->is_admin); + $this->assertSame('Ada Admin', $admin->name); + $this->assertSame('Caritas-Netz', app(Settings::class)->get('branding.portal_name')); + $this->assertSame('KEY-123', app(LicenseStore::class)->key()); + $this->assertFileExists(storage_path('.installed')); + + config(['inhaus.installed' => null]); + $this->assertTrue(Installation::isInstalled()); + $this->get('/install')->assertNotFound(); + } + + public function test_weak_admin_password_is_rejected(): void + { + $this->post('/install/konto', [ + 'portal_name' => 'Portal', 'first_name' => 'A', 'last_name' => 'B', 'email' => 'a@example.com', + 'password' => 'kurz', 'password_confirmation' => 'kurz', + ])->assertSessionHasErrors('password'); + + $this->assertFileDoesNotExist(storage_path('.installed')); + } + + public function test_installer_is_gone_once_installed(): void + { + config(['inhaus.installed' => true]); + + $this->get('/install')->assertNotFound(); + $this->post('/install/konto', [])->assertNotFound(); + } +} diff --git a/tests/Feature/SiteHealthTest.php b/tests/Feature/SiteHealthTest.php new file mode 100644 index 00000000..9e0e6afb --- /dev/null +++ b/tests/Feature/SiteHealthTest.php @@ -0,0 +1,42 @@ +requirements(); + + foreach ($requirements as $check) { + $this->assertNotSame(SiteHealth::ERROR, $check['status'], $check['label'].': '.$check['message']); + } + } + + public function test_page_shows_checks_and_cron_setup(): void + { + $this->actingAs(User::factory()->create())->get('/admin/systemzustand')->assertForbidden(); + + $this->actingAs(User::factory()->admin()->create()) + ->get('/admin/systemzustand') + ->assertOk() + ->assertSee('PHP-Version') + ->assertSee('Hintergrundaufgaben') + ->assertSee('php artisan schedule:run') + ->assertSee('/cron/'); + } + + public function test_byte_values_are_parsed(): void + { + $this->assertSame(128 * 1024 ** 2, SiteHealth::bytes('128M')); + $this->assertSame(2 * 1024 ** 3, SiteHealth::bytes('2G')); + $this->assertSame(-1, SiteHealth::bytes('-1')); + } +}