Reported: "bei mein profil muss der benutzername vom discord auch immer aktuell sein, wenn man sich umbenennt steht
noch der alte benutzername da".
users.discord_username ("Verknüpft als …" in "Mein Profil") was only set when logging in with Discord - whoever stays
logged in kept the old name after renaming. The session check (every 5 minutes, or "Jetzt mit Discord abgleichen")
already gets the username from Discord; discord_apply_member() now stores it as well, if Discord sends one. The
message after the manual check says that name, classes and groups are up to date.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
386 lines
16 KiB
PHP
386 lines
16 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
require_once __DIR__ . '/discord.php';
|
|
|
|
/**
|
|
* Discord-Login, Kontoanlage und Abgleich der Berechtigungsgruppen und Klassen mit den
|
|
* Discord-Rollen. Klassen: jede Rolle, deren Name eine Aion-Klasse enthaelt (auf dem Server heissen
|
|
* sie genau wie die Klassen, "Kantor", "Templer" ...), siehe discord_classes_from_roles().
|
|
*
|
|
* Berechtigungsgruppen mit hinterlegter Discord-Rolle (roles.discord_role_id) werden
|
|
* vollstaendig von Discord gesteuert: wer die Rolle hat, ist drin, wer sie nicht (mehr)
|
|
* hat, fliegt raus. Gruppen ohne Discord-Rolle bleiben unangetastet und werden weiter von
|
|
* Hand vergeben. Hat jemand mehrere verknuepfte Rollen (z.B. Sedes Luminis und Lumina
|
|
* Ascendens), bekommt er alle zugehoerigen Gruppen - die Rechte addieren sich.
|
|
*/
|
|
|
|
// Wie oft waehrend einer Sitzung neu bei Discord nachgefragt wird (Sekunden).
|
|
const DISCORD_SYNC_INTERVAL = 300;
|
|
|
|
function discord_store_tokens(int $userId, ?array $tokens): void
|
|
{
|
|
db()->prepare(
|
|
'UPDATE users SET discord_access_token = ?, discord_refresh_token = ?, discord_token_expires = ? WHERE id = ?'
|
|
)->execute([
|
|
$tokens['access_token'] ?? null,
|
|
$tokens['refresh_token'] ?? null,
|
|
$tokens['expires_at'] ?? null,
|
|
$userId,
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Gleicht die Discord-gesteuerten Gruppen eines Nutzers mit seinen Discord-Rollen ab.
|
|
*
|
|
* @param array<int, string> $discordRoleIds Rollen auf dem Server ([] = nicht auf dem Server)
|
|
*/
|
|
function discord_sync_roles(int $userId, array $discordRoleIds): void
|
|
{
|
|
$linked = db()->query('SELECT id, discord_role_id FROM roles WHERE discord_role_id IS NOT NULL')->fetchAll();
|
|
if (empty($linked)) {
|
|
return;
|
|
}
|
|
|
|
$add = db()->prepare('INSERT IGNORE INTO user_roles (user_id, role_id) VALUES (?, ?)');
|
|
$remove = db()->prepare('DELETE FROM user_roles WHERE user_id = ? AND role_id = ?');
|
|
|
|
foreach ($linked as $role) {
|
|
if (in_array((string) $role['discord_role_id'], $discordRoleIds, true)) {
|
|
$add->execute([$userId, (int) $role['id']]);
|
|
} else {
|
|
$remove->execute([$userId, (int) $role['id']]);
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Uebernimmt eine frisch abgefragte Mitgliedschaft: Rollen und Profilbild abgleichen, Zeitpunkt merken. */
|
|
function discord_apply_member(int $userId, array $member): void
|
|
{
|
|
discord_sync_roles($userId, $member['roles']);
|
|
db()->prepare('UPDATE users SET discord_synced_at = NOW() WHERE id = ?')->execute([$userId]);
|
|
// Anzeigename = Name auf dem Discord-Server (Spitzname, sonst globaler Name, sonst Benutzername)
|
|
$discordName = trim((string) ($member['nick'] ?? ''));
|
|
if ($discordName === '') {
|
|
$discordName = trim((string) ($member['global_name'] ?? ''));
|
|
}
|
|
if ($discordName === '') {
|
|
$discordName = trim((string) ($member['username'] ?? ''));
|
|
}
|
|
if ($discordName !== '') {
|
|
db()->prepare('UPDATE users SET display_name = ? WHERE id = ?')->execute([mb_substr($discordName, 0, 100), $userId]);
|
|
}
|
|
// Discord-Benutzername ("Verknuepft als …" in "Mein Profil") - bisher nur beim Anmelden ueber Discord gesetzt,
|
|
// nach einer Umbenennung bei Discord stand sonst bis zum naechsten Login noch der alte da
|
|
$discordUsername = trim((string) ($member['username'] ?? ''));
|
|
if ($discordUsername !== '') {
|
|
db()->prepare('UPDATE users SET discord_username = ? WHERE id = ?')->execute([mb_substr($discordUsername, 0, 100), $userId]);
|
|
}
|
|
// Beitritt zum Discord-Server merken ("Dabei seit" in Mitgliederliste und Profil)
|
|
$joined = !empty($member['joined_at']) ? strtotime($member['joined_at']) : false;
|
|
if ($joined !== false) {
|
|
try {
|
|
db()->prepare('UPDATE users SET discord_joined_at = ? WHERE id = ?')->execute([date('Y-m-d H:i:s', $joined), $userId]);
|
|
} catch (PDOException $e) {
|
|
// Spalte kommt erst mit dem naechsten Schema-Abgleich
|
|
}
|
|
}
|
|
try {
|
|
discord_sync_avatar($userId, $member);
|
|
} catch (Throwable $e) {
|
|
// Profilbild ist Nebensache - Anmeldung und Rollen sollen daran nicht scheitern.
|
|
}
|
|
try {
|
|
$classes = discord_classes_from_roles($member['roles']);
|
|
if ($classes !== null) {
|
|
user_store_classes($userId, $classes);
|
|
}
|
|
} catch (Throwable $e) {
|
|
// Klassen ebenso.
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Rollen des Discord-Servers (ID => Name, hoechste zuerst) ueber die Bot-API. Zwischengespeichert
|
|
* fuer 10 Minuten, damit nicht jeder Abgleich den Bot fragt; ist er offline, gilt der letzte Stand.
|
|
*
|
|
* @return array<string, string>
|
|
*/
|
|
function discord_guild_roles_cached(): array
|
|
{
|
|
// Pro Seitenaufruf nur einmal - "Alle abgleichen" geht sonst fuer jedes Konto erneut zum Bot
|
|
// (setting_get() liest die Einstellungen nur einmal pro Aufruf und sieht den neuen Stand nicht).
|
|
static $memo = null;
|
|
if ($memo !== null) {
|
|
return $memo;
|
|
}
|
|
$cached = json_decode(setting_get('discord_roles_cache'), true);
|
|
if (is_array($cached) && (time() - (int) ($cached['fetched_at'] ?? 0)) < 600) {
|
|
return $memo = (array) ($cached['roles'] ?? []);
|
|
}
|
|
|
|
$roles = (array) ($cached['roles'] ?? []);
|
|
try {
|
|
require_once __DIR__ . '/events_api.php';
|
|
$fresh = [];
|
|
foreach (fetch_guild_roles() as $role) {
|
|
$fresh[(string) ($role['role_id'] ?? '')] = (string) ($role['name'] ?? '');
|
|
}
|
|
$roles = $fresh;
|
|
} catch (Throwable $e) {
|
|
// Bot nicht erreichbar: alten Stand behalten.
|
|
}
|
|
try {
|
|
setting_set('discord_roles_cache', (string) json_encode(['fetched_at' => time(), 'roles' => $roles], JSON_UNESCAPED_UNICODE));
|
|
} catch (PDOException $e) {
|
|
// ohne settings-Tabelle eben ohne Zwischenspeicher
|
|
}
|
|
return $memo = $roles;
|
|
}
|
|
|
|
/**
|
|
* Die Klassen, die jemand auf Discord gewaehlt hat: alle seine Rollen, deren Name eine Aion-Klasse
|
|
* enthaelt (z.B. "⚔️ Gladiator"), die hoechste Rolle zuerst. Null, solange die Rollen des Servers
|
|
* nicht bekannt sind (Bot noch nie erreichbar) - dann bleiben die gespeicherten Klassen stehen.
|
|
*
|
|
* @param array<int, string> $memberRoleIds
|
|
* @return string[]|null
|
|
*/
|
|
function discord_classes_from_roles(array $memberRoleIds): ?array
|
|
{
|
|
$guildRoles = discord_guild_roles_cached();
|
|
if (!$guildRoles) {
|
|
return null;
|
|
}
|
|
$classes = [];
|
|
foreach ($guildRoles as $roleId => $name) {
|
|
if (in_array((string) $roleId, $memberRoleIds, true)) {
|
|
$class = class_from_text($name);
|
|
if ($class !== null && !in_array($class, $classes, true)) {
|
|
$classes[] = $class;
|
|
}
|
|
}
|
|
}
|
|
return $classes;
|
|
}
|
|
|
|
/**
|
|
* Klassen eines Kontos von Discord speichern (users.classes) und daraus die Main-Klasse
|
|
* (users.class_name) bestimmen: die im Profil gewaehlte (users.main_class), solange man die Klasse
|
|
* auf Discord noch hat, sonst die hoechste Klassenrolle. Ohne Klassenrolle hat man keine Klasse.
|
|
*
|
|
* @param string[] $classes Klassen laut Discord, hoechste Rolle zuerst
|
|
*/
|
|
function user_store_classes(int $userId, array $classes): void
|
|
{
|
|
$stmt = db()->prepare('SELECT main_class FROM users WHERE id = ?');
|
|
$stmt->execute([$userId]);
|
|
$chosen = $stmt->fetchColumn();
|
|
$main = is_string($chosen) && in_array($chosen, $classes, true) ? $chosen : ($classes[0] ?? null);
|
|
$ordered = array_values(array_filter(AION_CLASSES, static fn (string $class): bool => in_array($class, $classes, true)));
|
|
db()->prepare('UPDATE users SET classes = ?, class_name = ? WHERE id = ?')
|
|
->execute([$ordered ? implode(',', $ordered) : null, $main, $userId]);
|
|
}
|
|
|
|
/**
|
|
* Welche Rollen des Discord-Servers als Klassenrolle zaehlen: [Rollenname => Klasse], hoechste
|
|
* zuerst - zur Kontrolle fuer die Verwaltung (admin/roles.php).
|
|
*
|
|
* @param array<string, string> $guildRoles [Rollen-ID => Name]
|
|
* @return array<string, string>
|
|
*/
|
|
function discord_class_roles(array $guildRoles): array
|
|
{
|
|
$found = [];
|
|
foreach ($guildRoles as $name) {
|
|
$class = class_from_text((string) $name);
|
|
if ($class !== null) {
|
|
$found[(string) $name] = $class;
|
|
}
|
|
}
|
|
return $found;
|
|
}
|
|
|
|
/**
|
|
* Uebernimmt das Discord-Profilbild (Server-Profilbild vor globalem) als Profilbild der
|
|
* Website - solange avatar_sync an ist, d.h. der Nutzer kein eigenes Bild hochgeladen hat.
|
|
* Das Bild wird lokal gespeichert und nur neu geladen, wenn es sich bei Discord geaendert hat.
|
|
*/
|
|
function discord_sync_avatar(int $userId, array $member): void
|
|
{
|
|
if (empty($member['avatar_known'])) {
|
|
return;
|
|
}
|
|
$stmt = db()->prepare('SELECT discord_id, avatar_filename, avatar_sync, discord_avatar FROM users WHERE id = ?');
|
|
$stmt->execute([$userId]);
|
|
$row = $stmt->fetch();
|
|
if (!$row || empty($row['avatar_sync']) || empty($row['discord_id'])) {
|
|
return;
|
|
}
|
|
|
|
$discordId = (string) $row['discord_id'];
|
|
$url = null;
|
|
$key = '';
|
|
if ($member['guild_avatar'] !== '') {
|
|
$key = 'g:' . $member['guild_avatar'];
|
|
$url = 'https://cdn.discordapp.com/guilds/' . rawurlencode(discord_guild_id()) . '/users/' . rawurlencode($discordId)
|
|
. '/avatars/' . rawurlencode($member['guild_avatar']) . '.png?size=256';
|
|
} elseif ($member['user_avatar'] !== '') {
|
|
$key = 'u:' . $member['user_avatar'];
|
|
$url = 'https://cdn.discordapp.com/avatars/' . rawurlencode($discordId) . '/' . rawurlencode($member['user_avatar']) . '.png?size=256';
|
|
}
|
|
|
|
$dir = __DIR__ . '/../assets/uploads/avatars/';
|
|
$oldFile = (string) ($row['avatar_filename'] ?? '');
|
|
$oldIsDiscord = strpos($oldFile, 'discord_') === 0;
|
|
if ($key === (string) ($row['discord_avatar'] ?? '__none__') && ($key === '' || ($oldFile !== '' && is_file($dir . $oldFile)))) {
|
|
return; // unveraendert
|
|
}
|
|
|
|
$newFile = null;
|
|
if ($url !== null) {
|
|
$ch = curl_init($url);
|
|
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 6, CURLOPT_CONNECTTIMEOUT => 3,
|
|
CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 2]);
|
|
$image = curl_exec($ch);
|
|
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
curl_close($ch);
|
|
$info = is_string($image) && $status === 200 && strlen($image) <= 3 * 1024 * 1024 ? @getimagesizefromstring($image) : false;
|
|
$types = [IMAGETYPE_PNG => 'png', IMAGETYPE_JPEG => 'jpg', IMAGETYPE_GIF => 'gif', IMAGETYPE_WEBP => 'webp'];
|
|
if ($info === false || !isset($types[$info[2]])) {
|
|
return; // Discord nicht erreichbar o.ae. - beim naechsten Abgleich erneut
|
|
}
|
|
$newFile = 'discord_' . $userId . '_' . substr(sha1($key), 0, 12) . '.' . $types[$info[2]];
|
|
if (file_put_contents($dir . $newFile, $image) === false) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
db()->prepare('UPDATE users SET avatar_filename = ?, discord_avatar = ? WHERE id = ?')->execute([$newFile, $key, $userId]);
|
|
// Das alte Discord-Bild aufraeumen (selbst hochgeladene Bilder gibt es hier nicht, siehe avatar_sync).
|
|
if ($oldIsDiscord && $oldFile !== $newFile && is_file($dir . $oldFile)) {
|
|
@unlink($dir . $oldFile);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Macht aus dem Discord-Namen einen freien Benutzernamen fuer die Website.
|
|
*/
|
|
function discord_unique_username(string $discordName): string
|
|
{
|
|
$base = strtolower(preg_replace('/[^A-Za-z0-9._-]/', '', $discordName) ?? '');
|
|
if ($base === '') {
|
|
$base = 'discord';
|
|
}
|
|
$base = substr($base, 0, 40);
|
|
|
|
$stmt = db()->prepare('SELECT 1 FROM users WHERE username = ?');
|
|
$candidate = $base;
|
|
for ($i = 2; ; $i++) {
|
|
$stmt->execute([$candidate]);
|
|
if (!$stmt->fetchColumn()) {
|
|
return $candidate;
|
|
}
|
|
$candidate = $base . '_' . $i;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Findet das Konto zu einem Discord-Account oder legt ein neues an. Neue Konten sind noch
|
|
* nicht freigeschaltet (status = pending) und koennen sich nur ueber Discord anmelden.
|
|
*
|
|
* @param array{id: string, username: string, global_name: string} $discordUser
|
|
* @param array{roles: array<int, string>, nick: string} $member
|
|
* @return array{id: int, status: string, created: bool}
|
|
*/
|
|
function discord_find_or_create_user(array $discordUser, array $member): array
|
|
{
|
|
$stmt = db()->prepare('SELECT id, status FROM users WHERE discord_id = ?');
|
|
$stmt->execute([$discordUser['id']]);
|
|
$row = $stmt->fetch();
|
|
|
|
// Entwickler (DEVELOPER_DISCORD_IDS) sind immer freigeschaltet.
|
|
$isDeveloper = in_array((string) $discordUser['id'], DEVELOPER_DISCORD_IDS, true);
|
|
|
|
if ($row) {
|
|
$status = $isDeveloper ? 'active' : (string) $row['status'];
|
|
db()->prepare('UPDATE users SET discord_username = ?, status = ? WHERE id = ?')
|
|
->execute([$discordUser['username'], $status, (int) $row['id']]);
|
|
return ['id' => (int) $row['id'], 'status' => $status, 'created' => false];
|
|
}
|
|
|
|
// Anzeigename: Spitzname auf dem Server, sonst der globale Discord-Name.
|
|
$displayName = $member['nick'] !== '' ? $member['nick'] : ($discordUser['global_name'] ?: $discordUser['username']);
|
|
|
|
// Das Passwort kennt niemand - die Anmeldung laeuft nur ueber Discord, bis ein
|
|
// Administrator den Passwort-Login freischaltet und dabei ein Passwort setzt.
|
|
db()->prepare(
|
|
"INSERT INTO users (username, password_hash, display_name, status, must_change_password, password_login,
|
|
discord_id, discord_username)
|
|
VALUES (?, ?, ?, ?, 0, 0, ?, ?)"
|
|
)->execute([
|
|
discord_unique_username($discordUser['username']),
|
|
password_hash(bin2hex(random_bytes(24)), PASSWORD_DEFAULT),
|
|
mb_substr($displayName, 0, 100),
|
|
$isDeveloper ? 'active' : 'pending',
|
|
$discordUser['id'],
|
|
$discordUser['username'],
|
|
]);
|
|
|
|
return ['id' => (int) db()->lastInsertId(), 'status' => $isDeveloper ? 'active' : 'pending', 'created' => true];
|
|
}
|
|
|
|
/**
|
|
* Prueft erneut bei Discord, ob der Nutzer noch auf dem Server ist und welche Rollen er hat.
|
|
* Automatisch waehrend einer Sitzung hoechstens alle DISCORD_SYNC_INTERVAL Sekunden, mit
|
|
* $force (manueller Abgleich in der Benutzerverwaltung) sofort.
|
|
*
|
|
* @return string ok | skipped (Intervall noch nicht um) | no_token (nie per Discord angemeldet)
|
|
* | left (nicht mehr auf dem Server) | revoked (Token ungueltig) | error
|
|
*/
|
|
function discord_live_check(int $userId, bool $force = false): string
|
|
{
|
|
$stmt = db()->prepare(
|
|
'SELECT discord_access_token, discord_refresh_token, discord_token_expires, discord_synced_at
|
|
FROM users WHERE id = ?'
|
|
);
|
|
$stmt->execute([$userId]);
|
|
$row = $stmt->fetch();
|
|
|
|
if (!$row || empty($row['discord_refresh_token'])) {
|
|
return 'no_token';
|
|
}
|
|
if (!$force && $row['discord_synced_at'] !== null
|
|
&& strtotime((string) $row['discord_synced_at']) > time() - DISCORD_SYNC_INTERVAL) {
|
|
return 'skipped';
|
|
}
|
|
|
|
// Vor dem Abfragen schon als geprueft markieren: faellt Discord aus oder greift das
|
|
// Rate-Limit, wird nicht bei jedem Seitenaufruf erneut gewartet.
|
|
db()->prepare('UPDATE users SET discord_synced_at = NOW() WHERE id = ?')->execute([$userId]);
|
|
|
|
try {
|
|
$accessToken = (string) $row['discord_access_token'];
|
|
if ($row['discord_token_expires'] === null || strtotime((string) $row['discord_token_expires']) <= time()) {
|
|
$tokens = discord_refresh_token((string) $row['discord_refresh_token']);
|
|
if ($tokens === null) {
|
|
discord_store_tokens($userId, null);
|
|
return 'revoked';
|
|
}
|
|
discord_store_tokens($userId, $tokens);
|
|
$accessToken = $tokens['access_token'];
|
|
}
|
|
|
|
$member = discord_fetch_member($accessToken);
|
|
if ($member === null) {
|
|
discord_sync_roles($userId, []);
|
|
return 'left';
|
|
}
|
|
|
|
discord_apply_member($userId, $member);
|
|
return 'ok';
|
|
} catch (Throwable $e) {
|
|
// Discord nicht erreichbar o.ae.: bisherige Gruppen bleiben, naechster Versuch spaeter.
|
|
return 'error';
|
|
}
|
|
}
|