LuminaWebsite/includes/data_export.php
Maaxxs 1c0109264a Premades: apply for a place in the group or on the reserve, leads accept or decline on the website
Asked for: "füge ein, dass man sich für premaids auch bewerben kann" - every premade with a free place takes
applications unless its lead switches them off, and the bot sends DMs (a new application to the lead, a decline
to the applicant). Later: "man soll sich auch auf reserveplätze bewerben können".

- includes/premade_applications.php: the applications live on the website (premade_applications: premade ID and
  name, lead at that time, applicant, class, wished place group/reserve, message, status open/accepted/declined/
  withdrawn/closed, reason, who decided when; premade_options.applications_open). Rules: one open application
  per premade, at most 3 open in total, 7 days pause after a decline by the same premade, none while invited,
  when full or switched off. premade_applications_sync() matches them with the bot: applications of dissolved
  premades are closed, whoever is in the premade by now counts as accepted, name and lead stay current,
  decisions expire after 30 days.
- premades.php: "Bewerben" under every other premade with a free place. The popup asks for the place (group or
  reserve, taken places greyed out; the group is preselected unless it is full), the class (main preselected)
  and an optional message. "Meine Bewerbungen" lists the own ones with the answer for 14 days, withdrawing
  works there and on the card. Leads and the leadership (premades.manage) see open applications on the card,
  also outside the edit mode, with a "Reserve" tag and a confirmation that names the place; their number shows
  at the menu item "Premades" (premades without a lead count for the leadership). The edit mode switches
  applications off and on.
- premade_action.php: apply (checks the rules and the chosen place again), withdraw, application_accept (the
  bot puts the applicant on the wished place, on the other one if it was taken meanwhile; an open invitation
  becomes the membership on its place), application_decline (optional reason), applications_toggle. An
  invitation to someone with an open application carries its class, also when accepted in Discord.
  Dissolving a premade closes its applications, a new lead takes over the open ones.
- includes/raids_api.php: add_premade_member() passes the wished place and returns the place the bot gave;
  premade_free_slots().
- Bot (already deployed, with a backup): POST /api/premades/{id}/applications sends the DMs (to the lead with
  place, class, message and a link to the card; to the applicant with the reason), POST /members with source
  "application" tells the applicant where they ended up and, when the leadership accepted, the lead;
  add_premade_member() takes the wished place. If the bot cannot send a DM, the application is stored anyway.
- Live updates of the page and the menu number, schema version 62 (tables also in sql/schema.sql).
- Privacy: privacy policy (what is stored, who sees it, for how long), data export section premade_bewerbungen,
  account deletion, data reset area "Premade-Bewerbungen".
- Patch notes and README.

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

531 lines
27 KiB
PHP

<?php
declare(strict_types=1);
/**
* Datenauskunft (Art. 15 und 20 DSGVO): alles, was Website und Discord-Bot zu einem Konto
* gespeichert haben, als ZIP mit daten.json, LIESMICH.txt und den eigenen hochgeladenen Bildern.
*
* - Mitglieder laden ihre Daten selbst herunter: Mein Profil -> data_export.php.
* - Die Leitung (Recht users.export) laedt die Daten eines Mitglieds herunter oder erzeugt einen
* Download-Link fuer jemanden, der sich nicht mehr anmelden kann: admin/user_export.php, der Link
* fuehrt auf datenauskunft.php. Gespeichert wird nur der Hash des Links (wie bei auth_tokens).
*
* Bewusst nicht enthalten: Passwort-Hash sowie Discord- und Login-Schluessel (Sicherheit) und
* Meldungen ueber die Person im Discord-Bot - darin steht, wer gemeldet hat; die gibt die Leitung
* nur auf Anfrage und ohne die Meldenden heraus.
*
* Das ZIP baut data_export_zip() selbst (ohne die PHP-Erweiterung zip, die nicht ueberall da ist).
*/
require_once __DIR__ . '/member_profile.php'; // PROFILE_UPLOAD_DIR (Charaktere, Galerie)
require_once __DIR__ . '/bugs.php'; // BUG_UPLOAD_DIR
require_once __DIR__ . '/raids_api.php';
require_once __DIR__ . '/events_api.php';
require_once __DIR__ . '/activity_api.php';
const DATA_EXPORT_LINK_DAYS = 7;
const DATA_EXPORT_LINK_MAX_DOWNLOADS = 5;
// Eintraege abgelaufener Links bleiben so lange zur Nachvollziehbarkeit, dann werden sie geloescht
const DATA_EXPORT_LINK_KEEP_DAYS = 30;
// So viele der neuesten Aktivitaetschecks werden nach Antworten durchsucht (je Check eine Anfrage beim Bot)
const DATA_EXPORT_ACTIVITY_CHECKS = 60;
/** Abfrage fuer die Auskunft - schlaegt sie fehl (z.B. Tabelle fehlt), bleibt der Abschnitt leer. */
function data_export_rows(string $sql, array $params = []): array
{
try {
$stmt = db()->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll();
} catch (PDOException $e) {
return [];
}
}
/** Spalten entfernen, die nur intern sind (Fremdschluessel aufs eigene Konto, Sortierung). */
function data_export_strip(array $rows, array $columns): array
{
return array_map(static function (array $row) use ($columns): array {
foreach ($columns as $column) {
unset($row[$column]);
}
return $row;
}, $rows);
}
/** Datei aus einem Upload-Ordner (nur ein Dateiname, kein Pfad) oder null. */
function data_export_file(string $dir, ?string $filename): ?string
{
$filename = (string) $filename;
if ($filename === '' || strpbrk($filename, '/\\') !== false || !is_file($dir . $filename)) {
return null;
}
return $dir . $filename;
}
/**
* Konto fuer die Auskunft durch die Leitung - null, wenn es fehlt oder geschuetzt ist
* (Administratoren nur mit users.admin, Entwickler nur fuer Entwickler - wie in der Benutzerverwaltung).
*/
function data_export_target(int $userId): ?array
{
$rows = data_export_rows('SELECT id, username, display_name, status, is_admin, discord_id, avatar_filename FROM users WHERE id = ?', [$userId]);
$target = $rows[0] ?? null;
if ($target === null) {
return null;
}
if (!empty($target['is_admin']) && !user_has_permission('users.admin')) {
return null;
}
if (is_developer($target) && !is_developer(current_user())) {
return null;
}
return $target;
}
/**
* Alle Daten eines Kontos.
*
* @return array{data: array<string, mixed>, files: array<string, string>, name: string} files: Pfad im ZIP => Datei
* @throws RuntimeException
*/
function data_export_collect(int $userId): array
{
$account = data_export_rows('SELECT * FROM users WHERE id = ?', [$userId])[0] ?? null;
if ($account === null) {
throw new RuntimeException('Das Konto gibt es nicht (mehr).');
}
// Zugangsdaten gehoeren nicht in eine Datei, die man herumschickt
foreach (['password_hash', 'discord_access_token', 'discord_refresh_token', 'discord_token_expires', 'session_epoch', 'discord_avatar'] as $secret) {
unset($account[$secret]);
}
$discordId = (string) ($account['discord_id'] ?? '');
$account['discord_id'] = $discordId !== '' ? $discordId : null; // als Text - 19 Stellen sind fuer JSON-Zahlen zu lang
$files = [];
$avatar = data_export_file(__DIR__ . '/../assets/uploads/avatars/', $account['avatar_filename'] ?? null);
if ($avatar !== null) {
$account['datei_im_export'] = 'bilder/profilbild.' . strtolower(pathinfo($avatar, PATHINFO_EXTENSION));
$files[$account['datei_im_export']] = $avatar;
}
$characters = data_export_strip(data_export_rows('SELECT * FROM member_characters WHERE user_id = ? ORDER BY sort_order, id', [$userId]), ['user_id']);
foreach ($characters as &$character) {
// Berufe des Charakters (includes/professions.php), die Sammel-Spezialisierung steht in "gathering"
$character['berufe'] = data_export_rows('SELECT profession, stage, level, is_main FROM character_professions WHERE character_id = ?', [$character['id']]);
foreach (['portrait_filename' => 'portrait', 'image_filename' => 'bild'] as $column => $suffix) {
$path = data_export_file(PROFILE_UPLOAD_DIR, $character[$column] ?? null);
if ($path !== null) {
$character['datei_' . $suffix] = 'bilder/charaktere/' . $character['id'] . '-' . $suffix . '.' . strtolower(pathinfo($path, PATHINFO_EXTENSION));
$files[$character['datei_' . $suffix]] = $path;
}
}
}
unset($character);
$gallery = data_export_strip(data_export_rows('SELECT * FROM member_gallery WHERE user_id = ? ORDER BY sort_order, id', [$userId]), ['user_id']);
foreach ($gallery as &$picture) {
$path = data_export_file(PROFILE_UPLOAD_DIR, $picture['filename'] ?? null);
if ($path !== null) {
$picture['datei_im_export'] = 'bilder/galerie/' . $picture['id'] . '.' . strtolower(pathinfo($path, PATHINFO_EXTENSION));
$files[$picture['datei_im_export']] = $path;
}
}
unset($picture);
$gearSets = data_export_strip(data_export_rows('SELECT * FROM gear_sets WHERE user_id = ? ORDER BY sort_order, id', [$userId]), ['user_id']);
foreach ($gearSets as &$set) {
$set['ausruestung'] = data_export_rows(
'SELECT s.slot, i.name AS gegenstand, s.item_id, s.enchant, s.exceed, s.soul_imprint, s.manastones, s.godstone
FROM gear_set_slots s LEFT JOIN gear_items i ON i.id = s.item_id WHERE s.set_id = ? ORDER BY s.slot',
[$set['id']]
);
$set['skills'] = data_export_rows(
"SELECT k.id AS skill_id, COALESCE(NULLIF(k.name_de, ''), k.name) AS skill, k.kind, s.level, s.specs
FROM gear_set_skills s JOIN gear_skills k ON k.id = s.skill_id WHERE s.set_id = ? ORDER BY k.kind, k.sort_order",
[$set['id']]
);
$set['planung'] = [];
foreach (data_export_rows('SELECT section, data, updated_at FROM gear_set_plans WHERE set_id = ?', [$set['id']]) as $plan) {
$set['planung'][$plan['section']] = json_decode((string) $plan['data'], true) ?? $plan['data'];
}
}
unset($set);
$bugs = data_export_strip(data_export_rows('SELECT * FROM bug_reports WHERE user_id = ? ORDER BY id', [$userId]), ['user_id', 'handled_by']);
foreach ($bugs as &$bug) {
$bug['bilder'] = [];
foreach (data_export_rows('SELECT filename FROM bug_report_images WHERE bug_id = ? ORDER BY id', [$bug['id']]) as $i => $image) {
$path = data_export_file(BUG_UPLOAD_DIR, $image['filename']);
if ($path !== null) {
$name = 'bilder/fehlermeldungen/' . $bug['id'] . '-' . ($i + 1) . '.' . strtolower(pathinfo($path, PATHINFO_EXTENSION));
$bug['bilder'][] = $name;
$files[$name] = $path;
}
}
}
unset($bug);
$points = data_export_rows(
'SELECT a.awarded_at, a.category, a.title, a.note, e.points
FROM contribution_entries e JOIN contribution_awards a ON a.id = e.award_id WHERE e.user_id = ? ORDER BY a.awarded_at, a.id',
[$userId]
);
$data = [
'auskunft' => [
'erstellt_am' => date('Y-m-d H:i:s'),
'zeitzone' => date_default_timezone_get(),
'website' => site_url('/'),
'verantwortlich' => legal_operator()['name'],
'hinweis' => 'Datenauskunft nach Art. 15 und Art. 20 DSGVO. Was in den einzelnen Abschnitten steht, erklärt LIESMICH.txt.',
],
'konto' => $account,
'gruppen' => array_column(data_export_rows(
"SELECT COALESCE(NULLIF(r.display_name, ''), r.name) AS gruppe FROM user_roles ur JOIN roles r ON r.id = ur.role_id WHERE ur.user_id = ? ORDER BY r.name",
[$userId]
), 'gruppe'),
'einzelrechte' => data_export_rows(
'SELECT p.`key` AS berechtigung, p.description AS beschreibung, up.created_at AS vergeben_am
FROM user_permissions up JOIN permissions p ON p.id = up.permission_id WHERE up.user_id = ? ORDER BY p.`key`',
[$userId]
),
'charaktere' => $characters,
'galerie' => $gallery,
'kommentare' => data_export_strip(data_export_rows('SELECT * FROM gallery_comments WHERE author_id = ? ORDER BY id', [$userId]), ['author_id']),
'reaktionen' => data_export_strip(data_export_rows('SELECT * FROM reactions WHERE user_id = ? ORDER BY id', [$userId]), ['user_id', 'id']),
'gemeldete_inhalte' => data_export_strip(data_export_rows('SELECT * FROM content_reports WHERE reporter_id = ? ORDER BY id', [$userId]), ['reporter_id']),
'gear_sets' => $gearSets,
'kalender_termine' => data_export_strip(data_export_rows('SELECT * FROM calendar_entries WHERE user_id = ? ORDER BY starts_at', [$userId]), ['user_id']),
'kalender_teilnahmen' => data_export_rows(
'SELECT e.id AS termin_id, e.title, e.starts_at, p.created_at AS angemeldet_am
FROM calendar_participants p JOIN calendar_entries e ON e.id = p.entry_id WHERE p.user_id = ? ORDER BY e.starts_at',
[$userId]
),
'lumipunkte' => ['summe' => array_sum(array_map('intval', array_column($points, 'points'))), 'verlauf' => $points],
'shop_antraege' => data_export_strip(data_export_rows('SELECT * FROM shop_orders WHERE user_id = ? ORDER BY id', [$userId]), ['user_id', 'decided_by', 'delivered_by', 'award_id', 'warehouse_movement_id']),
'premade_bewerbungen' => data_export_rows(
'SELECT premade_name, class_name, IF(reserve, \'Reserve\', \'Gruppe\') AS platz, message, status, reason, created_at, decided_at FROM premade_applications WHERE user_id = ? ORDER BY created_at',
[$userId]
),
'legionsbeitraege' => [
'bezahlt' => data_export_rows(
'SELECT c.starts_on AS zyklus_von, c.ends_on AS zyklus_bis, c.amount AS kina, e.updated_at AS abgehakt_am
FROM dues_entries e JOIN dues_cycles c ON c.id = e.cycle_id WHERE e.user_id = ? ORDER BY c.starts_on',
[$userId]
),
'befreiungen' => data_export_rows(
'SELECT starts_on AS von, ends_on AS bis, note AS grund, created_at AS eingetragen_am FROM dues_exemptions WHERE user_id = ? ORDER BY starts_on',
[$userId]
),
],
'lagerhaus' => data_export_rows(
"SELECT m.occurred_at, IF(m.direction = 'in', 'von dir an die Legion', 'von der Legion an dich') AS richtung,
i.name AS gegenstand, m.quantity, m.note
FROM warehouse_movements m JOIN warehouse_items i ON i.id = m.item_id WHERE m.counterpart_user_id = ? ORDER BY m.occurred_at",
[$userId]
),
'raid_anwesenheit' => $discordId === '' ? [] : array_map(static function (array $row): array {
$row['raid_id'] = (string) $row['raid_id'];
return $row;
}, data_export_rows('SELECT raid_id, name, status, updated_at FROM raid_attendance WHERE discord_id = ? ORDER BY updated_at', [$discordId])),
'raids_als_raid_lead' => array_map(static fn (array $row): string => (string) $row['raid_id'],
data_export_rows('SELECT raid_id FROM raid_settings WHERE lead_user_id = ? ORDER BY raid_id', [$userId])),
'wiki' => [
'mitwirkend_seit' => data_export_rows('SELECT added_at FROM wiki_contributors WHERE user_id = ?', [$userId])[0]['added_at'] ?? null,
'angelegte_seiten' => data_export_rows('SELECT title, slug, created_at FROM wiki_pages WHERE created_by = ? ORDER BY created_at', [$userId]),
'bearbeitungen' => data_export_rows(
'SELECT r.title AS titel_damals, p.title AS seite_heute, r.summary, r.created_at
FROM wiki_revisions r LEFT JOIN wiki_pages p ON p.id = r.page_id WHERE r.edited_by = ? ORDER BY r.created_at',
[$userId]
),
],
'taktiken' => data_export_rows('SELECT id, map_slug, name, description, visibility, highlight, created_at, updated_at FROM tactics WHERE created_by = ? ORDER BY id', [$userId]),
'fehlermeldungen' => $bugs,
'angemeldete_geraete' => data_export_rows('SELECT login_method, user_agent, created_at, last_used_at, expires_at FROM auth_tokens WHERE user_id = ? ORDER BY created_at', [$userId]),
// Verwaltungsaktionen, die das Konto selbst ausgefuehrt hat - ohne Details, darin stehen oft andere Mitglieder
'protokoll_eigene_aktionen' => data_export_rows('SELECT created_at, area, title, ip FROM audit_log WHERE user_id = ? ORDER BY id', [$userId]),
'discord_bot' => data_export_bot($discordId),
];
return ['data' => $data, 'files' => $files, 'name' => (string) $account['username']];
}
/**
* Was der Discord-Bot zur Discord-ID gespeichert hat - ueber dieselbe Bot-API wie die Seiten
* Raids, Premades, Events und Aktivitaetscheck. Ist der Bot nicht erreichbar, steht das im Abschnitt.
*/
function data_export_bot(string $discordId): array
{
if ($discordId === '') {
return ['hinweis' => 'Kein Discord-Konto verknüpft - beim Discord-Bot ist zu diesem Konto nichts gespeichert.'];
}
$out = [
'hinweis' => 'Meldungen über dich (Reports) sind nicht enthalten, weil darin steht, wer gemeldet hat. Auf Anfrage bekommst du sie von der Legionsleitung ohne die Namen der Meldenden; der Bot löscht sie nach 10 Tagen.',
'raid_anmeldungen' => [],
'premades' => [],
'events_angelegt' => [],
'aktivitaetschecks' => [],
];
$errors = [];
try {
foreach (fetch_raids('all') as $raid) {
foreach ((array) ($raid['signups'] ?? []) as $signup) {
if ((string) ($signup['user_id'] ?? '') === $discordId) {
$out['raid_anmeldungen'][] = [
'raid_id' => (string) ($raid['raid_id'] ?? ''),
'titel' => $raid['title'] ?? '',
'termin' => $raid['date'] ?? (isset($raid['timestamp']) ? date('Y-m-d H:i', (int) $raid['timestamp']) : null),
'name' => $signup['name'] ?? '',
'klasse' => $signup['class'] ?? '',
'gruppe' => $signup['group'] ?? null,
'abgemeldet' => (int) ($signup['group'] ?? 0) === -1,
'raid_archiviert' => !empty($raid['archived']),
];
}
}
}
} catch (Throwable $e) {
$errors[] = 'Raids: ' . $e->getMessage();
}
try {
foreach (fetch_premades() as $premade) {
$isOwner = (string) ($premade['owner_id'] ?? '') === $discordId;
$mine = null; // nur der eigene Eintrag, nicht die anderen Mitglieder
foreach ((array) ($premade['members'] ?? []) as $member) {
if ((string) ($member['user_id'] ?? '') === $discordId) {
$mine = $member;
}
}
if ($isOwner || $mine !== null) {
$out['premades'][] = [
'id' => $premade['id'] ?? null,
'name' => $premade['name'] ?? '',
'rolle' => $isOwner ? 'Gründer' : 'Mitglied',
'status' => $mine['status'] ?? null,
'platz' => !empty($mine['reserve']) ? 'Reserve' : 'Gruppe',
'klasse' => $mine['class'] ?? ($isOwner ? ($premade['owner_class'] ?? null) : null),
];
}
}
} catch (Throwable $e) {
$errors[] = 'Premades: ' . $e->getMessage();
}
try {
foreach (fetch_events() as $event) {
if ((string) ($event['created_by'] ?? '') === $discordId) {
$out['events_angelegt'][] = ['name' => $event['name'] ?? '', 'nachricht' => $event['message'] ?? '', 'kanal' => $event['channel_name'] ?? null,
'naechster_termin' => $event['next_run'] ?? null, 'wiederholung_sekunden' => $event['interval_seconds'] ?? null];
}
}
} catch (Throwable $e) {
$errors[] = 'Events: ' . $e->getMessage();
}
try {
$checks = activity_api_request('GET', '', ['guild_id' => events_guild_id()])['checks'] ?? [];
usort($checks, static fn (array $a, array $b): int => (int) ($b['check_id'] ?? 0) <=> (int) ($a['check_id'] ?? 0));
foreach (array_slice($checks, 0, DATA_EXPORT_ACTIVITY_CHECKS) as $check) {
$detail = isset($check['responses']) ? $check : (activity_api_request('GET', '/' . (int) ($check['check_id'] ?? 0))['check'] ?? []);
$answer = null;
foreach ((array) ($detail['responses'] ?? []) as $response) {
if ((string) ($response['user_id'] ?? '') === $discordId) {
unset($response['user_id']);
$answer = $response;
}
}
if ($answer === null) {
$waiting = array_merge((array) ($detail['pending'] ?? []), (array) ($detail['result']['missing'] ?? []));
foreach ($waiting as $row) {
if ((string) ($row['user_id'] ?? '') === $discordId) {
$answer = ['status' => ($detail['status'] ?? '') === 'open' ? 'noch keine Antwort' : 'keine Antwort'];
}
}
}
if ($answer !== null) {
$out['aktivitaetschecks'][] = ['check_id' => $detail['check_id'] ?? null, 'titel' => $detail['title'] ?? '', 'frist' => $detail['deadline'] ?? null,
'status_check' => $detail['status'] ?? null, 'deine_antwort' => $answer];
}
}
} catch (Throwable $e) {
$errors[] = 'Aktivitätschecks: ' . $e->getMessage();
}
if ($errors) {
$out['fehler'] = array_merge(['Der Discord-Bot war nicht vollständig erreichbar - diese Teile fehlen. Lade die Auskunft später noch einmal herunter.'], $errors);
}
return $out;
}
/** Erklaerung, die als LIESMICH.txt im ZIP liegt. */
function data_export_readme(array $export): string
{
$lines = [
'Datenauskunft - Lumina Ascendens',
'Erstellt am ' . date('d.m.Y \u\m H:i \U\h\r'),
'',
'Diese Datei gehört zu deiner Datenauskunft nach Art. 15 und Art. 20 DSGVO. Sie enthält alles, was die Website',
'der Legion und unser Discord-Bot zu deinem Konto gespeichert haben.',
'',
'daten.json - alle Angaben in einem gängigen, maschinenlesbaren Format (JSON, UTF-8). Die Abschnitte:',
' konto dein Konto: Name, Discord-Verknüpfung, Klassen, Profiltext, Anmeldungen, Einstellungen',
' gruppen deine Berechtigungsgruppen',
' einzelrechte Berechtigungen, die dir einzeln (nicht über eine Gruppe) gegeben wurden',
' charaktere, galerie deine Charaktere (samt Berufen und Sammel-Spezialisierung) und Galeriebilder - auch eigene',
' Profil-Hintergründe und hochgeladene Premade-Banner (premade_id) - mit den Bildern im Ordner bilder/',
' kommentare, reaktionen was du unter Galeriebildern geschrieben bzw. mit welchem Emoji du reagiert hast',
' gemeldete_inhalte Inhalte, die du gemeldet hast',
' gear_sets deine Ausrüstungssets samt Skills und Planung',
' kalender_* Termine, die du eingetragen hast, und deine Teilnahmen',
' lumipunkte Punktestand und jede Vergabe bzw. jeder Abzug',
' shop_antraege deine Anträge im Lumishop',
' premade_bewerbungen deine Bewerbungen für Premades mit Klasse, Platz, Nachricht und Antwort',
' legionsbeitraege Zyklen, in denen du deinen Legionsbeitrag (Kina) bezahlt hast, und Befreiungen davon',
' lagerhaus Übergaben zwischen dir und der Legion',
' raid_anwesenheit deine eingetragene Anwesenheit bei Raids',
' wiki, taktiken Wiki-Seiten und -Bearbeitungen sowie Taktiken von dir',
' fehlermeldungen deine Fehlermeldungen samt Bildern und Browser-Kennung',
' angemeldete_geraete wo du über „Angemeldet bleiben“ angemeldet bist (Browser-Kennung)',
' protokoll_eigene_aktionen Verwaltungsaktionen, die du ausgeführt hast (Audit-Log, IP gekürzt)',
' discord_bot beim Discord-Bot: Raid-Anmeldungen, Premades, von dir angelegte Events, Aktivitätschecks',
'',
'Nicht enthalten sind Passwort-Hash und Zugangsschlüssel (aus Sicherheitsgründen) sowie Meldungen über dich im',
'Discord-Bot, weil darin steht, wer gemeldet hat. Die bekommst du auf Anfrage ohne die Namen der Meldenden.',
'',
'Zeitangaben sind deutsche Zeit (' . date_default_timezone_get() . ').',
'Fragen, Berichtigung oder Löschung: siehe ' . site_url('/datenschutz.php') . ' und ' . site_url('/impressum.php'),
];
if ($export['files']) {
$lines[] = '';
$lines[] = 'Enthaltene Bilder: ' . count($export['files']);
}
return implode("\r\n", $lines) . "\r\n";
}
/** DOS-Zeit und -Datum fuer ZIP-Eintraege. */
function data_export_dos_time(int $timestamp): array
{
$d = getdate($timestamp);
return [
($d['hours'] << 11) | ($d['minutes'] << 5) | intdiv($d['seconds'], 2),
((max(1980, $d['year']) - 1980) << 9) | ($d['mon'] << 5) | $d['mday'],
];
}
/**
* Baut ein ZIP in einen temporaeren Stream (grosse Archive landen auf der Platte statt im Speicher).
* Texte werden komprimiert, Bilder unveraendert gespeichert (sind schon komprimiert).
*
* @param array<string, string> $texts Name im ZIP => Inhalt
* @param array<string, string> $files Name im ZIP => Datei auf dem Server
* @return resource
*/
function data_export_zip(array $texts, array $files)
{
$out = fopen('php://temp/maxmemory:' . (8 * 1024 * 1024), 'w+b');
[$time, $date] = data_export_dos_time(time());
$central = '';
$count = 0;
$add = static function (string $name, string $content, bool $deflate) use ($out, $time, $date, &$central, &$count): void {
$crc = crc32($content);
$packed = $deflate ? (string) gzdeflate($content, 6) : $content;
$method = $deflate ? 8 : 0;
$flags = 0x0800; // Dateinamen in UTF-8
$offset = (int) ftell($out);
fwrite($out, pack('VvvvvvVVVvv', 0x04034b50, 20, $flags, $method, $time, $date, $crc, strlen($packed), strlen($content), strlen($name), 0) . $name);
fwrite($out, $packed);
$central .= pack('VvvvvvvVVVvvvvvVV', 0x02014b50, 20, 20, $flags, $method, $time, $date, $crc, strlen($packed), strlen($content),
strlen($name), 0, 0, 0, 0, 0, $offset) . $name;
$count++;
};
foreach ($texts as $name => $content) {
$add($name, $content, true);
}
foreach ($files as $name => $path) {
$content = @file_get_contents($path);
if ($content !== false) {
$add($name, $content, false);
}
}
$centralOffset = (int) ftell($out);
fwrite($out, $central);
fwrite($out, pack('VvvvvVVv', 0x06054b50, 0, 0, $count, $count, strlen($central), $centralOffset, 0));
rewind($out);
return $out;
}
/** Stellt die Auskunft zusammen und schickt sie als ZIP-Download. Beendet den Aufruf. */
function data_export_send(int $userId): void
{
$export = data_export_collect($userId);
$json = (string) json_encode($export['data'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
$zip = data_export_zip(['daten.json' => $json, 'LIESMICH.txt' => data_export_readme($export)], $export['files']);
$slug = trim((string) preg_replace('/[^a-z0-9_-]+/i', '-', $export['name']), '-') ?: 'konto';
session_write_close();
while (ob_get_level() > 0) {
ob_end_clean();
}
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="lumina-ascendens-daten-' . $slug . '-' . date('Y-m-d') . '.zip"');
header('Content-Length: ' . (int) (fstat($zip)['size'] ?? 0));
header('Cache-Control: no-store');
header('X-Content-Type-Options: nosniff');
fpassthru($zip);
fclose($zip);
exit;
}
// ---- Download-Links fuer Mitglieder ohne Zugang ----
/**
* Neuer Link fuer ein Konto. Die Adresse steht nirgends gespeichert (nur ihr Hash) - wer den Link
* verschicken will, muss ihn gleich kopieren.
*
* @return array{url: string, expires_at: string}
*/
function data_export_link_create(int $userId, int $createdBy): array
{
data_export_links_cleanup();
$token = bin2hex(random_bytes(24));
$expires = date('Y-m-d H:i:s', time() + DATA_EXPORT_LINK_DAYS * 86400);
db()->prepare('INSERT INTO data_export_links (user_id, token_hash, created_by, expires_at) VALUES (?, ?, ?, ?)')
->execute([$userId, hash('sha256', $token), $createdBy, $expires]);
return ['url' => site_url('/datenauskunft.php?t=' . $token), 'expires_at' => $expires];
}
/** Gueltiger Link zu einem Token (nicht abgelaufen, nicht widerrufen, Downloads uebrig) oder null. */
function data_export_link_find(string $token): ?array
{
if (!preg_match('/^[0-9a-f]{48}$/', $token)) {
return null;
}
$link = data_export_rows('SELECT * FROM data_export_links WHERE token_hash = ?', [hash('sha256', $token)])[0] ?? null;
return $link !== null && data_export_link_status($link) === 'aktiv' ? $link : null;
}
/** aktiv, widerrufen, aufgebraucht oder abgelaufen. */
function data_export_link_status(array $link): string
{
if ($link['revoked_at'] !== null) {
return 'widerrufen';
}
if ((int) $link['downloads'] >= DATA_EXPORT_LINK_MAX_DOWNLOADS) {
return 'aufgebraucht';
}
return strtotime((string) $link['expires_at']) > time() ? 'aktiv' : 'abgelaufen';
}
/** Eintraege von Links loeschen, die seit DATA_EXPORT_LINK_KEEP_DAYS abgelaufen sind. */
function data_export_links_cleanup(): void
{
try {
db()->prepare('DELETE FROM data_export_links WHERE expires_at < ?')
->execute([date('Y-m-d H:i:s', time() - DATA_EXPORT_LINK_KEEP_DAYS * 86400)]);
} catch (PDOException $e) {
// Tabelle kommt erst mit dem naechsten Schema-Abgleich
}
}