Files
MVC/WebTime/install_db.php
T
2026-06-24 09:18:21 +02:00

197 lines
6.6 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
if (php_sapi_name() !== 'cli') die("CLI only.\n");
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
require_once __DIR__ . '/WEBROOT/src/database/databaseConnect.php';
require_once __DIR__ . '/WEBROOT/src/utils/databaseMethods.php';
require_once __DIR__ . '/WEBROOT/src/MVC/Core/Model.php';
// ─── Config ──────────────────────────────────────────────────────────────────
$configPath = __DIR__ . '/WEBROOT/src/config/env.ini';
if (!file_exists($configPath)) die("❌ env.ini nicht gefunden: $configPath\n");
$config = parse_ini_file($configPath);
if ($config === false) die("❌ env.ini konnte nicht geparst werden.\n");
$env = strtoupper($config['APP_ENV'] ?? '');
$dbName = $config["DB_{$env}_DATABASE"] ?? '';
$workerUser = $config["DB_{$env}_USERNAME"] ?? '';
$workerPass = $config["DB_{$env}_PASSWORD"] ?? '';
if (!$env || !$dbName || !$workerUser || !$workerPass) {
die("❌ Unvollständige Konfiguration in env.ini.\n");
}
echo "🚀 Starte Datenbank-Setup als Root...\n";
echo " Umgebung : $env\n";
echo " Datenbank: $dbName\n";
echo " DB-User : $workerUser\n\n";
// ─── Root-Verbindung ─────────────────────────────────────────────────────────
$rootConn = db_connect_root();
if (!$rootConn) die("❌ Root-Verbindung fehlgeschlagen.\n");
try {
// 1. Datenbank
echo "📁 Erstelle Datenbank '$dbName'...\n";
$rootConn->query("CREATE DATABASE IF NOT EXISTS `$dbName` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
echo " ✅ Datenbank bereit.\n\n";
// 2. Worker-User (DROP + CREATE = sauber, kein GRANT-Fehler)
echo "👤 Lege Worker-User '$workerUser' an...\n";
foreach (['localhost', '%'] as $host) {
$rootConn->query("DROP USER IF EXISTS '$workerUser'@'$host'");
$rootConn->query("CREATE USER '$workerUser'@'$host' IDENTIFIED BY '$workerPass'");
echo " ✅ '$workerUser'@'$host' erstellt.\n";
}
// 3. Berechtigungen
echo "\n🔐 Vergebe Berechtigungen...\n";
foreach (['localhost', '%'] as $host) {
$rootConn->query("GRANT ALL PRIVILEGES ON `$dbName`.* TO '$workerUser'@'$host'");
echo " ✅ GRANT für '$workerUser'@'$host'.\n";
}
$rootConn->query("FLUSH PRIVILEGES");
echo " ✅ FLUSH PRIVILEGES.\n\n";
} catch (\mysqli_sql_exception $e) {
die("❌ Root-Setup fehlgeschlagen: " . $e->getMessage() . "\n");
} finally {
$rootConn->close();
}
// ─── Tabellen + Models ───────────────────────────────────────────────────────
echo "🚀 Tabellen-Installation...\n\n";
$tables = [
'Mailing' => [
'columns' => implode(', ', [
'`ID` INT AUTO_INCREMENT PRIMARY KEY',
'`DATUM` DATETIME NOT NULL',
'`SUBJECT` VARCHAR(255)',
'`MESSAGE` TEXT',
'`URL` VARCHAR(255)',
'`CLIENT_IP` VARCHAR(45)',
]),
'model' => <<<'PHP'
<?php
namespace MVC\Model;
use MVC\Core\Model;
class Mailing extends Model
{
protected static $table = "Mailing";
public static function log(
string $subject,
string $message,
string $url,
string $ip,
string $date
): bool {
return self::insert([
'DATUM' => $date,
'SUBJECT' => $subject,
'MESSAGE' => $message,
'URL' => $url,
'CLIENT_IP' => $ip,
]);
}
}
PHP
],
'Users' => [
'columns' => implode(', ', [
'`ID` INT AUTO_INCREMENT PRIMARY KEY',
'`USERNAME` VARCHAR(50) UNIQUE NOT NULL',
'`PASSWORD` VARCHAR(255) NOT NULL',
'`EMAIL` VARCHAR(100)',
'`ROLE` VARCHAR(20) DEFAULT \'user\'',
'`CREATED_AT` DATETIME DEFAULT CURRENT_TIMESTAMP',
]),
'model' => <<<'PHP'
<?php
namespace MVC\Model;
use MVC\Core\Model;
class Users extends Model
{
protected static $table = "Users";
public static function getByUsername(string $username): ?array
{
$result = self::where("USERNAME = ?", $username);
return $result[0] ?? null;
}
}
PHP
],
];
foreach ($tables as $name => $info) {
echo "--- Tabelle: $name ---\n";
try {
$created = DatabaseCreateTable($name, $info['columns']);
if ($created === false || $created === null) {
echo "❌ Tabelle '$name': DatabaseCreateTable schlug fehl.\n\n";
continue;
}
$path = __DIR__ . "/WEBROOT/src/MVC/Model/{$name}.php";
if (!file_exists($path)) {
$dir = dirname($path);
if (!is_dir($dir) && !mkdir($dir, 0755, true)) {
echo "❌ Verzeichnis konnte nicht erstellt werden: $dir\n\n";
continue;
}
if (file_put_contents($path, $info['model']) === false) {
echo "❌ Model-Datei konnte nicht geschrieben werden: $path\n\n";
continue;
}
echo "✅ Tabelle + Model '$name' erstellt.\n\n";
} else {
echo "ℹ️ Model '$name' existiert bereits.\n\n";
}
} catch (\Exception $e) {
echo "❌ Fehler bei '$name': " . $e->getMessage() . "\n\n";
}
}
// ─── Test-User ───────────────────────────────────────────────────────────────
echo "👤 Erstelle Test-User 'admin'...\n";
$usersModelPath = __DIR__ . '/WEBROOT/src/MVC/Model/Users.php';
if (!file_exists($usersModelPath)) {
echo "❌ Users.php nicht gefunden – überspringe User-Anlage.\n";
} else {
require_once $usersModelPath;
try {
if (!\MVC\Model\Users::getByUsername('admin')) {
\MVC\Model\Users::insert([
'USERNAME' => 'admin',
'PASSWORD' => password_hash('admin123', PASSWORD_BCRYPT),
'EMAIL' => 'admin@example.com',
'ROLE' => 'admin',
]);
echo "✅ Test-User 'admin' erstellt.\n";
echo "⚠️ Passwort nach erstem Login bitte ändern!\n";
} else {
echo "ℹ️ Test-User 'admin' existiert bereits.\n";
}
} catch (\Exception $e) {
echo "❌ Fehler beim Test-User: " . $e->getMessage() . "\n";
}
}
echo "\n✨ Installation abgeschlossen.\n";