LuminaWebsite/bot_api.php
Maaxxs 27470d0fd7 Accounts: whoever leaves the Discord server is deactivated; on return the account waits for approval again
Asked for: "wenn ein mitglied die legion verlässt, soll das benutzerprofil deaktiviert werden" - decided: leaving the
Discord server (also kick or ban) counts as leaving the legion; a returning member goes back to "Wartet auf
Freischaltung".

- includes/discord_auth.php: discord_member_left() disables active/pending accounts (status disabled, users.left_server_at,
  session_epoch + 1, Discord groups removed, log entry "Automatisch (...)"); developers stay untouched.
  discord_member_returned() puts such accounts back to pending (left_server_at cleared); accounts disabled by hand
  stay locked. discord_live_check() calls both, so the session check and "Jetzt mit Discord abgleichen" deactivate too.
- bot_api.php for the new bot cog (cogs/legion_members.py): member_left, member_joined, legion_accounts (Discord IDs of
  active/pending accounts) and legion_sync (the ones the bot misses on the server). Other guilds are ignored; a sync
  that would disable more than half of the accounts is refused with a warning in the log (at most once a day).
- discord_callback.php: a Discord login of a returned member puts the account back to pending instead of "gesperrt".
- includes/auth.php: logout message says the account was deactivated.
- Admin: users list shows "Discord verlassen am ...", the user form a hint; setting the status by hand clears the mark.
- Schema version 67 (users.left_server_at); account deletion clears it.
- Privacy page (automatic deactivation, bot sync), patch note, README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-27 23:30:37 +02:00

172 lines
8.5 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": "..."}]}
*
* Legion verlassen (cogs/legion_members.py im Bot, includes/discord_auth.php): Wer den Discord-Server verlaesst (auch
* gekickt oder gebannt), dessen Konto wird deaktiviert; tritt er wieder bei, wartet es wieder auf Freischaltung. Dazu
* gleicht der Bot regelmaessig ab, welche aktiven Konten nicht mehr auf dem Server sind. Andere Server zaehlen nicht.
* POST /bot_api.php?action=member_left {"guild_id": "...", "discord_id": "..."}
* POST /bot_api.php?action=member_joined {"guild_id": "...", "discord_id": "..."}
* GET /bot_api.php?action=legion_accounts -> {"guild_id": "...", "discord_ids": ["...", ...]}
* POST /bot_api.php?action=legion_sync {"guild_id": "...", "missing": ["...", ...]}
*/
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)) {
try {
$guildId = discord_guild_id();
} 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, 'discord_ids' => legion_account_discord_ids()]);
}
$body = json_decode((string) file_get_contents('php://input'), true);
if (!is_array($body) || (string) ($body['guild_id'] ?? '') !== $guildId) {
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'] ?? [])));
}
$stmt = db()->prepare('SELECT id FROM users WHERE discord_id = ?');
$stmt->execute([(string) ($body['discord_id'] ?? '')]);
$userId = $stmt->fetchColumn();
$changed = $userId !== false && ($action === 'member_left'
? discord_member_left((int) $userId, '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,
]);