LuminaWebsite/tactics_api.php
Maaxxs df656209c9 Map tactics live: strokes appear for everyone while they are drawn, several people can draw at once
- Whoever has a tactic open sees the strokes of the others while they are being drawn (with the
  name at the pen tip); saved and erased shapes appear at once, and after changes to steps or the
  tactic the map reloads by itself. Several people can draw in parallel, also in the same step.
- The panel shows who is in the tactic (a click jumps to their step), dots in the step list show
  who is where and blink while someone draws there; the step bar shows "✏️ Name" for the shown step.
- The Discord bot relays it (live_tactics.py in the bot repo, only in memory): tactics_api.php
  issues a ticket (action live_token: account, display name, tactic, may draw, 30 minutes, signed
  with raids_api.key via HMAC-SHA256, tactic_live_ticket() in includes/tactics.php). The browser
  receives via Server-Sent Events and sends batched strokes (at most every 70 ms), saved/removed
  shapes, changes and its own step via POST (assets/map/js/services/TacticLiveService.js).
  Only who may edit the tactic may draw live. Saving still happens only on the website.
- On a lost connection the panel says so, the map reconnects with a fresh ticket (backoff up to
  15 s), reloads the tactic and hands in what was drawn meanwhile. Reloads triggered by the live
  view keep the current state on network errors instead of closing the tactic.
- Optional config raids_api.live_url for a public bot address that differs from raids_api.url.
- Privacy policy (live view: direct connection to the bot server, what others see, nothing stored),
  patch notes and README updated.

Needs the matching bot update (live_tactics.py, api.py, main.py), deployed on 2026-09-25.

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

581 lines
30 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/tactics.php';
// Wird vom Karten-Viewer im iframe per fetch() aufgerufen - deshalb Fehler immer als JSON
// statt Weiterleitung auf die Login-Seite bzw. HTML-Fehlerseite.
if (!current_user()) {
http_response_code(401);
json_response(false, 'Bitte neu anmelden.');
}
if (!user_has_permission('map.view')) {
http_response_code(403);
json_response(false, 'Dir fehlt die Berechtigung, die Karte zu sehen.');
}
$userId = (int) current_user()['id'];
try {
$missing = tactics_missing_tables();
} catch (Throwable $e) {
json_response(false, 'Datenbankfehler: ' . $e->getMessage());
}
if (!empty($missing)) {
json_response(false, 'Die Tabellen für Taktiken fehlen noch - sie lassen sich auf der Kartenseite anlegen.', [
'missing_tables' => $missing,
]);
}
// ---- Lesen ----
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$slug = (string) ($_GET['map'] ?? '');
if (!tactics_valid_map($slug)) {
json_response(false, 'Unbekannte Karte.');
}
json_response(true, '', [
// Eigene Taktiken darf jeder mit map.view anlegen; was bei fremden geht, steht pro Taktik.
'can_create' => true,
'can_highlight' => user_has_permission('map.tactics.highlight'),
'tactics' => tactics_for_map($slug, $userId),
// Papierkorb: nur, was dieses Konto wiederherstellen darf
'deleted' => tactics_deleted_for_map($slug, $userId),
]);
}
// ---- Schreiben ----
$input = read_json_body();
verify_csrf_token($input['csrf_token'] ?? '');
$action = (string) ($input['action'] ?? '');
/** Liest einen Text aus dem Request, gekuerzt und auf die Hoechstlaenge geprueft. */
function tactic_text(array $input, string $key, int $max, string $label, bool $required): string
{
$value = trim((string) ($input[$key] ?? ''));
if ($required && $value === '') {
json_response(false, "Bitte $label angeben.");
}
if (mb_strlen($value) > $max) {
json_response(false, ucfirst($label) . " darf höchstens $max Zeichen lang sein.");
}
return $value;
}
/**
* Laedt eine Taktik, die das Konto sehen darf ($forEdit: auch bearbeiten darf) - sonst endet
* die Anfrage mit einer Fehlermeldung. Private Taktiken anderer gelten als nicht vorhanden.
*/
function tactic_load(int $tacticId, int $userId, bool $forEdit = true): array
{
$stmt = db()->prepare(
'SELECT id, map_slug, name, description, visibility, highlight, created_by FROM tactics WHERE id = ?'
);
$stmt->execute([$tacticId]);
$tactic = $stmt->fetch();
if (!$tactic || !tactic_can_view($tactic, $userId)) {
json_response(false, 'Diese Taktik gibt es nicht mehr - bitte die Seite neu laden.');
}
if ($forEdit && !tactic_can_edit($tactic, $userId)) {
json_response(false, ($tactic['highlight'] ?? '') === 'official'
? 'Offizielle Taktiken darf außer dem Ersteller nur bearbeiten, wer Taktiken hervorheben darf.'
: 'Diese Taktik darfst du nicht bearbeiten - nur der Ersteller und bei öffentlichen Taktiken die Strategen.');
}
return $tactic;
}
/**
* Sucht einen Schritt, prueft das Bearbeitungsrecht an seiner Taktik und liefert ihn - unter
* 'tactic' die Taktik (wie von tactic_load).
*/
function tactic_step_owner(int $stepId, int $userId): array
{
$stmt = db()->prepare('SELECT id, tactic_id, title, sort_order FROM tactic_steps WHERE id = ?');
$stmt->execute([$stepId]);
$step = $stmt->fetch();
if (!$step) {
json_response(false, 'Diesen Schritt gibt es nicht mehr - bitte die Seite neu laden.');
}
$step['tactic'] = tactic_load((int) $step['tactic_id'], $userId);
return $step;
}
/**
* Ins Audit-/Discord-Log gehoeren nur oeffentliche Taktiken und Eingriffe in fremde - private
* Entwuerfe einzelner Mitglieder wuerden den Kanal nur fluten.
*/
function tactic_should_log(array $tactic, int $userId): bool
{
return ($tactic['visibility'] ?? '') === 'public' || (int) ($tactic['created_by'] ?? 0) !== $userId;
}
function tactic_visibility_label(string $visibility): string
{
return $visibility === 'public' ? 'öffentlich' : 'privat (nur für den Ersteller)';
}
try {
switch ($action) {
// ---- Taktiken ----
case 'tactic_create':
$slug = (string) ($input['map'] ?? '');
if (!tactics_valid_map($slug)) {
json_response(false, 'Unbekannte Karte.');
}
$name = tactic_text($input, 'name', 120, 'einen Namen', true);
$description = tactic_text($input, 'description', 5000, 'die Beschreibung', false);
$visibility = in_array($input['visibility'] ?? '', TACTIC_VISIBILITIES, true) ? (string) $input['visibility'] : 'private';
$pdo = db();
$pdo->beginTransaction();
$pdo->prepare('INSERT INTO tactics (map_slug, name, description, visibility, created_by) VALUES (?, ?, ?, ?, ?)')
->execute([$slug, $name, $description, $visibility, $userId]);
$tacticId = (int) $pdo->lastInsertId();
// Ohne Titel - angezeigt wird dann "Schritt 1".
$stepId = tactic_append_step($tacticId, '');
$pdo->commit();
// Nur ganze, oeffentliche Taktiken ins Discord-Log - einzelne Zeichnungen und private
// Entwuerfe wuerden den Kanal fluten.
if ($visibility === 'public') {
admin_log('🗺️ Öffentliche Taktik angelegt', [
'Taktik' => $name,
'Karte' => $slug,
'Beschreibung' => mb_strimwidth($description, 0, 300, '…'),
], 'success');
}
json_response(true, 'Taktik angelegt.', ['tactic_id' => $tacticId, 'step_id' => $stepId]);
case 'tactic_copy':
// Kopieren darf jeder, der die Taktik sehen kann - so lassen sich auch offizielle als
// eigene Vorlage weiterfuehren. Die Kopie gehoert dem Kopierenden, ist standardmaessig
// privat und nicht hervorgehoben; die Vorlage bleibt unveraendert.
$source = tactic_load((int) ($input['tactic_id'] ?? 0), $userId, false);
$name = tactic_text($input, 'name', 120, 'einen Namen', false);
if ($name === '') {
$name = mb_substr('Kopie von ' . $source['name'], 0, 120);
}
$visibility = in_array($input['visibility'] ?? '', TACTIC_VISIBILITIES, true) ? (string) $input['visibility'] : 'private';
$pdo = db();
$pdo->beginTransaction();
$pdo->prepare('INSERT INTO tactics (map_slug, name, description, visibility, created_by) VALUES (?, ?, ?, ?, ?)')
->execute([(string) $source['map_slug'], $name, (string) ($source['description'] ?? ''), $visibility, $userId]);
$copyId = (int) $pdo->lastInsertId();
// Schritt fuer Schritt in derselben Reihenfolge, die Zeichnungen wie bei "+ Kopie dieses Schritts"
$sourceSteps = $pdo->prepare('SELECT id, title, description FROM tactic_steps WHERE tactic_id = ? ORDER BY sort_order, id');
$sourceSteps->execute([(int) $source['id']]);
$copyShapes = $pdo->prepare(
'INSERT INTO tactic_shapes (step_id, shape_type, label, color, width, points, created_by)
SELECT ?, shape_type, label, color, width, points, ? FROM tactic_shapes WHERE step_id = ? ORDER BY id'
);
$stepCount = 0;
foreach ($sourceSteps->fetchAll() as $sourceStep) {
$stepId = tactic_append_step($copyId, (string) $sourceStep['title'], (string) ($sourceStep['description'] ?? ''));
$copyShapes->execute([$stepId, $userId, (int) $sourceStep['id']]);
$stepCount++;
}
if ($stepCount === 0) {
tactic_append_step($copyId, '');
$stepCount = 1;
}
$pdo->commit();
// Private Kopien sind Entwuerfe einzelner Mitglieder - nur oeffentliche ins Log.
if ($visibility === 'public') {
admin_log('📋 Taktik kopiert', [
'Taktik' => $name,
'Vorlage' => (string) $source['name'],
'Karte' => (string) $source['map_slug'],
'Ersteller der Vorlage' => $source['created_by'] !== null ? admin_log_user((int) $source['created_by']) : '',
'Schritte' => (string) $stepCount,
], 'success');
}
json_response(true, 'Taktik kopiert.', ['tactic_id' => $copyId]);
case 'tactic_update':
$tacticId = (int) ($input['tactic_id'] ?? 0);
$old = tactic_load($tacticId, $userId);
$name = tactic_text($input, 'name', 120, 'einen Namen', true);
$description = tactic_text($input, 'description', 5000, 'die Beschreibung', false);
// Die Sichtbarkeit bestimmt nur der Ersteller - die Leitung kann eine fremde Taktik
// nicht auf privat stellen (sie waere dann fuer alle ausser ihm weg).
$visibility = (string) $old['visibility'];
if ((int) $old['created_by'] === $userId && in_array($input['visibility'] ?? '', TACTIC_VISIBILITIES, true)) {
$visibility = (string) $input['visibility'];
}
// Eine hervorgehobene Taktik darf auch der Ersteller nicht einfach verschwinden lassen.
if ($visibility !== $old['visibility'] && !tactic_can_change_visibility($old, $userId)) {
json_response(false, 'Hervorgehobene Taktiken kann nur privat stellen, wer Taktiken hervorheben darf - bitte zuerst die Hervorhebung entfernen lassen.');
}
// Private Taktiken koennen nicht hervorgehoben sein.
$highlight = $visibility === 'public' ? (string) $old['highlight'] : 'none';
tactic_snapshot_if_due($tacticId, $userId);
if ($highlight === 'none') {
db()->prepare(
"UPDATE tactics SET name = ?, description = ?, visibility = ?, highlight = 'none',
highlighted_by = NULL, highlighted_at = NULL, updated_at = NOW() WHERE id = ?"
)->execute([$name, $description, $visibility, $tacticId]);
} else {
db()->prepare('UPDATE tactics SET name = ?, description = ?, visibility = ?, updated_at = NOW() WHERE id = ?')
->execute([$name, $description, $visibility, $tacticId]);
}
if (tactic_should_log($old, $userId) || $visibility === 'public') {
$foreign = (int) $old['created_by'] !== $userId;
admin_log($foreign ? '🗺️ Fremde Taktik bearbeitet' : '🗺️ Taktik bearbeitet', [
'Taktik' => $name,
'Karte' => (string) $old['map_slug'],
'Ersteller' => $foreign && $old['created_by'] !== null ? admin_log_user((int) $old['created_by']) : '',
'Name' => admin_log_change($old['name'], $name),
'Beschreibung' => admin_log_text_change((string) ($old['description'] ?? ''), $description),
'Sichtbarkeit' => admin_log_change(tactic_visibility_label((string) $old['visibility']), tactic_visibility_label($visibility)),
'Hervorhebung' => $highlight !== $old['highlight'] ? 'entfernt (Taktik ist jetzt privat)' : '',
]);
}
json_response(true, 'Taktik gespeichert.');
case 'tactic_highlight':
if (!user_has_permission('map.tactics.highlight')) {
json_response(false, 'Dir fehlt die Berechtigung, Taktiken hervorzuheben.');
}
$tactic = tactic_load((int) ($input['tactic_id'] ?? 0), $userId, false);
if ($tactic['visibility'] !== 'public') {
json_response(false, 'Nur öffentliche Taktiken lassen sich hervorheben.');
}
$highlight = (string) ($input['highlight'] ?? '');
if (!array_key_exists($highlight, TACTIC_HIGHLIGHTS)) {
json_response(false, 'Unbekannte Hervorhebung.');
}
if ($highlight === $tactic['highlight']) {
json_response(true, '');
}
db()->prepare('UPDATE tactics SET highlight = ?, highlighted_by = ?, highlighted_at = ? WHERE id = ?')->execute([
$highlight,
$highlight === 'none' ? null : $userId,
$highlight === 'none' ? null : date('Y-m-d H:i:s'),
(int) $tactic['id'],
]);
$label = static fn (string $h): string => TACTIC_HIGHLIGHTS[$h] !== '' ? TACTIC_HIGHLIGHTS[$h] : 'keine';
admin_log($highlight === 'none' ? '🗺️ Hervorhebung einer Taktik entfernt' : '⭐ Taktik hervorgehoben', [
'Taktik' => (string) $tactic['name'],
'Karte' => (string) $tactic['map_slug'],
'Ersteller' => $tactic['created_by'] !== null ? admin_log_user((int) $tactic['created_by']) : '',
'Hervorhebung' => admin_log_change($label((string) $tactic['highlight']), $label($highlight)),
], $highlight === 'none' ? 'warning' : 'success');
json_response(true, $highlight === 'none' ? 'Hervorhebung entfernt.' : 'Als „' . TACTIC_HIGHLIGHTS[$highlight] . '“ markiert.');
case 'tactic_delete':
$tactic = tactic_load((int) ($input['tactic_id'] ?? 0), $userId);
if (!tactic_can_delete($tactic, $userId)) {
json_response(false, 'Hervorgehobene Taktiken kann nur löschen, wer Taktiken hervorheben darf - bitte zuerst die Hervorhebung entfernen lassen.');
}
$stepCount = db()->prepare('SELECT COUNT(*) FROM tactic_steps WHERE tactic_id = ?');
$stepCount->execute([(int) $tactic['id']]);
$steps = (string) $stepCount->fetchColumn();
$pdo = db();
$pdo->beginTransaction();
// Vorher immer sichern: die Taktik landet im Papierkorb ("Gelöschte" im Taktik-Panel).
tactic_snapshot((int) $tactic['id'], 'delete', $userId);
$pdo->prepare('DELETE FROM tactics WHERE id = ?')->execute([(int) $tactic['id']]);
$pdo->commit();
if (tactic_should_log($tactic, $userId)) {
admin_log((int) $tactic['created_by'] !== $userId ? '🗑️ Fremde Taktik gelöscht' : '🗑️ Taktik gelöscht', [
'Taktik' => $tactic['name'],
'Karte' => $tactic['map_slug'],
'Ersteller' => $tactic['created_by'] !== null ? admin_log_user((int) $tactic['created_by']) : '',
'Sichtbarkeit' => tactic_visibility_label((string) $tactic['visibility']),
'Hervorhebung' => TACTIC_HIGHLIGHTS[$tactic['highlight']] ?? '',
'Schritte' => $steps,
'Wiederherstellen' => TACTIC_REVISION_DAYS . ' Tage lang im Taktik-Panel unter „Gelöschte“',
], 'danger');
}
json_response(true, 'Taktik gelöscht.');
// ---- Schritte ----
case 'step_create':
$tacticId = (int) ($input['tactic_id'] ?? 0);
tactic_load($tacticId, $userId);
$title = tactic_text($input, 'title', 120, 'einen Titel', false);
$description = tactic_text($input, 'description', 5000, 'die Beschreibung', false);
$copyFrom = (int) ($input['copy_from'] ?? 0);
tactic_snapshot_if_due($tacticId, $userId);
$pdo = db();
$pdo->beginTransaction();
$stepId = tactic_append_step($tacticId, $title, $description);
// "Als Kopie": der neue Schritt startet mit den Zeichnungen des alten, damit
// man nur noch einzeichnen muss, was sich von einem Schritt zum naechsten aendert.
if ($copyFrom > 0) {
$source = tactic_step_owner($copyFrom, $userId);
if ((int) $source['tactic_id'] !== $tacticId) {
$pdo->rollBack();
json_response(false, 'Der Schritt gehört zu einer anderen Taktik.');
}
$pdo->prepare(
'INSERT INTO tactic_shapes (step_id, shape_type, label, color, width, points, created_by)
SELECT ?, shape_type, label, color, width, points, ? FROM tactic_shapes WHERE step_id = ? ORDER BY id'
)->execute([$stepId, $userId, $copyFrom]);
}
tactic_touch($tacticId);
$pdo->commit();
json_response(true, 'Schritt angelegt.', ['step_id' => $stepId]);
case 'step_update':
$step = tactic_step_owner((int) ($input['step_id'] ?? 0), $userId);
$title = tactic_text($input, 'title', 120, 'einen Titel', false);
$description = tactic_text($input, 'description', 5000, 'die Beschreibung', false);
tactic_snapshot_if_due((int) $step['tactic_id'], $userId);
db()->prepare('UPDATE tactic_steps SET title = ?, description = ? WHERE id = ?')
->execute([$title, $description, (int) $step['id']]);
tactic_touch((int) $step['tactic_id']);
json_response(true, 'Schritt gespeichert.');
case 'step_delete':
$step = tactic_step_owner((int) ($input['step_id'] ?? 0), $userId);
$tactic = $step['tactic'];
$order = db()->prepare('SELECT id FROM tactic_steps WHERE tactic_id = ? ORDER BY sort_order, id');
$order->execute([(int) $step['tactic_id']]);
$stepIds = array_map('intval', $order->fetchAll(PDO::FETCH_COLUMN));
if (count($stepIds) <= 1) {
json_response(false, 'Eine Taktik braucht mindestens einen Schritt.');
}
$shapeCount = db()->prepare('SELECT COUNT(*) FROM tactic_shapes WHERE step_id = ?');
$shapeCount->execute([(int) $step['id']]);
$shapes = (string) $shapeCount->fetchColumn();
tactic_snapshot_if_due((int) $step['tactic_id'], $userId);
db()->prepare('DELETE FROM tactic_steps WHERE id = ?')->execute([(int) $step['id']]);
tactic_touch((int) $step['tactic_id']);
// In fremden Taktiken zaehlt das wie eine Loeschung (Notbremse, siehe includes/security.php) -
// sonst liesse sich eine Taktik Schritt fuer Schritt unbemerkt leeren. Eigene bleiben still.
if ((int) ($tactic['created_by'] ?? 0) !== $userId) {
$position = array_search((int) $step['id'], $stepIds, true);
admin_log('🗑️ Schritt einer fremden Taktik gelöscht', [
'Taktik' => (string) $tactic['name'],
'Karte' => (string) $tactic['map_slug'],
'Ersteller' => $tactic['created_by'] !== null ? admin_log_user((int) $tactic['created_by']) : '',
'Schritt' => ($position !== false ? 'Schritt ' . ($position + 1) : '')
. ((string) $step['title'] !== '' ? ' – ' . $step['title'] : ''),
'Zeichnungen' => $shapes,
'Wiederherstellen' => 'im Taktik-Panel über „🕘 Verlauf“',
], 'danger');
}
json_response(true, 'Schritt gelöscht.');
case 'step_move':
$step = tactic_step_owner((int) ($input['step_id'] ?? 0), $userId);
$direction = (int) ($input['direction'] ?? 0) < 0 ? -1 : 1;
// Reihenfolge neu durchnummerieren und mit dem Nachbarn tauschen - so stoeren
// doppelte oder lueckenhafte sort_order-Werte nicht.
$stmt = db()->prepare('SELECT id FROM tactic_steps WHERE tactic_id = ? ORDER BY sort_order, id');
$stmt->execute([(int) $step['tactic_id']]);
$ids = array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN));
$index = array_search((int) $step['id'], $ids, true);
$target = $index + $direction;
if ($index === false || $target < 0 || $target >= count($ids)) {
json_response(true, '');
}
[$ids[$index], $ids[$target]] = [$ids[$target], $ids[$index]];
tactic_snapshot_if_due((int) $step['tactic_id'], $userId);
$pdo = db();
$pdo->beginTransaction();
$update = $pdo->prepare('UPDATE tactic_steps SET sort_order = ? WHERE id = ?');
foreach ($ids as $position => $id) {
$update->execute([$position + 1, $id]);
}
tactic_touch((int) $step['tactic_id']);
$pdo->commit();
json_response(true, 'Schritt verschoben.');
// ---- Zeichnungen ----
case 'shape_create':
$step = tactic_step_owner((int) ($input['step_id'] ?? 0), $userId);
$type = (string) ($input['type'] ?? '');
if (!in_array($type, TACTIC_SHAPE_TYPES, true)) {
json_response(false, 'Unbekannte Form.');
}
$points = tactic_clean_points($input['points'] ?? null, $type);
if ($points === null) {
json_response(false, 'Die Zeichnung ist ungültig oder liegt außerhalb der Karte.');
}
$color = (string) ($input['color'] ?? '');
if (preg_match('/^#[0-9a-fA-F]{6}$/', $color) !== 1) {
$color = '#ffd700';
}
$width = max(1, min(30, (int) ($input['width'] ?? 4)));
$label = tactic_text($input, 'label', 200, 'die Beschriftung', $type === 'text');
tactic_snapshot_if_due((int) $step['tactic_id'], $userId);
db()->prepare(
'INSERT INTO tactic_shapes (step_id, shape_type, label, color, width, points, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?)'
)->execute([(int) $step['id'], $type, $label, strtolower($color), $width, json_encode($points), $userId]);
$shapeId = (int) db()->lastInsertId();
tactic_touch((int) $step['tactic_id']);
json_response(true, '', ['shape' => [
'id' => $shapeId,
'type' => $type,
'label' => $label,
'color' => strtolower($color),
'width' => $width,
'points' => $points,
]]);
case 'shape_delete':
$shapeId = (int) ($input['shape_id'] ?? 0);
$stmt = db()->prepare(
'SELECT s.tactic_id FROM tactic_shapes sh JOIN tactic_steps s ON s.id = sh.step_id WHERE sh.id = ?'
);
$stmt->execute([$shapeId]);
$tacticId = (int) $stmt->fetchColumn();
if ($tacticId <= 0) {
json_response(true, ''); // schon weg
}
tactic_load($tacticId, $userId);
// Kein eigener Log-Eintrag pro Zeichnung - der Verlauf zeigt, wer wann etwas geaendert hat.
tactic_snapshot_if_due($tacticId, $userId);
db()->prepare('DELETE FROM tactic_shapes WHERE id = ?')->execute([$shapeId]);
tactic_touch($tacticId);
json_response(true, '');
// ---- Live-Ansicht ----
case 'live_token':
// Ticket fuer den Live-Verteiler im Bot (tactic_live_ticket): zuschauen darf, wer die Taktik
// sieht, live zeichnen, wer sie bearbeiten darf.
$tactic = tactic_load((int) ($input['tactic_id'] ?? 0), $userId, false);
$ticket = tactic_live_ticket($tactic, current_user());
if ($ticket === null) {
json_response(false, 'Die Live-Ansicht ist hier nicht eingerichtet.', ['live_unavailable' => true]);
}
json_response(true, '', $ticket);
// ---- Verlauf und Papierkorb ----
case 'revision_list':
// Nur fuer bestehende Taktiken, die das Konto bearbeiten darf (Staende aus privater
// Zeit filtert tactic_revision_list zusaetzlich) - geloeschte stehen im GET unter "deleted".
$tactic = tactic_load((int) ($input['tactic_id'] ?? 0), $userId);
json_response(true, '', ['revisions' => tactic_revision_list($tactic, $userId)]);
case 'revision_restore':
$stmt = db()->prepare(
'SELECT id, tactic_id, map_slug, name, visibility, highlight, owner_id, reason, snapshot, created_by, created_at
FROM tactic_revisions WHERE id = ?'
);
$stmt->execute([(int) ($input['revision_id'] ?? 0)]);
$revision = $stmt->fetch();
$gone = 'Diesen Stand gibt es nicht mehr - bitte die Seite neu laden.';
// Die Rechte haengen am gesicherten Stand: ein privater Stand bleibt fuer alle ausser
// dem Ersteller unsichtbar, auch wenn die Taktik inzwischen oeffentlich ist.
$subject = $revision ? tactic_revision_subject($revision) : [];
if (!$revision || !tactic_can_view($subject, $userId)) {
json_response(false, $gone);
}
$tacticId = (int) $revision['tactic_id'];
$exists = db()->prepare('SELECT COUNT(*) FROM tactics WHERE id = ?');
$exists->execute([$tacticId]);
// Gibt es die Taktik noch, gilt ausserdem, was die Taktik jetzt ist (tactic_load prueft
// Sehen und Bearbeiten - inzwischen private Taktiken anderer gelten als nicht vorhanden).
$current = (int) $exists->fetchColumn() > 0 ? tactic_load($tacticId, $userId) : null;
if ($current === null) {
// Geloeschte Taktik: nur aus der Sicherung vor dem Loeschen (ihrem neuesten Stand)
// und nur mit denselben Rechten, die das Loeschen gebraucht hat.
$newest = db()->prepare('SELECT id FROM tactic_revisions WHERE tactic_id = ? ORDER BY created_at DESC, id DESC LIMIT 1');
$newest->execute([$tacticId]);
if ((int) $newest->fetchColumn() !== (int) $revision['id']) {
json_response(false, $gone);
}
if (!tactic_can_delete($subject, $userId)) {
json_response(false, 'Diese Taktik darfst du nicht wiederherstellen - nur wer sie auch löschen dürfte.');
}
}
$data = json_decode((string) $revision['snapshot'], true);
if (!is_array($data) || !is_array($data['tactic'] ?? null) || !is_array($data['steps'] ?? null)) {
json_response(false, 'Dieser Stand ist beschädigt und lässt sich nicht wiederherstellen.');
}
$when = date('d.m.Y H:i', (int) strtotime((string) $revision['created_at']));
$pdo = db();
$pdo->beginTransaction();
if ($current !== null) {
// Der jetzige Stand kommt selbst in den Verlauf - so laesst sich auch das
// Wiederherstellen rueckgaengig machen. Sichtbarkeit und Hervorhebung bleiben, wie sie sind.
tactic_snapshot($tacticId, 'restore', $userId);
$pdo->prepare('DELETE FROM tactic_steps WHERE tactic_id = ?')->execute([$tacticId]); // Zeichnungen per ON DELETE CASCADE
$pdo->prepare('UPDATE tactics SET name = ?, description = ?, updated_at = NOW() WHERE id = ?')
->execute([(string) $revision['name'], (string) ($data['tactic']['description'] ?? ''), $tacticId]);
} else {
// Mit der alten ID (AUTO_INCREMENT vergibt sie nie neu), damit der Verlauf dranbleibt -
// und mit Ersteller, Sichtbarkeit und Hervorhebung wie vor dem Loeschen.
$highlight = $revision['visibility'] === 'public' ? (string) $revision['highlight'] : 'none';
$highlightedBy = (int) ($data['tactic']['highlighted_by'] ?? 0);
if ($highlight === 'none' || empty(tactic_existing_users([$highlightedBy]))) {
$highlightedBy = null;
}
try {
$pdo->prepare(
'INSERT INTO tactics (id, map_slug, name, description, visibility, highlight, highlighted_by,
highlighted_at, created_by, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())'
)->execute([
$tacticId,
(string) $revision['map_slug'],
(string) $revision['name'],
(string) ($data['tactic']['description'] ?? ''),
(string) $revision['visibility'],
$highlight,
$highlightedBy,
$highlight !== 'none' ? tactic_datetime($data['tactic']['highlighted_at'] ?? null) : null,
$revision['owner_id'] !== null ? (int) $revision['owner_id'] : null,
tactic_datetime($data['tactic']['created_at'] ?? null),
]);
} catch (PDOException $e) {
if ((int) ($e->errorInfo[1] ?? 0) !== 1062) {
throw $e;
}
$pdo->rollBack();
json_response(false, 'Diese Taktik wurde gerade schon wiederhergestellt - bitte die Seite neu laden.');
}
}
$steps = tactic_import_steps($tacticId, $data['steps']);
$pdo->commit();
$logged = $current ?? ['visibility' => $revision['visibility'], 'created_by' => $revision['owner_id']];
if (tactic_should_log($logged, $userId)) {
admin_log('♻️ Taktik wiederhergestellt', [
'Taktik' => (string) $revision['name'],
'Karte' => (string) $revision['map_slug'],
'Ersteller' => $logged['created_by'] !== null ? admin_log_user((int) $logged['created_by']) : '',
'Stand' => $current !== null ? 'vom ' . $when : 'vor dem Löschen am ' . $when . ' (aus dem Papierkorb)',
'Vorheriger Stand' => $current !== null ? 'im Verlauf gesichert' : '',
'Schritte' => (string) $steps,
], 'success');
}
json_response(true, $current !== null
? 'Der Stand vom ' . $when . ' ist wieder aktuell - der bisherige steht im Verlauf.'
: 'Taktik „' . $revision['name'] . '“ wiederhergestellt.', ['tactic_id' => $tacticId]);
default:
json_response(false, 'Unbekannte Aktion.');
}
} catch (Throwable $e) {
if (db()->inTransaction()) {
db()->rollBack();
}
json_response(false, 'Speichern fehlgeschlagen: ' . $e->getMessage());
}