LuminaWebsite/includes/admin_log.php
Maaxxs 338a00c21f Log all administrative website actions to the Discord log channel via the bot API
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 19:16:54 +02:00

157 lines
5.5 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
declare(strict_types=1);
/**
* Protokoll der Verwaltungsaktionen im Discord: Jede administrative Aenderung auf der Website
* wird ueber die Bot-API (POST /api/log) in den Log-Kanal des Servers geschrieben - denselben,
* den der Bot fuer seine eigenen Admin-Aktionen nutzt (/set_logchannel).
*
* Die Eintraege werden gesammelt und erst gesendet, nachdem die Seite an den Browser
* ausgeliefert ist. Ist der Bot nicht erreichbar, geht der Eintrag verloren, die Aktion auf der
* Website funktioniert aber ganz normal weiter.
*/
require_once __DIR__ . '/raids_api.php';
// Farben der Log-Eintraege (wie die Embeds im Bot)
const ADMIN_LOG_COLORS = [
'info' => 0x5865F2, // blau: angelegt / geaendert
'success' => 0x3BA55D, // gruen: freigeschaltet / bewilligt / wiederhergestellt
'warning' => 0xF0B232, // gelb: abgelehnt / archiviert / entzogen
'danger' => 0xED4245, // rot: geloescht
];
/**
* Einen Verwaltungseintrag fuer den Discord-Log vormerken.
*
* @param string $title Kurzbeschreibung mit Emoji, z.B. "👤 Benutzer bearbeitet"
* @param array<string, scalar|null> $fields Details als Name => Wert (leere Werte werden weggelassen)
* @param string $tone info | success | warning | danger
*/
function admin_log(string $title, array $fields = [], string $tone = 'info'): void
{
static $registered = false;
$user = current_user();
$actor = 'Unbekannt';
if ($user) {
$actor = $user['display_name'] !== '' ? $user['display_name'] : $user['username'];
if (!empty($user['discord_id'])) {
$actor .= ' (<@' . $user['discord_id'] . '>)';
}
}
$embedFields = [];
foreach ($fields as $name => $value) {
$value = trim((string) $value);
if ($value === '') {
continue;
}
$embedFields[] = [
'name' => mb_substr((string) $name, 0, 256),
'value' => mb_substr($value, 0, 1024),
'inline' => mb_strlen($value) <= 40,
];
if (count($embedFields) >= 25) {
break;
}
}
$GLOBALS['admin_log_queue'][] = [
'title' => mb_substr($title, 0, 256),
'description' => '**Von:** ' . $actor,
'fields' => $embedFields,
'color' => ADMIN_LOG_COLORS[$tone] ?? ADMIN_LOG_COLORS['info'],
];
if (!$registered) {
$registered = true;
register_shutdown_function('admin_log_flush');
}
}
/**
* Hilfsfunktion fuer Log-Felder: Name eines Website-Kontos, mit Discord-Erwaehnung falls verknuepft.
*/
function admin_log_user(int $userId): string
{
try {
$stmt = db()->prepare('SELECT username, display_name, discord_id FROM users WHERE id = ?');
$stmt->execute([$userId]);
$row = $stmt->fetch();
} catch (PDOException $e) {
$row = false;
}
if (!$row) {
return 'Konto #' . $userId;
}
$name = $row['display_name'] !== '' ? $row['display_name'] : $row['username'];
return $name . (!empty($row['discord_id']) ? ' (<@' . $row['discord_id'] . '>)' : '');
}
/** Titel und Termin eines Raids fuer Log-Felder (vor dem Loeschen abfragen). */
function admin_log_raid(int $raidId): string
{
try {
$raid = fetch_raid_by_id($raidId);
$when = !empty($raid['timestamp']) ? ' – ' . date('d.m.Y H:i', (int) $raid['timestamp']) . ' Uhr' : '';
return (string) ($raid['title'] ?? 'Raid') . $when;
} catch (Throwable $e) {
return 'Raid #' . $raidId;
}
}
/** Discord-Nutzer als Erwaehnung (fuer Stellen, an denen nur die Discord-ID bekannt ist). */
function admin_log_discord(int|string|null $discordId, string $fallbackName = ''): string
{
$discordId = (string) $discordId;
if ($discordId === '' || $discordId === '0') {
return $fallbackName;
}
return ($fallbackName !== '' ? $fallbackName . ' ' : '') . '(<@' . $discordId . '>)';
}
/** Sendet alle vorgemerkten Eintraege - laeuft automatisch am Ende des Requests. */
function admin_log_flush(): void
{
$queue = $GLOBALS['admin_log_queue'] ?? [];
$GLOBALS['admin_log_queue'] = [];
if (empty($queue) || !function_exists('curl_init')) {
return;
}
// Antwort zuerst an den Browser schicken, damit niemand auf den Bot warten muss. Die Sitzung
// vorher speichern - sonst wartet die naechste Seite (z.B. nach redirect()) auf ihre Sperre.
if (session_status() === PHP_SESSION_ACTIVE) {
session_write_close();
}
if (function_exists('fastcgi_finish_request')) {
@fastcgi_finish_request();
}
try {
$config = raids_api_config();
$guildId = reports_guild_id();
} catch (Throwable $e) {
return; // Bot-API nicht konfiguriert
}
$url = preg_replace('#/raids$#', '', $config['url']) . '/log';
foreach ($queue as $entry) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_TIMEOUT => 5,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_HTTPHEADER => ['X-API-Key: ' . $config['key'], 'Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode(['guild_id' => $guildId] + $entry, JSON_UNESCAPED_UNICODE),
]);
$response = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response === false || $status < 200 || $status >= 300) {
error_log('admin_log: Eintrag "' . $entry['title'] . '" konnte nicht an den Bot gesendet werden (HTTP ' . $status . ')');
}
}
}