Newwebshop/app/Admin/controllers/AdminSettingsController.php

326 lines
11 KiB
PHP

<?php
/**
* Copyright seit 2024 Webshop System
*
* Admin-Einstellungen-Controller für das Webshop-System
*
* @author Webshop System
* @license GPL v3
*/
namespace App\Admin\Controllers;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Exception;
class AdminSettingsController
{
public function index()
{
// Session prüfen
session_start();
if (!isset($_SESSION['admin_user_id'])) {
header('Location: /admin/login');
exit;
}
// DB-Verbindung herstellen
$connectionParams = [
'dbname' => getenv('DB_DATABASE') ?: 'freeshop',
'user' => getenv('DB_USERNAME') ?: 'freeshop_user',
'password' => getenv('DB_PASSWORD') ?: 'freeshop_password',
'host' => getenv('DB_HOST') ?: 'db',
'driver' => 'pdo_mysql',
'port' => getenv('DB_PORT') ?: 3306,
'charset' => 'utf8mb4',
];
try {
$conn = DriverManager::getConnection($connectionParams);
// Alle Einstellungen laden
$stmt = $conn->prepare('SELECT * FROM ws_configuration ORDER BY category, name');
$stmt->execute();
$settings = [];
while ($row = $stmt->fetchAssociative()) {
$settings[$row['category']][] = $row;
}
$this->render('admin/settings/index.html.twig', [
'title' => 'Webshop Admin - Einstellungen',
'user_name' => $_SESSION['admin_user_name'],
'settings' => $settings
]);
} catch (Exception $e) {
$this->render('admin/settings/index.html.twig', [
'title' => 'Webshop Admin - Einstellungen',
'user_name' => $_SESSION['admin_user_name'],
'settings' => [],
'error' => 'Datenbankfehler: ' . $e->getMessage()
]);
}
}
public function edit()
{
// Session prüfen
session_start();
if (!isset($_SESSION['admin_user_id'])) {
header('Location: /admin/login');
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$this->update();
return;
}
// DB-Verbindung herstellen
$connectionParams = [
'dbname' => getenv('DB_DATABASE') ?: 'freeshop',
'user' => getenv('DB_USERNAME') ?: 'freeshop_user',
'password' => getenv('DB_PASSWORD') ?: 'freeshop_password',
'host' => getenv('DB_HOST') ?: 'db',
'driver' => 'pdo_mysql',
'port' => getenv('DB_PORT') ?: 3306,
'charset' => 'utf8mb4',
];
try {
$conn = DriverManager::getConnection($connectionParams);
// Alle Einstellungen laden
$stmt = $conn->prepare('SELECT * FROM ws_configuration ORDER BY category, name');
$stmt->execute();
$settings = [];
while ($row = $stmt->fetchAssociative()) {
$settings[$row['category']][] = $row;
}
$this->render('admin/settings/edit.html.twig', [
'title' => 'Webshop Admin - Einstellungen bearbeiten',
'user_name' => $_SESSION['admin_user_name'],
'settings' => $settings
]);
} catch (Exception $e) {
header('Location: /admin/settings?error=Datenbankfehler: ' . $e->getMessage());
exit;
}
}
private function update()
{
$connectionParams = [
'dbname' => getenv('DB_DATABASE') ?: 'freeshop',
'user' => getenv('DB_USERNAME') ?: 'freeshop_user',
'password' => getenv('DB_PASSWORD') ?: 'freeshop_password',
'host' => getenv('DB_HOST') ?: 'db',
'driver' => 'pdo_mysql',
'port' => getenv('DB_PORT') ?: 3306,
'charset' => 'utf8mb4',
];
try {
$conn = DriverManager::getConnection($connectionParams);
// Alle POST-Daten durchgehen und Einstellungen aktualisieren
foreach ($_POST as $key => $value) {
if (strpos($key, 'setting_') === 0) {
$settingName = substr($key, 8); // 'setting_' entfernen
$stmt = $conn->prepare('UPDATE ws_configuration SET value = ?, updated_at = NOW() WHERE name = ?');
$stmt->execute([$value, $settingName]);
}
}
header('Location: /admin/settings?success=Einstellungen erfolgreich gespeichert');
exit;
} catch (Exception $e) {
header('Location: /admin/settings/edit?error=Datenbankfehler: ' . $e->getMessage());
exit;
}
}
public function backup()
{
// Session prüfen
session_start();
if (!isset($_SESSION['admin_user_id'])) {
header('Location: /admin/login');
exit;
}
$connectionParams = [
'dbname' => getenv('DB_DATABASE') ?: 'freeshop',
'user' => getenv('DB_USERNAME') ?: 'freeshop_user',
'password' => getenv('DB_PASSWORD') ?: 'freeshop_password',
'host' => getenv('DB_HOST') ?: 'db',
'driver' => 'pdo_mysql',
'port' => getenv('DB_PORT') ?: 3306,
'charset' => 'utf8mb4',
];
try {
$conn = DriverManager::getConnection($connectionParams);
// Alle Tabellen für Backup laden
$tables = ['ws_user', 'ws_product', 'ws_category', 'ws_order', 'ws_order_product', 'ws_configuration'];
$backup = [];
foreach ($tables as $table) {
$stmt = $conn->prepare('SELECT * FROM ' . $table);
$stmt->execute();
$backup[$table] = $stmt->fetchAllAssociative();
}
$backupData = [
'timestamp' => date('Y-m-d_H-i-s'),
'tables' => $backup
];
// Backup-Datei erstellen
$backupDir = __DIR__ . '/../../../backups/';
if (!is_dir($backupDir)) {
mkdir($backupDir, 0755, true);
}
$filename = 'backup_' . date('Y-m-d_H-i-s') . '.json';
$filepath = $backupDir . $filename;
file_put_contents($filepath, json_encode($backupData, JSON_PRETTY_PRINT));
header('Location: /admin/settings?success=Backup erfolgreich erstellt: ' . $filename);
exit;
} catch (Exception $e) {
header('Location: /admin/settings?error=Backup-Fehler: ' . $e->getMessage());
exit;
}
}
public function restore()
{
// Session prüfen
session_start();
if (!isset($_SESSION['admin_user_id'])) {
header('Location: /admin/login');
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Location: /admin/settings?error=Ungültige Anfrage');
exit;
}
$backupFile = $_FILES['backup_file'] ?? null;
if (!$backupFile || $backupFile['error'] !== UPLOAD_ERR_OK) {
header('Location: /admin/settings?error=Backup-Datei konnte nicht hochgeladen werden');
exit;
}
$connectionParams = [
'dbname' => getenv('DB_DATABASE') ?: 'freeshop',
'user' => getenv('DB_USERNAME') ?: 'freeshop_user',
'password' => getenv('DB_PASSWORD') ?: 'freeshop_password',
'host' => getenv('DB_HOST') ?: 'db',
'driver' => 'pdo_mysql',
'port' => getenv('DB_PORT') ?: 3306,
'charset' => 'utf8mb4',
];
try {
$conn = DriverManager::getConnection($connectionParams);
// Backup-Daten laden
$backupData = json_decode(file_get_contents($backupFile['tmp_name']), true);
if (!$backupData || !isset($backupData['tables'])) {
header('Location: /admin/settings?error=Ungültige Backup-Datei');
exit;
}
// Tabellen zurücksetzen
foreach ($backupData['tables'] as $table => $data) {
// Tabelle leeren
$conn->executeStatement('DELETE FROM ' . $table);
// Daten wiederherstellen
if (!empty($data)) {
foreach ($data as $row) {
$columns = implode(', ', array_keys($row));
$values = implode(', ', array_fill(0, count($row), '?'));
$sql = 'INSERT INTO ' . $table . ' (' . $columns . ') VALUES (' . $values . ')';
$stmt = $conn->prepare($sql);
$stmt->execute(array_values($row));
}
}
}
header('Location: /admin/settings?success=Datenbank erfolgreich wiederhergestellt');
exit;
} catch (Exception $e) {
header('Location: /admin/settings?error=Wiederherstellungsfehler: ' . $e->getMessage());
exit;
}
}
public function clearCache()
{
// Session prüfen
session_start();
if (!isset($_SESSION['admin_user_id'])) {
header('Location: /admin/login');
exit;
}
try {
// Cache-Verzeichnisse leeren
$cacheDirs = [
__DIR__ . '/../../../cache/',
__DIR__ . '/../../../var/cache/',
__DIR__ . '/../../../tmp/'
];
foreach ($cacheDirs as $dir) {
if (is_dir($dir)) {
$this->clearDirectory($dir);
}
}
header('Location: /admin/settings?success=Cache erfolgreich geleert');
exit;
} catch (Exception $e) {
header('Location: /admin/settings?error=Cache-Fehler: ' . $e->getMessage());
exit;
}
}
private function clearDirectory($dir)
{
$files = glob($dir . '*');
foreach ($files as $file) {
if (is_file($file)) {
unlink($file);
} elseif (is_dir($file)) {
$this->clearDirectory($file);
rmdir($file);
}
}
}
protected function render($template, $data = [])
{
// Einfache Template-Engine (später durch Twig ersetzen)
extract($data);
include __DIR__ . '/../../templates/' . $template;
}
}