Mirrors the bot's event planner (/event_planen, /event_liste) on the
website: list all scheduled reminders with a filter for recurring/one-off,
create, edit and delete them. Both sides talk to the same bot database, so
a reminder scheduled in Discord shows up here right away and vice versa -
sending stays with the bot's background job.
Channel and role are real dropdowns pulled from the Discord server instead
of raw IDs (channels the bot cannot post in are disabled), and the form
shows a live preview of the later Discord message, like the bot does before
scheduling. The timestamp is sent as "TT.MM.JJJJ HH:MM" and converted on
the bot side, exactly like the raids, so both ends use the same timezone.
New permissions events.view / events.manage - existing installs have to
add and assign them once under Berechtigungsgruppen.
Needs the matching bot-side API additions (PATCH /api/events/{id},
GET /api/guilds/{id}/channels and /roles, next_run_raw on POST /api/events,
channel/role names in the event list), which live in the separate bot repo.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
353 lines
11 KiB
PHP
353 lines
11 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
require_once __DIR__ . '/raids_api.php';
|
|
|
|
/**
|
|
* Die Event-Erinnerungen haengen - genau wie Raids/Premades/Reports - an dem einen in
|
|
* config.php unter raids_api.guild_id hinterlegten Discord-Server.
|
|
*
|
|
* @throws RuntimeException
|
|
*/
|
|
function events_guild_id(): int
|
|
{
|
|
return reports_guild_id();
|
|
}
|
|
|
|
/**
|
|
* Fuehrt einen Request gegen die Event-API des Bots aus (/api/events/...) - analog zu
|
|
* reports_api_request().
|
|
*
|
|
* @param array<string, mixed> $queryParams
|
|
* @param array<string, mixed>|null $jsonBody
|
|
* @return array<string, mixed>
|
|
* @throws RuntimeException
|
|
*/
|
|
function events_api_request(string $method, string $path = '', array $queryParams = [], ?array $jsonBody = null): array
|
|
{
|
|
// /api/events liegt - wie /api/reports - eine Ebene ueber /api/raids.
|
|
$base = preg_replace('#/raids$#', '', raids_api_config()['url']);
|
|
|
|
return bot_api_request($method, $base . '/events' . $path, $queryParams, $jsonBody, 'Event-API');
|
|
}
|
|
|
|
/**
|
|
* Fuehrt einen Request gegen die Server-Struktur-Endpunkte des Bots aus
|
|
* (/api/guilds/{guild_id}/...), ueber die Kanaele und Rollen abgefragt werden.
|
|
*
|
|
* @return array<string, mixed>
|
|
* @throws RuntimeException
|
|
*/
|
|
function guilds_api_request(string $path): array
|
|
{
|
|
$base = preg_replace('#/raids$#', '', raids_api_config()['url']);
|
|
|
|
return bot_api_request('GET', $base . '/guilds/' . events_guild_id() . $path, [], null, 'Bot-API');
|
|
}
|
|
|
|
/**
|
|
* Gemeinsamer cURL-Aufruf fuer die Event-/Guild-Endpunkte. Anders als die aelteren
|
|
* *_api_request()-Funktionen bekommt er die fertige URL uebergeben, damit nicht fuer jeden
|
|
* neuen Endpunkt dieselben 40 Zeilen cURL-Code kopiert werden muessen.
|
|
*
|
|
* @param array<string, mixed> $queryParams
|
|
* @param array<string, mixed>|null $jsonBody
|
|
* @return array<string, mixed>
|
|
* @throws RuntimeException
|
|
*/
|
|
function bot_api_request(string $method, string $url, array $queryParams, ?array $jsonBody, string $label): array
|
|
{
|
|
if (!function_exists('curl_init')) {
|
|
throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.');
|
|
}
|
|
|
|
if (!empty($queryParams)) {
|
|
$url .= '?' . http_build_query($queryParams);
|
|
}
|
|
|
|
$headers = ['X-API-Key: ' . raids_api_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 ' . $label . ' fehlgeschlagen: ' . $curlError);
|
|
}
|
|
|
|
$data = json_decode((string) $response, true);
|
|
|
|
if ($httpCode < 200 || $httpCode >= 300) {
|
|
$detail = is_array($data) ? ($data['detail'] ?? '') : '';
|
|
$message = $label . ' antwortete mit Statuscode ' . $httpCode . '.';
|
|
if (is_string($detail) && $detail !== '') {
|
|
$message .= ' (' . $detail . ')';
|
|
}
|
|
throw new RuntimeException($message);
|
|
}
|
|
|
|
if (!is_array($data)) {
|
|
throw new RuntimeException('Unerwartetes Antwortformat der ' . $label . '.');
|
|
}
|
|
|
|
return $data;
|
|
}
|
|
|
|
/**
|
|
* Alle geplanten Event-Erinnerungen des Servers, aufsteigend nach naechster Erinnerung.
|
|
*
|
|
* @return array<int, array<string, mixed>>
|
|
* @throws RuntimeException
|
|
*/
|
|
function fetch_events(): array
|
|
{
|
|
$data = events_api_request('GET', '', ['guild_id' => events_guild_id()]);
|
|
|
|
if (($data['status'] ?? '') !== 'success' || !is_array($data['events'] ?? null)) {
|
|
throw new RuntimeException('Unerwartetes Antwortformat der Event-API.');
|
|
}
|
|
|
|
return $data['events'];
|
|
}
|
|
|
|
/**
|
|
* Textkanaele des Servers (inkl. Kategorie und der Info, ob der Bot dort posten darf).
|
|
*
|
|
* @return array<int, array<string, mixed>>
|
|
* @throws RuntimeException
|
|
*/
|
|
function fetch_guild_channels(): array
|
|
{
|
|
$data = guilds_api_request('/channels');
|
|
|
|
if (($data['status'] ?? '') !== 'success' || !is_array($data['channels'] ?? null)) {
|
|
throw new RuntimeException('Unerwartetes Antwortformat der Bot-API.');
|
|
}
|
|
|
|
return $data['channels'];
|
|
}
|
|
|
|
/**
|
|
* Rollen des Servers (ohne @everyone), hoechste zuerst.
|
|
*
|
|
* @return array<int, array<string, mixed>>
|
|
* @throws RuntimeException
|
|
*/
|
|
function fetch_guild_roles(): array
|
|
{
|
|
$data = guilds_api_request('/roles');
|
|
|
|
if (($data['status'] ?? '') !== 'success' || !is_array($data['roles'] ?? null)) {
|
|
throw new RuntimeException('Unerwartetes Antwortformat der Bot-API.');
|
|
}
|
|
|
|
return $data['roles'];
|
|
}
|
|
|
|
/**
|
|
* Legt eine neue Event-Erinnerung an. Der Zeitpunkt wird als "TT.MM.JJJJ HH:MM" uebergeben und
|
|
* erst vom Bot in einen Timestamp umgerechnet - genau wie bei der Raid-Erstellung, damit beide
|
|
* Seiten garantiert dieselbe Zeitzone verwenden.
|
|
*
|
|
* @return int Die neue Event-ID.
|
|
* @throws RuntimeException
|
|
*/
|
|
function create_event(string $name, string $message, int $channelId, int $roleId, string $nextRunRaw,
|
|
int $intervalSeconds, int $createdBy): int
|
|
{
|
|
$data = events_api_request('POST', '', [], [
|
|
'guild_id' => events_guild_id(),
|
|
'channel_id' => $channelId,
|
|
'role_id' => $roleId,
|
|
'name' => $name,
|
|
'message' => $message,
|
|
'next_run_raw' => $nextRunRaw,
|
|
'interval_seconds' => $intervalSeconds,
|
|
'created_by' => $createdBy,
|
|
]);
|
|
|
|
return (int) ($data['event_id'] ?? 0);
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $fields Nur die zu aendernden Felder (name, message, channel_id,
|
|
* role_id, next_run_raw, interval_seconds).
|
|
* @throws RuntimeException
|
|
*/
|
|
function update_event(int $eventId, array $fields): void
|
|
{
|
|
events_api_request('PATCH', '/' . $eventId, [], $fields);
|
|
}
|
|
|
|
/** @throws RuntimeException */
|
|
function delete_event(int $eventId): void
|
|
{
|
|
events_api_request('DELETE', '/' . $eventId);
|
|
}
|
|
|
|
/**
|
|
* Prueft und normalisiert die Formularfelder aus dem Anlegen-/Bearbeiten-Formular. Beide Wege
|
|
* nutzen dieselben Felder und damit auch dieselbe Pruefung.
|
|
*
|
|
* @param array<string, mixed> $input Dekodierter JSON-Body.
|
|
* @return array<string, mixed>|string Die fertigen Felder, oder eine Fehlermeldung als String.
|
|
*/
|
|
function event_fields_from_input(array $input)
|
|
{
|
|
$name = trim((string) ($input['name'] ?? ''));
|
|
$message = trim((string) ($input['message'] ?? ''));
|
|
$channelId = (int) ($input['channel_id'] ?? 0);
|
|
$roleId = (int) ($input['role_id'] ?? 0);
|
|
$nextRunRaw = trim((string) ($input['next_run_raw'] ?? ''));
|
|
$intervalValue = (int) ($input['interval_value'] ?? 0);
|
|
$intervalUnit = (string) ($input['interval_unit'] ?? 'minutes');
|
|
|
|
if ($name === '') {
|
|
return 'Bitte einen Namen für das Event angeben.';
|
|
}
|
|
if (mb_strlen($name) > 100) {
|
|
return 'Der Name darf höchstens 100 Zeichen lang sein.';
|
|
}
|
|
if ($message === '') {
|
|
return 'Bitte eine Nachricht angeben.';
|
|
}
|
|
if (mb_strlen($message) > 3900) {
|
|
return 'Die Nachricht darf höchstens 3900 Zeichen lang sein.';
|
|
}
|
|
if ($channelId <= 0) {
|
|
return 'Bitte einen Kanal auswählen.';
|
|
}
|
|
if ($roleId <= 0) {
|
|
return 'Bitte eine Rolle auswählen.';
|
|
}
|
|
if (!in_array($intervalUnit, ['minutes', 'hours', 'days'], true)) {
|
|
return 'Ungültige Einheit für die Wiederholung.';
|
|
}
|
|
if ($intervalValue < 0) {
|
|
return 'Die Wiederholung darf nicht negativ sein.';
|
|
}
|
|
|
|
// Der Bot erwartet "TT.MM.JJJJ HH:MM" und rechnet selbst in einen Timestamp um (siehe
|
|
// create_event()) - hier wird nur geprueft, dass es ueberhaupt ein gueltiges Datum ist.
|
|
if (preg_match('/^(\d{2})\.(\d{2})\.(\d{4}) (\d{2}):(\d{2})$/', $nextRunRaw, $m) !== 1
|
|
|| !checkdate((int) $m[2], (int) $m[1], (int) $m[3])
|
|
|| (int) $m[4] > 23 || (int) $m[5] > 59) {
|
|
return 'Bitte einen gültigen Zeitpunkt für die erste Erinnerung angeben.';
|
|
}
|
|
|
|
return [
|
|
'name' => $name,
|
|
'message' => $message,
|
|
'channel_id' => $channelId,
|
|
'role_id' => $roleId,
|
|
'next_run_raw' => $nextRunRaw,
|
|
'interval_seconds' => event_interval_to_seconds($intervalValue, $intervalUnit),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Formatiert ein Wiederholungs-Intervall (Sekunden) so, wie es der Bot in /event_liste anzeigt,
|
|
* nur ausgeschrieben: 0 = einmalig, sonst die groesste glatte Einheit (Tage/Stunden/Minuten).
|
|
*/
|
|
function event_interval_label(int $seconds): string
|
|
{
|
|
if ($seconds <= 0) {
|
|
return 'Einmalig';
|
|
}
|
|
if ($seconds % 86400 === 0) {
|
|
$days = intdiv($seconds, 86400);
|
|
if ($days === 1) {
|
|
return 'Täglich';
|
|
}
|
|
if ($days === 7) {
|
|
return 'Wöchentlich';
|
|
}
|
|
return 'Alle ' . $days . ' Tage';
|
|
}
|
|
if ($seconds % 3600 === 0) {
|
|
$hours = intdiv($seconds, 3600);
|
|
return $hours === 1 ? 'Stündlich' : 'Alle ' . $hours . ' Stunden';
|
|
}
|
|
|
|
$minutes = max(1, intdiv($seconds, 60));
|
|
return $minutes === 1 ? 'Jede Minute' : 'Alle ' . $minutes . ' Minuten';
|
|
}
|
|
|
|
/**
|
|
* Zerlegt ein Intervall in Wert + Einheit fuer das Bearbeiten-Formular (z.B. 604800 -> [7, 'days']).
|
|
*
|
|
* @return array{value: int, unit: string}
|
|
*/
|
|
function event_interval_parts(int $seconds): array
|
|
{
|
|
if ($seconds <= 0) {
|
|
return ['value' => 0, 'unit' => 'minutes'];
|
|
}
|
|
if ($seconds % 86400 === 0) {
|
|
return ['value' => intdiv($seconds, 86400), 'unit' => 'days'];
|
|
}
|
|
if ($seconds % 3600 === 0) {
|
|
return ['value' => intdiv($seconds, 3600), 'unit' => 'hours'];
|
|
}
|
|
|
|
return ['value' => max(1, intdiv($seconds, 60)), 'unit' => 'minutes'];
|
|
}
|
|
|
|
/**
|
|
* Rechnet Wert + Einheit aus dem Formular in Sekunden um (Gegenstueck zu event_interval_parts()).
|
|
*/
|
|
function event_interval_to_seconds(int $value, string $unit): int
|
|
{
|
|
if ($value <= 0) {
|
|
return 0;
|
|
}
|
|
|
|
return match ($unit) {
|
|
'days' => $value * 86400,
|
|
'hours' => $value * 3600,
|
|
default => $value * 60,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* "in 3 Tagen" / "vor 5 Minuten" - kurze, relative Zeitangabe passend zu Discords <t:...:R>,
|
|
* damit die Website dieselbe Information zeigt wie die Bot-Uebersicht.
|
|
*/
|
|
function event_relative_time(int $timestamp): string
|
|
{
|
|
$diff = $timestamp - time();
|
|
$past = $diff < 0;
|
|
$diff = abs($diff);
|
|
|
|
if ($diff < 60) {
|
|
$text = 'weniger als einer Minute';
|
|
} elseif ($diff < 3600) {
|
|
$minutes = intdiv($diff, 60);
|
|
$text = $minutes . ($minutes === 1 ? ' Minute' : ' Minuten');
|
|
} elseif ($diff < 86400) {
|
|
$hours = intdiv($diff, 3600);
|
|
$text = $hours . ($hours === 1 ? ' Stunde' : ' Stunden');
|
|
} else {
|
|
$days = intdiv($diff, 86400);
|
|
$text = $days . ($days === 1 ? ' Tag' : ' Tagen');
|
|
}
|
|
|
|
return $past ? 'vor ' . $text : 'in ' . $text;
|
|
}
|