'Anwesend', 'absent' => 'Abwesend', ]; // Lumipunkte pro Raid: fest +1 fuer jede Teilnahme, kein Abzug. Andere Werte (bis 10) legt nur // fest, wer raids.points hat (die Sedes Luminis). const RAID_POINTS_DEFAULT_PRESENT = 1; const RAID_POINTS_DEFAULT_ABSENT = 0; const RAID_POINTS_MAX = 10; // Seit diesem Tag gilt der feste Punkt auch fuer Raids, die im Discord erstellt wurden (die Website // legt ihre Einstellungen dann beim ersten Anzeigen an). Aeltere Raids bleiben, wie sie waren. const RAID_POINTS_DEFAULT_SINCE = '2026-09-23 00:00:00'; /** Liefert die Fehlermeldung, wenn die Punkte fuer einen Raid nicht zwischen 0 und 10 liegen. */ function raid_points_error(int $present, int $absent): ?string { if ($present < 0 || $present > RAID_POINTS_MAX || $absent < 0 || $absent > RAID_POINTS_MAX) { return 'Lumipunkte: 0 bis ' . RAID_POINTS_MAX . ' pro Raid.'; } return null; } /** "+1 Lumipunkt pro Teilnahme, kein Abzug" - fuer alle, die die Werte nicht selbst festlegen. */ function raid_points_summary(int $present, int $absent): string { if ($present <= 0 && $absent <= 0) { return 'Keine automatischen Lumipunkte'; } $text = $present > 0 ? '+' . $present . ' Lumipunkt' . ($present === 1 ? '' : 'e') . ' pro Teilnahme' : 'Keine Punkte für die Teilnahme'; return $text . ($absent > 0 ? ', −' . $absent . ' bei Abwesenheit' : ', kein Abzug'); } /** Ganze Zahl aus einem Formularwert - oder null, wenn es keine ist. */ function raid_points_input($value): ?int { $raw = is_int($value) ? (string) $value : trim((string) $value); return ctype_digit($raw) ? (int) $raw : null; } /** * Lumipunkte fuer einen neuen Raid, wenn der Ersteller sie nicht selbst festlegen darf (raids.points): * Raids der Leitung (raids.manage) bringen den festen Punkt, Raids eines Mitglieds als Raid-Lead keine - * die legt die Leitung bei Bedarf nachtraeglich fest. * * @return array{0: int, 1: int} [fuer Anwesende, Abzug fuer Abwesende] */ function raid_points_defaults_for_creator(): array { return user_has_permission('raids.manage') ? [RAID_POINTS_DEFAULT_PRESENT, RAID_POINTS_DEFAULT_ABSENT] : [0, 0]; } /** Raid-Lead eines Raids (Website-Konto) oder null. */ function raid_lead_id(int $raidId): ?int { $stmt = db()->prepare('SELECT lead_user_id FROM raid_settings WHERE raid_id = ?'); $stmt->execute([$raidId]); $lead = $stmt->fetchColumn(); return $lead !== false && $lead !== null ? (int) $lead : null; } /** * Darf das aktuelle Konto den Raid verwalten? Wer alle Raids seines Bereichs verwaltet (Legion: raids.manage, * Consilium: consilium.raids.manage) jeden dort, der Raid-Lead seinen eigenen. Den Bereich fragt es beim Bot ab. */ function raid_can_manage(int $raidId): bool { $user = current_user(); if ($user === null || $raidId <= 0) { return false; } $area = raid_area_of($raidId); if ($area === null) { return false; } return raid_area_can_manage_all($area) || (raid_area_visible($area) && raid_lead_id($raidId) === (int) $user['id']); } function raid_settings_save_lead(int $raidId, int $userId): void { db()->prepare('INSERT INTO raid_settings (raid_id, lead_user_id) VALUES (?, ?) ON DUPLICATE KEY UPDATE lead_user_id = VALUES(lead_user_id)') ->execute([$raidId, $userId]); } /** * Legt fuer neue Raids ohne eigene Einstellungen (z.B. im Discord erstellt) den festen Punkt * (+1 pro Teilnahme) an, damit auch sie beim Archivieren Lumipunkte bringen. * * @param array $raidIds */ function raid_settings_ensure_defaults(array $raidIds): void { $since = strtotime(RAID_POINTS_DEFAULT_SINCE); $ids = []; foreach ($raidIds as $raidId) { $raidId = (int) $raidId; if ($raidId > 0 && raid_posted_at($raidId) >= $since) { $ids[$raidId] = true; } } if (empty($ids)) { return; } try { $pdo = db(); $placeholders = implode(',', array_fill(0, count($ids), '?')); $stmt = $pdo->prepare("SELECT raid_id FROM raid_settings WHERE raid_id IN ($placeholders)"); $stmt->execute(array_keys($ids)); foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $existing) { unset($ids[(int) $existing]); } $insert = $pdo->prepare('INSERT IGNORE INTO raid_settings (raid_id, points_present, points_absent) VALUES (?, ?, ?)'); foreach (array_keys($ids) as $raidId) { $insert->execute([$raidId, RAID_POINTS_DEFAULT_PRESENT, RAID_POINTS_DEFAULT_ABSENT]); } } catch (PDOException $e) { // Nicht kritisch - beim naechsten Aufruf erneut. } } /** @return array{points_present: int, points_absent: int, auto_processed_at: ?string, auto_result: ?string, attendance_checked_at: ?string, checked_by: ?string, lead_user_id: ?int, lead_name: ?string} */ function raid_settings_get(int $raidId): array { $stmt = db()->prepare( "SELECT s.points_present, s.points_absent, s.auto_processed_at, s.auto_result, s.attendance_checked_at, COALESCE(NULLIF(u.display_name, ''), u.username) AS checked_by, s.lead_user_id, COALESCE(NULLIF(l.display_name, ''), l.username) AS lead_name FROM raid_settings s LEFT JOIN users u ON u.id = s.attendance_checked_by LEFT JOIN users l ON l.id = s.lead_user_id WHERE s.raid_id = ?" ); $stmt->execute([$raidId]); $row = $stmt->fetch(); return [ 'points_present' => (int) ($row['points_present'] ?? 0), 'points_absent' => (int) ($row['points_absent'] ?? 0), 'auto_processed_at' => $row['auto_processed_at'] ?? null, 'auto_result' => $row['auto_result'] ?? null, 'attendance_checked_at' => $row['attendance_checked_at'] ?? null, 'checked_by' => $row['checked_by'] ?? null, 'lead_user_id' => isset($row['lead_user_id']) ? (int) $row['lead_user_id'] : null, 'lead_name' => $row['lead_name'] ?? null, ]; } /** * Alle Einstellungen auf einmal (fuer die Raid-Uebersicht), mit Name, Discord-ID und Status des Raid-Leads. * * @return array> raid_id => Einstellungen */ function raid_settings_all(): array { $settings = []; $rows = db()->query( "SELECT s.*, COALESCE(NULLIF(l.display_name, ''), l.username) AS lead_name, l.discord_id AS lead_discord_id, l.status AS lead_status FROM raid_settings s LEFT JOIN users l ON l.id = s.lead_user_id" )->fetchAll(); foreach ($rows as $row) { $settings[(string) $row['raid_id']] = $row; } return $settings; } function raid_settings_save_points(int $raidId, int $present, int $absent): void { db()->prepare( 'INSERT INTO raid_settings (raid_id, points_present, points_absent) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE points_present = VALUES(points_present), points_absent = VALUES(points_absent)' )->execute([$raidId, $present, $absent]); } /** * Was die Raid-Nachricht im Discord zusaetzlich zeigt und nur hier auf der Website liegt: den Raid-Lead * (Discord-ID, und der Name, falls er nicht auf dem Server ist) und die Lumipunkte als Text. * lead_id 0 bzw. '' = nichts anzeigen. * * @param array|null $setting Zeile aus raid_settings_all() (spart die Abfrage), [] = keine * @return array{lead_id: int, lead_name: string, points_text: string} */ function raid_bot_extras(int $raidId, ?array $setting = null, ?bool $consilium = null): array { // Consilium-Raids (mit den verbuendeten Legionen) bringen keine Lumipunkte - die Nachricht nennt keine. Ohne // Angabe: laut Zwischenspeicher der aktiven Raids (includes/raids_api.php) $consilium ??= in_array((string) $raidId, (array) (raids_nav_cache()['consilium'] ?? []), true); if ($setting === null) { $stmt = db()->prepare( "SELECT s.points_present, s.points_absent, s.lead_user_id, COALESCE(NULLIF(l.display_name, ''), l.username) AS lead_name, l.discord_id AS lead_discord_id FROM raid_settings s LEFT JOIN users l ON l.id = s.lead_user_id WHERE s.raid_id = ?" ); $stmt->execute([$raidId]); $setting = $stmt->fetch() ?: []; } if (empty($setting)) { return ['lead_id' => 0, 'lead_name' => '', 'points_text' => '']; } $hasLead = !empty($setting['lead_user_id']); return [ 'lead_id' => $hasLead ? (int) ($setting['lead_discord_id'] ?? 0) : 0, 'lead_name' => $hasLead ? (string) ($setting['lead_name'] ?? '') : '', 'points_text' => $consilium ? '' : raid_points_summary((int) ($setting['points_present'] ?? 0), (int) ($setting['points_absent'] ?? 0)), ]; } /** * Raid-Lead und Lumipunkte an den Bot schicken, damit die Discord-Nachricht sie zeigt. Ist die Nachricht * dort geloescht, postet der Bot sie neu - dann zieht die raid_id hier mit um. * * @param array{lead_id: int, lead_name: string, points_text: string}|null $extras * @return int Die (ggf. neue) raid_id */ function raid_push_extras(int $raidId, ?array $extras = null): int { try { $result = update_raid($raidId, $extras ?? raid_bot_extras($raidId)); $newRaidId = (int) ($result['raid_id'] ?? $raidId) ?: $raidId; raid_rename_id($raidId, $newRaidId); return $newRaidId; } catch (Throwable $e) { return $raidId; // Nicht schlimm - raid_sync_extras() holt es beim naechsten Anzeigen nach. } } /** * Gleicht Raid-Lead und Lumipunkte der aktiven Raids mit dem Bot ab - fuer Raids von vor dem Umbau (09/2026) * und falls eine Aenderung den Bot nicht erreicht hat. Hoechstens $limit Raids pro Aufruf (jeder kostet eine * Bearbeitung der Discord-Nachricht). Gibt true zurueck, wenn sich dabei eine raid_id geaendert hat. * * @param array> $raids Raids aus fetch_raids() * @param array> $settings raid_settings_all() */ function raid_sync_extras(array $raids, array $settings, int $limit = 3): bool { $renamed = false; foreach ($raids as $raid) { if (!array_key_exists('points_text', $raid)) { return false; // Bot von vor dem Umbau - kennt die Felder noch nicht } if (!empty($raid['archived']) || $limit <= 0) { continue; } $raidId = (int) ($raid['raid_id'] ?? 0); $want = raid_bot_extras($raidId, $settings[(string) $raidId] ?? [], raid_area($raid) === 'consilium'); $have = [ 'lead_id' => (int) ($raid['lead_id'] ?? 0), 'lead_name' => (string) ($raid['lead_name'] ?? ''), 'points_text' => (string) ($raid['points_text'] ?? ''), ]; if ($raidId <= 0 || $want === $have) { continue; } $limit--; $renamed = raid_push_extras($raidId, $want) !== $raidId || $renamed; } return $renamed; } /** * Die Raid-API postet die Discord-Nachricht neu, wenn sie geloescht wurde - dann aendert sich * die raid_id. Einstellungen, Anwesenheit und Vergaben ziehen mit um. */ function raid_rename_id(int $oldId, int $newId): void { if ($oldId === $newId || $newId <= 0) { return; } $pdo = db(); $pdo->beginTransaction(); try { // Hat eine andere Seite fuer die neue ID inzwischen schon den festen Punkt angelegt (unberuehrt), // weicht diese Zeile den Einstellungen des Raids. $hasOld = $pdo->prepare('SELECT 1 FROM raid_settings WHERE raid_id = ?'); $hasOld->execute([$oldId]); if ($hasOld->fetchColumn()) { $pdo->prepare('DELETE FROM raid_settings WHERE raid_id = ? AND auto_processed_at IS NULL AND attendance_checked_at IS NULL') ->execute([$newId]); $pdo->prepare('UPDATE IGNORE raid_settings SET raid_id = ? WHERE raid_id = ?')->execute([$newId, $oldId]); } $pdo->prepare('UPDATE IGNORE raid_attendance SET raid_id = ? WHERE raid_id = ?')->execute([$newId, $oldId]); $pdo->prepare('UPDATE contribution_awards SET raid_id = ? WHERE raid_id = ?')->execute([$newId, $oldId]); $pdo->commit(); } catch (Throwable $e) { $pdo->rollBack(); throw $e; } } /** * Anwesenheitsliste eines Raids. * * @return array Discord-ID => Eintrag */ function raid_attendance_get(int $raidId): array { $stmt = db()->prepare('SELECT discord_id, name, status FROM raid_attendance WHERE raid_id = ?'); $stmt->execute([$raidId]); $list = []; foreach ($stmt->fetchAll() as $row) { $list[(string) $row['discord_id']] = ['status' => (string) $row['status'], 'name' => (string) $row['name']]; } return $list; } /** * Anmeldungen eines Raids, aufgeteilt: in einer Gruppe, auf der Ersatzbank, abgemeldet. * Ausstehende Premade-Einladungen zaehlen nicht als Anmeldung. * * @return array{groups: array, bench: array, declined: array} */ function raid_signups_split(array $raid): array { $split = ['groups' => [], 'bench' => [], 'declined' => []]; foreach ((array) ($raid['signups'] ?? []) as $signup) { $group = (int) ($signup['group'] ?? 0); if ($group < 0) { $split['declined'][] = $signup; } elseif (($signup['class'] ?? '') === 'Ausstehend') { continue; } elseif ($group === 0) { $split['bench'][] = $signup; } else { $split['groups'][] = $signup; } } return $split; } /** * Aktive Website-Konten der Legion je Discord-ID - nur sie bekommen Lumipunkte, Verbuendete aus dem Consilium nicht. * * @return array Discord-ID => user_id */ function raid_user_ids_by_discord(): array { $map = []; $rows = db()->query("SELECT u.id, u.discord_id FROM users u WHERE u.status = 'active' AND u.discord_id IS NOT NULL AND " . sql_is_legion_member('u'))->fetchAll(); foreach ($rows as $row) { $map[(string) $row['discord_id']] = (int) $row['id']; } return $map; } /** Wurden fuer diesen Raid schon Lumipunkte vergeben (von Hand oder automatisch)? */ function raid_has_awards(int $raidId): bool { $stmt = db()->prepare('SELECT 1 FROM contribution_awards WHERE raid_id = ? LIMIT 1'); $stmt->execute([$raidId]); return (bool) $stmt->fetchColumn(); } /** * Automatische Lumipunkte fuer archivierte Raids. * * Laeuft bei jedem Aufruf der Raid- und Punkteseiten und direkt nach dem Archivieren - so * werden auch Raids erfasst, die im Discord ueber den Knopf archiviert wurden (die Website * erfaehrt davon sonst nichts). Kosten: eine Abfrage, solange nichts offen ist. * * - Schon Punkte fuer den Raid vergeben? Dann entfaellt die Automatik. * - Anwesenheitsliste gefuehrt: Anwesende bekommen die Punkte, Abwesende den Abzug. * - Keine Liste: alle, die in einer Gruppe angemeldet waren, bekommen die Punkte (kein Abzug). * * @param array>|null $raids Bereits geladene Raids (spart eine API-Abfrage) * @return array Meldungen je verarbeitetem Raid */ function raid_process_auto_points(?array $raids = null): array { if ($raids !== null) { raid_settings_ensure_defaults(array_map(static fn (array $raid) => $raid['raid_id'] ?? 0, $raids)); } try { $pending = db()->query( 'SELECT raid_id, points_present, points_absent FROM raid_settings WHERE auto_processed_at IS NULL AND (points_present > 0 OR points_absent > 0)' )->fetchAll(); } catch (PDOException $e) { return []; } if (empty($pending)) { return []; } // Nur archivierte Raids zaehlen. Sind die mitgegebenen Raids nicht alle dabei, frisch laden. $raidsById = []; foreach ((array) $raids as $raid) { $raidsById[(string) ($raid['raid_id'] ?? '')] = $raid; } $missing = array_filter($pending, static fn (array $p): bool => !isset($raidsById[(string) $p['raid_id']])); if (!empty($missing)) { try { foreach (fetch_raids('all') as $raid) { $raidsById[(string) ($raid['raid_id'] ?? '')] = $raid; } } catch (Throwable $e) { return []; // Raid-API nicht erreichbar - beim naechsten Aufruf erneut } } $messages = []; $userIds = null; foreach ($pending as $setting) { $raidId = (int) $setting['raid_id']; $raid = $raidsById[(string) $raidId] ?? null; if ($raid === null || (empty($raid['archived']) && empty($raid['archived_at']))) { continue; // noch aktiv (oder geloescht) - nichts zu tun } $messages[] = raid_run_auto_points($raidId, $raid, (int) $setting['points_present'], (int) $setting['points_absent'], $userIds); } return $messages; } /** Vergibt die automatischen Punkte fuer einen archivierten Raid und merkt sich das Ergebnis. */ function raid_run_auto_points(int $raidId, array $raid, int $pointsPresent, int $pointsAbsent, ?array &$userIds): string { $pdo = db(); $title = (string) ($raid['title'] ?? 'Raid'); $timestamp = (int) ($raid['timestamp'] ?? 0); $awardedAt = $timestamp > 0 ? date('Y-m-d H:i:s', $timestamp) : date('Y-m-d H:i:s'); // Gegen doppelte Vergabe bei gleichzeitigen Seitenaufrufen: Zeile sperren und erneut pruefen. $pdo->beginTransaction(); $lock = $pdo->prepare('SELECT auto_processed_at FROM raid_settings WHERE raid_id = ? FOR UPDATE'); $lock->execute([$raidId]); if ($lock->fetchColumn() !== null) { $pdo->commit(); return ''; } $finish = static function (string $result) use ($pdo, $raidId): string { $pdo->prepare('UPDATE raid_settings SET auto_processed_at = NOW(), auto_result = ? WHERE raid_id = ?') ->execute([mb_substr($result, 0, 255), $raidId]); $pdo->commit(); return $result; }; // Raids des Consilium Elyseum (mit den verbuendeten Legionen) bringen keine automatischen Lumipunkte if (raid_area($raid) === 'consilium') { return $finish('Keine Lumipunkte: „' . $title . '“ ist ein Raid des Consilium Elyseum.'); } if (raid_has_awards($raidId)) { return $finish('Übersprungen: Für „' . $title . '“ wurden schon vorher Punkte vergeben.'); } $userIds ??= raid_user_ids_by_discord(); $attendance = raid_attendance_get($raidId); $present = []; $absent = []; if (!empty($attendance)) { foreach ($attendance as $discordId => $entry) { $userId = $userIds[$discordId] ?? null; if ($userId === null) { continue; } if ($entry['status'] === 'present') { $present[] = $userId; } elseif ($entry['status'] === 'absent') { $absent[] = $userId; } } } else { foreach (raid_signups_split($raid)['groups'] as $signup) { $userId = $userIds[(string) ($signup['user_id'] ?? '')] ?? null; if ($userId !== null) { $present[] = $userId; } } } $present = array_values(array_unique($present)); $absent = array_values(array_unique($absent)); $insertAward = $pdo->prepare( "INSERT INTO contribution_awards (category, title, note, raid_id, awarded_at, created_by) VALUES ('raid', ?, ?, ?, ?, NULL)" ); $insertEntry = $pdo->prepare('INSERT INTO contribution_entries (award_id, user_id, points) VALUES (?, ?, ?)'); $parts = []; if ($pointsPresent > 0 && !empty($present)) { $insertAward->execute([mb_substr($title, 0, 150), 'Automatisch beim Archivieren' . (empty($attendance) ? ' (ohne Anwesenheitsliste: alle Teilnehmer)' : ''), $raidId, $awardedAt]); $awardId = (int) $pdo->lastInsertId(); foreach ($present as $userId) { $insertEntry->execute([$awardId, $userId, $pointsPresent]); } $parts[] = count($present) . '× +' . $pointsPresent; } if ($pointsAbsent > 0 && !empty($absent)) { $insertAward->execute([mb_substr('Abwesend: ' . $title, 0, 150), 'Automatisch beim Archivieren', $raidId, $awardedAt]); $awardId = (int) $pdo->lastInsertId(); foreach ($absent as $userId) { $insertEntry->execute([$awardId, $userId, -$pointsAbsent]); } $parts[] = count($absent) . '× −' . $pointsAbsent; } return $finish(empty($parts) ? 'Keine automatischen Punkte für „' . $title . '“: niemand mit Website-Konto zu berücksichtigen.' : 'Automatische Lumipunkte für „' . $title . '“ vergeben: ' . implode(', ', $parts) . '.'); } /** Ist fuer den Bot-Rueckkanal ein gemeinsamer Schluessel eingetragen? (config.php: bot_callback.key) */ function bot_callback_key(): ?string { $config = require __DIR__ . '/../config.php'; $key = (string) ($config['bot_callback']['key'] ?? ''); return strlen($key) >= 16 ? $key : null; }