LuminaWebsite/includes/account_deletion.php
Maaxxs 5aaf44eaec Consilium Elyseum: allied legions get their own view - own raids, calendar entries, member tab and shared live map sessions
Asked for: alliances ("Consilium Elyseum") with their own view, a member-list tab with the allied legions and their
members, an own raid area, a calendar that shows them only alliance entries, and live map sessions the legion can
share with them - watching only, or drawing only with an extra permission. There is one Discord role "Consilium
Elyseum" for all allies, so which legion each ally belongs to is stored on the website.

- Permissions consilium.view / consilium.draw / consilium.manage. An account with consilium.view but without
  dashboard.view is a guest of the Consilium (consilium_only(), sql_is_consilium_only()) and sees only the alliance
  area; raids, calendar and map stay restricted even with extra rights like raids.view or map.view.
- includes/consilium.php; consilium.php is the allies' start page instead of the dashboard (next raids and entries,
  legions, running shared map sessions); admin/consilium.php: setup hints, allied legions, member assignment.
  users.consilium_legion_id, table consilium_legions (schema 69); allies pick their legion under Mein Profil.
- Members: new tab "Consilium Elyseum" (legions with their members), the only tab allies see. Legion-only lists
  (dues, Lumipunkte, member pickers, raid and activity points) leave allies out.
- Raids: two areas, legion and Consilium, told apart by the Discord channel ("Consilium-Raids" under Verwaltung ->
  Discord-Bot, settings.consilium_raid_channel; the bot API returns channel_id). Allies only see and sign up for
  Consilium raids, which give no Lumipunkte; raids created in the Consilium area are posted to its channel.
- Calendar: audience "Consilium Elyseum". Allies see only those entries and the Consilium raids (also in their iCal
  subscription), their own entries are always Consilium entries; the public calendar shows no Consilium raids; the
  legion sees them marked with 🤝.
- Map: whoever may edit a public tactic shares its running live session with the Consilium (consilium_share, logged).
  The share lives in the bot's live relay and only for that session: it ends with "Freigabe beenden" or 60 s after
  the last legion member left; making the tactic private or deleting it ends it as well. Allies see only running
  shared sessions under Karte (and on their start page), join and watch; with consilium.draw they add strokes,
  areas, points and text - no figures, nothing moved, erased or undone, no tactics, steps, copies or history.
  Enforced in tactics_api.php (guest branch: shared tactics only, only live_token and shape_create) and in the relay
  (guest tickets, event whitelist, guests are disconnected when the share ends). Needs the bot update (api.py,
  database/db.py, live_tactics.py).
- Navigation, privacy page, patch note, README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 01:36:49 +02:00

338 lines
17 KiB
PHP

<?php
declare(strict_types=1);
/**
* Konto loeschen: Das Konto wird nicht entfernt, sondern unkenntlich gemacht - Persoenliches
* (Profil, Bilder, Charaktere, Galerie, Gear-Sets, Zugaenge) wird geloescht, Beitraege zur Legion
* (Kommentare, Wiki, Lumipunkte, Raid-Anwesenheit, Lagerhaus ...) bleiben als ACCOUNT_DELETED_NAME
* erhalten, ohne Namen und Discord-ID.
*
* Ablauf: Das Mitglied beantragt die Loeschung (Mein Profil -> Konto & Daten, account_delete.php),
* wird ueberall abgemeldet, und nach ACCOUNT_DELETION_DAYS Tagen fuehrt account_deletion_run_due()
* sie aus (laeuft nebenbei in der bootstrap). Meldet es sich vorher wieder an, bricht
* account_deletion_on_login() die Loeschung ab und sagt ihm das. Die Leitung kann die Loeschung
* auch planen, abbrechen oder sofort ausfuehren (admin/user_export.php, Recht users.delete).
*/
const ACCOUNT_DELETION_DAYS = 7;
const ACCOUNT_DELETED_NAME = 'Ehemaliges Mitglied';
// Wie oft nebenbei nach faelligen Loeschungen gesehen wird (Sekunden)
const ACCOUNT_DELETION_CHECK_INTERVAL = 900;
// "Wer" im Log, wenn die Frist abgelaufen ist (kein Konto - sonst stuende der zufaellige Besucher dort)
const ACCOUNT_DELETION_SYSTEM_ACTOR = ['id' => null, 'username' => 'system', 'display_name' => 'Automatisch (Löschfrist abgelaufen)'];
/** Konto, das beim Anmelden bzw. im Log als "wer" steht. */
function account_deletion_actor(int $userId): ?array
{
$stmt = db()->prepare('SELECT id, username, display_name, discord_id FROM users WHERE id = ?');
$stmt->execute([$userId]);
return $stmt->fetch() ?: null;
}
/** Loeschung planen: in ACCOUNT_DELETION_DAYS Tagen, alle Sitzungen und "Angemeldet bleiben" enden. */
function account_deletion_request(int $userId, ?array $actor = null): string
{
$due = date('Y-m-d H:i:s', time() + ACCOUNT_DELETION_DAYS * 86400);
db()->prepare('UPDATE users SET deletion_scheduled_at = ?, session_epoch = session_epoch + 1 WHERE id = ? AND deleted_at IS NULL')
->execute([$due, $userId]);
db()->prepare('DELETE FROM auth_tokens WHERE user_id = ?')->execute([$userId]);
$self = $actor !== null && (int) $actor['id'] === $userId;
admin_log($self ? '🗑️ Kontolöschung beantragt' : '🗑️ Kontolöschung geplant', [
'Konto' => admin_log_user($userId),
'Wird ausgeführt' => date('d.m.Y, H:i', (int) strtotime($due)) . ' Uhr - Anmelden bricht sie ab',
], 'warning', 'users', $actor);
return $due;
}
/** Geplante Loeschung abbrechen (Leitung oder Anmeldung). */
function account_deletion_cancel(int $userId, string $reason, ?array $actor = null): void
{
$stmt = db()->prepare('UPDATE users SET deletion_scheduled_at = NULL WHERE id = ? AND deletion_scheduled_at IS NOT NULL AND deleted_at IS NULL');
$stmt->execute([$userId]);
if ($stmt->rowCount() > 0) {
admin_log('↩️ Kontolöschung abgebrochen', ['Konto' => admin_log_user($userId), 'Grund' => $reason], 'info', 'users', $actor);
}
}
/**
* Beim Anmelden (auth_login_session): Wer seine Loeschung beantragt hat und sich vor Ablauf der
* Frist wieder anmeldet, bricht sie damit ab und bekommt das angezeigt. Ist die Frist schon
* abgelaufen, wird das Konto jetzt geloescht und die Anmeldung beendet.
*/
function account_deletion_on_login(int $userId): void
{
try {
$stmt = db()->prepare('SELECT deletion_scheduled_at FROM users WHERE id = ? AND deleted_at IS NULL');
$stmt->execute([$userId]);
$due = $stmt->fetchColumn();
} catch (PDOException $e) {
return; // Spalte kommt erst mit dem naechsten Schema-Abgleich
}
if (!is_string($due) || $due === '') {
return;
}
if (strtotime($due) <= time()) {
account_anonymize($userId, ACCOUNT_DELETION_SYSTEM_ACTOR);
auth_force_logout('Dein Konto wurde wie beantragt gelöscht.');
redirect('/login.php');
}
account_deletion_cancel($userId, 'Anmeldung vor Ablauf der Frist', account_deletion_actor($userId));
set_flash('info', 'Du hattest die Löschung deines Kontos für den ' . date('d.m.Y', (int) strtotime($due))
. ' beantragt. Weil du dich angemeldet hast, ist sie abgebrochen - dein Konto bleibt bestehen. Möchtest du es doch löschen, '
. 'beantrage es unter „Mein Profil“ → „Konto & Daten“ erneut.');
}
/**
* Aus der bootstrap: hoechstens alle 15 Minuten account_deletion_run_due() vormerken - es laeuft erst,
* nachdem die Seite ausgeliefert ist (wie admin_log_flush), damit kein Besucher auf den Bot wartet.
*/
function account_deletion_schedule_run(): void
{
if (time() - (int) setting_get('account_deletion_checked') < ACCOUNT_DELETION_CHECK_INTERVAL) {
return;
}
register_shutdown_function(static function (): void {
if (session_status() === PHP_SESSION_ACTIVE) {
session_write_close();
}
if (function_exists('fastcgi_finish_request')) {
@fastcgi_finish_request();
}
account_deletion_run_due();
});
}
/** Faellige Loeschungen ausfuehren und beim Discord-Bot Liegengebliebenes nachholen. */
function account_deletion_run_due(): void
{
if (time() - (int) setting_get('account_deletion_checked') < ACCOUNT_DELETION_CHECK_INTERVAL) {
return;
}
try {
setting_set('account_deletion_checked', (string) time());
$due = db()->query(
'SELECT id FROM users WHERE deletion_scheduled_at IS NOT NULL AND deletion_scheduled_at <= NOW() AND deleted_at IS NULL'
)->fetchAll(PDO::FETCH_COLUMN);
} catch (PDOException $e) {
return;
}
foreach ($due as $userId) {
try {
account_anonymize((int) $userId, ACCOUNT_DELETION_SYSTEM_ACTOR);
} catch (Throwable $e) {
security_log('⚠️ Kontolöschung fehlgeschlagen', ['Konto' => '#' . (int) $userId, 'Fehler' => $e->getMessage()]);
}
}
account_deletion_bot_retry();
}
/**
* Beim Discord-Bot unkenntlich machen (POST /api/privacy/anonymize im Bot): laufende Raid-Anmeldungen
* und Premade-Mitgliedschaften weg, der Rest mit Konto-Nummer und ACCOUNT_DELETED_NAME statt
* Discord-ID und Name. Gibt false zurueck, wenn der Bot nicht erreichbar war.
*/
function account_deletion_bot(string $discordId, int $userId, array $names): bool
{
require_once __DIR__ . '/raids_api.php';
require_once __DIR__ . '/events_api.php';
try {
$base = (string) preg_replace('#/raids$#', '', raids_api_config()['url']);
bot_api_request('POST', $base . '/privacy/anonymize', [], [
'user_id' => (int) $discordId,
'replacement_id' => $userId,
'replacement_name' => ACCOUNT_DELETED_NAME,
'names' => array_slice(array_values(array_unique(array_filter(array_map('trim', $names)))), 0, 10),
], 'Bot-API');
return true;
} catch (Throwable $e) {
return false;
}
}
/**
* Auftraege fuer den Bot, die noch offen sind - direkt aus der Datenbank, nicht ueber setting_get(): das
* merkt sich Werte fuer den ganzen Aufruf und wuerde einen gerade hinzugefuegten Auftrag uebersehen.
*/
function account_deletion_bot_queue(): array
{
try {
$stmt = db()->prepare('SELECT value FROM settings WHERE `key` = ?');
$stmt->execute(['account_deletion_bot_queue']);
$queue = json_decode((string) $stmt->fetchColumn(), true);
} catch (PDOException $e) {
$queue = null;
}
return is_array($queue) ? $queue : [];
}
/**
* War der Bot beim Loeschen nicht erreichbar, steht der Auftrag in den Einstellungen und wird bei jedem
* Durchlauf erneut versucht, bis der Bot ihn erledigt hat. Nach einer Woche gibt es einen Hinweis im Log.
*/
function account_deletion_bot_retry(): void
{
$queue = account_deletion_bot_queue();
if (!$queue) {
return;
}
$left = [];
foreach ($queue as $job) {
// Gerade eben gescheitert - nicht im selben Durchlauf gleich noch einmal auf den Bot warten
if (time() - (int) ($job['since'] ?? 0) < 600) {
$left[] = $job;
continue;
}
if (account_deletion_bot((string) ($job['discord_id'] ?? ''), (int) ($job['user_id'] ?? 0), (array) ($job['names'] ?? []))) {
admin_log('🗑️ Gelöschtes Konto auch beim Discord-Bot unkenntlich gemacht', ['Konto' => '#' . (int) ($job['user_id'] ?? 0)],
'info', 'users', ACCOUNT_DELETION_SYSTEM_ACTOR);
continue;
}
if (empty($job['warned']) && time() - (int) ($job['since'] ?? time()) > 7 * 86400) {
security_log('⚠️ Discord-Bot seit einer Woche nicht erreichbar - gelöschtes Konto dort noch nicht bereinigt', [
'Konto' => '#' . (int) ($job['user_id'] ?? 0),
'Hinweis' => 'Wird weiter versucht, sobald der Bot wieder läuft',
], 'danger');
$job['warned'] = true;
}
$left[] = $job;
}
setting_set('account_deletion_bot_queue', $left ? (string) json_encode($left, JSON_UNESCAPED_UNICODE) : '');
}
/**
* Macht ein Konto unkenntlich. Loescht Persoenliches samt Dateien, entfernt Namen und Discord-ID
* aus allem, was fuer die Legion bestehen bleibt - auch beim Discord-Bot (account_deletion_bot). Nicht
* erfasst: fruehere Nachrichten im Log-Kanal auf Discord, Meldungen ueber die Person im Bot (verfallen nach
* 10 Tagen) und Details anderer Audit-Log-Eintraege (verfallen nach 12 Monaten).
*/
function account_anonymize(int $userId, ?array $actor = null): void
{
require_once __DIR__ . '/member_profile.php'; // PROFILE_UPLOAD_DIR
require_once __DIR__ . '/bugs.php'; // BUG_UPLOAD_DIR
$pdo = db();
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ? AND deleted_at IS NULL');
$stmt->execute([$userId]);
$user = $stmt->fetch();
if (!$user) {
return;
}
$discordId = (string) ($user['discord_id'] ?? '');
$ids = static function (string $sql, array $params) use ($pdo): array {
$s = $pdo->prepare($sql);
$s->execute($params);
return array_map('intval', $s->fetchAll(PDO::FETCH_COLUMN));
};
$in = static fn (array $list): string => implode(',', array_map('intval', $list)) ?: '0';
// Dateien merken, geloescht werden sie erst nach dem erfolgreichen Speichern
$files = [];
if (!empty($user['avatar_filename'])) {
$files[] = __DIR__ . '/../assets/uploads/avatars/' . $user['avatar_filename'];
}
foreach (data_rows_column($pdo, 'SELECT portrait_filename FROM member_characters WHERE user_id = ? UNION SELECT image_filename FROM member_characters WHERE user_id = ? UNION SELECT filename FROM member_gallery WHERE user_id = ?', [$userId, $userId, $userId]) as $file) {
$files[] = PROFILE_UPLOAD_DIR . $file;
}
$bugIds = $ids('SELECT id FROM bug_reports WHERE user_id = ?', [$userId]);
foreach (data_rows_column($pdo, 'SELECT filename FROM bug_report_images WHERE bug_id IN (' . $in($bugIds) . ')', []) as $file) {
$files[] = BUG_UPLOAD_DIR . $file;
}
// Zuerst der Discord-Bot - danach kennt die Website die Discord-ID nicht mehr. Ist er nicht
// erreichbar, merkt sich die Website den Auftrag und holt ihn nach (account_deletion_bot_retry).
$botStatus = '';
if ($discordId !== '') {
$names = [(string) $user['display_name'], (string) ($user['discord_username'] ?? ''), (string) $user['username']];
if (account_deletion_bot($discordId, $userId, $names)) {
$botStatus = 'unkenntlich gemacht';
} else {
$queue = account_deletion_bot_queue();
$queue[] = ['discord_id' => $discordId, 'user_id' => $userId, 'names' => $names, 'since' => time()];
setting_set('account_deletion_bot_queue', (string) json_encode($queue, JSON_UNESCAPED_UNICODE));
$botStatus = 'nicht erreichbar - wird nachgeholt';
}
}
$pdo->beginTransaction();
try {
// --- Persoenliches loeschen ---
$pictureIds = $ids('SELECT id FROM member_gallery WHERE user_id = ?', [$userId]);
$commentIds = $ids('SELECT id FROM gallery_comments WHERE gallery_id IN (' . $in($pictureIds) . ')', []);
$pdo->exec("DELETE FROM reactions WHERE (content_type = 'picture' AND content_id IN (" . $in($pictureIds) . "))
OR (content_type = 'comment' AND content_id IN (" . $in($commentIds) . '))');
$pdo->exec("DELETE FROM content_reports WHERE (content_type = 'picture' AND content_id IN (" . $in($pictureIds) . "))
OR (content_type = 'comment' AND content_id IN (" . $in($commentIds) . '))');
foreach ([
"DELETE FROM premade_banners WHERE banner IN (SELECT CONCAT('gallery:', id) FROM member_gallery WHERE user_id = ?)",
'DELETE FROM member_gallery WHERE user_id = ?', // Kommentare darunter per CASCADE
'DELETE FROM member_characters WHERE user_id = ?',
'DELETE FROM gear_sets WHERE user_id = ?', // Ausruestung, Skills, Planung per CASCADE
'DELETE FROM user_roles WHERE user_id = ?',
'DELETE FROM user_permissions WHERE user_id = ?',
'DELETE FROM auth_tokens WHERE user_id = ?',
'DELETE FROM wiki_contributors WHERE user_id = ?',
'DELETE FROM calendar_participants WHERE user_id = ?',
'DELETE FROM calendar_feeds WHERE user_id = ?', // Kalender-Abo
'DELETE FROM data_export_links WHERE user_id = ?',
'DELETE FROM dues_exemptions WHERE user_id = ?', // Befreiungen von Legionsbeitraegen - der Grund ist oft persoenlich
'DELETE FROM dues_reminders WHERE user_id = ?', // Erinnerungen an Legionsbeitraege (Protokoll, ggf. noch der Text)
'DELETE FROM premade_applications WHERE user_id = ?', // Bewerbungen fuer Premades samt Nachricht
"DELETE FROM tactic_revisions WHERE owner_id = ? AND visibility = 'private'",
"DELETE FROM tactics WHERE created_by = ? AND visibility = 'private'", // Schritte und Zeichnungen per CASCADE
] as $sql) {
$pdo->prepare($sql)->execute([$userId]);
}
// Bilder an Fehlermeldungen zeigen oft den Namen (Screenshot der Website) - Text bleibt
$pdo->exec('DELETE FROM bug_report_images WHERE bug_id IN (' . $in($bugIds) . ')');
// --- Was bleibt: ohne Namen und ohne Hinweise auf die Person ---
$pdo->prepare('UPDATE bug_reports SET user_agent = NULL, screenshot_url = NULL WHERE user_id = ?')->execute([$userId]);
$pdo->prepare('UPDATE shop_orders SET note = NULL WHERE user_id = ?')->execute([$userId]); // oft der Charaktername
$pdo->prepare('UPDATE warehouse_movements SET counterpart_name = NULL WHERE counterpart_user_id = ?')->execute([$userId]);
$pdo->prepare('UPDATE audit_log SET actor_name = ? WHERE user_id = ?')->execute([ACCOUNT_DELETED_NAME, $userId]);
if ($discordId !== '') {
// Anwesenheit bleibt fuer Lumipunkte und Statistik - statt der Discord-ID die Konto-Nummer
// (echte Discord-IDs sind 17-19 Stellen lang, das kann nie kollidieren)
$pdo->prepare('UPDATE raid_attendance SET discord_id = ?, name = ? WHERE discord_id = ?')
->execute([$userId, ACCOUNT_DELETED_NAME, $discordId]);
// Platz als Lead in der Standard-Reihenfolge der Premades
$pdo->prepare('DELETE FROM premade_lead_order WHERE discord_id = ?')->execute([$discordId]);
}
$pdo->prepare(
"UPDATE users SET username = CONCAT('geloescht-', id), display_name = ?, password_hash = ?, password_login = 0,
must_change_password = 0, is_admin = 0, status = 'disabled', session_epoch = session_epoch + 1,
discord_id = NULL, discord_username = NULL, discord_access_token = NULL, discord_refresh_token = NULL,
discord_token_expires = NULL, discord_synced_at = NULL, discord_joined_at = NULL, left_server_at = NULL, consilium_legion_id = NULL,
class_name = NULL, classes = NULL, main_class = NULL, profile_bio = NULL, profile_background = NULL,
gallery_comments_enabled = 0, avatar_filename = NULL, avatar_sync = 0, discord_avatar = NULL,
tour_completed_at = NULL, sidebar_order = NULL, patchnotes_seen = NULL, gallery_seen_at = NULL, raids_seen_at = NULL, announcement_dismissed = NULL,
last_login = NULL, last_seen_at = NULL, deletion_scheduled_at = NULL, deleted_at = NOW()
WHERE id = ?"
)->execute([ACCOUNT_DELETED_NAME, password_hash(bin2hex(random_bytes(24)), PASSWORD_DEFAULT), $userId]);
$pdo->commit();
} catch (Throwable $e) {
$pdo->rollBack();
throw $e;
}
foreach ($files as $path) {
$name = basename($path);
if ($name !== '' && strpbrk($name, '/\\') === false && is_file($path)) {
@unlink($path);
}
}
// Ohne Namen - sonst stuende er wieder im Log
admin_log('🗑️ Konto gelöscht (unkenntlich gemacht)', [
'Konto' => '#' . $userId,
'Bilder gelöscht' => (string) count($files),
'Discord-Bot' => $botStatus,
], 'warning', 'users', $actor);
}
/** Erste Spalte einer Abfrage als Liste von Texten (leere Werte weg). */
function data_rows_column(PDO $pdo, string $sql, array $params): array
{
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
return array_values(array_filter(array_map('strval', $stmt->fetchAll(PDO::FETCH_COLUMN)), static fn (string $v): bool => $v !== ''));
}