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>
280 lines
11 KiB
PHP
280 lines
11 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* Discord-OAuth fuer Login und Verknuepfung.
|
|
*
|
|
* Scopes: "identify" (wer ist das) und "guilds.members.read" (ist er auf dem Legions-Server,
|
|
* welche Rollen hat er dort). Mit dem zweiten laesst sich die Mitgliedschaft ueber das Token
|
|
* des Nutzers selbst pruefen - die Website braucht dafuer keinen Bot-Token.
|
|
*/
|
|
|
|
const DISCORD_API = 'https://discord.com/api/v10';
|
|
const DISCORD_SCOPES = 'identify guilds.members.read';
|
|
|
|
/**
|
|
* @return array{client_id: string, client_secret: string, redirect_uri: string}
|
|
* @throws RuntimeException
|
|
*/
|
|
function discord_config(): array
|
|
{
|
|
$configPath = __DIR__ . '/../config.php';
|
|
if (!file_exists($configPath)) {
|
|
throw new RuntimeException('Konfigurationsdatei fehlt.');
|
|
}
|
|
|
|
$config = require $configPath;
|
|
$discord = $config['discord'] ?? [];
|
|
|
|
if (empty($discord['client_id']) || empty($discord['client_secret']) || empty($discord['redirect_uri'])) {
|
|
throw new RuntimeException('Discord-Login ist nicht konfiguriert (config.php: discord.client_id / client_secret / redirect_uri fehlt).');
|
|
}
|
|
|
|
return $discord;
|
|
}
|
|
|
|
/**
|
|
* Der Discord-Server der Legion. Eigene Angabe unter discord.guild_id, sonst derselbe Server
|
|
* wie fuer Raids/Reports/Events (raids_api.guild_id).
|
|
*
|
|
* @throws RuntimeException
|
|
*/
|
|
function discord_guild_id(): string
|
|
{
|
|
$config = require __DIR__ . '/../config.php';
|
|
$guildId = $config['discord']['guild_id'] ?? $config['raids_api']['guild_id'] ?? null;
|
|
if (!$guildId) {
|
|
throw new RuntimeException('Der Discord-Server ist nicht konfiguriert (config.php: discord.guild_id oder raids_api.guild_id).');
|
|
}
|
|
return (string) $guildId;
|
|
}
|
|
|
|
/** @throws RuntimeException */
|
|
function discord_authorize_url(string $state): string
|
|
{
|
|
$config = discord_config();
|
|
|
|
$params = [
|
|
'client_id' => $config['client_id'],
|
|
'redirect_uri' => $config['redirect_uri'],
|
|
'response_type' => 'code',
|
|
'scope' => DISCORD_SCOPES,
|
|
'state' => $state,
|
|
// Wer schon einmal zugestimmt hat, wird ohne erneute Rueckfrage direkt zurueckgeschickt.
|
|
'prompt' => 'none',
|
|
];
|
|
|
|
return 'https://discord.com/oauth2/authorize?' . http_build_query($params);
|
|
}
|
|
|
|
/**
|
|
* Ein HTTP-Aufruf gegen Discord. Liefert Statuscode und dekodierte Antwort.
|
|
*
|
|
* @return array{status: int, data: mixed}
|
|
* @throws RuntimeException bei Verbindungsfehlern
|
|
*/
|
|
function discord_http(string $method, string $url, array $headers = [], ?array $form = null): array
|
|
{
|
|
if (!function_exists('curl_init')) {
|
|
throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.');
|
|
}
|
|
|
|
$ch = curl_init($url);
|
|
$options = [
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_CUSTOMREQUEST => $method,
|
|
CURLOPT_TIMEOUT => 10,
|
|
CURLOPT_HTTPHEADER => $headers,
|
|
];
|
|
if ($form !== null) {
|
|
$options[CURLOPT_POSTFIELDS] = http_build_query($form);
|
|
$options[CURLOPT_HTTPHEADER][] = 'Content-Type: application/x-www-form-urlencoded';
|
|
}
|
|
curl_setopt_array($ch, $options);
|
|
|
|
$response = curl_exec($ch);
|
|
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
$error = curl_error($ch);
|
|
|
|
if ($response === false) {
|
|
throw new RuntimeException('Verbindung zu Discord fehlgeschlagen: ' . $error);
|
|
}
|
|
|
|
return ['status' => $status, 'data' => json_decode((string) $response, true)];
|
|
}
|
|
|
|
/**
|
|
* Oeffentliche Angaben zum Discord-Server ueber die Einladung (ohne Bot-Token): Name,
|
|
* Beschreibung, Mitglieder und wie viele gerade online sind. Die Antwort wird 15 Minuten
|
|
* in der Tabelle settings zwischengespeichert, damit nicht jeder Seitenaufruf Discord fragt.
|
|
* Ist Discord nicht erreichbar, gilt der letzte bekannte Stand (oder null).
|
|
*
|
|
* @return array{name: string, description: string, members: int, online: int, tag: string}|null
|
|
*/
|
|
function discord_invite_info(): ?array
|
|
{
|
|
$cached = json_decode(setting_get('discord_invite_cache'), true);
|
|
if (is_array($cached) && (time() - (int) ($cached['fetched_at'] ?? 0)) < 900) {
|
|
return $cached['info'] ?? null;
|
|
}
|
|
|
|
$info = $cached['info'] ?? null;
|
|
if (function_exists('curl_init')) {
|
|
$ch = curl_init('https://discord.com/api/v10/invites/' . rawurlencode(DISCORD_INVITE_CODE) . '?with_counts=true');
|
|
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 3, CURLOPT_CONNECTTIMEOUT => 2]);
|
|
$response = curl_exec($ch);
|
|
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
$data = $status === 200 ? json_decode((string) $response, true) : null;
|
|
if (is_array($data) && isset($data['approximate_member_count'])) {
|
|
$info = [
|
|
// Server-Name ohne die Deko-Sterne ("🌟 - Lumina Ascendens - 🌟").
|
|
'name' => trim((string) preg_replace('/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/u', '', (string) ($data['guild']['name'] ?? ''))),
|
|
'description' => (string) ($data['guild']['description'] ?? ''),
|
|
'members' => (int) $data['approximate_member_count'],
|
|
'online' => (int) ($data['approximate_presence_count'] ?? 0),
|
|
'tag' => (string) ($data['profile']['tag'] ?? ''),
|
|
];
|
|
}
|
|
}
|
|
|
|
// Auch bei einem Fehler den Zeitpunkt merken, sonst fragt jeder Aufruf erneut.
|
|
try {
|
|
setting_set('discord_invite_cache', (string) json_encode(['fetched_at' => time(), 'info' => $info]));
|
|
} catch (PDOException $e) {
|
|
// Ohne settings-Tabelle eben ohne Zwischenspeicher.
|
|
}
|
|
return $info;
|
|
}
|
|
|
|
/**
|
|
* Wandelt eine Token-Antwort von Discord in das Format um, das in users gespeichert wird.
|
|
*
|
|
* @return array{access_token: string, refresh_token: string, expires_at: string}
|
|
*/
|
|
function discord_token_row(array $data): array
|
|
{
|
|
// Eine Minute Puffer, damit ein Token nicht mitten in einer Anfrage ablaeuft.
|
|
$expiresIn = max(60, (int) ($data['expires_in'] ?? 604800) - 60);
|
|
|
|
return [
|
|
'access_token' => (string) $data['access_token'],
|
|
'refresh_token' => (string) ($data['refresh_token'] ?? ''),
|
|
'expires_at' => date('Y-m-d H:i:s', time() + $expiresIn),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Tauscht den OAuth-Code nach dem Login gegen ein Token.
|
|
*
|
|
* @return array{access_token: string, refresh_token: string, expires_at: string}
|
|
* @throws RuntimeException
|
|
*/
|
|
function discord_exchange_code(string $code): array
|
|
{
|
|
$config = discord_config();
|
|
$result = discord_http('POST', DISCORD_API . '/oauth2/token', [], [
|
|
'client_id' => $config['client_id'],
|
|
'client_secret' => $config['client_secret'],
|
|
'grant_type' => 'authorization_code',
|
|
'code' => $code,
|
|
'redirect_uri' => $config['redirect_uri'],
|
|
]);
|
|
|
|
if ($result['status'] !== 200 || empty($result['data']['access_token'])) {
|
|
throw new RuntimeException('Discord hat den Login-Code nicht akzeptiert.');
|
|
}
|
|
|
|
return discord_token_row($result['data']);
|
|
}
|
|
|
|
/**
|
|
* Holt mit dem Refresh-Token ein neues Access-Token. Null, wenn Discord das Token nicht
|
|
* mehr annimmt (z.B. weil der Nutzer die App in Discord entfernt hat) - dann muss er sich
|
|
* neu anmelden.
|
|
*
|
|
* @return array{access_token: string, refresh_token: string, expires_at: string}|null
|
|
* @throws RuntimeException bei Verbindungs- oder Serverfehlern
|
|
*/
|
|
function discord_refresh_token(string $refreshToken): ?array
|
|
{
|
|
$config = discord_config();
|
|
$result = discord_http('POST', DISCORD_API . '/oauth2/token', [], [
|
|
'client_id' => $config['client_id'],
|
|
'client_secret' => $config['client_secret'],
|
|
'grant_type' => 'refresh_token',
|
|
'refresh_token' => $refreshToken,
|
|
]);
|
|
|
|
// Nur "invalid_grant" heisst wirklich: Token widerrufen/abgelaufen. Andere Fehler (etwa
|
|
// ein falsches Client-Secret in config.php) sollen nicht alle Nutzer abmelden.
|
|
if ($result['status'] === 400 && ($result['data']['error'] ?? '') === 'invalid_grant') {
|
|
return null;
|
|
}
|
|
if ($result['status'] !== 200 || empty($result['data']['access_token'])) {
|
|
throw new RuntimeException('Discord-Token konnte nicht erneuert werden (Status ' . $result['status'] . ').');
|
|
}
|
|
|
|
return discord_token_row($result['data']);
|
|
}
|
|
|
|
/**
|
|
* Der Discord-Account hinter einem Token.
|
|
*
|
|
* @return array{id: string, username: string, global_name: string}
|
|
* @throws RuntimeException
|
|
*/
|
|
function discord_fetch_user(string $accessToken): array
|
|
{
|
|
$result = discord_http('GET', DISCORD_API . '/users/@me', ['Authorization: Bearer ' . $accessToken]);
|
|
$data = $result['data'];
|
|
|
|
if ($result['status'] !== 200 || !is_array($data) || empty($data['id'])) {
|
|
throw new RuntimeException('Discord-Benutzerdaten konnten nicht abgerufen werden.');
|
|
}
|
|
|
|
return [
|
|
'id' => (string) $data['id'],
|
|
'username' => (string) ($data['username'] ?? ''),
|
|
'global_name' => (string) ($data['global_name'] ?? ''),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Die Mitgliedschaft auf dem Legions-Server - mit $guildId auf einem anderen (dem Server des Consilium Elyseum):
|
|
* Rollen-IDs und Server-Spitzname. Null, wenn der Account nicht auf dem Server ist.
|
|
*
|
|
* @return array{roles: array<int, string>, nick: string, avatar_known: bool, guild_avatar: string, user_avatar: string}|null
|
|
* @throws RuntimeException bei Verbindungsfehlern, abgelaufenem Token oder Rate-Limit
|
|
*/
|
|
function discord_fetch_member(string $accessToken, ?string $guildId = null): ?array
|
|
{
|
|
$result = discord_http(
|
|
'GET',
|
|
DISCORD_API . '/users/@me/guilds/' . rawurlencode($guildId ?? discord_guild_id()) . '/member',
|
|
['Authorization: Bearer ' . $accessToken]
|
|
);
|
|
|
|
// 404 "Unknown Guild": der Account ist nicht (mehr) auf dem Server.
|
|
if ($result['status'] === 404) {
|
|
return null;
|
|
}
|
|
if ($result['status'] !== 200 || !is_array($result['data'])) {
|
|
throw new RuntimeException('Discord-Mitgliedschaft konnte nicht geprüft werden (Status ' . $result['status'] . ').');
|
|
}
|
|
|
|
$data = $result['data'];
|
|
return [
|
|
'roles' => array_map('strval', (array) ($data['roles'] ?? [])),
|
|
'nick' => (string) ($data['nick'] ?? ''),
|
|
// Fuer den Anzeigenamen: Server-Spitzname, sonst globaler Discord-Name, sonst Benutzername
|
|
'global_name' => (string) ($data['user']['global_name'] ?? ''),
|
|
'username' => (string) ($data['user']['username'] ?? ''),
|
|
// Profilbild: das Server-Profilbild hat Vorrang vor dem globalen. avatar_known = false,
|
|
// wenn Discord das Nutzerobjekt nicht mitschickt - dann bleibt das Bild, wie es ist.
|
|
'avatar_known' => isset($data['user']) && is_array($data['user']),
|
|
'guild_avatar' => (string) ($data['avatar'] ?? ''),
|
|
'user_avatar' => (string) ($data['user']['avatar'] ?? ''),
|
|
// Beitritt zum Discord-Server (ISO 8601), fuer "Dabei seit" auf der Website
|
|
'joined_at' => (string) ($data['joined_at'] ?? ''),
|
|
];
|
|
}
|