LuminaWebsite/includes/account_deletion.php
Maaxxs 592269d300 Permissions per person: grant single permissions to users in addition to their groups
In the user form (admin/user_form.php) a new section "Einzelne Berechtigungen" lists all
permissions, with the group-assign rights (roles.assign.<ID>) shown by group name as in the role
form. It opens by itself when the user already has some. A shield marks what the user already
gets through one of the ticked groups; the tooltip says who granted a permission and when.

- New table user_permissions (user, permission, granted_by, created_at; schema 52, also in
  sql/schema.sql). user_has_permission() now resolves through user_permission_keys() (groups UNION
  direct permissions, falls back to groups only while the table is missing), and
  discord_ids_with_permission() and the raids.manage recipients in bot_api.php include direct
  permissions too.
- New core permission users.permissions: only with it can someone grant or revoke direct
  permissions, and only ones they have themselves (current_user_permission_ids()); others are
  greyed out and ignored on the server even if submitted. Your own direct permissions can only be
  changed by someone else (except developers). Without the right the section is a read-only list.
  On update, groups with roles.manage get users.permissions.
- Saving applies only the changes, so the remaining entries keep who granted them and when.
  Grants and revokes go into the audit log ("Einzelrechte erteilt/entzogen/jetzt").
- User list: "+N Einzelrechte" badge next to the groups (title lists them), searchable; the live
  fingerprint of the page includes user_permissions.
- Data export gets a section "einzelrechte", account deletion removes them, and the privacy
  policy mentions both. Patch notes, README and the roles page intro updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 02:20:58 +02:00

331 lines
16 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 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 data_export_links WHERE user_id = ?',
"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]);
}
$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,
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 !== ''));
}