LuminaWebsite/includes/admin_log.php
Maaxxs 17ccd3e26f Discord bot as overview: everything is managed on the website, raid signup in one click
The bot (Aion2_RaidPlaner, deployed 2026-09-25) has no slash commands any more. Raids,
premades, events, activity checks and reports are created and managed only here; in Discord
members sign up for raids, answer invitations and activity checks and report players.

- Raid signup works the same in Discord and here: the bot assigns the group (perform_signup),
  the website only sends the wish (raid_signup(..., $wish)) and shows the reason when it did
  not fit (locked, role full, raid full). raid_wish_is_sensible() and the role constants are
  gone. Declining ("Abmelden") now keeps the player under "Abgemeldet" (raid_decline, new bot
  endpoint .../decline) like in Discord; the raid card shows "Du hast dich abgemeldet" with
  "Doch anmelden". Class input is checked against AION_CLASSES.
- The Discord message shows the raid lead and the Lumipunkte: raid_create_action/raid_edit_action
  send lead_id/lead_name/points_text, raid_sync_extras() on raids.php pushes them for raids
  where the bot is missing them (at most 3 per page view, follows changed raid IDs).
- bot_api.php?action=member: main class (profile choice) and whether the person has an
  (active) account - the bot preselects the class and hints that Lumipunkte need an account.
- New page Verwaltung -> Discord-Bot (admin/bot.php, includes/discord_bot.php, permission
  bot.manage, on update granted to groups with raids.manage; schema 53): raid, log and report
  channel, post the premade overview (updates itself) and the report panel (the bot replaces
  the previous one), resync all raid messages (reposted raids move their settings via
  raid_rename_id). Audit area "Discord-Bot", sidebar entry with a new bot icon.
- Reports: after picking a player in the filter, delete all of their reports at once
  (DELETE /api/reports/user/{id}), which also lifts the auto-mute.
- Calendar and raid logs no longer count declined players as signed up / on the bench.
- Texts that mentioned bot commands (events, activity check, config example, README) updated;
  privacy policy mentions the main-class lookup and that declines stay visible. Patch notes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 03:15:55 +02:00

246 lines
9.2 KiB
PHP
Raw Permalink 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 (Verwaltung ->
* Discord-Bot), in dem auch der Bot seine eigenen Meldungen ablegt.
*
* 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
* @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), 1 abgemeldet". */
function admin_log_raid_signups(?array $raid): string
{
if ($raid === null) {
return '';
}
$groups = array_map(static fn ($s): int => (int) ($s['group'] ?? 0), (array) ($raid['signups'] ?? []));
$inGroups = count(array_filter($groups, static fn (int $g): bool => $g >= 1));
$bench = count(array_filter($groups, static fn (int $g): bool => $g === 0));
$declined = count($groups) - $inGroups - $bench;
return ($inGroups + $bench) . ' (' . $inGroups . ' in Gruppen, ' . $bench . ' auf der Ersatzbank)'
. ($declined > 0 ? ', ' . $declined . ' abgemeldet' : '');
}
/** "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 . ')');
}
}
}