HifiPlanet-Website/hifi/api/src/Controllers/DatabaseConfigController.php
Maaxxs f3ab7d0816 Initial commit: HifiPlanet Car-Hifi Shop (Frontend + Backend)
React/Vite Frontend (hifi-src) + PHP/MariaDB Backend (hifi/api) fuer
den Car-Hifi Umbau-Shop HifiPlanet in Amorbach, inkl. Admin-Panel,
2FA, Wartungsmodus, Cookie-Consent und rechtlichen Pflichtseiten.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-05 13:37:06 +02:00

65 lines
2.2 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Controllers;
use App\Support\Http;
use PDO;
use PDOException;
class DatabaseConfigController
{
private static function configPath(): string
{
return __DIR__ . '/../../config/db.php';
}
private static function currentConfig(): array
{
return require self::configPath();
}
public static function show(): void
{
$config = self::currentConfig();
unset($config['pass']);
Http::send(['config' => $config, 'has_password' => (self::currentConfig()['pass'] ?? '') !== '']);
}
public static function update(): void
{
$body = Http::jsonBody();
$current = self::currentConfig();
$host = trim($body['host'] ?? '');
$name = trim($body['name'] ?? '');
$user = trim($body['user'] ?? '');
$charset = trim($body['charset'] ?? '') ?: 'utf8mb4';
// Leeres Passwort im Formular = aktuelles Passwort beibehalten.
$pass = ($body['password'] ?? '') !== '' ? $body['password'] : $current['pass'];
if ($host === '' || $name === '' || $user === '') {
Http::error('Host, Datenbankname und Benutzer sind erforderlich', 422);
}
$newConfig = ['host' => $host, 'name' => $name, 'user' => $user, 'pass' => $pass, 'charset' => $charset];
// Erst mit den NEUEN Zugangsdaten testen, bevor irgendetwas gespeichert wird –
// damit man sich nicht versehentlich aussperrt.
try {
$dsn = "mysql:host={$host};dbname={$name};charset={$charset}";
new PDO($dsn, $user, $pass, [PDO::ATTR_TIMEOUT => 5]);
} catch (PDOException $e) {
Http::error('Verbindung mit diesen Zugangsdaten fehlgeschlagen: ' . $e->getMessage(), 422);
}
$php = "<?php\n\n// Wird über das Admin-Panel (Einstellungen -> Datenbank) verwaltet.\n"
. "// Diese Datei wird bei Änderungen automatisch neu geschrieben.\n"
. "return " . var_export($newConfig, true) . ";\n";
if (@file_put_contents(self::configPath(), $php) === false) {
Http::error('Verbindung erfolgreich getestet, aber die Konfigurationsdatei konnte nicht geschrieben werden (Dateirechte prüfen).', 500);
}
Http::send(['ok' => true]);
}
}