235 lines
12 KiB
PHP
235 lines
12 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
|
|
*
|
|
* Raids automatisch archivieren (cogs/raid_autoarchive.py im Bot): 1,5 Stunden nach Raidbeginn erinnert der Bot dieselben
|
|
* Leute wie bei der Anwesenheit (attendance_recipients), den Raid zu archivieren; 2 Stunden nach Beginn archiviert er
|
|
* ihn selbst und meldet das hier - die Website vergibt dann die Lumipunkte wie beim Archivieren von Hand.
|
|
* POST /bot_api.php?action=raid_archived {"raid_id": "..."}
|
|
*
|
|
* 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/members.py in Siel, dem Bot der Elyos Allianz - bis 29.09.2026 cogs/legion_members.py in
|
|
* Nezekan; 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.
|
|
*
|
|
* Legionen der Elyos Allianz (Siel, features/alliance_overview.py): je Legion eine Rolle auf deren Discord-Server. Wer
|
|
* die Rolle hat, steht auf der Website bei dieser Legion - ohne Login (consilium_sync_legion_roles()).
|
|
* POST /bot_api.php?action=consilium_legions {"guild_id": "...", "legions": [{"role_id": "...", "name": "...", "members": ["...", ...]}]}
|
|
*/
|
|
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 === 'consilium_legions') {
|
|
// Legionsrollen vom Discord-Server der Elyos Allianz (Siel, features/alliance_overview.py) - siehe
|
|
// consilium_sync_legion_roles() in includes/consilium.php
|
|
$body = json_decode((string) file_get_contents('php://input'), true);
|
|
if (!is_array($body) || (string) ($body['guild_id'] ?? '') !== consilium_guild_id() || consilium_guild_id() === '') {
|
|
bot_api_reply(200, ['status' => 'success', 'ignored' => true]);
|
|
}
|
|
try {
|
|
bot_api_reply(200, ['status' => 'success', 'result' => consilium_sync_legion_roles(
|
|
is_array($body['legions'] ?? null) ? $body['legions'] : []
|
|
)]);
|
|
} catch (PDOException $e) {
|
|
bot_api_reply(503, ['status' => 'error', 'message' => 'Die Website ist dafür noch nicht eingerichtet.']);
|
|
}
|
|
}
|
|
if ($action === 'raid_archived') {
|
|
// Der Bot hat einen Raid 2 Stunden nach Beginn automatisch archiviert (cogs/raid_autoarchive.py) - danach
|
|
// passiert dasselbe wie beim Archivieren auf der Website (raid_archive.php): Lumipunkte und Log-Eintrag.
|
|
$body = json_decode((string) file_get_contents('php://input'), true);
|
|
$raidId = (int) (is_array($body) ? ($body['raid_id'] ?? 0) : 0);
|
|
if ($raidId <= 0) {
|
|
bot_api_reply(400, ['status' => 'error', 'message' => 'raid_id fehlt.']);
|
|
}
|
|
try {
|
|
$raid = fetch_raid_by_id($raidId);
|
|
} catch (Throwable $e) {
|
|
$raid = null;
|
|
}
|
|
if ($raid === null || (empty($raid['archived']) && empty($raid['archived_at']))) {
|
|
bot_api_reply(409, ['status' => 'error', 'message' => 'Der Raid ist nicht archiviert.']);
|
|
}
|
|
raid_settings_ensure_defaults([$raidId]); // fester Punkt auch fuer im Discord erstellte Raids
|
|
$messages = array_values(array_filter(raid_process_auto_points([$raid])));
|
|
admin_log('📦 Raid automatisch archiviert', [
|
|
'Raid' => admin_log_raid($raidId),
|
|
'Grund' => '2 Stunden nach Raidbeginn noch nicht archiviert',
|
|
'Anmeldungen' => admin_log_raid_signups($raid),
|
|
'Lumipunkte' => implode("\n", $messages),
|
|
], 'warning');
|
|
bot_api_reply(200, ['status' => 'success', 'messages' => $messages]);
|
|
}
|
|
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,
|
|
]);
|