- Raids: "Max. Spieler" only whole numbers up to groups x 5 (max. 10 groups / 50), gearscore only a number; fixed +1 Lumipunkt per participation, other values only with the new raids.points permission; pick an existing premade per group when creating a raid; unchanged legacy values no longer block editing - Raid page updates itself every 15 s while visible (raids_live.php, cards rendered by includes/raid_card.php), open editors and confirm dialogs are kept - Restore takes the new raid_id from the bot (archived messages are now deleted in Discord) and moves settings, attendance and awards; website signups send the server display name - Premades: dissolve by leadership needs a reason, lead gets DMs on join/assign/decline/remove (source/actor_id sent to the bot), transfer picker skips players who already lead a group, website accept keeps the one-group rule, no commas in names - Site-wide Lumina dialog (assets/js/confirm-dialog.js) replaces confirm/prompt/alert via data-confirm; error flashes are a dialog you confirm with OK - Calendar: audience per entry (all / leadership takes part / internal) with the new calendar.leadership permission; day cells list all entries and scroll - Gear planner: main-hand picker filtered by the set's class, mismatches marked, "keine Klasse" option, link to an external skill/Daevanion plan per set - Map: correct kisk icons (Elyos on Verteron/Abyss, Altgard fixed), per-map max zoom and bounded panning, German texts, data source note - Tactics: toolbar as a uniform grid, whole-tactic copy, automatic versions with restore and a 90-day trash, official tactics protected - Global thin gold scrollbars, readable hover colours, "Sedes Luminis" spelling, patch notes and README, schema version 34 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1016 lines
34 KiB
PHP
1016 lines
34 KiB
PHP
<?php
|
||
declare(strict_types=1);
|
||
|
||
const RAID_STATUSES = ['active', 'archived', 'all'];
|
||
|
||
/**
|
||
* Lesbare Fehlermeldung fuer eine abgelehnte Bot-API-Anfrage. FastAPI liefert bei 422
|
||
* (Validierung) in "detail" ein Array mit englischen Einzelfehlern - das gehoert nicht vor
|
||
* die Nutzer, deshalb gibt es dafuer einen verstaendlichen Hinweis.
|
||
*/
|
||
function bot_api_error_message(string $label, int $httpCode, $data): string
|
||
{
|
||
if ($httpCode === 422) {
|
||
return 'Die Eingabe wurde abgelehnt - ein Wert ist ungültig oder zu lang.';
|
||
}
|
||
$detail = is_array($data) && is_string($data['detail'] ?? null) ? $data['detail'] : '';
|
||
$message = $label . ' antwortete mit Statuscode ' . $httpCode . '.';
|
||
return $detail !== '' ? $message . ' (' . $detail . ')' : $message;
|
||
}
|
||
|
||
/**
|
||
* @return array<string, mixed>
|
||
* @throws RuntimeException
|
||
*/
|
||
function raids_api_config(): array
|
||
{
|
||
$configPath = __DIR__ . '/../config.php';
|
||
if (!file_exists($configPath)) {
|
||
throw new RuntimeException('Konfigurationsdatei fehlt.');
|
||
}
|
||
|
||
$config = require $configPath;
|
||
$apiUrl = $config['raids_api']['url'] ?? '';
|
||
$apiKey = $config['raids_api']['key'] ?? '';
|
||
|
||
if ($apiUrl === '' || $apiKey === '') {
|
||
throw new RuntimeException('Raid-API ist nicht konfiguriert (config.php: raids_api.url / raids_api.key fehlt).');
|
||
}
|
||
|
||
return ['url' => rtrim($apiUrl, '/'), 'key' => $apiKey];
|
||
}
|
||
|
||
/**
|
||
* Fuehrt einen Request gegen die Raid-API aus und liefert die dekodierte
|
||
* JSON-Antwort zurueck.
|
||
*
|
||
* @param string $path Wird an die Basis-URL angehaengt, z.B. "/123/signup".
|
||
* @param array<string, mixed>|null $jsonBody Wird bei POST/DELETE als JSON-Body mitgeschickt.
|
||
* @return array<string, mixed>
|
||
* @throws RuntimeException
|
||
*/
|
||
function raids_api_request(string $method, string $path = '', array $queryParams = [], ?array $jsonBody = null): array
|
||
{
|
||
if (!function_exists('curl_init')) {
|
||
throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.');
|
||
}
|
||
|
||
$config = raids_api_config();
|
||
$url = $config['url'] . $path;
|
||
if (!empty($queryParams)) {
|
||
$url .= '?' . http_build_query($queryParams);
|
||
}
|
||
|
||
$headers = ['X-API-Key: ' . $config['key']];
|
||
|
||
$ch = curl_init($url);
|
||
$options = [
|
||
CURLOPT_RETURNTRANSFER => true,
|
||
CURLOPT_CUSTOMREQUEST => $method,
|
||
CURLOPT_TIMEOUT => 10,
|
||
CURLOPT_SSL_VERIFYPEER => true,
|
||
];
|
||
|
||
if ($jsonBody !== null) {
|
||
$headers[] = 'Content-Type: application/json';
|
||
$options[CURLOPT_POSTFIELDS] = json_encode($jsonBody, JSON_UNESCAPED_UNICODE);
|
||
}
|
||
|
||
$options[CURLOPT_HTTPHEADER] = $headers;
|
||
curl_setopt_array($ch, $options);
|
||
|
||
$response = curl_exec($ch);
|
||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||
$curlError = curl_error($ch);
|
||
curl_close($ch);
|
||
|
||
if ($response === false) {
|
||
throw new RuntimeException('Verbindung zur Raid-API fehlgeschlagen: ' . $curlError);
|
||
}
|
||
|
||
$data = json_decode($response, true);
|
||
|
||
if ($httpCode < 200 || $httpCode >= 300) {
|
||
throw new RuntimeException(bot_api_error_message('Raid-API', $httpCode, $data));
|
||
}
|
||
|
||
if (!is_array($data)) {
|
||
throw new RuntimeException('Unerwartetes Antwortformat der Raid-API.');
|
||
}
|
||
|
||
return $data;
|
||
}
|
||
|
||
// Laengengrenzen der Raid-API (RaidCreate/RaidUpdate in api.py des Bots).
|
||
const RAID_FIELD_LIMITS = [
|
||
'title' => ['Titel', 60],
|
||
'requirements' => ['Anforderungen', 80],
|
||
'gearscore' => ['Gearscore', 50], // neue Werte sind nur noch Zahlen (raid_normalize_gearscore)
|
||
'group_names' => ['Gruppennamen (zusammen)', 150],
|
||
];
|
||
|
||
/**
|
||
* Prueft die Textfelder eines Raids gegen die Grenzen der API - so gibt es eine klare
|
||
* Meldung statt eines abgelehnten Requests. Liefert die Fehlermeldung oder null.
|
||
*
|
||
* @param array<string, mixed> $fields
|
||
*/
|
||
function raid_fields_error(array $fields): ?string
|
||
{
|
||
foreach (RAID_FIELD_LIMITS as $key => [$label, $max]) {
|
||
if (isset($fields[$key]) && mb_strlen((string) $fields[$key], 'UTF-8') > $max) {
|
||
return $label . ': höchstens ' . $max . ' Zeichen.';
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* @return array<int, array<string, mixed>>
|
||
* @throws RuntimeException
|
||
*/
|
||
function fetch_raids(string $status = 'active'): array
|
||
{
|
||
if (!in_array($status, RAID_STATUSES, true)) {
|
||
$status = 'active';
|
||
}
|
||
|
||
$data = raids_api_request('GET', '', ['status' => $status]);
|
||
|
||
if (($data['status'] ?? '') !== 'success' || !isset($data['raids']) || !is_array($data['raids'])) {
|
||
throw new RuntimeException('Unerwartetes Antwortformat der Raid-API.');
|
||
}
|
||
|
||
return raids_apply_display_names($data['raids']);
|
||
}
|
||
|
||
/**
|
||
* Ersetzt die Namen in den Anmeldungen durch den Anzeigenamen des verknuepften
|
||
* Website-Kontos. Der Bot speichert den Namen zum Zeitpunkt der Anmeldung; der Anzeigename
|
||
* folgt dagegen immer dem aktuellen Namen auf dem Discord-Server.
|
||
*
|
||
* @param array<int, array<string, mixed>> $raids
|
||
* @return array<int, array<string, mixed>>
|
||
*/
|
||
function raids_apply_display_names(array $raids): array
|
||
{
|
||
$ids = [];
|
||
foreach ($raids as $raid) {
|
||
foreach ((array) ($raid['signups'] ?? []) as $signup) {
|
||
if (!empty($signup['user_id'])) {
|
||
$ids[(string) $signup['user_id']] = true;
|
||
}
|
||
}
|
||
}
|
||
if (empty($ids)) {
|
||
return $raids;
|
||
}
|
||
|
||
try {
|
||
$placeholders = implode(',', array_fill(0, count($ids), '?'));
|
||
$stmt = db()->prepare(
|
||
"SELECT discord_id, display_name FROM users WHERE discord_id IN ($placeholders) AND display_name <> ''"
|
||
);
|
||
$stmt->execute(array_keys($ids));
|
||
$names = [];
|
||
foreach ($stmt->fetchAll() as $row) {
|
||
$names[(string) $row['discord_id']] = (string) $row['display_name'];
|
||
}
|
||
} catch (PDOException $e) {
|
||
return $raids;
|
||
}
|
||
|
||
foreach ($raids as &$raid) {
|
||
foreach ((array) ($raid['signups'] ?? []) as $i => $signup) {
|
||
$id = (string) ($signup['user_id'] ?? '');
|
||
if (isset($names[$id])) {
|
||
$raid['signups'][$i]['name'] = $names[$id];
|
||
}
|
||
}
|
||
}
|
||
unset($raid);
|
||
return $raids;
|
||
}
|
||
|
||
/** @throws RuntimeException */
|
||
function archive_raid(int $raidId): void
|
||
{
|
||
raids_api_request('DELETE', '/' . $raidId);
|
||
}
|
||
|
||
/**
|
||
* Holt einen archivierten Raid zurueck. Der Bot loescht archivierte Raids kurz nach dem Archivieren
|
||
* aus dem Discord-Kanal und postet sie beim Wiederherstellen neu - dann aendert sich die raid_id
|
||
* (= Discord-Nachrichten-ID). Liefert die aktuell gueltige raid_id.
|
||
*
|
||
* @throws RuntimeException
|
||
*/
|
||
function restore_raid(int $raidId): int
|
||
{
|
||
$data = raids_api_request('POST', '/' . $raidId . '/restore');
|
||
return (int) ($data['raid_id'] ?? $raidId) ?: $raidId;
|
||
}
|
||
|
||
/**
|
||
* Loescht einen Raid ENDGUELTIG (keine Historie, keine Wiederherstellung), im
|
||
* Gegensatz zu archive_raid(). Nur fuer bereits archivierte Raids gedacht.
|
||
*
|
||
* @throws RuntimeException
|
||
*/
|
||
function delete_raid_permanently(int $raidId): void
|
||
{
|
||
raids_api_request('DELETE', '/' . $raidId . '/permanent');
|
||
}
|
||
|
||
/**
|
||
* @param int|null $group Feste Zielgruppe (0 = Ersatzbank) oder null, damit der Bot
|
||
* automatisch nach Rollen-Caps zuteilt.
|
||
* @return array<string, mixed> Die von der API zugewiesene Anmeldung (u.a. tatsaechliche "group").
|
||
* @throws RuntimeException
|
||
*/
|
||
function raid_signup(int $raidId, int $discordId, string $discordName, string $className, ?int $group): array
|
||
{
|
||
$data = raids_api_request('POST', '/' . $raidId . '/signup', [], [
|
||
'user_id' => $discordId,
|
||
'name' => $discordName,
|
||
'class' => $className,
|
||
'group' => $group,
|
||
]);
|
||
|
||
return $data['signup'] ?? [];
|
||
}
|
||
|
||
/** @throws RuntimeException */
|
||
function raid_unsignup(int $raidId, int $discordId): void
|
||
{
|
||
raids_api_request('DELETE', '/' . $raidId . '/signup/' . $discordId);
|
||
}
|
||
|
||
/** @throws RuntimeException */
|
||
function move_signup(int $raidId, int $discordId, int $group): void
|
||
{
|
||
raids_api_request('PATCH', '/' . $raidId . '/signup/' . $discordId, [], ['group' => $group]);
|
||
}
|
||
|
||
/**
|
||
* @param array<string, mixed> $fields Nur die zu aendernden Felder, z.B.
|
||
* ['title' => ..., 'date_raw' => ..., 'requirements' => ..., 'gearscore' => ...,
|
||
* 'group_names' => ..., 'max_slots' => ..., 'locked_groups' => [1, 3]]
|
||
* @return array<string, mixed> Antwort der API. Enthaelt die aktuell gueltige raid_id -
|
||
* die API postet die Discord-Nachricht automatisch neu, falls sie zwischenzeitlich
|
||
* manuell geloescht wurde, wobei sich die raid_id (= Discord-Message-ID) aendert.
|
||
* @throws RuntimeException
|
||
*/
|
||
function update_raid(int $raidId, array $fields): array
|
||
{
|
||
return raids_api_request('PATCH', '/' . $raidId, [], $fields);
|
||
}
|
||
|
||
/**
|
||
* Erstellt einen neuen Raid ueber den in config.php (raids_api.guild_id) hinterlegten
|
||
* Discord-Server. Die API postet ihn automatisch in den per /set_raidchannel im Bot
|
||
* konfigurierten Standard-Raid-Kanal dieses Servers - die Website muss dafuer keine
|
||
* Kanal-ID kennen/verwalten.
|
||
*
|
||
* @param array<string, mixed> $fields title, date_raw, requirements, group_names
|
||
* (Pflicht), max_slots, gearscore (optional)
|
||
* @return array<string, mixed> Antwort der API inkl. raid_id
|
||
* @throws RuntimeException
|
||
*/
|
||
function create_raid(array $fields): array
|
||
{
|
||
$configPath = __DIR__ . '/../config.php';
|
||
if (!file_exists($configPath)) {
|
||
throw new RuntimeException('Konfigurationsdatei fehlt.');
|
||
}
|
||
$config = require $configPath;
|
||
$guildId = $config['raids_api']['guild_id'] ?? null;
|
||
if (!$guildId) {
|
||
throw new RuntimeException('Raid-Erstellung ist nicht konfiguriert (config.php: raids_api.guild_id fehlt).');
|
||
}
|
||
|
||
$fields['guild_id'] = (int) $guildId;
|
||
|
||
return raids_api_request('POST', '', [], $fields);
|
||
}
|
||
|
||
/** @throws RuntimeException */
|
||
function invite_premade(int $raidId, int $premadeId, int $group): int
|
||
{
|
||
$data = raids_api_request('POST', '/' . $raidId . '/premades/' . $premadeId . '/invite', [], ['group' => $group]);
|
||
|
||
return (int) ($data['invited_count'] ?? 0);
|
||
}
|
||
|
||
/**
|
||
* Fuehrt einen Request gegen die Premades-API aus (liegt unter derselben Basis-URL
|
||
* wie die Raid-API, eine Ebene ueber "/raids") und liefert die dekodierte
|
||
* JSON-Antwort zurueck. Analog zu raids_api_request(), nur mit eigener Basis-URL.
|
||
*
|
||
* @param array<string, mixed>|null $jsonBody
|
||
* @return array<string, mixed>
|
||
* @throws RuntimeException
|
||
*/
|
||
function premades_api_request(string $method, string $path = '', ?array $jsonBody = null): array
|
||
{
|
||
if (!function_exists('curl_init')) {
|
||
throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.');
|
||
}
|
||
|
||
$config = raids_api_config();
|
||
// /api/premades liegt eine Ebene ueber /api/raids.
|
||
$base = preg_replace('#/raids$#', '', $config['url']);
|
||
$url = $base . '/premades' . $path;
|
||
|
||
$headers = ['X-API-Key: ' . $config['key']];
|
||
|
||
$ch = curl_init($url);
|
||
$options = [
|
||
CURLOPT_RETURNTRANSFER => true,
|
||
CURLOPT_CUSTOMREQUEST => $method,
|
||
CURLOPT_TIMEOUT => 10,
|
||
CURLOPT_SSL_VERIFYPEER => true,
|
||
];
|
||
|
||
if ($jsonBody !== null) {
|
||
$headers[] = 'Content-Type: application/json';
|
||
$options[CURLOPT_POSTFIELDS] = json_encode($jsonBody, JSON_UNESCAPED_UNICODE);
|
||
}
|
||
|
||
$options[CURLOPT_HTTPHEADER] = $headers;
|
||
curl_setopt_array($ch, $options);
|
||
|
||
$response = curl_exec($ch);
|
||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||
$curlError = curl_error($ch);
|
||
curl_close($ch);
|
||
|
||
if ($response === false) {
|
||
throw new RuntimeException('Verbindung zur Premades-API fehlgeschlagen: ' . $curlError);
|
||
}
|
||
|
||
$data = json_decode($response, true);
|
||
|
||
if ($httpCode < 200 || $httpCode >= 300) {
|
||
throw new RuntimeException(bot_api_error_message('Premades-API', $httpCode, $data));
|
||
}
|
||
|
||
if (!is_array($data)) {
|
||
throw new RuntimeException('Unerwartetes Antwortformat der Premades-API.');
|
||
}
|
||
|
||
return $data;
|
||
}
|
||
|
||
/**
|
||
* @return array<int, array<string, mixed>>
|
||
* @throws RuntimeException
|
||
*/
|
||
function fetch_premades(): array
|
||
{
|
||
$data = premades_api_request('GET');
|
||
|
||
if (($data['status'] ?? '') !== 'success' || !is_array($data['premades'] ?? null)) {
|
||
throw new RuntimeException('Unerwartetes Antwortformat der Premades-API.');
|
||
}
|
||
|
||
return $data['premades'];
|
||
}
|
||
|
||
const PREMADE_NAME_MIN = 3;
|
||
const PREMADE_NAME_MAX = 50; // Grenze der Bot-API (PremadeCreate/PremadeRename)
|
||
|
||
/**
|
||
* Bereinigt einen Premade-Namen (Leerraum am Rand weg, mehrfache Leerzeichen zu einem).
|
||
*/
|
||
function normalize_premade_name(string $name): string
|
||
{
|
||
return trim((string) preg_replace('/\s+/u', ' ', $name));
|
||
}
|
||
|
||
/**
|
||
* Prueft einen (bereinigten) Premade-Namen. Liefert die Fehlermeldung oder null, wenn er passt:
|
||
* 3-50 Zeichen, beginnt mit Buchstabe/Ziffer, danach nur Buchstaben, Ziffern, Leerzeichen und
|
||
* gaengige Satzzeichen - "." oder Steuerzeichen sind kein Gruppenname.
|
||
*/
|
||
function premade_name_error(string $name): ?string
|
||
{
|
||
$length = mb_strlen($name, 'UTF-8');
|
||
if ($length < PREMADE_NAME_MIN || $length > PREMADE_NAME_MAX) {
|
||
return 'Der Name der Premade muss ' . PREMADE_NAME_MIN . ' bis ' . PREMADE_NAME_MAX . ' Zeichen lang sein.';
|
||
}
|
||
// Kein Komma: Raid-Gruppen stehen kommagetrennt im Bot - eine Premade "A, B" wuerde beim
|
||
// Einladen in einen Raid zu zwei Gruppen.
|
||
if (!preg_match("/^[\p{L}\p{N}][\p{L}\p{N} .'&!?()#:+_\-]*$/u", $name)) {
|
||
return 'Der Name der Premade muss mit einem Buchstaben oder einer Ziffer beginnen und darf nur Buchstaben, Ziffern, Leerzeichen und . \' & ! ? ( ) # : + _ - enthalten (kein Komma).';
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* Gibt es schon eine andere Premade mit diesem Namen (ohne Gross-/Kleinschreibung)?
|
||
*
|
||
* @param array<int, array<string, mixed>> $premades
|
||
*/
|
||
function premade_name_taken(array $premades, string $name, int $exceptId = 0): bool
|
||
{
|
||
$needle = mb_strtolower($name, 'UTF-8');
|
||
foreach ($premades as $premade) {
|
||
if ((int) ($premade['id'] ?? 0) !== $exceptId
|
||
&& mb_strtolower(normalize_premade_name((string) ($premade['name'] ?? '')), 'UTF-8') === $needle) {
|
||
return true;
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/**
|
||
* @return array{id: int, name: string, owner_id: int}
|
||
* @throws RuntimeException
|
||
*/
|
||
function create_premade(string $name, ?int $ownerId): array
|
||
{
|
||
// $ownerId null = Gruppe ohne Lead (nur die Leitung legt solche Gruppen an)
|
||
$data = premades_api_request('POST', '', ['name' => $name, 'owner_id' => $ownerId]);
|
||
|
||
return [
|
||
'id' => (int) ($data['premade_id'] ?? 0),
|
||
'name' => (string) ($data['name'] ?? $name),
|
||
'owner_id' => isset($data['owner_id']) ? (int) $data['owner_id'] : $ownerId,
|
||
];
|
||
}
|
||
|
||
/** @throws RuntimeException */
|
||
function rename_premade(int $premadeId, string $name): void
|
||
{
|
||
premades_api_request('PATCH', '/' . $premadeId, ['name' => $name]);
|
||
}
|
||
|
||
const PREMADE_DISSOLVE_REASON_MIN = 5;
|
||
const PREMADE_DISSOLVE_REASON_MAX = 500;
|
||
|
||
/**
|
||
* Loest eine Premade auf. Der Bot schreibt allen Mitgliedern eine PN - loest die Leitung eine
|
||
* fremde Gruppe auf ($byLeadership), bekommt der Lead die Begruendung mit.
|
||
*
|
||
* @throws RuntimeException
|
||
*/
|
||
function delete_premade(int $premadeId, string $reason = '', bool $byLeadership = false, ?int $actorId = null): void
|
||
{
|
||
premades_api_request('DELETE', '/' . $premadeId, [
|
||
'reason' => $reason !== '' ? $reason : null,
|
||
'by_leadership' => $byLeadership,
|
||
'actor_id' => $actorId,
|
||
]);
|
||
}
|
||
|
||
/**
|
||
* 'pending' verschickt eine Einladung per PN, 'accepted' traegt direkt ein (Einteilung durch die
|
||
* Leitung, ohne "nur eine Gruppe"-Regel) - mit $notify bekommt der Spieler dazu eine PN.
|
||
* $source sagt dem Bot, wem er noch Bescheid gibt: 'accept' (Einladung angenommen) bzw. 'assign'
|
||
* (von der Leitung eingeteilt) - der Lead der Gruppe bekommt dann eine PN.
|
||
*
|
||
* @throws RuntimeException
|
||
*/
|
||
function add_premade_member(int $premadeId, int $userId, string $status = 'accepted', bool $notify = false, ?string $source = null, ?int $actorId = null): void
|
||
{
|
||
$body = ['user_id' => $userId, 'status' => $status, 'notify' => $notify, 'source' => $source, 'actor_id' => $actorId];
|
||
if ($status === 'pending') {
|
||
// Damit Annehmen/Ablehnen im Discord auch im Log-Kanal landet.
|
||
try {
|
||
$body['guild_id'] = reports_guild_id();
|
||
} catch (Throwable $e) {
|
||
// ohne Log-Kanal geht es auch
|
||
}
|
||
}
|
||
premades_api_request('POST', '/' . $premadeId . '/members', $body);
|
||
}
|
||
|
||
/**
|
||
* $source: 'decline' (Einladung abgelehnt - der Lead bekommt eine PN), 'remove' (entfernt - der
|
||
* Spieler und, wenn es nicht der Lead selbst war, der Lead bekommen eine PN) oder 'withdraw'
|
||
* (Einladung zurueckgezogen).
|
||
*
|
||
* @throws RuntimeException
|
||
*/
|
||
function remove_premade_member(int $premadeId, int $userId, ?string $source = null, ?int $actorId = null): void
|
||
{
|
||
premades_api_request('DELETE', '/' . $premadeId . '/members/' . $userId,
|
||
$source !== null ? ['source' => $source, 'actor_id' => $actorId] : null);
|
||
}
|
||
|
||
/** @throws RuntimeException */
|
||
function set_premade_member_class(int $premadeId, int $userId, string $className): void
|
||
{
|
||
premades_api_request('PATCH', '/' . $premadeId . '/members/' . $userId, ['class' => $className]);
|
||
}
|
||
|
||
/** @throws RuntimeException */
|
||
function transfer_premade_owner(int $premadeId, int $newOwnerId): void
|
||
{
|
||
premades_api_request('POST', '/' . $premadeId . '/transfer', ['new_owner_id' => $newOwnerId]);
|
||
}
|
||
|
||
/**
|
||
* Ermittelt die Beziehung eines Discord-Nutzers zu einer Liste von Premades: 'owner'
|
||
* (Lead) oder 'accepted' (Mitglied). Laut Bot-Logik kann ein Nutzer nie mehr als einer
|
||
* Premade gleichzeitig als Owner/Mitglied angehoeren (siehe is_user_in_any_premade im Bot).
|
||
*
|
||
* @param array<int, array<string, mixed>> $premades
|
||
* @return array{premade: array<string, mixed>, status: string}|null
|
||
*/
|
||
function find_my_premade(array $premades, int $discordId): ?array
|
||
{
|
||
foreach ($premades as $premade) {
|
||
if ((int) ($premade['owner_id'] ?? 0) === $discordId) {
|
||
return ['premade' => $premade, 'status' => 'owner'];
|
||
}
|
||
foreach ($premade['members'] ?? [] as $member) {
|
||
if ((int) ($member['user_id'] ?? 0) === $discordId && ($member['status'] ?? '') === 'accepted') {
|
||
return ['premade' => $premade, 'status' => 'accepted'];
|
||
}
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* Die Premade, die der Nutzer selbst leitet - jeder darf hoechstens eine eigene gruenden.
|
||
*
|
||
* @param array<int, array<string, mixed>> $premades
|
||
*/
|
||
function find_owned_premade(array $premades, int $discordId): ?array
|
||
{
|
||
foreach ($premades as $premade) {
|
||
if ((int) ($premade['owner_id'] ?? 0) === $discordId) {
|
||
return $premade;
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* Steht der Nutzer schon in dieser Premade (Lead, Mitglied oder offene Einladung)?
|
||
*
|
||
* @param array<string, mixed> $premade
|
||
*/
|
||
function premade_has_user(array $premade, int $discordId, bool $includePending = true): bool
|
||
{
|
||
if ((int) ($premade['owner_id'] ?? 0) === $discordId) {
|
||
return true;
|
||
}
|
||
foreach ($premade['members'] ?? [] as $member) {
|
||
if ((int) ($member['user_id'] ?? 0) === $discordId
|
||
&& (($member['status'] ?? '') === 'accepted' || ($includePending && ($member['status'] ?? '') === 'pending'))) {
|
||
return true;
|
||
}
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/**
|
||
* Belegte Plaetze einer Premade (Lead, Mitglieder und offene Einladungen) - eine Gruppe hat 5.
|
||
*
|
||
* @param array<string, mixed> $premade
|
||
*/
|
||
function premade_slot_count(array $premade): int
|
||
{
|
||
$ownerId = (int) ($premade['owner_id'] ?? 0);
|
||
$count = $ownerId > 0 ? 1 : 0;
|
||
foreach ($premade['members'] ?? [] as $member) {
|
||
if ((int) ($member['user_id'] ?? 0) !== $ownerId) {
|
||
$count++;
|
||
}
|
||
}
|
||
return $count;
|
||
}
|
||
|
||
/**
|
||
* @param array<int, array<string, mixed>> $premades
|
||
* @return array<int, array<string, mixed>> Alle Premades, bei denen der Nutzer eine offene
|
||
* (noch nicht angenommene) Einladung hat.
|
||
*/
|
||
function find_my_pending_invites(array $premades, int $discordId): array
|
||
{
|
||
$result = [];
|
||
foreach ($premades as $premade) {
|
||
foreach ($premade['members'] ?? [] as $member) {
|
||
if ((int) ($member['user_id'] ?? 0) === $discordId && ($member['status'] ?? '') === 'pending') {
|
||
$result[] = $premade;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
return $result;
|
||
}
|
||
|
||
// Bevorzugt den von der Bot-API aufgeloesten Discord-Anzeigenamen (die API kennt Discord direkt,
|
||
// die Website nicht); faellt auf den verknuepften Website-Account und zuletzt auf die rohe
|
||
// Discord-ID zurueck, falls beides fehlt (z.B. Bot offline beim API-Aufruf).
|
||
// Wird sowohl von premades.php als auch vom Dashboard-Widget genutzt.
|
||
function premade_name_for(int $discordId, array $namesByDiscordId, ?string $apiName = null): string
|
||
{
|
||
if ($apiName !== null && $apiName !== '') {
|
||
return $apiName;
|
||
}
|
||
return $namesByDiscordId[$discordId] ?? ('Discord-Nutzer ' . $discordId);
|
||
}
|
||
|
||
// Baut ein fuer avatar_html() nutzbares Nutzer-Array: das echte, hochgeladene Profilbild,
|
||
// falls die Discord-ID zu einem verknuepften Website-Account gehoert, sonst ein Platzhalter
|
||
// mit dem Anfangsbuchstaben des (von der API aufgeloesten) Namens.
|
||
function premade_avatar_user(int $discordId, array $linkedUsersByDiscordId, string $displayName): array
|
||
{
|
||
if (isset($linkedUsersByDiscordId[$discordId])) {
|
||
return $linkedUsersByDiscordId[$discordId];
|
||
}
|
||
return ['id' => $discordId, 'display_name' => $displayName, 'username' => $displayName, 'avatar_filename' => null];
|
||
}
|
||
|
||
/**
|
||
* Baut die feste 5er-Slot-Darstellung einer Premade (Lead + bis zu 4 weitere,
|
||
* mit ausgegrauten Platzhaltern aufgefuellt) - genutzt sowohl von premades.php
|
||
* als auch vom "Meine Premade"-Widget im Dashboard.
|
||
*
|
||
* @param array<string, mixed> $premade
|
||
* @param array<int, string> $namesByDiscordId
|
||
* @return array<int, array<string, mixed>>
|
||
*/
|
||
function build_premade_slots(array $premade, array $namesByDiscordId): array
|
||
{
|
||
$ownerId = (int) ($premade['owner_id'] ?? 0);
|
||
$members = is_array($premade['members'] ?? null) ? $premade['members'] : [];
|
||
$accepted = array_filter($members, fn ($m) => ($m['status'] ?? '') === 'accepted' && (int) ($m['user_id'] ?? 0) !== $ownerId);
|
||
$pending = array_filter($members, fn ($m) => ($m['status'] ?? '') === 'pending');
|
||
|
||
// Von der Leitung angelegte Gruppen koennen (noch) ohne Lead sein.
|
||
$slots = [];
|
||
if ($ownerId > 0) {
|
||
$ownerName = premade_name_for($ownerId, $namesByDiscordId, $premade['owner_name'] ?? null);
|
||
$slots[] = ['type' => 'lead', 'id' => $ownerId, 'name' => $ownerName, 'class' => $premade['owner_class'] ?? null];
|
||
}
|
||
foreach ($accepted as $member) {
|
||
$mid = (int) ($member['user_id'] ?? 0);
|
||
$slots[] = ['type' => 'accepted', 'id' => $mid, 'name' => premade_name_for($mid, $namesByDiscordId, $member['name'] ?? null), 'class' => $member['class'] ?? null];
|
||
}
|
||
foreach ($pending as $member) {
|
||
$mid = (int) ($member['user_id'] ?? 0);
|
||
$slots[] = ['type' => 'pending', 'id' => $mid, 'name' => premade_name_for($mid, $namesByDiscordId, $member['name'] ?? null), 'class' => $member['class'] ?? null];
|
||
}
|
||
while (count($slots) < 5) {
|
||
$slots[] = ['type' => 'empty'];
|
||
}
|
||
return $slots;
|
||
}
|
||
|
||
/**
|
||
* Sucht einen einzelnen Raid (inkl. aktueller Signups) anhand seiner ID.
|
||
*
|
||
* @return array<string, mixed>|null
|
||
* @throws RuntimeException
|
||
*/
|
||
function fetch_raid_by_id(int $raidId): ?array
|
||
{
|
||
foreach (fetch_raids('all') as $raid) {
|
||
if ((int) ($raid['raid_id'] ?? 0) === $raidId) {
|
||
return $raid;
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
// Rollen-Zuordnung 1:1 aus ROLE_MAPPING in teamplaner.py uebernommen.
|
||
const RAID_ROLE_MAPPING = [
|
||
'Templer' => 'Tank',
|
||
'Kleriker' => 'Heal',
|
||
'Kantor' => 'Heal',
|
||
'Gladiator' => 'DPS',
|
||
'Assassine' => 'DPS',
|
||
'Jäger' => 'DPS',
|
||
'Magier' => 'DPS',
|
||
'Beschwörer' => 'DPS',
|
||
];
|
||
const RAID_GROUP_SIZE = 5;
|
||
const RAID_ROLE_CAPS = ['Tank' => 1, 'Heal' => 1, 'DPS' => 3];
|
||
// Mehr Gruppen passen nicht in die Discord-Nachricht (hoechstens 25 Felder je Embed).
|
||
const RAID_MAX_GROUPS = 10;
|
||
const RAID_MAX_SLOTS = RAID_MAX_GROUPS * RAID_GROUP_SIZE;
|
||
const RAID_GEARSCORE_MAX = 99999;
|
||
|
||
/** Anzahl der Gruppen in der kommagetrennten Liste der Gruppennamen. */
|
||
function raid_group_count(string $groupNames): int
|
||
{
|
||
return count(array_filter(array_map('trim', explode(',', $groupNames)), static fn (string $name): bool => $name !== ''));
|
||
}
|
||
|
||
/**
|
||
* Prueft "Max. Spieler": nur ganze Zahlen von 1 bis Gruppen x 5 (hoechstens 50) - mehr Plaetze
|
||
* koennten ohnehin nur auf der Ersatzbank landen. Liefert die Fehlermeldung oder null.
|
||
*
|
||
* @param mixed $value
|
||
*/
|
||
function raid_slots_error($value, int $groupCount): ?string
|
||
{
|
||
if ($groupCount < 1) {
|
||
return 'Bitte mindestens eine Gruppe angeben.';
|
||
}
|
||
if ($groupCount > RAID_MAX_GROUPS) {
|
||
return 'Höchstens ' . RAID_MAX_GROUPS . ' Gruppen pro Raid.';
|
||
}
|
||
$max = min(RAID_MAX_SLOTS, $groupCount * RAID_GROUP_SIZE);
|
||
$raw = is_int($value) ? (string) $value : trim((string) $value);
|
||
if (!ctype_digit($raw) || (int) $raw < 1 || (int) $raw > $max) {
|
||
return 'Max. Spieler: nur ganze Zahlen von 1 bis ' . $max . ' (' . $groupCount
|
||
. ($groupCount === 1 ? ' Gruppe' : ' Gruppen') . ' à ' . RAID_GROUP_SIZE . ' Plätze).';
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* Gearscore: leer oder eine Zahl von 1 bis 99.999. Punkte und Leerzeichen als Tausendertrenner
|
||
* sind erlaubt ("2.100"), gespeichert wird nur die Zahl.
|
||
*
|
||
* @return array{0: string, 1: ?string} [bereinigter Wert, Fehlermeldung oder null]
|
||
*/
|
||
function raid_normalize_gearscore(string $raw): array
|
||
{
|
||
$clean = str_replace(['.', ' ', "\u{00A0}"], '', trim($raw));
|
||
if ($clean === '') {
|
||
return ['', null];
|
||
}
|
||
if (!ctype_digit($clean) || (int) $clean < 1 || (int) $clean > RAID_GEARSCORE_MAX) {
|
||
return [$raw, 'Gearscore: nur eine Zahl von 1 bis 99.999 – oder das Feld leer lassen.'];
|
||
}
|
||
return [(string) (int) $clean, null];
|
||
}
|
||
|
||
/** Gearscore fuer die Anzeige: Zahlen mit Tausenderpunkt, alte Freitexte unveraendert. */
|
||
function raid_gearscore_label(string $gearscore): string
|
||
{
|
||
return ctype_digit($gearscore) ? number_format((int) $gearscore, 0, ',', '.') : $gearscore;
|
||
}
|
||
|
||
/**
|
||
* Prueft, ob eine gewuenschte Gruppe fuer eine Klasse nach den gleichen Rollen-Caps
|
||
* Sinn ergeben wuerde wie der Smart-Sort-Algorithmus des Bots (Tank/Heal je max. 1,
|
||
* DPS max. 3 pro 5er-Gruppe). Die Ersatzbank (Gruppe 0) ist immer erlaubt.
|
||
*
|
||
* @param array<int, array<string, mixed>> $signups Aktuelle Anmeldungen des Raids.
|
||
*/
|
||
function raid_wish_is_sensible(array $signups, int $discordId, string $className, int $desiredGroup): bool
|
||
{
|
||
if ($desiredGroup <= 0) {
|
||
return true;
|
||
}
|
||
|
||
$role = RAID_ROLE_MAPPING[$className] ?? 'DPS';
|
||
$counts = ['Tank' => 0, 'Heal' => 0, 'DPS' => 0];
|
||
$total = 0;
|
||
|
||
foreach ($signups as $signup) {
|
||
if ((int) ($signup['user_id'] ?? 0) === $discordId) {
|
||
continue; // eigene bestehende Anmeldung nicht mitzaehlen
|
||
}
|
||
if ((int) ($signup['group'] ?? 0) !== $desiredGroup) {
|
||
continue;
|
||
}
|
||
$memberRole = RAID_ROLE_MAPPING[$signup['class'] ?? ''] ?? 'DPS';
|
||
$counts[$memberRole]++;
|
||
$total++;
|
||
}
|
||
|
||
if ($total >= RAID_GROUP_SIZE) {
|
||
return false;
|
||
}
|
||
|
||
return $counts[$role] < RAID_ROLE_CAPS[$role];
|
||
}
|
||
|
||
/**
|
||
* Discord-Server-ID aus config.php - identisch zur Quelle, die create_raid() fuer die
|
||
* Raid-Erstellung nutzt. Reports/Einstellungen sind (wie Raids/Premades) an genau den einen
|
||
* dort konfigurierten Server gebunden.
|
||
*
|
||
* @throws RuntimeException
|
||
*/
|
||
function reports_guild_id(): int
|
||
{
|
||
$configPath = __DIR__ . '/../config.php';
|
||
if (!file_exists($configPath)) {
|
||
throw new RuntimeException('Konfigurationsdatei fehlt.');
|
||
}
|
||
$config = require $configPath;
|
||
$guildId = $config['raids_api']['guild_id'] ?? null;
|
||
if (!$guildId) {
|
||
throw new RuntimeException('Reports sind nicht konfiguriert (config.php: raids_api.guild_id fehlt).');
|
||
}
|
||
return (int) $guildId;
|
||
}
|
||
|
||
/**
|
||
* Fuehrt einen Request gegen die Reports-API aus (/api/reports/...) - analog zu
|
||
* premades_api_request(), nur mit Unterstuetzung fuer Query-Parameter (z.B. guild_id).
|
||
*
|
||
* @param array<string, mixed> $queryParams
|
||
* @param array<string, mixed>|null $jsonBody
|
||
* @return array<string, mixed>
|
||
* @throws RuntimeException
|
||
*/
|
||
function reports_api_request(string $method, string $path = '', array $queryParams = [], ?array $jsonBody = null): array
|
||
{
|
||
if (!function_exists('curl_init')) {
|
||
throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.');
|
||
}
|
||
|
||
$config = raids_api_config();
|
||
// /api/reports liegt eine Ebene ueber /api/raids.
|
||
$base = preg_replace('#/raids$#', '', $config['url']);
|
||
$url = $base . '/reports' . $path;
|
||
if (!empty($queryParams)) {
|
||
$url .= '?' . http_build_query($queryParams);
|
||
}
|
||
|
||
$headers = ['X-API-Key: ' . $config['key']];
|
||
|
||
$ch = curl_init($url);
|
||
$options = [
|
||
CURLOPT_RETURNTRANSFER => true,
|
||
CURLOPT_CUSTOMREQUEST => $method,
|
||
CURLOPT_TIMEOUT => 10,
|
||
CURLOPT_SSL_VERIFYPEER => true,
|
||
];
|
||
|
||
if ($jsonBody !== null) {
|
||
$headers[] = 'Content-Type: application/json';
|
||
$options[CURLOPT_POSTFIELDS] = json_encode($jsonBody, JSON_UNESCAPED_UNICODE);
|
||
}
|
||
|
||
$options[CURLOPT_HTTPHEADER] = $headers;
|
||
curl_setopt_array($ch, $options);
|
||
|
||
$response = curl_exec($ch);
|
||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||
$curlError = curl_error($ch);
|
||
curl_close($ch);
|
||
|
||
if ($response === false) {
|
||
throw new RuntimeException('Verbindung zur Reports-API fehlgeschlagen: ' . $curlError);
|
||
}
|
||
|
||
$data = json_decode($response, true);
|
||
|
||
if ($httpCode < 200 || $httpCode >= 300) {
|
||
throw new RuntimeException(bot_api_error_message('Reports-API', $httpCode, $data));
|
||
}
|
||
|
||
if (!is_array($data)) {
|
||
throw new RuntimeException('Unerwartetes Antwortformat der Reports-API.');
|
||
}
|
||
|
||
return $data;
|
||
}
|
||
|
||
/**
|
||
* @return array<int, array<string, mixed>>
|
||
* @throws RuntimeException
|
||
*/
|
||
function fetch_reports(bool $includeArchived = true): array
|
||
{
|
||
$data = reports_api_request('GET', '', ['guild_id' => reports_guild_id(), 'include_archived' => $includeArchived ? 'true' : 'false']);
|
||
|
||
if (($data['status'] ?? '') !== 'success' || !is_array($data['reports'] ?? null)) {
|
||
throw new RuntimeException('Unerwartetes Antwortformat der Reports-API.');
|
||
}
|
||
|
||
return $data['reports'];
|
||
}
|
||
|
||
/** @throws RuntimeException */
|
||
function delete_report(int $reportId): void
|
||
{
|
||
reports_api_request('DELETE', '/' . $reportId);
|
||
}
|
||
|
||
/** @throws RuntimeException */
|
||
function set_report_archived(int $reportId, bool $archived): void
|
||
{
|
||
reports_api_request('PATCH', '/' . $reportId, [], ['archived' => $archived]);
|
||
}
|
||
|
||
/**
|
||
* @return array<int, array<string, mixed>>
|
||
* @throws RuntimeException
|
||
*/
|
||
function fetch_report_weights(): array
|
||
{
|
||
$data = reports_api_request('GET', '/weights', ['guild_id' => reports_guild_id()]);
|
||
|
||
if (($data['status'] ?? '') !== 'success' || !is_array($data['roles'] ?? null)) {
|
||
throw new RuntimeException('Unerwartetes Antwortformat der Reports-API.');
|
||
}
|
||
|
||
return $data['roles'];
|
||
}
|
||
|
||
/** @throws RuntimeException */
|
||
function set_report_weight(int $roleId, int $points): void
|
||
{
|
||
reports_api_request('PATCH', '/weights/' . $roleId, [], ['guild_id' => reports_guild_id(), 'points' => $points]);
|
||
}
|
||
|
||
/**
|
||
* @return array<int, array<string, mixed>>
|
||
* @throws RuntimeException
|
||
*/
|
||
function fetch_mute_exclusions(): array
|
||
{
|
||
$data = reports_api_request('GET', '/mute-exclusions', ['guild_id' => reports_guild_id()]);
|
||
|
||
if (($data['status'] ?? '') !== 'success' || !is_array($data['roles'] ?? null)) {
|
||
throw new RuntimeException('Unerwartetes Antwortformat der Reports-API.');
|
||
}
|
||
|
||
return $data['roles'];
|
||
}
|
||
|
||
/** @throws RuntimeException */
|
||
function set_mute_exclusion(int $roleId, bool $excluded): void
|
||
{
|
||
reports_api_request('PATCH', '/mute-exclusions/' . $roleId, [], ['guild_id' => reports_guild_id(), 'excluded' => $excluded]);
|
||
}
|
||
|
||
/**
|
||
* Liest/schreibt die Mute-Punkte-Schwelle ueber den generischen Server-Settings-Endpunkt des
|
||
* Bots (/api/settings/{guild_id}), der auch Log-/Report-/Raid-Kanal verwaltet - die Website
|
||
* nutzt davon bisher nur die Schwelle.
|
||
*
|
||
* @throws RuntimeException
|
||
*/
|
||
function fetch_mute_threshold(): int
|
||
{
|
||
if (!function_exists('curl_init')) {
|
||
throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.');
|
||
}
|
||
|
||
$guildId = reports_guild_id();
|
||
$config = raids_api_config();
|
||
$base = preg_replace('#/raids$#', '', $config['url']);
|
||
$url = $base . '/settings/' . $guildId;
|
||
|
||
$ch = curl_init($url);
|
||
curl_setopt_array($ch, [
|
||
CURLOPT_RETURNTRANSFER => true,
|
||
CURLOPT_HTTPHEADER => ['X-API-Key: ' . $config['key']],
|
||
CURLOPT_TIMEOUT => 10,
|
||
CURLOPT_SSL_VERIFYPEER => true,
|
||
]);
|
||
$response = curl_exec($ch);
|
||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||
$curlError = curl_error($ch);
|
||
curl_close($ch);
|
||
|
||
if ($response === false) {
|
||
throw new RuntimeException('Verbindung zur Settings-API fehlgeschlagen: ' . $curlError);
|
||
}
|
||
$data = json_decode($response, true);
|
||
if ($httpCode < 200 || $httpCode >= 300 || !is_array($data)) {
|
||
throw new RuntimeException('Settings-API antwortete mit Statuscode ' . $httpCode . '.');
|
||
}
|
||
|
||
return (int) ($data['mute_threshold'] ?? 10);
|
||
}
|
||
|
||
/** @throws RuntimeException */
|
||
function set_mute_threshold(int $threshold): void
|
||
{
|
||
if (!function_exists('curl_init')) {
|
||
throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.');
|
||
}
|
||
|
||
$guildId = reports_guild_id();
|
||
$config = raids_api_config();
|
||
$base = preg_replace('#/raids$#', '', $config['url']);
|
||
$url = $base . '/settings/' . $guildId;
|
||
|
||
$ch = curl_init($url);
|
||
curl_setopt_array($ch, [
|
||
CURLOPT_RETURNTRANSFER => true,
|
||
CURLOPT_CUSTOMREQUEST => 'PATCH',
|
||
CURLOPT_HTTPHEADER => ['X-API-Key: ' . $config['key'], 'Content-Type: application/json'],
|
||
CURLOPT_POSTFIELDS => json_encode(['mute_threshold' => $threshold], JSON_UNESCAPED_UNICODE),
|
||
CURLOPT_TIMEOUT => 10,
|
||
CURLOPT_SSL_VERIFYPEER => true,
|
||
]);
|
||
$response = curl_exec($ch);
|
||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||
$curlError = curl_error($ch);
|
||
curl_close($ch);
|
||
|
||
if ($response === false) {
|
||
throw new RuntimeException('Verbindung zur Settings-API fehlgeschlagen: ' . $curlError);
|
||
}
|
||
if ($httpCode < 200 || $httpCode >= 300) {
|
||
throw new RuntimeException('Settings-API antwortete mit Statuscode ' . $httpCode . '.');
|
||
}
|
||
}
|