LuminaWebsite/includes/discord.php
2026-09-21 19:33:05 +02:00

275 lines
10 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: 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): ?array
{
$result = discord_http(
'GET',
DISCORD_API . '/users/@me/guilds/' . rawurlencode(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'] ?? ''),
// 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'] ?? ''),
];
}