LuminaWebsite/includes/account_deletion.php
Maaxxs cd8716e791 Data export and account deletion (anonymization) with a grace period
- Data export (Art. 15/20 GDPR, includes/data_export.php): ZIP with daten.json, LIESMICH.txt and the
  member's own images (avatar, characters, gallery, bug reports). It covers every table related to the
  account plus, via the bot API, raid sign-ups, premades, created events and activity checks. Password hash,
  tokens and player reports (they name the reporters) are left out. The ZIP is written by data_export_zip(),
  so the PHP zip extension is not needed.
- Members find export and deletion under "Mein Profil" at the very bottom in a collapsed "Konto & Daten"
  section (data_export.php, account_delete.php).
- Leadership: new icon "Daten & Löschung" in the user admin (admin/user_export.php, permission users.export).
  It downloads the export or creates a download link for someone without access (datenauskunft.php?t=...,
  7 days, 5 downloads, only the SHA-256 hash stored in data_export_links). The link page shows a button first,
  so link previews don't use up downloads. It also works in maintenance mode.
- Account deletion (includes/account_deletion.php): the account is anonymized instead of removed.
  - Deleted: profile, avatar, characters, gallery, gear sets, private tactics, groups, tokens, calendar
    participations and bug report images.
  - Contributions remain as "Ehemaliges Mitglied" without name or Discord ID.
  - Requested by the member (type LÖSCHEN) or by the leadership (users.delete, also immediately).
  - Executed after 7 days by account_deletion_run_due(); logging in before that cancels it and tells the member.
- The user admin shows "Löschung am ..." and "Gelöscht (unkenntlich)". Privacy policy, README and a
  leadership patch note are updated. Schema v44 (users.deletion_scheduled_at, users.deleted_at, data_export_links).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 17:02:42 +02:00

216 lines
12 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.');
}
/** Faellige Loeschungen ausfuehren - laeuft nebenbei in der bootstrap, hoechstens alle 15 Minuten. */
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()]);
}
}
}
/**
* Macht ein Konto unkenntlich. Loescht Persoenliches samt Dateien, entfernt Namen und Discord-ID
* aus allem, was fuer die Legion bestehen bleibt. Nicht erfasst: Daten beim Discord-Bot, Nachrichten
* im Log-Kanal auf Discord und Details anderer Audit-Log-Eintraege (die 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;
}
$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 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, 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)], '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 !== ''));
}