LuminaWebsite/bot_api.php
Maaxxs b96bbd1780 Consilium: own Discord server - its roles decide who sees the Consilium; rights for Consilium raids and entries
Asked for: the alliances move to their own Discord server with the roles Force Commander, Legion Lead, Legion
Officer and Legionär. Decided: everyone with a role there sees the Consilium (our members too), no role per legion
(assignment stays on the website), new accounts are approved by our admins, rights per role as planned, a
permission for Consilium calendar entries that is assigned later. Server ID 1553882046793777283.

- Two Discord servers: settings.consilium_guild_id (seeded, Verwaltung -> Discord-Bot with a check whether the bot
  is there); a group's role lies on one of them (roles.discord_guild_id, NULL = legion, schema 71). Login and the
  periodic sync read both memberships (discord_fetch_memberships/discord_apply_memberships) and sync groups per
  server; name, avatar, joined date and classes come from the legion server, for allies from the Consilium server.
- Leaving: whoever leaves a server loses its groups; an account is deactivated only when it is on neither
  (discord_member_left_guild; bot_api.php takes in_guilds from the bot, the sync checks all servers, older bot
  versions cannot deactivate Consilium members). Logout text no longer names a server.
- Group form lists the roles of both servers, the group list marks Consilium roles; Consilium-Raids channel is
  chosen from the Consilium server's channels.
- Rights per area: consilium.raids / consilium.raids.manage for Consilium raids (create, manage, restore, delete),
  raids.create / raids.manage only for legion raids (raid_area_can_create, raid_area_can_manage_all,
  raid_can_manage asks the raid's area). consilium.calendar: only with it Consilium calendar entries (allies without
  it cannot add entries; legion members with it get "Für wen?" with legion/Consilium).
- Consilium member list: everyone with a role on the Consilium server - our legion as its own section, allied legions,
  without legion - with the Consilium ranks as tags; legion list and profiles leave the Consilium groups out for
  those who do not see the Consilium. Allies pick their class in the profile.
- Consilium admin page: setup checklist for the new structure with the groups of the Consilium server and their
  rights (setup only for roles.manage). Privacy page, README.

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

184 lines
9.4 KiB
PHP

<?php
/**
* Rueckkanal fuer den Discord-Bot. Header: X-Bot-Key: <config.php bot_callback.key>
*
* Anwesenheit (cogs/attendance.py im Bot): Wenn die Uhrzeit eines Raids erreicht ist, fragt der Bot
* hier nach, wer eine Erinnerung zur Anwesenheitsliste bekommen soll: der Raid-Lead (hat den Raid auf der
* Website angelegt) - auch wenn er selbst nicht angemeldet ist. Hat der Raid keinen (z.B. aeltere Raids),
* alle Angemeldeten mit einem aktiven Website-Konto und der Berechtigung raids.manage. Die PN schickt der Bot.
* GET /bot_api.php?action=attendance_recipients&raid_id=...&discord_ids=1,2,3
*
* Raid-Anmeldung im Discord (cogs/teamplaner.py, website.py im Bot): Main-Klasse eines Spielers (im Profil
* waehlbar) und ob er ein (freigeschaltetes) Konto hat - ohne gibt es keine Lumipunkte.
* GET /bot_api.php?action=member&discord_id=...
*
* Legionsbeitraege (cogs/dues_reminders.py im Bot, includes/dues_reminders.php): Der Bot holt jede Minute die
* Erinnerungen ab, die er per PN verschicken soll (mit fertigem Text), und meldet danach zurueck, was angekommen ist.
* GET /bot_api.php?action=dues_reminders
* POST /bot_api.php?action=dues_reminders_done {"results": [{"id": 1, "ok": true}, {"id": 2, "ok": false, "error": "..."}]}
*
* Server verlassen (cogs/legion_members.py im Bot, includes/discord_auth.php): Es zaehlen der Server der Legion und
* der des Consilium Elyseum. Wer einen verlaesst (auch gekickt oder gebannt), verliert dessen Gruppen; ist er auf
* keinem mehr, wird sein Konto deaktiviert, tritt er wieder bei, wartet es wieder auf Freischaltung. Dazu gleicht der
* Bot regelmaessig ab, welche aktiven Konten auf keinem der Server mehr sind. Andere Server zaehlen nicht.
* POST /bot_api.php?action=member_left {"guild_id": "...", "discord_id": "...", "in_guilds": ["...", ...]}
* POST /bot_api.php?action=member_joined {"guild_id": "...", "discord_id": "...", "in_guilds": ["...", ...]}
* GET /bot_api.php?action=legion_accounts -> {"guild_id": "...", "guild_ids": ["...", ...], "discord_ids": ["...", ...]}
* POST /bot_api.php?action=legion_sync {"guild_id": "...", "guilds": ["...", ...], "missing": ["...", ...]}
* in_guilds: Server, auf denen der Bot die Person noch sieht; guilds: Server, die er fuer "missing" geprueft hat.
*/
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/raid_attendance.php';
header('Content-Type: application/json; charset=UTF-8');
function bot_api_reply(int $status, array $data): void
{
http_response_code($status);
echo json_encode($data, JSON_UNESCAPED_UNICODE);
exit;
}
$expectedKey = bot_callback_key();
if ($expectedKey === null) {
bot_api_reply(503, ['status' => 'error', 'message' => 'bot_callback.key ist in config.php nicht eingetragen.']);
}
$givenKey = (string) ($_SERVER['HTTP_X_BOT_KEY'] ?? '');
if (!hash_equals($expectedKey, $givenKey)) {
bot_api_reply(403, ['status' => 'error', 'message' => 'Ungültiger Schlüssel.']);
}
$action = (string) ($_GET['action'] ?? '');
if ($action === 'member') {
$discordId = (string) ($_GET['discord_id'] ?? '');
if (!ctype_digit($discordId)) {
bot_api_reply(400, ['status' => 'error', 'message' => 'discord_id fehlt.']);
}
$stmt = db()->prepare('SELECT status, class_name, classes FROM users WHERE discord_id = ? LIMIT 1');
$stmt->execute([$discordId]);
$member = $stmt->fetch();
bot_api_reply(200, [
'status' => 'success',
'account' => $member !== false,
'active' => $member !== false && $member['status'] === 'active',
'main_class' => $member !== false && in_array((string) $member['class_name'], AION_CLASSES, true) ? (string) $member['class_name'] : null,
'classes' => $member !== false ? classes_from_list($member['classes']) : [],
]);
}
if ($action === 'dues_reminders' || $action === 'dues_reminders_done') {
require_once __DIR__ . '/includes/raids_api.php';
require_once __DIR__ . '/includes/dues_reminders.php';
try {
if ($action === 'dues_reminders') {
$guildId = 0;
try {
$guildId = reports_guild_id(); // fuer den Log-Kanal
} catch (Throwable $e) {
// ohne Log-Kanal geht es auch
}
bot_api_reply(200, ['status' => 'success', 'guild_id' => (string) $guildId, 'reminders' => dues_remind_poll()]);
}
$body = json_decode((string) file_get_contents('php://input'), true);
bot_api_reply(200, ['status' => 'success', 'done' => dues_remind_done(is_array($body['results'] ?? null) ? $body['results'] : [])]);
} catch (PDOException $e) {
// Tabelle kommt erst mit dem naechsten Schema-Abgleich (beim ersten Seitenaufruf nach dem Hochladen)
bot_api_reply(503, ['status' => 'error', 'message' => 'Die Erinnerungen an die Legionsbeiträge sind noch nicht eingerichtet.']);
}
}
if (in_array($action, ['member_left', 'member_joined', 'legion_accounts', 'legion_sync'], true)) {
// Zwei Server: der der Legion und der des Consilium Elyseum (includes/discord_auth.php) - ein Konto bleibt aktiv,
// solange es auf einem von beiden ist
try {
$guildId = discord_guild_id();
$guildIds = discord_relevant_guilds();
} catch (RuntimeException $e) {
bot_api_reply(503, ['status' => 'error', 'message' => $e->getMessage()]);
}
try {
if ($action === 'legion_accounts') {
bot_api_reply(200, ['status' => 'success', 'guild_id' => $guildId, 'guild_ids' => $guildIds,
'discord_ids' => legion_account_discord_ids()]);
}
$body = json_decode((string) file_get_contents('php://input'), true);
$bodyGuild = is_array($body) ? (string) ($body['guild_id'] ?? '') : '';
if (!in_array($bodyGuild, $guildIds, true)) {
bot_api_reply(200, ['status' => 'success', 'ignored' => true]); // ein anderer Server, auf dem der Bot ist
}
if ($action === 'legion_sync') {
bot_api_reply(200, ['status' => 'success'] + legion_sync_missing(
(array) ($body['missing'] ?? []),
is_array($body['guilds'] ?? null) ? $body['guilds'] : [$bodyGuild]
));
}
$stmt = db()->prepare('SELECT id FROM users WHERE discord_id = ?');
$stmt->execute([(string) ($body['discord_id'] ?? '')]);
$userId = $stmt->fetchColumn();
// in_guilds: Server, auf denen der Bot die Person (noch) sieht - fehlt bei aelteren Bot-Versionen
$inGuilds = is_array($body['in_guilds'] ?? null) ? $body['in_guilds'] : null;
$changed = $userId !== false && ($action === 'member_left'
? discord_member_left_guild((int) $userId, $bodyGuild, $inGuilds, 'Bot: Server verlassen')
: discord_member_returned((int) $userId, 'Bot: wieder beigetreten'));
bot_api_reply(200, ['status' => 'success', 'changed' => $changed]);
} catch (PDOException $e) {
// Spalte kommt erst mit dem naechsten Schema-Abgleich (beim ersten Seitenaufruf nach dem Hochladen)
bot_api_reply(503, ['status' => 'error', 'message' => 'Die Website ist dafür noch nicht eingerichtet.']);
}
}
if ($action !== 'attendance_recipients') {
bot_api_reply(400, ['status' => 'error', 'message' => 'Unbekannte Aktion.']);
}
$raidId = (string) ($_GET['raid_id'] ?? '');
if (!ctype_digit($raidId)) {
bot_api_reply(400, ['status' => 'error', 'message' => 'raid_id fehlt.']);
}
$discordIds = array_values(array_filter(
array_map('trim', explode(',', (string) ($_GET['discord_ids'] ?? ''))),
static fn (string $id): bool => $id !== '' && ctype_digit($id)
));
// Der Raid-Lead ist fuer die Anwesenheit zustaendig
$leadStmt = db()->prepare(
"SELECT u.discord_id FROM raid_settings s JOIN users u ON u.id = s.lead_user_id
WHERE s.raid_id = ? AND u.status = 'active' AND u.discord_id IS NOT NULL"
);
$leadStmt->execute([$raidId]);
$leadDiscordId = $leadStmt->fetchColumn();
$recipients = [];
if ($leadDiscordId !== false && $leadDiscordId !== null) {
$recipients = [(string) $leadDiscordId];
} elseif (!empty($discordIds)) {
$placeholders = implode(',', array_fill(0, count($discordIds), '?'));
$stmt = db()->prepare(
"SELECT DISTINCT u.discord_id FROM users u
WHERE u.status = 'active' AND u.discord_id IN ($placeholders)
AND (u.is_admin = 1 OR EXISTS (
SELECT 1 FROM user_roles ur
JOIN role_permissions rp ON rp.role_id = ur.role_id
JOIN permissions p ON p.id = rp.permission_id
WHERE ur.user_id = u.id AND p.`key` = 'raids.manage'
) OR EXISTS (
SELECT 1 FROM user_permissions up
JOIN permissions p ON p.id = up.permission_id
WHERE up.user_id = u.id AND p.`key` = 'raids.manage'
))"
);
$stmt->execute($discordIds);
$recipients = array_map('strval', $stmt->fetchAll(PDO::FETCH_COLUMN));
}
// Raidbeginn: Einstellungen (fester Punkt) auch fuer im Discord erstellte Raids anlegen.
raid_settings_ensure_defaults([(int) $raidId]);
$settings = raid_settings_get((int) $raidId);
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = (string) ($_SERVER['HTTP_HOST'] ?? '');
bot_api_reply(200, [
'status' => 'success',
'recipients' => $recipients,
// Schon kontrolliert (z.B. vor Raidbeginn)? Dann braucht es keine Erinnerung mehr.
'checked' => $settings['attendance_checked_at'] !== null,
'url' => $scheme . '://' . $host . '/raid_attendance.php?raid=' . $raidId,
]);