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:
parent
43244d751a
commit
029dbd243d
38 changed files with 2274 additions and 12 deletions
80
app/Support/BackgroundTasks.php
Normal file
80
app/Support/BackgroundTasks.php
Normal 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
49
app/Support/EnvFile.php
Normal 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).'"';
|
||||
}
|
||||
}
|
||||
58
app/Support/Feedback/FeedbackChannels.php
Normal file
58
app/Support/Feedback/FeedbackChannels.php
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
80
app/Support/Feedback/FeedbackClient.php
Normal file
80
app/Support/Feedback/FeedbackClient.php
Normal 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;
|
||||
}
|
||||
}
|
||||
137
app/Support/Feedback/FeedbackOutbox.php
Normal file
137
app/Support/Feedback/FeedbackOutbox.php
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
58
app/Support/Feedback/FeedbackResult.php
Normal file
58
app/Support/Feedback/FeedbackResult.php
Normal 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);
|
||||
}
|
||||
}
|
||||
64
app/Support/Feedback/TechnicalInfo.php
Normal file
64
app/Support/Feedback/TechnicalInfo.php
Normal 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
262
app/Support/SiteHealth.php
Normal 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue