query('SELECT COUNT(*) FROM users')->fetchColumn() > 0; } catch (PDOException) { $hasUsers = false; } if ($hasUsers) { install_fail(409, 'Es gibt bereits Benutzer. Installation abgebrochen.'); } $schemaFile = __DIR__ . '/sql/schema.sql'; if (!is_file($schemaFile)) { install_fail(500, 'schema.sql fehlt.'); } try { $sql = (string) file_get_contents($schemaFile); $sql = preg_replace('/^\s*--.*$/m', '', $sql) ?? $sql; $statements = preg_split('/;\s*(?:\r?\n|$)/', $sql) ?: []; foreach ($statements as $statement) { $statement = trim($statement); if ($statement === '') { continue; } try { $pdo->exec($statement); } catch (PDOException $error) { // Ein erneuter Lauf darf an einer bereits vorhandenen // Fremdschlüssel-Bedingung nicht scheitern. $code = (int) ($error->errorInfo[1] ?? 0); if (str_contains($statement, 'ADD CONSTRAINT') && in_array($code, [121, 1005, 1061, 1826], true) ) { continue; } throw $error; } } $stmt = $pdo->prepare( 'INSERT INTO users (username, display_name, email, password_hash, role, status, must_change_password, auth_epoch, created_at, password_changed_at) VALUES (?, ?, ?, ?, ?, ?, 0, 1, ?, ?)' ); $now = utc_now(); $stmt->execute([ $adminUser, mb_substr($adminDisplay, 0, 64, 'UTF-8'), $adminEmail !== '' ? $adminEmail : null, hash_password($adminPassword), 'admin', 'active', $now, $now, ]); $adminId = (int) $pdo->lastInsertId(); audit('install.admin', 'user', $adminId, $adminUser, $adminId); foreach (['', 'logs', 'uploads'] as $sub) { $dir = storage_path($sub); if (!is_dir($dir)) { @mkdir($dir, 0770, true); } } $guard = storage_path('.htaccess'); if (!is_file($guard)) { @file_put_contents($guard, "Require all denied\n"); } @file_put_contents(storage_path('.installed'), utc_now() . "\n"); } catch (Throwable $error) { install_fail(500, 'Installation fehlgeschlagen: ' . $error->getMessage()); } @unlink(__FILE__); header('Content-Type: text/plain; charset=utf-8'); echo "installiert\n"; echo "admin=" . $adminUser . "\n";