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 $fields Details als Name => Wert (leere Werte werden weggelassen) * @param string $tone info | success | warning | danger * @param string|null $area Bereich im Audit-Log (Standard: aus dem Skriptnamen, siehe AUDIT_AREAS) * @param array|null $actor Wer es war, falls nicht das angemeldete Konto ([] = niemand angemeldet) */ function admin_log(string $title, array $fields = [], string $tone = 'info', ?string $area = null, ?array $actor = null): void { static $registered = false; // Dauerhaft in der Datenbank (Audit-Log) - auch wenn der Bot gerade nicht erreichbar ist. audit_store($title, $fields, $tone, $area, $actor); // Viele Loeschungen in kurzer Zeit -> Notbremse (siehe includes/security.php) if ($tone === 'danger' && $area !== 'security') { security_note_destructive(); } $user = $actor ?? 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; } } /** Anmeldungen eines Raids fuer Log-Felder, z.B. "14 (12 in Gruppen, 2 auf der Ersatzbank)". */ function admin_log_raid_signups(?array $raid): string { if ($raid === null) { return ''; } $signups = (array) ($raid['signups'] ?? []); $bench = count(array_filter($signups, static fn ($s) => (int) ($s['group'] ?? 0) <= 0)); return count($signups) . ' (' . (count($signups) - $bench) . ' in Gruppen, ' . $bench . ' auf der Ersatzbank)'; } /** "Gruppe 2 (Tanks)" bzw. "Ersatzbank" fuer Log-Felder - $raid aus fetch_raid_by_id(). */ function admin_log_raid_group(?array $raid, int $group): string { if ($group <= 0) { return 'Ersatzbank'; } $names = array_values(array_filter(array_map('trim', explode(',', (string) ($raid['groups'] ?? ''))))); $name = $names[$group - 1] ?? ''; return 'Gruppe ' . $group . ($name !== '' && $name !== 'Gruppe ' . $group ? ' (' . $name . ')' : ''); } /** * Discord-Nutzer fuer Log-Felder: Name plus Erwaehnung. Ohne mitgegebenen Namen wird er ueber das * verknuepfte Website-Konto aufgeloest - sonst bliebe im Audit-Log (das Erwaehnungen entfernt) * nichts uebrig. */ function admin_log_discord(int|string|null $discordId, string $fallbackName = ''): string { $discordId = (string) $discordId; if ($discordId === '' || $discordId === '0') { return $fallbackName; } if ($fallbackName === '') { $fallbackName = admin_log_discord_name($discordId); } return $fallbackName . ' (<@' . $discordId . '>)'; } /** Anzeigename zu einer Discord-ID (Website-Konto), sonst "Discord-ID …". */ function admin_log_discord_name(string $discordId): string { static $cache = []; if (!isset($cache[$discordId])) { try { $stmt = db()->prepare("SELECT COALESCE(NULLIF(display_name, ''), NULLIF(discord_username, ''), username) FROM users WHERE discord_id = ?"); $stmt->execute([$discordId]); $name = $stmt->fetchColumn(); } catch (PDOException $e) { $name = false; } $cache[$discordId] = $name !== false && $name !== null ? (string) $name : 'Discord-ID ' . $discordId; } return $cache[$discordId]; } /** * "alt → neu" fuer Log-Felder, leer wenn sich nichts geaendert hat (leere Felder laesst das Log * weg). Lange Texte werden gekuerzt; leere Werte erscheinen als "–". */ function admin_log_change(mixed $old, mixed $new, int $maxLength = 120): string { $format = static function (mixed $value) use ($maxLength): string { if (is_bool($value)) { return $value ? 'ja' : 'nein'; } $value = trim(preg_replace('/\s+/u', ' ', (string) $value) ?? ''); return $value === '' ? '–' : mb_strimwidth($value, 0, $maxLength, '…'); }; $old = $format($old); $new = $format($new); return $old === $new ? '' : $old . ' → ' . $new; } /** Umfang einer Textaenderung, z.B. "1.204 → 1.380 Zeichen (+176)". Leer, wenn gleich. */ function admin_log_text_change(string $old, string $new): string { if ($old === $new) { return ''; } $a = mb_strlen($old); $b = mb_strlen($new); $diff = $b - $a; return number_format($a, 0, ',', '.') . ' → ' . number_format($b, 0, ',', '.') . ' Zeichen (' . ($diff >= 0 ? '+' : '−') . number_format(abs($diff), 0, ',', '.') . ')'; } /** 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 . ')'); } } }