httpCode = $httpCode; } } /** * Siel, der Bot der Elyos Allianz (config.php: siel_api.url = https://bot.lumina-ascendens.de/website-api/raids, * siel_api.key). Er postet die Raids der Elyos Allianz auf deren Discord-Server und kennt dessen Kanaele und Rollen. * null = nicht eingerichtet - dann macht Nezekan (raids_api) weiter alles. * * @return array{url: string, key: string}|null */ function siel_api_config(): ?array { static $cfg = false; if ($cfg === false) { $configPath = __DIR__ . '/../config.php'; $config = file_exists($configPath) ? require $configPath : []; $url = is_array($config) ? (string) ($config['siel_api']['url'] ?? '') : ''; $key = is_array($config) ? (string) ($config['siel_api']['key'] ?? '') : ''; $cfg = $url !== '' && $key !== '' ? ['url' => rtrim($url, '/'), 'key' => $key] : null; } return $cfg; } /** * @return array * @throws RuntimeException */ function raids_api_config(): array { $configPath = __DIR__ . '/../config.php'; if (!file_exists($configPath)) { throw new RuntimeException('Konfigurationsdatei fehlt.'); } $config = require $configPath; $apiUrl = $config['raids_api']['url'] ?? ''; $apiKey = $config['raids_api']['key'] ?? ''; if ($apiUrl === '' || $apiKey === '') { throw new RuntimeException('Raid-API ist nicht konfiguriert (config.php: raids_api.url / raids_api.key fehlt).'); } // live_url (optional): oeffentliche Adresse der Bot-API fuer die Live-Ansicht der Karte, falls die // Browser sie anders erreichen als die Website (sonst url ohne /api/raids, siehe tactic_live_ticket). return ['url' => rtrim($apiUrl, '/'), 'key' => $apiKey, 'live_url' => rtrim((string) ($config['raids_api']['live_url'] ?? ''), '/')]; } /** * Fuehrt einen Request gegen die Raid-API aus und liefert die dekodierte * JSON-Antwort zurueck. * * @param string $path Wird an die Basis-URL angehaengt, z.B. "/123/signup". * @param array|null $jsonBody Wird bei POST/DELETE als JSON-Body mitgeschickt. * @param int $timeout Sekunden bis zum Abbruch (die Seitenleiste wartet kuerzer, raids_nav_upcoming()). * @return array * @throws RuntimeException */ function raids_api_request(string $method, string $path = '', array $queryParams = [], ?array $jsonBody = null, int $timeout = 10, string $backend = 'nezekan'): array { if (!function_exists('curl_init')) { throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.'); } // 'siel': der Bot der Elyos Allianz, sonst Nezekan (Legion) $config = $backend === 'siel' ? siel_api_config() : raids_api_config(); if ($config === null) { throw new RuntimeException('Siel ist nicht eingerichtet (config.php: siel_api.url / siel_api.key fehlt).'); } $label = $backend === 'siel' ? 'Siel' : 'Raid-API'; $url = $config['url'] . $path; if (!empty($queryParams)) { $url .= '?' . http_build_query($queryParams); } $headers = ['X-API-Key: ' . $config['key']]; $ch = curl_init($url); $options = [ CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_TIMEOUT => $timeout, CURLOPT_SSL_VERIFYPEER => true, ]; if ($jsonBody !== null) { $headers[] = 'Content-Type: application/json'; $options[CURLOPT_POSTFIELDS] = json_encode($jsonBody, JSON_UNESCAPED_UNICODE); } $options[CURLOPT_HTTPHEADER] = $headers; curl_setopt_array($ch, $options); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlError = curl_error($ch); curl_close($ch); if ($response === false) { throw new RuntimeException('Verbindung zu ' . $label . ' fehlgeschlagen: ' . $curlError); } $data = json_decode($response, true); if ($httpCode < 200 || $httpCode >= 300) { throw new BotApiException(bot_api_error_message($label, $httpCode, $data), $httpCode); } if (!is_array($data)) { throw new RuntimeException('Unerwartetes Antwortformat von ' . $label . '.'); } return $data; } /** * Raids beider Bots: Nezekan (Legion, aeltere Raids der Elyos Allianz) und Siel (Raids der Elyos Allianz). Jeder Raid * bekommt "bot" ('nezekan' oder 'siel'). Ist Siel nicht erreichbar, fehlen nur dessen Raids (siel_raids_error()). * * @return array> * @throws RuntimeException wenn Nezekan nicht antwortet */ function raids_fetch_combined(string $status, int $timeout = 10): array { $data = raids_api_request('GET', '', ['status' => $status], null, $timeout); if (($data['status'] ?? '') !== 'success' || !isset($data['raids']) || !is_array($data['raids'])) { throw new RuntimeException('Unerwartetes Antwortformat der Raid-API.'); } $raids = array_map(static fn (array $raid): array => $raid + ['bot' => 'nezekan'], $data['raids']); if (siel_api_config() !== null) { try { $siel = raids_api_request('GET', '', ['status' => $status], null, $timeout, 'siel'); foreach ((array) ($siel['raids'] ?? []) as $raid) { if (is_array($raid)) { $raid['bot'] = 'siel'; raid_backend_remember((int) ($raid['raid_id'] ?? 0), 'siel'); $raids[] = $raid; } } siel_raids_error(''); } catch (Throwable $e) { siel_raids_error($e->getMessage()); } usort($raids, static fn (array $a, array $b): int => (int) ($a['timestamp'] ?? 0) <=> (int) ($b['timestamp'] ?? 0)); } return $raids; } /** Letzter Fehler beim Abruf der Raids von Siel ('' = alles gut) - lesen ohne, setzen mit Argument. */ function siel_raids_error(?string $set = null): string { static $error = ''; if ($set !== null) { $error = $set; } return $error; } /** Merkt sich, welcher Bot einen Raid postet (fuer Anfragen per raid_id). Ohne Bot: lesen ('' = unbekannt). */ function raid_backend_remember(int $raidId, ?string $backend = null): string { static $known = []; if ($backend !== null && $raidId > 0) { $known[$raidId] = $backend; } return $known[$raidId] ?? ''; } /** * Anfrage zu einem bestimmten Raid - an den Bot, der ihn gepostet hat. Ist er unbekannt, zuerst Nezekan; kennt der * gefragte Bot den Raid nicht (404), der andere. * * @return array * @throws RuntimeException */ function raid_backend_request(int $raidId, string $method, string $path, ?array $jsonBody = null): array { $order = raid_backend_remember($raidId) === 'siel' ? ['siel', 'nezekan'] : ['nezekan', 'siel']; if (siel_api_config() === null) { $order = ['nezekan']; } foreach ($order as $i => $backend) { try { $data = raids_api_request($method, $path, [], $jsonBody, 10, $backend); raid_backend_remember($raidId, $backend); return $data; } catch (BotApiException $e) { if ($e->httpCode !== 404 || $i === count($order) - 1) { throw $e; } } } throw new RuntimeException('Raid nicht gefunden.'); } // Laengengrenzen der Raid-API (RaidCreate/RaidUpdate in api.py des Bots). const RAID_FIELD_LIMITS = [ 'title' => ['Titel', 60], 'requirements' => ['Anforderungen', 80], 'gearscore' => ['Gearscore', 50], // neue Werte sind nur noch Zahlen (raid_normalize_gearscore) 'group_names' => ['Gruppennamen (zusammen)', 150], ]; /** * Prueft die Textfelder eines Raids gegen die Grenzen der API - so gibt es eine klare * Meldung statt eines abgelehnten Requests. Liefert die Fehlermeldung oder null. * * @param array $fields */ function raid_fields_error(array $fields): ?string { foreach (RAID_FIELD_LIMITS as $key => [$label, $max]) { if (isset($fields[$key]) && mb_strlen((string) $fields[$key], 'UTF-8') > $max) { return $label . ': höchstens ' . $max . ' Zeichen.'; } } return null; } /** * @return array> * @throws RuntimeException */ function fetch_raids(string $status = 'active'): array { if (!in_array($status, RAID_STATUSES, true)) { $status = 'active'; } $raids = raids_fetch_combined($status); // Die aktiven Raids stecken auch in "all" - so bleibt die Zahl in der Seitenleiste nebenbei aktuell if ($status !== 'archived') { raids_nav_store($raids); } return raids_apply_display_names($raids); } // ---- Zwei Raid-Bereiche: Legion und Consilium Elyseum ---- // Consilium-Raids (mit den verbuendeten Legionen) stehen in einem eigenen Discord-Kanal (Verwaltung -> Discord-Bot, // "Consilium-Raids"). Die Raid-API liefert zu jedem Raid seinen Kanal (channel_id), die Website merkt sich den Kanal der // Consilium-Raids in settings.consilium_raid_channel (includes/discord_bot.php). Mitglieder verbuendeter Legionen // sehen nur Consilium-Raids, die Legion beide Bereiche. /** Kanal der Consilium-Raids, 0 = nicht eingerichtet. */ function consilium_raid_channel(): int { return (int) setting_get('consilium_raid_channel'); } /** 'consilium' fuer Raids von Siel und aeltere im Kanal der Consilium-Raids, sonst 'legion'. */ function raid_area(array $raid): string { if (($raid['bot'] ?? '') === 'siel') { return 'consilium'; } $channel = consilium_raid_channel(); return $channel > 0 && (int) ($raid['channel_id'] ?? 0) === $channel ? 'consilium' : 'legion'; } /** Darf das angemeldete Konto Raids dieses Bereichs sehen und sich dafuer anmelden? */ function raid_area_visible(string $area): bool { if ($area === 'consilium') { return consilium_raid_channel() > 0 && consilium_can_view(); } return user_has_permission('raids.view') && !consilium_only(); } /** * Darf das angemeldete Konto in diesem Bereich Raids anlegen (und wird dabei Raid-Lead)? Legion: raids.create bzw. * raids.manage, Consilium: consilium.raids bzw. consilium.raids.manage - die Rechte gelten nur im eigenen Bereich. */ function raid_area_can_create(string $area): bool { if (!raid_area_visible($area)) { return false; } return $area === 'consilium' ? user_has_permission('consilium.raids') || user_has_permission('consilium.raids.manage') : user_has_permission('raids.create') || user_has_permission('raids.manage'); } /** Darf das angemeldete Konto alle Raids dieses Bereichs verwalten? Legion: raids.manage, Consilium: consilium.raids.manage. */ function raid_area_can_manage_all(string $area): bool { return raid_area_visible($area) && user_has_permission($area === 'consilium' ? 'consilium.raids.manage' : 'raids.manage'); } /** Bereich eines Raids nach seiner ID (fragt den Bot) - null, wenn es ihn nicht gibt oder der Bot nicht antwortet. */ function raid_area_of(int $raidId): ?string { try { $raid = fetch_raid_by_id($raidId); } catch (Throwable $e) { return null; } return $raid !== null ? raid_area($raid) : null; } /** * Nur die Raids eines Bereichs - ohne Bereich alle, die das angemeldete Konto sehen darf. * * @param array> $raids * @return array> */ function raids_in_area(array $raids, ?string $area = null): array { return array_values(array_filter($raids, static fn (array $raid): bool => $area === null ? raid_area_visible(raid_area($raid)) : raid_area($raid) === $area)); } // Anstehende Raids als Zahl in der Seitenleiste (includes/header.php) - wie die Kachel im Dashboard und der // Reiter "Aktiv" alle noch nicht archivierten. Die Raids liegen beim Bot - damit nicht jeder Seitenaufruf dort // nachfragt, stehen ihre IDs in settings.raids_nav_cache und werden hoechstens alle RAIDS_NAV_CACHE_TTL // Sekunden neu geholt; fetch_raids() frischt sie nebenbei auf. const RAIDS_NAV_CACHE_TTL = 300; /** * Liest (ohne Argument) oder schreibt den Zwischenspeicher der Seitenleiste. Innerhalb eines Aufrufs * gilt der zuletzt geschriebene Stand - setting_get() kennt nur den vom Anfang des Aufrufs. * * @param array{fetched_at: int, raids: array, sig: string}|null $value * @return array|null */ function raids_nav_cache(?array $value = null): ?array { static $current = false; if ($value !== null) { $current = $value; try { setting_set('raids_nav_cache', (string) json_encode($value)); } catch (PDOException $e) { // Ohne settings-Tabelle eben ohne Zwischenspeicher. } return $value; } if ($current === false) { $decoded = json_decode(setting_get('raids_nav_cache'), true); $current = is_array($decoded) ? $decoded : null; } return $current; } /** * Merkt sich von den Raids der API die IDs der aktiven - und einen Fingerabdruck von Terminen, Plaetzen * und Anmeldungen, an dem das Dashboard live merkt, dass sich etwas getan hat (includes/live_updates.php). * * @param array> $raids * @return array */ function raids_nav_store(array $raids): array { $active = []; foreach ($raids as $raid) { if (empty($raid['archived']) && empty($raid['archived_at'])) { $active[(string) (int) ($raid['raid_id'] ?? 0)] = $raid; } } // Nach ID sortiert - "all" und "active" liefern die Raids nicht unbedingt in derselben Reihenfolge ksort($active, SORT_STRING); $list = array_map('strval', array_keys($active)); // Welche davon Consilium-Raids sind - die zaehlen nur fuer die, die sie sehen (raids_nav_upcoming()) $consilium = array_map('strval', array_keys(array_filter($active, static fn (array $raid): bool => raid_area($raid) === 'consilium'))); $sig = substr(md5((string) json_encode(array_map(static fn (array $raid): array => [ $raid['title'] ?? '', $raid['timestamp'] ?? 0, $raid['max_slots'] ?? 0, $raid['groups'] ?? '', $raid['signups'] ?? [], ], array_values($active)))), 0, 16); // Die Live-Aktualisierung der Raid-Seite fragt oft - unveraendert und frisch nicht jedes Mal schreiben $cached = raids_nav_cache(); if (!is_array($cached) || ($cached['raids'] ?? null) !== $list || ($cached['sig'] ?? '') !== $sig || ($cached['consilium'] ?? []) !== $consilium || time() - (int) ($cached['fetched_at'] ?? 0) >= 60) { raids_nav_cache(['fetched_at' => time(), 'raids' => $list, 'sig' => $sig, 'consilium' => $consilium]); } return $list; } /** * IDs der anstehenden (aktiven) Raids fuer die Seitenleiste - alle oder nur die eines Bereichs ('legion', * 'consilium'). Ist der Zwischenspeicher aelter als RAIDS_NAV_CACHE_TTL, fragt die Funktion den Bot mit kurzer * Wartezeit; antwortet er nicht, gilt der letzte Stand. * * @return array */ function raids_nav_upcoming(?string $area = null): array { $cached = raids_nav_cache(); $list = is_array($cached['raids'] ?? null) ? $cached['raids'] : []; if (time() - (int) ($cached['fetched_at'] ?? 0) >= RAIDS_NAV_CACHE_TTL) { // Zeitpunkt vorher merken - sonst fragt bei einem Ausfall des Bots jeder Seitenaufruf erneut raids_nav_cache(['fetched_at' => time(), 'raids' => $list, 'sig' => (string) ($cached['sig'] ?? ''), 'consilium' => (array) ($cached['consilium'] ?? [])]); try { $list = raids_nav_store(raids_fetch_combined('active', 3)); } catch (Throwable $e) { // Bot nicht erreichbar oder nicht eingerichtet - dann eben der letzte Stand } } $ids = array_map('intval', $list); if ($area === null) { return $ids; } $consilium = array_map('intval', (array) (raids_nav_cache()['consilium'] ?? [])); return array_values($area === 'consilium' ? array_intersect($ids, $consilium) : array_diff($ids, $consilium)); } /** * Anstehende Raids, die das angemeldete Konto sehen darf (Legion und/oder Consilium Elyseum). * * @return array */ function raids_nav_upcoming_visible(): array { $ids = []; foreach (['legion', 'consilium'] as $area) { if (raid_area_visible($area)) { $ids = array_merge($ids, raids_nav_upcoming($area)); } } return $ids; } /** * Wann ein Raid im Discord gepostet wurde: Die raid_id ist die ID der Discord-Nachricht, die oberen Bits * sind Millisekunden seit 2015. Postet der Bot einen Raid neu (Wiederherstellen), zaehlt er wieder als neu. */ function raid_posted_at(int $raidId): int { return intdiv($raidId >> 22, 1000) + 1420070400; } /** * Merkt, dass das Mitglied die Raids gesehen hat (users.raids_seen_at), und liefert den Zeitpunkt davor: * Was danach gepostet wurde, ist neu. Wer noch nie auf der Raid-Seite war, bekommt die letzten 7 Tage. */ function raids_mark_seen(int $userId): int { $stmt = db()->prepare('SELECT raids_seen_at FROM users WHERE id = ?'); $stmt->execute([$userId]); $seenAt = $stmt->fetchColumn(); db()->prepare('UPDATE users SET raids_seen_at = NOW() WHERE id = ?')->execute([$userId]); return is_string($seenAt) && $seenAt !== '' ? (int) strtotime($seenAt) : time() - 7 * 86400; } /** * Ersetzt die Namen in den Anmeldungen durch den Anzeigenamen des verknuepften * Website-Kontos. Der Bot speichert den Namen zum Zeitpunkt der Anmeldung; der Anzeigename * folgt dagegen immer dem aktuellen Namen auf dem Discord-Server. * * @param array> $raids * @return array> */ function raids_apply_display_names(array $raids): array { $ids = []; foreach ($raids as $raid) { foreach ((array) ($raid['signups'] ?? []) as $signup) { if (!empty($signup['user_id'])) { $ids[(string) $signup['user_id']] = true; } } } if (empty($ids)) { return $raids; } try { $placeholders = implode(',', array_fill(0, count($ids), '?')); $stmt = db()->prepare( "SELECT discord_id, display_name FROM users WHERE discord_id IN ($placeholders) AND display_name <> ''" ); $stmt->execute(array_keys($ids)); $names = []; foreach ($stmt->fetchAll() as $row) { $names[(string) $row['discord_id']] = (string) $row['display_name']; } } catch (PDOException $e) { return $raids; } foreach ($raids as &$raid) { foreach ((array) ($raid['signups'] ?? []) as $i => $signup) { $id = (string) ($signup['user_id'] ?? ''); if (isset($names[$id])) { $raid['signups'][$i]['name'] = $names[$id]; } } } unset($raid); return $raids; } /** @throws RuntimeException */ function archive_raid(int $raidId): void { raid_backend_request($raidId, 'DELETE', '/' . $raidId); } /** * Holt einen archivierten Raid zurueck. Der Bot loescht archivierte Raids kurz nach dem Archivieren * aus dem Discord-Kanal und postet sie beim Wiederherstellen neu - dann aendert sich die raid_id * (= Discord-Nachrichten-ID). Liefert die aktuell gueltige raid_id. * * @throws RuntimeException */ function restore_raid(int $raidId): int { $data = raid_backend_request($raidId, 'POST', '/' . $raidId . '/restore'); return (int) ($data['raid_id'] ?? $raidId) ?: $raidId; } /** * Loescht einen Raid ENDGUELTIG (keine Historie, keine Wiederherstellung), im * Gegensatz zu archive_raid(). Nur fuer bereits archivierte Raids gedacht. * * @throws RuntimeException */ function delete_raid_permanently(int $raidId): void { raid_backend_request($raidId, 'DELETE', '/' . $raidId . '/permanent'); } /** * Meldet an bzw. aendert Klasse und Gruppe - der Bot teilt zu, mit derselben Logik wie bei der Anmeldung * im Discord (Rollen: je Gruppe 1 Tank, 1 Heiler, 3 DPS; gesperrte Gruppen nur fuer die, die schon drin sind). * * @param int|null $wish Wunschgruppe (0 = Ersatzbank) oder null = automatisch. Passt sie nicht, teilt * der Bot automatisch zu und nennt den Grund. * @return array Die Anmeldung mit der tatsaechlichen "group", dazu "matched_wish" und * "reason" ('locked' gesperrt, 'full' Rolle in der Gruppe voll, 'cap' Raid voll). * @throws RuntimeException */ function raid_signup(int $raidId, int $discordId, string $discordName, string $className, ?int $wish = null): array { $data = raid_backend_request($raidId, 'POST', '/' . $raidId . '/signup', [ 'user_id' => $discordId, 'name' => $discordName, 'class' => $className, 'wish' => $wish, ]); return array_merge((array) ($data['signup'] ?? []), [ 'matched_wish' => (bool) ($data['matched_wish'] ?? true), 'reason' => $data['reason'] ?? null, ]); } /** * Abmelden: Der Spieler steht danach unter "Abgemeldet" - wie mit "Abmelden" im Discord. So sieht die * Leitung, wer abgesagt hat. * * @throws RuntimeException */ function raid_decline(int $raidId, int $discordId, string $name): void { raid_backend_request($raidId, 'POST', '/' . $raidId . '/signup/' . $discordId . '/decline', ['name' => $name]); } /** @throws RuntimeException */ function move_signup(int $raidId, int $discordId, int $group): void { raid_backend_request($raidId, 'PATCH', '/' . $raidId . '/signup/' . $discordId, ['group' => $group]); } /** * @param array $fields Nur die zu aendernden Felder, z.B. * ['title' => ..., 'date_raw' => ..., 'requirements' => ..., 'gearscore' => ..., * 'group_names' => ..., 'max_slots' => ..., 'locked_groups' => [1, 3]] * @return array Antwort der API. Enthaelt die aktuell gueltige raid_id - * die API postet die Discord-Nachricht automatisch neu, falls sie zwischenzeitlich * manuell geloescht wurde, wobei sich die raid_id (= Discord-Message-ID) aendert. * @throws RuntimeException */ function update_raid(int $raidId, array $fields): array { return raid_backend_request($raidId, 'PATCH', '/' . $raidId, $fields); } /** * Erstellt einen neuen Raid ueber den in config.php (raids_api.guild_id) hinterlegten * Discord-Server. Der Bot postet ihn in den Raid-Kanal dieses Servers (Verwaltung -> Discord-Bot). * Raids der Elyos Allianz postet Siel (siel_api_config()), sonst - wie frueher - Nezekan. * * @param array $fields title, date_raw, requirements, group_names * (Pflicht), max_slots, gearscore, lead_id, lead_name, points_text (optional) * @param string $area 'consilium': in den Kanal der Consilium-Raids statt in den Raid-Kanal der Legion * @return array Antwort der API inkl. raid_id * @throws RuntimeException */ function create_raid(array $fields, string $area = 'legion'): array { if ($area === 'consilium') { $channel = consilium_raid_channel(); if ($channel <= 0) { throw new RuntimeException('Für Raids von ' . CONSILIUM_NAME . ' ist noch kein Kanal eingerichtet (Verwaltung → Discord-Bot).'); } $fields['channel_id'] = $channel; } $configPath = __DIR__ . '/../config.php'; if (!file_exists($configPath)) { throw new RuntimeException('Konfigurationsdatei fehlt.'); } $config = require $configPath; $guildId = $config['raids_api']['guild_id'] ?? null; if (!$guildId) { throw new RuntimeException('Raid-Erstellung ist nicht konfiguriert (config.php: raids_api.guild_id fehlt).'); } $fields['guild_id'] = (int) $guildId; // Raids der Elyos Allianz postet Siel (auf deren Server), sobald er eingerichtet ist $backend = $area === 'consilium' && siel_api_config() !== null ? 'siel' : 'nezekan'; $data = raids_api_request('POST', '', [], $fields, 10, $backend); raid_backend_remember((int) ($data['raid_id'] ?? 0), $backend); return $data; } /** @throws RuntimeException */ function invite_premade(int $raidId, int $premadeId, int $group): int { $data = raids_api_request('POST', '/' . $raidId . '/premades/' . $premadeId . '/invite', [], ['group' => $group]); return (int) ($data['invited_count'] ?? 0); } /** * Fuehrt einen Request gegen die Premades-API aus (liegt unter derselben Basis-URL * wie die Raid-API, eine Ebene ueber "/raids") und liefert die dekodierte * JSON-Antwort zurueck. Analog zu raids_api_request(), nur mit eigener Basis-URL. * * @param array|null $jsonBody * @param int $timeout Sekunden bis zum Abbruch (die Live-Aktualisierung wartet kuerzer, includes/live_updates.php). * @return array * @throws RuntimeException */ function premades_api_request(string $method, string $path = '', ?array $jsonBody = null, int $timeout = 10): array { if (!function_exists('curl_init')) { throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.'); } $config = raids_api_config(); // /api/premades liegt eine Ebene ueber /api/raids. $base = preg_replace('#/raids$#', '', $config['url']); $url = $base . '/premades' . $path; $headers = ['X-API-Key: ' . $config['key']]; $ch = curl_init($url); $options = [ CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_TIMEOUT => $timeout, CURLOPT_SSL_VERIFYPEER => true, ]; if ($jsonBody !== null) { $headers[] = 'Content-Type: application/json'; $options[CURLOPT_POSTFIELDS] = json_encode($jsonBody, JSON_UNESCAPED_UNICODE); } $options[CURLOPT_HTTPHEADER] = $headers; curl_setopt_array($ch, $options); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlError = curl_error($ch); curl_close($ch); if ($response === false) { throw new RuntimeException('Verbindung zur Premades-API fehlgeschlagen: ' . $curlError); } $data = json_decode($response, true); if ($httpCode < 200 || $httpCode >= 300) { throw new RuntimeException(bot_api_error_message('Premades-API', $httpCode, $data)); } if (!is_array($data)) { throw new RuntimeException('Unerwartetes Antwortformat der Premades-API.'); } return $data; } /** * @return array> * @throws RuntimeException */ function fetch_premades(int $timeout = 10): array { $data = premades_api_request('GET', '', null, $timeout); if (($data['status'] ?? '') !== 'success' || !is_array($data['premades'] ?? null)) { throw new RuntimeException('Unerwartetes Antwortformat der Premades-API.'); } return $data['premades']; } const PREMADE_NAME_MIN = 3; const PREMADE_NAME_MAX = 50; // Grenze der Bot-API (PremadeCreate/PremadeRename) /** * Bereinigt einen Premade-Namen (Leerraum am Rand weg, mehrfache Leerzeichen zu einem). */ function normalize_premade_name(string $name): string { return trim((string) preg_replace('/\s+/u', ' ', $name)); } /** * Prueft einen (bereinigten) Premade-Namen. Liefert die Fehlermeldung oder null, wenn er passt: * 3-50 Zeichen, beginnt mit Buchstabe/Ziffer, danach nur Buchstaben, Ziffern, Leerzeichen und * gaengige Satzzeichen - "." oder Steuerzeichen sind kein Gruppenname. */ function premade_name_error(string $name): ?string { $length = mb_strlen($name, 'UTF-8'); if ($length < PREMADE_NAME_MIN || $length > PREMADE_NAME_MAX) { return 'Der Name der Premade muss ' . PREMADE_NAME_MIN . ' bis ' . PREMADE_NAME_MAX . ' Zeichen lang sein.'; } // Kein Komma: Raid-Gruppen stehen kommagetrennt im Bot - eine Premade "A, B" wuerde beim // Einladen in einen Raid zu zwei Gruppen. if (!preg_match("/^[\p{L}\p{N}][\p{L}\p{N} .'&!?()#:+_\-]*$/u", $name)) { return 'Der Name der Premade muss mit einem Buchstaben oder einer Ziffer beginnen und darf nur Buchstaben, Ziffern, Leerzeichen und . \' & ! ? ( ) # : + _ - enthalten (kein Komma).'; } return null; } /** * Gibt es schon eine andere Premade mit diesem Namen (ohne Gross-/Kleinschreibung)? * * @param array> $premades */ function premade_name_taken(array $premades, string $name, int $exceptId = 0): bool { $needle = mb_strtolower($name, 'UTF-8'); foreach ($premades as $premade) { if ((int) ($premade['id'] ?? 0) !== $exceptId && mb_strtolower(normalize_premade_name((string) ($premade['name'] ?? '')), 'UTF-8') === $needle) { return true; } } return false; } /** * @return array{id: int, name: string, owner_id: int} * @throws RuntimeException */ function create_premade(string $name, ?int $ownerId, bool $hidden = false): array { // $ownerId null = Gruppe ohne Lead (nur die Leitung legt solche Gruppen an); $hidden siehe premade_visible_to() $data = premades_api_request('POST', '', ['name' => $name, 'owner_id' => $ownerId, 'hidden' => $hidden]); return [ 'id' => (int) ($data['premade_id'] ?? 0), 'name' => (string) ($data['name'] ?? $name), 'owner_id' => isset($data['owner_id']) ? (int) $data['owner_id'] : $ownerId, ]; } /** @throws RuntimeException */ function rename_premade(int $premadeId, string $name): void { premades_api_request('PATCH', '/' . $premadeId, ['name' => $name]); } /** * Premade verstecken bzw. wieder zeigen (nur mit premades.manage). Der Bot laesst versteckte in der * Discord-Uebersicht weg; auf der Website filtert premade_visible_to(). * * @throws RuntimeException */ function set_premade_hidden(int $premadeId, bool $hidden): void { premades_api_request('PUT', '/' . $premadeId . '/hidden', ['hidden' => $hidden]); } const PREMADE_DISSOLVE_REASON_MIN = 5; const PREMADE_DISSOLVE_REASON_MAX = 500; /** * Loest eine Premade auf. Der Bot schreibt allen Mitgliedern eine PN - loest die Leitung eine * fremde Gruppe auf ($byLeadership), bekommt der Lead die Begruendung mit. * * @throws RuntimeException */ function delete_premade(int $premadeId, string $reason = '', bool $byLeadership = false, ?int $actorId = null): void { premades_api_request('DELETE', '/' . $premadeId, [ 'reason' => $reason !== '' ? $reason : null, 'by_leadership' => $byLeadership, 'actor_id' => $actorId, ]); } /** * 'pending' verschickt eine Einladung per PN, 'accepted' traegt direkt ein (Einteilung durch die * Leitung bzw. angenommene Einladung) - mit $notify bekommt der Spieler dazu eine PN. * $source sagt dem Bot, wem er noch Bescheid gibt: 'accept' (Einladung angenommen) bzw. 'assign' * (von der Leitung eingeteilt) - der Lead der Gruppe bekommt dann eine PN. $class waehlt die * Klasse vor (premade_default_class()); null laesst eine schon hinterlegte stehen. Der Bot vergibt * den Platz selbst: frei in der Gruppe, sonst die Reserve - mit $reserve umgekehrt (Bewerbung fuer * die Reserve). Sind beide voll, lehnt er ab. Wer schon eingeladen ist, behaelt seinen Platz. * * @return bool|null der vergebene Platz (true = Reserve), null bei einem Bot, der ihn noch nicht meldet * @throws RuntimeException */ function add_premade_member(int $premadeId, int $userId, string $status = 'accepted', bool $notify = false, ?string $source = null, ?int $actorId = null, ?string $class = null, bool $reserve = false): ?bool { $body = ['user_id' => $userId, 'status' => $status, 'notify' => $notify, 'source' => $source, 'actor_id' => $actorId]; if ($class !== null && $class !== '') { $body['class'] = $class; } if ($reserve) { $body['reserve'] = true; } if ($status === 'pending') { // Damit Annehmen/Ablehnen im Discord auch im Log-Kanal landet. try { $body['guild_id'] = reports_guild_id(); } catch (Throwable $e) { // ohne Log-Kanal geht es auch } } $response = premades_api_request('POST', '/' . $premadeId . '/members', $body); return isset($response['reserve']) ? (bool) $response['reserve'] : null; } /** * $source: 'decline' (Einladung abgelehnt - der Lead bekommt eine PN), 'remove' (entfernt - der * Spieler und, wenn es nicht der Lead selbst war, der Lead bekommen eine PN) oder 'withdraw' * (Einladung zurueckgezogen). * * @throws RuntimeException */ function remove_premade_member(int $premadeId, int $userId, ?string $source = null, ?int $actorId = null): void { premades_api_request('DELETE', '/' . $premadeId . '/members/' . $userId, $source !== null ? ['source' => $source, 'actor_id' => $actorId] : null); } /** @throws RuntimeException */ function set_premade_member_class(int $premadeId, int $userId, string $className): void { premades_api_request('PATCH', '/' . $premadeId . '/members/' . $userId, ['class' => $className]); } /** * Schiebt ein Mitglied auf die Reserve (ein bisheriger Reservist tauscht in die Gruppe) bzw. zurueck * in die Gruppe (braucht einen freien Platz). Der Lead bleibt immer in der Gruppe. * * @throws RuntimeException */ function set_premade_member_reserve(int $premadeId, int $userId, bool $reserve): void { premades_api_request('PATCH', '/' . $premadeId . '/members/' . $userId, ['reserve' => $reserve]); } /** * Reihenfolge der Spieler in der Gruppe (ohne Lead und Reserve) - wer fehlt, kommt dahinter. Der Lead steht immer * vorne; die Reihenfolge gilt auch in der Premade-Uebersicht im Discord. * * @param int[] $userIds * @throws RuntimeException */ function set_premade_member_order(int $premadeId, array $userIds): void { try { premades_api_request('PUT', '/' . $premadeId . '/order', ['user_ids' => array_values(array_map('intval', $userIds))]); } catch (RuntimeException $e) { // Ein Bot ohne diese Schnittstelle (noch nicht aktualisiert) antwortet mit FastAPIs "Not Found" bzw. "Method // Not Allowed" - eine unbekannte Premade meldet er dagegen mit eigenem Text if (preg_match('/Statuscode (404|405)\.( \((Not Found|Method Not Allowed)\))?$/', $e->getMessage())) { throw new RuntimeException('Der Discord-Bot kann die Reihenfolge noch nicht speichern - er muss erst aktualisiert werden.'); } throw $e; } } /** * @param bool $allowMultipleLead der neue Lead darf neben dieser noch andere Premades leiten - das Limit * (PREMADE_LEAD_MAX, premades.lead_multiple) prueft die Website, der Bot laesst es dann zu * @throws RuntimeException */ function transfer_premade_owner(int $premadeId, int $newOwnerId, bool $allowMultipleLead = false): void { premades_api_request('POST', '/' . $premadeId . '/transfer', ['new_owner_id' => $newOwnerId, 'allow_multiple_lead' => $allowMultipleLead]); } // Eine Premade hat 5 Plaetze in der Gruppe (Lead, Mitglieder, offene Einladungen) und einen auf der // Reserve (Ersatzbank). Mitglied sein kann man in beliebig vielen Premades, leiten bis zu PREMADE_LEAD_MAX - // mit premades.lead_multiple mehr. Den Platz vergibt und prueft der Bot (database/db.py im Bot-Repo). const PREMADE_MAIN_SLOTS = 5; const PREMADE_RESERVE_SLOTS = 1; const PREMADE_LEAD_MAX = 3; /** * Alle Premades, in denen der Nutzer Lead oder angenommenes Mitglied ist - die eigene(n) geleitete(n) * zuerst. * * @param array> $premades * @return array, status: string}> */ function find_my_premades(array $premades, int $discordId): array { $owned = []; $member = []; foreach ($premades as $premade) { if ((int) ($premade['owner_id'] ?? 0) === $discordId) { $owned[] = ['premade' => $premade, 'status' => 'owner']; } elseif (premade_has_user($premade, $discordId, false)) { $member[] = ['premade' => $premade, 'status' => 'accepted']; } } return array_merge($owned, $member); } /** * Wie viele Premades der Nutzer leitet. * * @param array> $premades */ function premade_owned_count(array $premades, int $discordId): int { return count(array_filter($premades, static fn (array $p): bool => (int) ($p['owner_id'] ?? 0) === $discordId)); } /** Darf dieser Spieler (Discord-ID) mehr als PREMADE_LEAD_MAX Premades leiten (premades.lead_multiple)? */ function premade_may_lead_multiple(int $discordId): bool { return in_array((string) $discordId, discord_ids_with_permission('premades.lead_multiple'), true); } /** * Darf dieser Spieler noch eine (weitere) Premade leiten - gruenden, als Lead eingesetzt werden oder die Leitung * uebertragen bekommen? Bis zu PREMADE_LEAD_MAX, mit premades.lead_multiple beliebig viele. * * @param array> $premades */ function premade_may_lead_another(array $premades, int $discordId): bool { return premade_owned_count($premades, $discordId) < PREMADE_LEAD_MAX || premade_may_lead_multiple($discordId); } /** * Vorausgewaehlte Klasse eines Spielers in einer Premade: seine Main-Klasse laut Discord-Rollen * (wie bei der Raid-Anmeldung), null ohne verknuepftes Website-Konto. */ function premade_default_class(int $discordId): ?string { static $cache = []; if (!array_key_exists($discordId, $cache)) { $stmt = db()->prepare("SELECT class_name, classes FROM users WHERE discord_id = ? AND status = 'active'"); $stmt->execute([$discordId]); $row = $stmt->fetch(); $cache[$discordId] = $row ? (user_classes($row)[0] ?? null) : null; } return $cache[$discordId]; } /** * Steht der Nutzer schon in dieser Premade (Lead, Mitglied oder offene Einladung)? * * @param array $premade */ function premade_has_user(array $premade, int $discordId, bool $includePending = true): bool { if ((int) ($premade['owner_id'] ?? 0) === $discordId) { return true; } foreach ($premade['members'] ?? [] as $member) { if ((int) ($member['user_id'] ?? 0) === $discordId && (($member['status'] ?? '') === 'accepted' || ($includePending && ($member['status'] ?? '') === 'pending'))) { return true; } } return false; } /** Hat die Leitung die Premade versteckt (Schalter liegt im Bot)? */ function premade_is_hidden(array $premade): bool { return !empty($premade['hidden']); } /** * Darf das Konto (Discord-ID, 0 = nicht verknuepft) diese Premade sehen? Versteckte nur ihre eigenen Leute - Lead, * Mitglieder, offene Einladungen - und wer alle Premades verwaltet (premades.manage). Fuer alle anderen gibt es sie * nicht: nicht in der Liste, nicht zum Bewerben, nicht zum Einladen in Raids. * fetch_premades() liefert weiter alle - die Abgleiche (Banner, Bewerbungen) brauchen die vollstaendige Liste. * * @param array $premade */ function premade_visible_to(array $premade, int $discordId): bool { return !premade_is_hidden($premade) || user_has_permission('premades.manage') || ($discordId > 0 && premade_has_user($premade, $discordId)); } /** * Nur die Premades, die das Konto sehen darf (premade_visible_to), Reihenfolge bleibt. * * @param array> $premades * @return array> */ function premades_visible_to(array $premades, int $discordId): array { return array_values(array_filter($premades, static fn (array $p): bool => premade_visible_to($p, $discordId))); } /** * Belegte Plaetze einer Premade (Lead, Mitglieder und offene Einladungen): [Gruppe, Reserve]. * * @param array $premade * @return array{0: int, 1: int} */ function premade_slot_counts(array $premade): array { $ownerId = (int) ($premade['owner_id'] ?? 0); $counts = [$ownerId > 0 ? 1 : 0, 0]; foreach ($premade['members'] ?? [] as $member) { if ((int) ($member['user_id'] ?? 0) !== $ownerId) { $counts[!empty($member['reserve']) ? 1 : 0]++; } } return $counts; } /** Sind alle Plaetze belegt - Gruppe und Reserve? */ function premade_is_full(array $premade): bool { [$main, $reserve] = premade_slot_counts($premade); return $main >= PREMADE_MAIN_SLOTS && $reserve >= PREMADE_RESERVE_SLOTS; } /** * Welche Plaetze noch frei sind (offene Einladungen belegen ihren Platz): [Gruppe, Reserve]. * * @return array{0: bool, 1: bool} */ function premade_free_slots(array $premade): array { [$main, $reserve] = premade_slot_counts($premade); return [$main < PREMADE_MAIN_SLOTS, $reserve < PREMADE_RESERVE_SLOTS]; } /** * @param array> $premades * @return array> Alle Premades, bei denen der Nutzer eine offene * (noch nicht angenommene) Einladung hat. */ function find_my_pending_invites(array $premades, int $discordId): array { $result = []; foreach ($premades as $premade) { foreach ($premade['members'] ?? [] as $member) { if ((int) ($member['user_id'] ?? 0) === $discordId && ($member['status'] ?? '') === 'pending') { $result[] = $premade; break; } } } return $result; } // Bevorzugt den von der Bot-API aufgeloesten Discord-Anzeigenamen (die API kennt Discord direkt, // die Website nicht); faellt auf den verknuepften Website-Account und zuletzt auf die rohe // Discord-ID zurueck, falls beides fehlt (z.B. Bot offline beim API-Aufruf). // Wird sowohl von premades.php als auch vom Dashboard-Widget genutzt. function premade_name_for(int $discordId, array $namesByDiscordId, ?string $apiName = null): string { if ($apiName !== null && $apiName !== '') { return $apiName; } return $namesByDiscordId[$discordId] ?? ('Discord-Nutzer ' . $discordId); } // Baut ein fuer avatar_html() nutzbares Nutzer-Array: das echte, hochgeladene Profilbild, // falls die Discord-ID zu einem verknuepften Website-Account gehoert, sonst ein Platzhalter // mit dem Anfangsbuchstaben des (von der API aufgeloesten) Namens. function premade_avatar_user(int $discordId, array $linkedUsersByDiscordId, string $displayName): array { if (isset($linkedUsersByDiscordId[$discordId])) { return $linkedUsersByDiscordId[$discordId]; } return ['id' => $discordId, 'display_name' => $displayName, 'username' => $displayName, 'avatar_filename' => null]; } /** * Baut die feste Slot-Darstellung einer Premade: 5 Plaetze in der Gruppe (Lead zuerst, dann Mitglieder * und offene Einladungen, mit Platzhaltern aufgefuellt) und als 6. die Reserve (reserve => true) - * genutzt von premades.php und vom "Meine Premade"-Widget im Dashboard. * * @param array $premade * @param array $namesByDiscordId * @return array> */ function build_premade_slots(array $premade, array $namesByDiscordId): array { $ownerId = (int) ($premade['owner_id'] ?? 0); $members = is_array($premade['members'] ?? null) ? $premade['members'] : []; $slotOf = static function (array $member, string $type) use ($namesByDiscordId): array { $mid = (int) ($member['user_id'] ?? 0); return ['type' => $type, 'id' => $mid, 'name' => premade_name_for($mid, $namesByDiscordId, $member['name'] ?? null), 'class' => $member['class'] ?? null, 'reserve' => !empty($member['reserve'])]; }; // Von der Leitung angelegte Gruppen koennen (noch) ohne Lead sein. $main = []; $reserve = []; if ($ownerId > 0) { $ownerName = premade_name_for($ownerId, $namesByDiscordId, $premade['owner_name'] ?? null); $main[] = ['type' => 'lead', 'id' => $ownerId, 'name' => $ownerName, 'class' => $premade['owner_class'] ?? null, 'reserve' => false]; } // In der Reihenfolge des Bots (Platz in der Gruppe, auf der Website umsortierbar) - offene Einladungen behalten // ihren Platz foreach ($members as $member) { $status = (string) ($member['status'] ?? ''); if (!in_array($status, ['accepted', 'pending'], true) || (int) ($member['user_id'] ?? 0) === $ownerId) { continue; } if (!empty($member['reserve'])) { $reserve[] = $slotOf($member, $status); } else { $main[] = $slotOf($member, $status); } } while (count($main) < PREMADE_MAIN_SLOTS) { $main[] = ['type' => 'empty', 'reserve' => false]; } while (count($reserve) < PREMADE_RESERVE_SLOTS) { $reserve[] = ['type' => 'empty', 'reserve' => true]; } return array_merge($main, $reserve); } /** * Sucht einen einzelnen Raid (inkl. aktueller Signups) anhand seiner ID. * * @return array|null * @throws RuntimeException */ function fetch_raid_by_id(int $raidId): ?array { foreach (fetch_raids('all') as $raid) { if ((int) ($raid['raid_id'] ?? 0) === $raidId) { return $raid; } } return null; } // Welche Gruppe zu welcher Klasse passt (je Gruppe 1 Tank, 1 Heiler, 3 DPS), entscheidet der Bot // (cogs/teamplaner.py) - fuer Anmeldungen im Discord und auf der Website gleich. const RAID_GROUP_SIZE = 5; // Mehr Gruppen passen nicht in die Discord-Nachricht (hoechstens 25 Felder je Embed). const RAID_MAX_GROUPS = 10; const RAID_MAX_SLOTS = RAID_MAX_GROUPS * RAID_GROUP_SIZE; const RAID_GEARSCORE_MAX = 99999; /** Anzahl der Gruppen in der kommagetrennten Liste der Gruppennamen. */ function raid_group_count(string $groupNames): int { return count(array_filter(array_map('trim', explode(',', $groupNames)), static fn (string $name): bool => $name !== '')); } /** * Prueft "Max. Spieler": nur ganze Zahlen von 1 bis Gruppen x 5 (hoechstens 50) - mehr Plaetze * koennten ohnehin nur auf der Ersatzbank landen. Liefert die Fehlermeldung oder null. * * @param mixed $value */ function raid_slots_error($value, int $groupCount): ?string { if ($groupCount < 1) { return 'Bitte mindestens eine Gruppe angeben.'; } if ($groupCount > RAID_MAX_GROUPS) { return 'Höchstens ' . RAID_MAX_GROUPS . ' Gruppen pro Raid.'; } $max = min(RAID_MAX_SLOTS, $groupCount * RAID_GROUP_SIZE); $raw = is_int($value) ? (string) $value : trim((string) $value); if (!ctype_digit($raw) || (int) $raw < 1 || (int) $raw > $max) { return 'Max. Spieler: nur ganze Zahlen von 1 bis ' . $max . ' (' . $groupCount . ($groupCount === 1 ? ' Gruppe' : ' Gruppen') . ' à ' . RAID_GROUP_SIZE . ' Plätze).'; } return null; } /** * Gearscore: leer oder eine Zahl von 1 bis 99.999. Punkte und Leerzeichen als Tausendertrenner * sind erlaubt ("2.100"), gespeichert wird nur die Zahl. * * @return array{0: string, 1: ?string} [bereinigter Wert, Fehlermeldung oder null] */ function raid_normalize_gearscore(string $raw): array { $clean = str_replace(['.', ' ', "\u{00A0}"], '', trim($raw)); if ($clean === '') { return ['', null]; } if (!ctype_digit($clean) || (int) $clean < 1 || (int) $clean > RAID_GEARSCORE_MAX) { return [$raw, 'Gearscore: nur eine Zahl von 1 bis 99.999 – oder das Feld leer lassen.']; } return [(string) (int) $clean, null]; } /** Gearscore fuer die Anzeige: Zahlen mit Tausenderpunkt, alte Freitexte unveraendert. */ function raid_gearscore_label(string $gearscore): string { return ctype_digit($gearscore) ? number_format((int) $gearscore, 0, ',', '.') : $gearscore; } /** * Discord-Server-ID aus config.php - identisch zur Quelle, die create_raid() fuer die * Raid-Erstellung nutzt. Reports/Einstellungen sind (wie Raids/Premades) an genau den einen * dort konfigurierten Server gebunden. * * @throws RuntimeException */ function reports_guild_id(): int { $configPath = __DIR__ . '/../config.php'; if (!file_exists($configPath)) { throw new RuntimeException('Konfigurationsdatei fehlt.'); } $config = require $configPath; $guildId = $config['raids_api']['guild_id'] ?? null; if (!$guildId) { throw new RuntimeException('Reports sind nicht konfiguriert (config.php: raids_api.guild_id fehlt).'); } return (int) $guildId; } /** * Fuehrt einen Request gegen die Reports-API aus (/api/reports/...) - analog zu * premades_api_request(), nur mit Unterstuetzung fuer Query-Parameter (z.B. guild_id). * * @param array $queryParams * @param array|null $jsonBody * @return array * @throws RuntimeException */ function reports_api_request(string $method, string $path = '', array $queryParams = [], ?array $jsonBody = null, int $timeout = 10): array { if (!function_exists('curl_init')) { throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.'); } $config = raids_api_config(); // /api/reports liegt eine Ebene ueber /api/raids. $base = preg_replace('#/raids$#', '', $config['url']); $url = $base . '/reports' . $path; if (!empty($queryParams)) { $url .= '?' . http_build_query($queryParams); } $headers = ['X-API-Key: ' . $config['key']]; $ch = curl_init($url); $options = [ CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_TIMEOUT => $timeout, CURLOPT_SSL_VERIFYPEER => true, ]; if ($jsonBody !== null) { $headers[] = 'Content-Type: application/json'; $options[CURLOPT_POSTFIELDS] = json_encode($jsonBody, JSON_UNESCAPED_UNICODE); } $options[CURLOPT_HTTPHEADER] = $headers; curl_setopt_array($ch, $options); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlError = curl_error($ch); curl_close($ch); if ($response === false) { throw new RuntimeException('Verbindung zur Reports-API fehlgeschlagen: ' . $curlError); } $data = json_decode($response, true); if ($httpCode < 200 || $httpCode >= 300) { throw new RuntimeException(bot_api_error_message('Reports-API', $httpCode, $data)); } if (!is_array($data)) { throw new RuntimeException('Unerwartetes Antwortformat der Reports-API.'); } return $data; } /** * Datei, die der Melder im Discord-Formular hochgeladen hat (liegt beim Bot). * * @return array{data: string, type: string, name: string}|null null, wenn der Report keine Datei (mehr) hat * @throws RuntimeException */ function fetch_report_file(int $reportId): ?array { $config = raids_api_config(); $name = ''; $ch = curl_init(preg_replace('#/raids$#', '', $config['url']) . '/reports/' . $reportId . '/file'); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_HTTPHEADER => ['X-API-Key: ' . $config['key']], // Originalname der Datei (URL-kodiert, siehe api.py get_report_file_api) CURLOPT_HEADERFUNCTION => static function ($ch, string $line) use (&$name): int { if (stripos($line, 'x-file-name:') === 0) { $name = rawurldecode(trim(substr($line, 12))); } return strlen($line); }, ]); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $type = (string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE); $curlError = curl_error($ch); curl_close($ch); if ($response === false) { throw new RuntimeException('Verbindung zur Reports-API fehlgeschlagen: ' . $curlError); } if ($httpCode === 404) { return null; } if ($httpCode < 200 || $httpCode >= 300) { throw new RuntimeException(bot_api_error_message('Reports-API', $httpCode, json_decode($response, true))); } return ['data' => $response, 'type' => strtolower(trim(explode(';', $type)[0])), 'name' => $name]; } /** * @return array> * @throws RuntimeException */ function fetch_reports(bool $includeArchived = true): array { $data = reports_api_request('GET', '', ['guild_id' => reports_guild_id(), 'include_archived' => $includeArchived ? 'true' : 'false']); if (($data['status'] ?? '') !== 'success' || !is_array($data['reports'] ?? null)) { throw new RuntimeException('Unerwartetes Antwortformat der Reports-API.'); } reports_nav_store($data['reports']); return $data['reports']; } // Offene (nicht archivierte) Reports als Zahl in der Seitenleiste. Wie bei den Raids liegen sie beim Bot - // die Zahl steht in settings.reports_nav_cache und wird hoechstens alle REPORTS_NAV_CACHE_TTL Sekunden neu // geholt; fetch_reports() (die Reports-Seite, auch nach dem Archivieren) frischt sie sofort auf. const REPORTS_NAV_CACHE_TTL = 120; /** * Liest (ohne Argument) oder schreibt den Zwischenspeicher - innerhalb eines Aufrufs gilt der zuletzt * geschriebene Stand. * * @param array{fetched_at: int, open: int}|null $value * @return array|null */ function reports_nav_cache(?array $value = null): ?array { static $current = false; if ($value !== null) { $current = $value; try { setting_set('reports_nav_cache', (string) json_encode($value)); } catch (PDOException $e) { // Ohne settings-Tabelle eben ohne Zwischenspeicher. } return $value; } if ($current === false) { $decoded = json_decode(setting_get('reports_nav_cache'), true); $current = is_array($decoded) ? $decoded : null; } return $current; } /** * Merkt sich, wie viele der Reports offen (nicht archiviert) sind. * * @param array> $reports */ function reports_nav_store(array $reports): int { $open = count(array_filter($reports, static fn (array $report): bool => empty($report['archived']))); $cached = reports_nav_cache(); if (!is_array($cached) || (int) ($cached['open'] ?? -1) !== $open || time() - (int) ($cached['fetched_at'] ?? 0) >= 60) { reports_nav_cache(['fetched_at' => time(), 'open' => $open]); } return $open; } /** * Zahl der offenen Reports fuer die Seitenleiste. Ist der Zwischenspeicher aelter als REPORTS_NAV_CACHE_TTL, * fragt die Funktion den Bot mit kurzer Wartezeit; antwortet er nicht, gilt der letzte Stand. */ function reports_nav_open(): int { $cached = reports_nav_cache(); $open = (int) ($cached['open'] ?? 0); if (time() - (int) ($cached['fetched_at'] ?? 0) >= REPORTS_NAV_CACHE_TTL) { // Zeitpunkt vorher merken - sonst fragt bei einem Ausfall des Bots jeder Seitenaufruf erneut reports_nav_cache(['fetched_at' => time(), 'open' => $open]); try { $data = reports_api_request('GET', '', ['guild_id' => reports_guild_id(), 'include_archived' => 'false'], null, 3); if (($data['status'] ?? '') === 'success' && is_array($data['reports'] ?? null)) { $open = reports_nav_store($data['reports']); } } catch (Throwable $e) { // Bot nicht erreichbar oder nicht eingerichtet - dann eben der letzte Stand } } return $open; } /** @throws RuntimeException */ function delete_report(int $reportId): void { reports_api_request('DELETE', '/' . $reportId); } /** * Loescht alle Reports gegen einen Spieler und hebt seinen Auto-Mute auf. * * @throws RuntimeException */ function clear_user_reports(int $reportedId): void { reports_api_request('DELETE', '/user/' . $reportedId, ['guild_id' => reports_guild_id()]); } /** @throws RuntimeException */ function set_report_archived(int $reportId, bool $archived): void { reports_api_request('PATCH', '/' . $reportId, [], ['archived' => $archived]); } /** * @return array> * @throws RuntimeException */ function fetch_report_weights(): array { $data = reports_api_request('GET', '/weights', ['guild_id' => reports_guild_id()]); if (($data['status'] ?? '') !== 'success' || !is_array($data['roles'] ?? null)) { throw new RuntimeException('Unerwartetes Antwortformat der Reports-API.'); } return $data['roles']; } /** @throws RuntimeException */ function set_report_weight(int $roleId, int $points): void { reports_api_request('PATCH', '/weights/' . $roleId, [], ['guild_id' => reports_guild_id(), 'points' => $points]); } /** * @return array> * @throws RuntimeException */ function fetch_mute_exclusions(): array { $data = reports_api_request('GET', '/mute-exclusions', ['guild_id' => reports_guild_id()]); if (($data['status'] ?? '') !== 'success' || !is_array($data['roles'] ?? null)) { throw new RuntimeException('Unerwartetes Antwortformat der Reports-API.'); } return $data['roles']; } /** @throws RuntimeException */ function set_mute_exclusion(int $roleId, bool $excluded): void { reports_api_request('PATCH', '/mute-exclusions/' . $roleId, [], ['guild_id' => reports_guild_id(), 'excluded' => $excluded]); } /** * Liest/schreibt die Mute-Punkte-Schwelle ueber den generischen Server-Settings-Endpunkt des * Bots (/api/settings/{guild_id}), der auch Log-/Report-/Raid-Kanal verwaltet - die Website * nutzt davon bisher nur die Schwelle. * * @throws RuntimeException */ function fetch_mute_threshold(): int { if (!function_exists('curl_init')) { throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.'); } $guildId = reports_guild_id(); $config = raids_api_config(); $base = preg_replace('#/raids$#', '', $config['url']); $url = $base . '/settings/' . $guildId; $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['X-API-Key: ' . $config['key']], CURLOPT_TIMEOUT => 10, CURLOPT_SSL_VERIFYPEER => true, ]); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlError = curl_error($ch); curl_close($ch); if ($response === false) { throw new RuntimeException('Verbindung zur Settings-API fehlgeschlagen: ' . $curlError); } $data = json_decode($response, true); if ($httpCode < 200 || $httpCode >= 300 || !is_array($data)) { throw new RuntimeException('Settings-API antwortete mit Statuscode ' . $httpCode . '.'); } return (int) ($data['mute_threshold'] ?? 10); } /** @throws RuntimeException */ function set_mute_threshold(int $threshold): void { if (!function_exists('curl_init')) { throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.'); } $guildId = reports_guild_id(); $config = raids_api_config(); $base = preg_replace('#/raids$#', '', $config['url']); $url = $base . '/settings/' . $guildId; $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => 'PATCH', CURLOPT_HTTPHEADER => ['X-API-Key: ' . $config['key'], 'Content-Type: application/json'], CURLOPT_POSTFIELDS => json_encode(['mute_threshold' => $threshold], JSON_UNESCAPED_UNICODE), CURLOPT_TIMEOUT => 10, CURLOPT_SSL_VERIFYPEER => true, ]); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlError = curl_error($ch); curl_close($ch); if ($response === false) { throw new RuntimeException('Verbindung zur Settings-API fehlgeschlagen: ' . $curlError); } if ($httpCode < 200 || $httpCode >= 300) { throw new RuntimeException('Settings-API antwortete mit Statuscode ' . $httpCode . '.'); } }