The bot (Aion2_RaidPlaner, deployed 2026-09-25) has no slash commands any more. Raids,
premades, events, activity checks and reports are created and managed only here; in Discord
members sign up for raids, answer invitations and activity checks and report players.
- Raid signup works the same in Discord and here: the bot assigns the group (perform_signup),
the website only sends the wish (raid_signup(..., $wish)) and shows the reason when it did
not fit (locked, role full, raid full). raid_wish_is_sensible() and the role constants are
gone. Declining ("Abmelden") now keeps the player under "Abgemeldet" (raid_decline, new bot
endpoint .../decline) like in Discord; the raid card shows "Du hast dich abgemeldet" with
"Doch anmelden". Class input is checked against AION_CLASSES.
- The Discord message shows the raid lead and the Lumipunkte: raid_create_action/raid_edit_action
send lead_id/lead_name/points_text, raid_sync_extras() on raids.php pushes them for raids
where the bot is missing them (at most 3 per page view, follows changed raid IDs).
- bot_api.php?action=member: main class (profile choice) and whether the person has an
(active) account - the bot preselects the class and hints that Lumipunkte need an account.
- New page Verwaltung -> Discord-Bot (admin/bot.php, includes/discord_bot.php, permission
bot.manage, on update granted to groups with raids.manage; schema 53): raid, log and report
channel, post the premade overview (updates itself) and the report panel (the bot replaces
the previous one), resync all raid messages (reposted raids move their settings via
raid_rename_id). Audit area "Discord-Bot", sidebar entry with a new bot icon.
- Reports: after picking a player in the filter, delete all of their reports at once
(DELETE /api/reports/user/{id}), which also lifts the auto-mute.
- Calendar and raid logs no longer count declined players as signed up / on the bench.
- Texts that mentioned bot commands (events, activity check, config example, README) updated;
privacy policy mentions the main-class lookup and that declines stay visible. Patch notes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
357 lines
15 KiB
PHP
357 lines
15 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* Schutz vor Missbrauch und Audit-Log:
|
|
* - Audit-Log: jede Verwaltungsaktion (admin_log) und jedes Sicherheitsereignis landet dauerhaft
|
|
* in der Datenbank - unabhaengig davon, ob der Discord-Bot gerade erreichbar ist.
|
|
* - Tempolimits pro Konto (Formulare, Uploads, Kommentare, Fehlermeldungen).
|
|
* - Login-Bremse nach Fehlversuchen - pro IP bzw. IP + Benutzername, NICHT pro Konto: sonst
|
|
* koennte jemand ein bekanntes Konto mit Absicht dauerhaft sperren.
|
|
* - Notbremse: Wer in kurzer Zeit auffaellig viel loescht, wird automatisch gesperrt (gehacktes Konto).
|
|
* - Sitzungen eines Kontos sofort beenden (users.session_epoch).
|
|
*/
|
|
|
|
// Bereiche im Audit-Log: Schluessel => Beschriftung
|
|
const AUDIT_AREAS = [
|
|
'users' => 'Benutzer & Rechte',
|
|
'security' => 'Sicherheit',
|
|
'raids' => 'Raids',
|
|
'premades' => 'Premades',
|
|
'events' => 'Events',
|
|
'map' => 'Karte',
|
|
'warehouse' => 'Lagerhaus',
|
|
'contributions' => 'Lumipunkte',
|
|
'shop' => 'Lumishop',
|
|
'members' => 'Profile',
|
|
'wiki' => 'Wiki',
|
|
'gear' => 'Gear-Planer',
|
|
'reports' => 'Reports',
|
|
'bugs' => 'Fehlermeldungen',
|
|
'site' => 'Wartung & Ankündigung',
|
|
'discord' => 'Discord-Bot',
|
|
'other' => 'Sonstiges',
|
|
];
|
|
|
|
// Tempolimits: Art => [hoechstens, in Sekunden]
|
|
const SECURITY_LIMITS = [
|
|
'post' => [120, 300], // abgeschickte Formulare/Aktionen pro Konto
|
|
'upload' => [30, 600], // hochgeladene Bilder pro Konto
|
|
'comment' => [6, 300], // Kommentare unter Galeriebildern pro Konto
|
|
'report' => [10, 600], // Meldungen (Melden-Knopf) pro Konto
|
|
'reaction' => [60, 300], // Reaktionen (Emojis) pro Konto
|
|
'calendar' => [8, 3600], // eigene Kalender-Termine pro Konto
|
|
'bug' => [5, 3600], // Fehlermeldungen pro Konto
|
|
'discord_sync' => [10, 3600], // "Jetzt mit Discord abgleichen" im Profil pro Konto (dazu hoechstens alle 30 s)
|
|
'export' => [6, 3600], // Datenauskunft herunterladen (eigene oder fuer andere) pro Konto
|
|
'login_ip' => [15, 900], // fehlgeschlagene Logins pro IP (egal welches Konto)
|
|
'login_pair' => [5, 900], // fehlgeschlagene Logins pro IP + Benutzername
|
|
'destructive' => [20, 600], // Loeschungen pro Konto, danach automatische Sperre
|
|
];
|
|
|
|
// Diese Skripte schicken im Hintergrund viele kleine Anfragen (Zeichnen, Tour, Bot, Gear-Abgleich) - kein Tempolimit.
|
|
const SECURITY_POST_EXEMPT = ['bot_api.php', 'tactics_api.php', 'tour_action.php', 'gear_items_action.php'];
|
|
|
|
/** Bereich einer Aktion anhand des aufgerufenen Skripts (raid_delete_action.php -> raids). */
|
|
function audit_area_for_script(string $script): string
|
|
{
|
|
$name = basename($script, '.php');
|
|
$prefixes = [
|
|
'raid' => 'raids', 'premade' => 'premades', 'event' => 'events', 'tactics' => 'map', 'map' => 'map',
|
|
'warehouse' => 'warehouse', 'contributions' => 'contributions', 'shop' => 'shop',
|
|
'member' => 'members', 'gallery' => 'members', 'moderation' => 'members', 'reaction' => 'members', 'calendar' => 'events', 'wiki' => 'wiki', 'gear' => 'gear', 'report' => 'reports', 'bug' => 'bugs',
|
|
'user' => 'users', 'role' => 'users', 'discord' => 'users', 'settings' => 'users',
|
|
'site' => 'site', 'announcement' => 'site', 'bot' => 'discord',
|
|
];
|
|
foreach ($prefixes as $prefix => $area) {
|
|
if (strpos($name, $prefix) === 0) {
|
|
return $area;
|
|
}
|
|
}
|
|
return 'other';
|
|
}
|
|
|
|
/** IP des Besuchers, gekuerzt (IPv4: letzter Block 0, IPv6: nur die ersten vier Bloecke). */
|
|
function client_ip_masked(): ?string
|
|
{
|
|
$ip = (string) ($_SERVER['REMOTE_ADDR'] ?? '');
|
|
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
|
|
return preg_replace('/\.\d+$/', '.0', $ip);
|
|
}
|
|
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
|
|
return implode(':', array_slice(explode(':', $ip), 0, 4)) . '::';
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/** Schluessel fuer die IP in den Tempolimits (gehasht, die Tabelle wird nach 2 Tagen geleert). */
|
|
function client_ip_key(): string
|
|
{
|
|
return substr(hash('sha256', 'ip|' . ($_SERVER['REMOTE_ADDR'] ?? '')), 0, 40);
|
|
}
|
|
|
|
/**
|
|
* Discord-Codes im Text lesbar machen: Rollen (<@&id>) werden ueber die verknuepften
|
|
* Berechtigungsgruppen benannt, Kanaele (<#id>) und einzelne Nutzer (<@id>) bekommen einen
|
|
* Klartext statt der rohen Syntax.
|
|
*/
|
|
function audit_readable_discord(string $value): string
|
|
{
|
|
$value = preg_replace_callback('/<@&(\d+)>/', static function (array $m): string {
|
|
try {
|
|
$stmt = db()->prepare("SELECT COALESCE(NULLIF(display_name, ''), name) FROM roles WHERE discord_role_id = ?");
|
|
$stmt->execute([$m[1]]);
|
|
$name = $stmt->fetchColumn();
|
|
} catch (PDOException $e) {
|
|
$name = false;
|
|
}
|
|
return $name !== false ? '@' . $name : 'Discord-Rolle ' . $m[1];
|
|
}, $value) ?? $value;
|
|
$value = preg_replace('/<#(\d+)>/', 'Kanal-ID $1', $value) ?? $value;
|
|
return preg_replace_callback('/<@!?(\d+)>/', static fn (array $m): string => function_exists('admin_log_discord_name')
|
|
? admin_log_discord_name($m[1]) : 'Discord-ID ' . $m[1], $value) ?? $value;
|
|
}
|
|
|
|
// So lange bleiben Eintraege im Audit-Log (steht so in der Datenschutzerklaerung)
|
|
const AUDIT_LOG_KEEP_MONTHS = 12;
|
|
|
|
/**
|
|
* Eintrag ins Audit-Log. Discord-Erwaehnungen "(<@123>)" hinter einem Namen werden entfernt,
|
|
* uebrige Discord-Codes lesbar gemacht (audit_readable_discord).
|
|
*
|
|
* @param array<string, scalar|null> $fields
|
|
*/
|
|
function audit_store(string $title, array $fields, string $tone, ?string $area = null, ?array $actor = null): void
|
|
{
|
|
$actor = $actor ?? current_user();
|
|
$clean = [];
|
|
foreach ($fields as $name => $value) {
|
|
$value = trim(audit_readable_discord(preg_replace('/\s*\(<@!?\d+>\)/', '', (string) $value) ?? ''));
|
|
if ($value !== '') {
|
|
$clean[(string) $name] = mb_substr($value, 0, 1000);
|
|
}
|
|
}
|
|
$actorName = '';
|
|
if ($actor) {
|
|
$actorName = ($actor['display_name'] ?? '') !== '' ? (string) $actor['display_name'] : (string) ($actor['username'] ?? '');
|
|
}
|
|
try {
|
|
db()->prepare(
|
|
'INSERT INTO audit_log (user_id, actor_name, area, title, details, tone, ip) VALUES (?, ?, ?, ?, ?, ?, ?)'
|
|
)->execute([
|
|
!empty($actor['id']) ? (int) $actor['id'] : null, // ohne id: System (z.B. abgelaufene Loeschfrist)
|
|
mb_substr($actorName, 0, 100),
|
|
$area ?? audit_area_for_script((string) ($_SERVER['SCRIPT_NAME'] ?? '')),
|
|
mb_substr($title, 0, 256),
|
|
$clean ? json_encode($clean, JSON_UNESCAPED_UNICODE) : null,
|
|
$tone,
|
|
client_ip_masked(),
|
|
]);
|
|
// Nebenbei aufraeumen: Eintraege aelter als AUDIT_LOG_KEEP_MONTHS (Speicherdauer laut datenschutz.php)
|
|
if (random_int(1, 50) === 1) {
|
|
db()->prepare('DELETE FROM audit_log WHERE created_at < ?')
|
|
->execute([date('Y-m-d H:i:s', (int) strtotime('-' . AUDIT_LOG_KEEP_MONTHS . ' months'))]);
|
|
}
|
|
} catch (PDOException $e) {
|
|
// Tabelle fehlt (noch) - die eigentliche Aktion soll daran nicht scheitern.
|
|
}
|
|
}
|
|
|
|
/** Sicherheitsereignis: Audit-Log (Bereich "Sicherheit") und Discord-Log. */
|
|
function security_log(string $title, array $fields = [], string $tone = 'warning', ?array $actor = null): void
|
|
{
|
|
admin_log($title, $fields, $tone, 'security', $actor);
|
|
}
|
|
|
|
// ---- Tempolimits ----
|
|
|
|
function rate_limit_count(string $bucket, string $subject, int $windowSeconds): int
|
|
{
|
|
try {
|
|
$stmt = db()->prepare(
|
|
'SELECT COUNT(*) FROM rate_limits WHERE bucket = ? AND subject = ? AND created_at > ?'
|
|
);
|
|
$stmt->execute([$bucket, $subject, date('Y-m-d H:i:s', time() - $windowSeconds)]);
|
|
return (int) $stmt->fetchColumn();
|
|
} catch (PDOException $e) {
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
function rate_limit_add(string $bucket, string $subject, int $times = 1): void
|
|
{
|
|
try {
|
|
$insert = db()->prepare('INSERT INTO rate_limits (bucket, subject) VALUES (?, ?)');
|
|
for ($i = 0; $i < $times; $i++) {
|
|
$insert->execute([$bucket, $subject]);
|
|
}
|
|
// Ab und zu aufraeumen - laenger als zwei Tage braucht kein Limit zurueckzuschauen.
|
|
if (random_int(1, 50) === 1) {
|
|
db()->prepare('DELETE FROM rate_limits WHERE created_at < ?')->execute([date('Y-m-d H:i:s', time() - 172800)]);
|
|
}
|
|
} catch (PDOException $e) {
|
|
// Tabelle fehlt (noch)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Prueft ein Tempolimit fuer das angemeldete Konto und zaehlt die Aktion mit.
|
|
* Beim ersten Ueberschreiten im Zeitfenster gibt es einen Eintrag im Audit- und Discord-Log.
|
|
*
|
|
* @return bool true = erlaubt
|
|
*/
|
|
function security_throttle(string $bucket, int $amount = 1): bool
|
|
{
|
|
$user = current_user();
|
|
if (!$user || !isset(SECURITY_LIMITS[$bucket])) {
|
|
return true;
|
|
}
|
|
[$max, $window] = SECURITY_LIMITS[$bucket];
|
|
$subject = 'u' . (int) $user['id'];
|
|
|
|
if (rate_limit_count($bucket, $subject, $window) + $amount > $max) {
|
|
if (rate_limit_count('notice_' . $bucket, $subject, $window) === 0) {
|
|
rate_limit_add('notice_' . $bucket, $subject);
|
|
security_log('⏱️ Tempolimit erreicht', [
|
|
'Art' => security_bucket_label($bucket),
|
|
'Limit' => $max . ' in ' . round($window / 60) . ' Minuten',
|
|
'Seite' => basename((string) ($_SERVER['SCRIPT_NAME'] ?? '')),
|
|
]);
|
|
}
|
|
return false;
|
|
}
|
|
rate_limit_add($bucket, $subject, $amount);
|
|
return true;
|
|
}
|
|
|
|
function security_bucket_label(string $bucket): string
|
|
{
|
|
return [
|
|
'post' => 'Aktionen/Formulare',
|
|
'upload' => 'Bilder hochladen',
|
|
'comment' => 'Kommentare',
|
|
'report' => 'Meldungen',
|
|
'reaction' => 'Reaktionen',
|
|
'calendar' => 'Kalender-Termine',
|
|
'bug' => 'Fehlermeldungen',
|
|
'discord_sync' => 'Discord-Abgleich im Profil',
|
|
'export' => 'Datenauskunft herunterladen',
|
|
'destructive' => 'Löschungen',
|
|
][$bucket] ?? $bucket;
|
|
}
|
|
|
|
/** Meldung und zurueck zur vorigen Seite (bzw. JSON-Fehler bei Hintergrund-Anfragen). */
|
|
function security_reject(string $message): void
|
|
{
|
|
$accept = (string) ($_SERVER['HTTP_ACCEPT'] ?? '');
|
|
if (stripos($accept, 'application/json') !== false || !empty($_SERVER['HTTP_X_REQUESTED_WITH'])) {
|
|
http_response_code(429);
|
|
header('Content-Type: application/json; charset=UTF-8');
|
|
echo json_encode(['ok' => false, 'error' => $message], JSON_UNESCAPED_UNICODE);
|
|
exit;
|
|
}
|
|
set_flash('error', $message);
|
|
$back = (string) ($_SERVER['HTTP_REFERER'] ?? '');
|
|
$host = (string) ($_SERVER['HTTP_HOST'] ?? '');
|
|
$path = parse_url($back, PHP_URL_HOST) === $host ? (string) parse_url($back, PHP_URL_PATH) : '';
|
|
$query = (string) parse_url($back, PHP_URL_QUERY);
|
|
redirect($path !== '' ? $path . ($query !== '' ? '?' . $query : '') : '/dashboard.php');
|
|
}
|
|
|
|
/** Allgemeines Tempolimit fuer alle abgeschickten Formulare angemeldeter Konten (aus bootstrap.php). */
|
|
function security_guard_post(): void
|
|
{
|
|
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST' || empty($_SESSION['user_id'])) {
|
|
return;
|
|
}
|
|
$script = basename((string) ($_SERVER['SCRIPT_NAME'] ?? ''));
|
|
// Die Live-Vorschau im Wiki-Editor schickt beim Tippen laufend Anfragen.
|
|
if (in_array($script, SECURITY_POST_EXEMPT, true) || ($_POST['action'] ?? '') === 'preview') {
|
|
return;
|
|
}
|
|
if (!security_throttle('post')) {
|
|
security_reject('Zu viele Aktionen in kurzer Zeit. Bitte warte ein paar Minuten und versuche es dann erneut.');
|
|
}
|
|
}
|
|
|
|
// ---- Login-Bremse ----
|
|
|
|
/** Leer = Login-Versuch erlaubt, sonst die Meldung fuer die Login-Seite. */
|
|
function login_throttle_check(string $username): string
|
|
{
|
|
[$maxIp, $window] = SECURITY_LIMITS['login_ip'];
|
|
[$maxPair] = SECURITY_LIMITS['login_pair'];
|
|
if (rate_limit_count('login_ip', client_ip_key(), $window) >= $maxIp
|
|
|| rate_limit_count('login_pair', login_pair_key($username), $window) >= $maxPair) {
|
|
return 'Zu viele fehlgeschlagene Anmeldungen von deinem Anschluss. Bitte warte 15 Minuten '
|
|
. 'und versuche es dann erneut - oder melde dich über Discord an.';
|
|
}
|
|
return '';
|
|
}
|
|
|
|
function login_pair_key(string $username): string
|
|
{
|
|
return substr(hash('sha256', 'pair|' . ($_SERVER['REMOTE_ADDR'] ?? '') . '|' . mb_strtolower(trim($username))), 0, 40);
|
|
}
|
|
|
|
/** Fehlversuch zaehlen; beim Erreichen einer Sperre ein Eintrag im Audit- und Discord-Log. */
|
|
function login_throttle_fail(string $username): void
|
|
{
|
|
[$maxIp, $window] = SECURITY_LIMITS['login_ip'];
|
|
[$maxPair] = SECURITY_LIMITS['login_pair'];
|
|
rate_limit_add('login_ip', client_ip_key());
|
|
rate_limit_add('login_pair', login_pair_key($username));
|
|
|
|
$ipCount = rate_limit_count('login_ip', client_ip_key(), $window);
|
|
$pairCount = rate_limit_count('login_pair', login_pair_key($username), $window);
|
|
if ($ipCount === $maxIp || $pairCount === $maxPair) {
|
|
security_log('🔐 Login-Sperre nach Fehlversuchen', [
|
|
'Benutzername' => mb_substr($username, 0, 60),
|
|
'IP (gekürzt)' => (string) client_ip_masked(),
|
|
'Gesperrt' => $ipCount >= $maxIp ? 'diese IP für alle Konten (15 Min.)' : 'diese IP für dieses Konto (15 Min.)',
|
|
], 'warning', []);
|
|
}
|
|
}
|
|
|
|
// ---- Notbremse und Sitzungen ----
|
|
|
|
/** Wird bei jeder Loeschung (admin_log mit Ton "danger") aufgerufen. */
|
|
function security_note_destructive(): void
|
|
{
|
|
$user = current_user();
|
|
if (!$user) {
|
|
return;
|
|
}
|
|
[$max, $window] = SECURITY_LIMITS['destructive'];
|
|
$subject = 'u' . (int) $user['id'];
|
|
rate_limit_add('destructive', $subject);
|
|
if (rate_limit_count('destructive', $subject, $window) !== $max + 1) {
|
|
return;
|
|
}
|
|
// Entwickler werden nicht gesperrt (sonst kaeme niemand mehr an ihr Konto), aber gemeldet.
|
|
if (is_developer($user)) {
|
|
security_log('🚨 Auffällig viele Löschungen (Entwickler-Konto, nicht gesperrt)', [
|
|
'Konto' => admin_log_user((int) $user['id']),
|
|
'Löschungen' => 'mehr als ' . $max . ' in ' . round($window / 60) . ' Minuten',
|
|
], 'danger');
|
|
return;
|
|
}
|
|
security_lock_account((int) $user['id'], 'Mehr als ' . $max . ' Löschungen in ' . round($window / 60) . ' Minuten', true);
|
|
}
|
|
|
|
/** Konto sperren und alle Sitzungen beenden. */
|
|
function security_lock_account(int $userId, string $reason, bool $automatic = false): void
|
|
{
|
|
db()->prepare("UPDATE users SET status = 'disabled', session_epoch = session_epoch + 1 WHERE id = ?")->execute([$userId]);
|
|
security_log($automatic ? '🚨 Konto automatisch gesperrt' : '🔒 Konto gesperrt und abgemeldet', [
|
|
'Konto' => admin_log_user($userId),
|
|
'Grund' => $reason,
|
|
'Hinweis' => $automatic ? 'Möglicherweise gehackt - bitte prüfen. Entsperren über die Benutzerverwaltung (Status „Aktiv“).' : '',
|
|
], 'danger');
|
|
}
|
|
|
|
/** Alle Sitzungen eines Kontos beenden (naechster Seitenaufruf meldet ab). */
|
|
function security_end_sessions(int $userId): void
|
|
{
|
|
db()->prepare('UPDATE users SET session_epoch = session_epoch + 1 WHERE id = ?')->execute([$userId]);
|
|
}
|