Repository navigation
Expand file tree
/
Copy pathindex.php
More file actions
510 lines (452 loc) · 22.7 KB
/
Copy pathindex.php
File metadata and controls
510 lines (452 loc) · 22.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
<?php
/**
* ============================================================================
* Realms Bans
* ============================================================================
*
* Plugin Name: Realms Bans
* Description: A modern, secure, and responsive web interface for LiteBans punishment management system.
* Version: 5.1
* Market URI: https://builtbybit.com/resources/litebansu-litebans-website.69448/
* Author URI: https://yamiru.com
* License: MIT
* License URI: https://opensource.org/licenses/MIT
* ============================================================================
*/
declare(strict_types=1);
if (extension_loaded('zlib') && !ini_get('zlib.output_compression') && !headers_sent()) {
ini_set('zlib.output_compression', '1');
}
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
$envLoaderPath = __DIR__ . '/core/EnvLoader.php';
if (!file_exists($envLoaderPath)) {
die('EnvLoader.php not found at: ' . $envLoaderPath);
}
require_once $envLoaderPath;
try {
core\EnvLoader::load();
} catch (Exception $e) {
die('Failed to load environment: ' . $e->getMessage());
}
require_once __DIR__ . '/core/Logger.php';
$logger = \core\Logger::getInstance();
$logger->rotateIfNeeded();
function showErrorPage(int $code, string $title, string $message, ?string $details = null): string {
http_response_code($code);
$safeTitle = htmlspecialchars($title, ENT_QUOTES, 'UTF-8');
$safeMessage = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
$scriptPath = dirname($_SERVER['SCRIPT_NAME'] ?? '');
$basePath = ($scriptPath === '/' || $scriptPath === '\\') ? '' : $scriptPath;
$homeUrl = htmlspecialchars($basePath ?: '/', ENT_QUOTES, 'UTF-8');
$detailsHtml = '';
$debug = core\EnvLoader::get('DEBUG', 'false') === 'true';
if ($details && $debug) {
$safeDetails = htmlspecialchars($details, ENT_QUOTES, 'UTF-8');
$detailsHtml = "<div class='alert alert-secondary mt-3 text-start'><small><strong>Debug info:</strong><br><pre style='white-space: pre-wrap; word-break: break-all; margin: 0; font-size: 12px;'>{$safeDetails}</pre></small></div>";
}
$assetBase = defined('BASE_PATH') ? rtrim(BASE_PATH, '/') : '';
return <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow">
<title>{$code} - {$safeTitle}</title>
<link href="{$assetBase}/assets/vendor/bootstrap/bootstrap.min.css" rel="stylesheet">
<link href="{$assetBase}/assets/css/icons.css" rel="stylesheet">
<style>
body { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); min-height: 100vh; display: flex; align-items: center; justify-content: center; }
.error-card { background: rgba(255,255,255,0.95); backdrop-filter: blur(10px); border-radius: 1rem; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1); max-width: 600px; }
.copyright-footer { position: fixed; bottom: 0; left: 0; right: 0; background: rgba(0,0,0,0.8); color: white; text-align: center; padding: 0.5rem; font-size: 0.8rem; }
</style>
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-12">
<div class="card error-card mx-auto">
<div class="card-body text-center p-5">
<h1 class="display-1 text-danger mb-4">{$code}</h1>
<h2 class="mb-3">{$safeTitle}</h2>
<p class="lead text-muted mb-4">{$safeMessage}</p>
{$detailsHtml}
<a href="{$homeUrl}" class="btn btn-danger btn-lg mt-3"><i class="fas fa-home"></i> Go Home</a>
</div>
</div>
</div>
</div>
</div>
<div class="copyright-footer">Built for RealmsNetwork by <strong>THEMPGUY</strong></div>
</body>
</html>
HTML;
}
function parseDatabaseError(PDOException $e): array {
$code = $e->getCode();
$message = $e->getMessage();
$sqlstate = $e->errorInfo[0] ?? '';
$userMessage = 'Unable to connect to the database.';
$details = "Error: {$message}";
// Parse specific error codes (MySQL numeric or PostgreSQL SQLSTATE)
if ($code == 1045 || stripos($message, 'Access denied') !== false || $sqlstate === '28P01' || stripos($message, 'password authentication failed') !== false) {
$userMessage = 'Database access denied - invalid username or password.';
$details = "Check DB_USER and DB_PASS in your .env file.\n\nOriginal error: {$message}";
}
elseif ($code == 1049 || stripos($message, 'Unknown database') !== false || $sqlstate === '3D000' || (stripos($message, 'database') !== false && stripos($message, 'does not exist') !== false)) {
$userMessage = 'Database does not exist.';
$details = "Check DB_NAME in your .env file - the specified database was not found.\n\nOriginal error: {$message}";
}
elseif ($code == 1044 || stripos($message, 'access denied for user') !== false) {
$userMessage = 'Database access denied - user lacks privileges.';
$details = "The database user does not have permission to access this database.\n\nOriginal error: {$message}";
}
elseif ($code == 2002 || $code == 2003 || stripos($message, 'Connection refused') !== false || stripos($message, 'No such file') !== false || $sqlstate === '08001' || $sqlstate === '08006' || stripos($message, 'could not connect to server') !== false) {
$userMessage = 'Cannot connect to database server.';
$details = "Check DB_HOST and DB_PORT in your .env file.\nThe database server may be down or not accepting connections.\n\nOriginal error: {$message}";
}
elseif ($code == 1146 || stripos($message, "doesn't exist") !== false || stripos($message, "does not exist") !== false) {
$userMessage = 'Database table not found.';
$details = "Check TABLE_PREFIX in your .env file.\nMake sure configured punishment plugin has created the required tables.\n\nOriginal error: {$message}";
}
elseif ($code == 2006 || $code == 2013 || stripos($message, 'gone away') !== false || stripos($message, 'server closed the connection') !== false) {
$userMessage = 'Database connection lost.';
$details = "The connection to database was lost. Server may be overloaded.\n\nOriginal error: {$message}";
}
elseif ($code == 1040 || stripos($message, 'Too many connections') !== false) {
$userMessage = 'Too many database connections.';
$details = "The database server has too many connections. Try again later.\n\nOriginal error: {$message}";
}
elseif (stripos($message, 'timeout') !== false || stripos($message, 'timed out') !== false) {
$userMessage = 'Database connection timeout.';
$details = "Connection to database timed out. Server may be slow or unreachable.\n\nOriginal error: {$message}";
}
return [
'userMessage' => $userMessage,
'details' => $details . "\n\nError code: {$code}\nSQLSTATE: {$sqlstate}\nFile: {$e->getFile()}\nLine: {$e->getLine()}"
];
}
require_once __DIR__ . '/core/AvatarCache.php';
\core\AvatarCache::serveCached((string)parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH));
session_start([
'cookie_httponly' => true,
'cookie_secure' => isset($_SERVER['HTTPS']),
'cookie_samesite' => 'Lax',
'use_strict_mode' => true,
'gc_maxlifetime' => (int)core\EnvLoader::get('SESSION_LIFETIME', 3600)
]);
header('Content-Type: text/html; charset=UTF-8');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
$scriptPath = dirname($_SERVER['SCRIPT_NAME']);
$basePath = ($scriptPath === '/' || $scriptPath === '\\') ? '' : $scriptPath;
define('BASE_PATH', $basePath);
define('BASE_DIR', __DIR__);
$requiredFiles = [
'config/app.php',
'config/database.php',
'core/SecurityManager.php',
'core/LanguageManager.php',
'core/ThemeManager.php',
'core/DatabaseRepository.php',
'core/RememberMeManager.php',
'core/SiteExtras.php',
'controllers/BaseController.php',
'controllers/HomeController.php',
'controllers/PunishmentsController.php',
'controllers/DetailController.php',
'controllers/StatsController.php',
'controllers/AdminController.php',
'controllers/ProtestController.php',
'controllers/AiController.php',
'controllers/PrivacyController.php'
];
foreach ($requiredFiles as $file) {
$fullPath = BASE_DIR . '/' . $file;
if (!file_exists($fullPath)) {
$logger->critical("Required file missing: {$file}");
die(showErrorPage(500, 'System Error', 'Required system file missing: ' . $file));
}
require_once $fullPath;
}
try {
$config = require BASE_DIR . '/config/app.php';
if (!is_array($config)) {
throw new RuntimeException('Configuration file must return an array');
}
} catch (Exception $e) {
$logger->critical("Config load error: " . $e->getMessage());
die(showErrorPage(500, 'Configuration Error', 'Failed to load configuration.', $e->getMessage()));
}
try {
$dbConfig = new DatabaseConfig();
$config['db_name'] = $dbConfig->getDatabase();
$config['db_driver'] = $dbConfig->getDriver();
} catch (InvalidArgumentException $e) {
$logger->error("Database config error: " . $e->getMessage());
die(showErrorPage(500, 'Configuration Error', $e->getMessage(), "Check your .env file for correct database settings."));
} catch (RuntimeException $e) {
$logger->error("Database config error: " . $e->getMessage());
die(showErrorPage(500, 'Configuration Error', $e->getMessage()));
}
date_default_timezone_set($config['timezone'] ?? 'UTC');
function url(string $path = ''): string {
$path = ltrim($path, '/');
$basePath = rtrim(BASE_PATH, '/');
if ($path === '') {
return $basePath ?: '/';
}
if ($basePath && strpos($path, ltrim($basePath, '/')) === 0) {
return '/' . $path;
}
return $basePath . '/' . $path;
}
function assetBase(): string {
$url = trim((string)\core\EnvLoader::get('ASSETS_URL', ''));
return preg_match('#^https?://[^\s/?\#]+(/[\w./-]*)?$#i', rtrim($url, '/')) ? rtrim($url, '/') : rtrim(BASE_PATH, '/');
}
function bundle(string $type): string {
$files = (require BASE_DIR . '/assets/bundle-map.php')[$type] ?? [];
$stamp = '';
foreach ($files as $file) {
$full = BASE_DIR . '/assets/' . $file;
$stamp .= $file . (is_file($full) ? filemtime($full) . ':' . filesize($full) : '') . '|';
}
return assetBase() . '/assets/bundle.php?t=' . ($type === 'js' ? 'js' : 'css') . '&v=' . substr(md5($stamp), 0, 10);
}
function asset(string $path): string {
$path = ltrim($path, '/');
$fullPath = BASE_DIR . '/' . $path;
$version = is_file($fullPath) ? '?v=' . substr(md5(filemtime($fullPath) . ':' . filesize($fullPath)), 0, 8) : '';
return assetBase() . '/' . $path . $version;
}
function isUserAuthenticated(): bool {
if (!isset($_SESSION['admin_authenticated'])) {
$rememberMe = new \core\RememberMeManager();
$tokenData = $rememberMe->validateToken();
if ($tokenData !== null) {
$_SESSION['admin_authenticated'] = true;
$_SESSION['admin_login_time'] = time();
if ($tokenData['user_id'] === 'legacy') {
$_SESSION['admin_user'] = 'Administrator';
} else {
require_once BASE_DIR . '/core/AuthManager.php';
$config = require BASE_DIR . '/config/app.php';
$authManager = new \core\AuthManager($config);
$user = $authManager->getUserById($tokenData['user_id']);
if ($user && ($user['active'] ?? true)) {
$_SESSION['admin_user'] = $user['name'];
$_SESSION['admin_user_id'] = $user['id'];
} else {
$rememberMe->clearCurrentToken();
return false;
}
}
\core\Logger::getInstance()->info('Session restored from remember me token');
return true;
}
return false;
}
if (time() - ($_SESSION['admin_login_time'] ?? 0) > 7200) {
unset($_SESSION['admin_authenticated']);
unset($_SESSION['admin_user_id']);
return false;
}
$_SESSION['admin_login_time'] = time();
return true;
}
try {
if (isset($_GET['lang'])) {
$selectedLang = preg_replace('/[^a-z]/', '', substr($_GET['lang'], 0, 2));
if (in_array($selectedLang, ['ar', 'cs', 'de', 'gr', 'en', 'es', 'fr', 'hu', 'it', 'ja', 'pl', 'ro', 'ru', 'sk', 'sr', 'tr', 'cn', 'nl', 'pt', 'ko', 'uk', 'vi', 'id', 'sv', 'no'])) {
$_SESSION['selected_lang'] = $selectedLang;
setcookie('selected_lang', $selectedLang, [
'expires' => time() + 86400 * 30,
'path' => BASE_PATH ?: '/',
'secure' => isset($_SERVER['HTTPS']),
'httponly' => true,
'samesite' => 'Lax'
]);
$_COOKIE['selected_lang'] = $selectedLang;
}
session_write_close();
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
$cleanUrl = strtok($_SERVER['REQUEST_URI'], '?');
$keptQuery = $_GET;
unset($keptQuery['lang']);
if ($keptQuery) {
$cleanUrl .= '?' . http_build_query($keptQuery);
}
header("Location: " . $cleanUrl, true, 303);
exit;
}
if (isset($_GET['theme'])) {
$selectedTheme = preg_replace('/[^a-z]/', '', strtolower($_GET['theme']));
if (in_array($selectedTheme, ['light', 'dark'])) {
setcookie('selected_theme', $selectedTheme, [
'expires' => time() + 86400 * 30,
'path' => BASE_PATH ?: '/',
'secure' => isset($_SERVER['HTTPS']),
'httponly' => false,
'samesite' => 'Lax'
]);
$_COOKIE['selected_theme'] = $selectedTheme;
}
session_write_close();
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
$cleanUrl = $_SERVER['REQUEST_URI'];
$cleanUrl = preg_replace('/[?&]theme=[^&]*/', '', $cleanUrl);
$cleanUrl = str_replace('&&', '&', $cleanUrl);
$cleanUrl = rtrim($cleanUrl, '?&');
header("Location: " . $cleanUrl, true, 303);
exit;
}
try {
// Get connection parameters from environment
$driver = core\EnvLoader::get('DB_DRIVER', 'mysql');
$host = core\EnvLoader::get('DB_HOST', 'localhost');
$port = core\EnvLoader::get('DB_PORT', $driver === 'pgsql' ? '5432' : '3306');
$dbname = core\EnvLoader::get('DB_NAME', '');
$user = core\EnvLoader::get('DB_USER', '');
$pass = core\EnvLoader::get('DB_PASS', '');
// Build DSN based on driver
if ($driver === 'pgsql') {
$dsn = "pgsql:host=$host;port=$port;dbname=$dbname;options='--client_encoding=UTF8'";
} else {
$dsn = "mysql:host=$host;port=$port;dbname=$dbname;charset=utf8mb4";
}
$connection = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
$repository = new DatabaseRepository($connection, $dbConfig->getTablePrefix());
if (!$repository->testConnection()) {
throw new RuntimeException('Database connection test failed');
}
} catch (PDOException $e) {
$errorInfo = parseDatabaseError($e);
$logger->databaseError($e, 'connection');
die(showErrorPage(500, 'Database Error', $errorInfo['userMessage'], $errorInfo['details']));
}
if (preg_match('#/avatar/([A-Za-z0-9_-]{1,40})\.webp$#', (string)parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), $avatarMatch)) {
session_write_close();
require_once BASE_DIR . '/core/AvatarCache.php';
\core\AvatarCache::serve($avatarMatch[1], $repository->getConnection(), $repository->getTablePrefix(), $config);
}
$lang = new LanguageManager(LanguageManager::detectLanguage());
$theme = new ThemeManager();
try {
$stats = $repository->getStats();
} catch (PDOException $e) {
$logger->databaseError($e, 'getStats');
$stats = ['bans' => 0, 'mutes' => 0, 'warnings' => 0, 'kicks' => 0];
}
$requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?? '/';
if (!empty(BASE_PATH) && strpos($requestUri, BASE_PATH) === 0) {
$requestUri = substr($requestUri, strlen(BASE_PATH));
}
$requestUri = '/' . trim($requestUri, '/');
$route = explode('/', trim($requestUri, '/'));
$GLOBALS['stats'] = $stats;
$GLOBALS['config'] = $config;
$requireLogin = $config['require_login'] ?? false;
$isAdminRoute = str_starts_with($requestUri, '/admin');
if ($requireLogin && !$isAdminRoute && !isUserAuthenticated()) {
$_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
header("Location: " . url('admin'));
exit;
}
if ($requestUri === '/' || $requestUri === '/index.php') {
(new HomeController($repository, $lang, $theme, $config))->index();
} elseif ($requestUri === '/search') {
(new HomeController($repository, $lang, $theme, $config))->search();
} elseif ($requestUri === '/bans') {
(new PunishmentsController($repository, $lang, $theme, $config))->bans();
} elseif ($requestUri === '/mutes') {
(new PunishmentsController($repository, $lang, $theme, $config))->mutes();
} elseif ($requestUri === '/warnings') {
(new PunishmentsController($repository, $lang, $theme, $config))->warnings();
} elseif ($requestUri === '/kicks') {
(new PunishmentsController($repository, $lang, $theme, $config))->kicks();
} elseif ($requestUri === '/stats' || $requestUri === '/statistics') {
(new StatsController($repository, $lang, $theme, $config))->index();
} elseif ($requestUri === '/stats/clear-cache' && $_SERVER['REQUEST_METHOD'] === 'POST') {
(new StatsController($repository, $lang, $theme, $config))->clearCache();
} elseif ($requestUri === '/detail' || $requestUri === '/detail.php' || (isset($route[0]) && $route[0] === 'detail')) {
(new DetailController($repository, $lang, $theme, $config))->show();
} elseif ($requestUri === '/privacy') {
(new PrivacyController($repository, $lang, $theme, $config))->index();
} elseif (preg_match('#^/([a-f0-9]{32})\.txt$#', $requestUri, $keyMatch) && \core\SiteExtras::indexNowKey(false) === $keyMatch[1]) {
header('Content-Type: text/plain; charset=UTF-8');
echo $keyMatch[1];
} elseif ($requestUri === '/protest') {
(new ProtestController($repository, $lang, $theme, $config))->index();
} elseif ($requestUri === '/protest/submit' && $_SERVER['REQUEST_METHOD'] === 'POST') {
(new ProtestController($repository, $lang, $theme, $config))->submit();
} elseif ($requestUri === '/ai/stats.json' || $requestUri === '/ai/stats') {
(new AiController($repository, $lang, $theme, $config))->stats();
} elseif ($requestUri === '/agent.json' || $requestUri === '/agent') {
(new AiController($repository, $lang, $theme, $config))->manifest();
} elseif ($requestUri === '/sitemap.xml' || $requestUri === '/sitemap') {
(new AiController($repository, $lang, $theme, $config))->sitemap();
} elseif ($requestUri === '/robots.txt') {
(new AiController($repository, $lang, $theme, $config))->robots();
} elseif ($requestUri === '/llms.txt') {
(new AiController($repository, $lang, $theme, $config))->llms();
} elseif (str_starts_with($requestUri, '/admin')) {
if (!($config['admin_enabled'] ?? false)) {
echo showErrorPage(403, 'Forbidden', 'Admin panel is disabled.');
exit;
}
$admin = new AdminController($repository, $lang, $theme, $config);
match ($requestUri) {
'/admin' => $admin->index(),
'/admin/login' => $admin->login(),
'/admin/logout' => $admin->logout(),
'/admin/keep-alive' => $admin->keepAlive(),
'/admin/clear-cache' => $admin->clearCache(),
'/admin/clear-all-cache' => $admin->clearAllCache(),
'/admin/test-database' => $admin->testDatabase(),
'/admin/check-github-version' => $admin->checkGitHubVersion(),
'/admin/export' => $admin->export(),
'/admin/import' => $admin->import(),
'/admin/phpinfo' => $admin->phpinfo(),
'/admin/search-punishments' => $admin->searchPunishments(),
'/admin/remove-punishment' => $admin->removePunishment(),
'/admin/modify-reason' => $admin->modifyReason(),
'/admin/case-evidence' => $admin->caseEvidence(),
'/admin/site-extras' => $admin->siteExtras(),
'/admin/templates' => $admin->templates(),
'/admin/indexnow' => $admin->indexNow(),
'/admin/check-llms' => $admin->checkLlms(),
'/admin/save-settings' => $admin->saveSettings(),
'/admin/oauth-callback' => $admin->oauthCallback(),
'/admin/oauth-prepare' => $admin->oauthPrepare(),
'/admin/users' => $admin->getUsers(),
'/admin/users/add' => $admin->addUser(),
'/admin/users/update' => $admin->updateUser(),
'/admin/users/delete' => $admin->deleteUser(),
default => print showErrorPage(404, 'Not Found', 'The requested admin page does not exist.')
};
} else {
$logger->debug('404 Not Found', ['uri' => $requestUri]);
echo showErrorPage(404, 'Page Not Found', 'The requested page does not exist.');
}
} catch (PDOException $e) {
$errorInfo = parseDatabaseError($e);
$logger->databaseError($e, 'runtime');
echo showErrorPage(500, 'Database Error', $errorInfo['userMessage'], $errorInfo['details']);
} catch (Exception $e) {
$logger->exception($e, 'Application error');
$details = "Message: {$e->getMessage()}\nFile: {$e->getFile()}\nLine: {$e->getLine()}";
echo showErrorPage(500, 'Server Error', 'An unexpected error occurred.', $details);
}