LuminaWebsite/tactics_api.php
Maaxxs 03597f14ad Raidplaner: tactics on the maps of all dungeons and raids, with tokens that move from step to step
Asked for in Discord: "raidplan.io bitte einbauen für die harten Dungeons". raidplan.io has no Aion 2
(only WoW, FFXIV, Lost Ark, New World), so the map tactics got what it offers.

- Dungeon maps: the in-game map textures of 11 expeditions, 7 transcendence dungeons, the 3 sanctuaries
  (Ludra, Corroded Decontamination Facility, Chalice of Muspel), the 6 awakening towers and 3
  subjugations, as published by the DPS meter Waffle-ens/waffle_meter (dotnet/Assets/Maps, pinned
  commit). assets/map/dungeons/dungeons.json is kept by hand: groups, slugs (= tactics.map_slug),
  German names from the Global client (aion2.app), KR/TW-only dungeons marked as unavailable, boss
  hints for the awakening towers. scripts/download_dungeon_maps.py fetches the images, writes
  dungeons/<slug>.webp (2048 px, about 3 MB in total, in Git) and the previews, and finds the dungeon
  area (bounds) by comparing each map with the shared background of all maps. Two empty arenas
  (round, square) are drawn in code.
- Viewer: image maps and arenas next to the tile maps (MapView.drawImageMap/drawArena, half zoom
  steps, opens fitted to the dungeon beside the tactic panel), map picker with the tabs "Welt" and
  "Dungeons & Raids", each area remembers its last map, no category panel without markers. The mouse
  wheel zooms to the cursor.
- New page raidplan.php ("Raidplaner" in the menu, map.view) = map.php started in the dungeon area.
  Location links on dungeon maps point to /raidplan.php and are recognized in texts and by the
  calendar picker.
- Tokens (shape type 'token', TokenIcons.js): classes, roles, players 1-8, markers A-D and symbols,
  boss, add, danger, stack, spread, tower, orb, bomb. Colour and size come from the toolbar, numbers
  and letters count up while placing, tokens are drawn above areas. Server whitelist
  TACTIC_TOKEN_ICONS.
- Move tool (✥) with label/delete actions above the selected shape, double click and Del; new action
  shape_update in tactics_api.php (points and label, same permissions, snapshot before). Undo also
  reverts moves and labels. Rectangle and cone tools, saved as areas.
- Step transitions: tactic_shapes.ref is kept by "Kopie dieses Schritts", tactic copies and restores
  (existing shapes get s<id>), so the same shape glides to its new place when stepping or playing;
  play button (and space) runs through all steps. 🔗 copies a link to the tactic and step
  (?taktik=&schritt=), which opens it after loading.
- Live view: the bot relay only knows the old shape types and events, so placing tokens and moving
  send "changed" and the others reload - no bot deploy needed.
- Schema version 60 (tactic_shapes.icon, .ref, enum 'token'; also in sql/schema.sql), tour step on the
  dashboard, patch notes and README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 12:45:00 +02:00

625 lines
33 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']]);
// Mit derselben Kennung (ref) je Zeichnung - die Figuren laufen in der Kopie ebenso von Schritt zu Schritt.
$copyShapes = $pdo->prepare(
'INSERT INTO tactic_shapes (step_id, shape_type, label, icon, color, width, points, ref, created_by)
SELECT ?, shape_type, label, icon, color, width, points, ref, ? 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.
// Die Kennung (ref) bleibt gleich - verschobene Figuren laufen beim Blaettern an ihre neue Stelle.
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, icon, color, width, points, ref, created_by)
SELECT ?, shape_type, label, icon, color, width, points, ref, ? 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.');
}
$icon = tactic_clean_icon($type, $input['icon'] ?? null);
if ($icon === null) {
json_response(false, 'Unbekannte Figur - bitte die Seite neu laden.');
}
$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');
$ref = tactic_new_ref();
tactic_snapshot_if_due((int) $step['tactic_id'], $userId);
db()->prepare(
'INSERT INTO tactic_shapes (step_id, shape_type, label, icon, color, width, points, ref, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'
)->execute([(int) $step['id'], $type, $label, $icon, strtolower($color), $width, json_encode($points), $ref, $userId]);
$shapeId = (int) db()->lastInsertId();
tactic_touch((int) $step['tactic_id']);
json_response(true, '', ['shape' => [
'id' => $shapeId,
'type' => $type,
'label' => $label,
'icon' => $icon,
'color' => strtolower($color),
'width' => $width,
'points' => $points,
'ref' => $ref,
]]);
case 'shape_update':
// Verschieben (neue Stuetzpunkte, gleiche Form) und Beschriften - Art, Farbe und Figur bleiben.
$stmt = db()->prepare(
'SELECT sh.id, sh.step_id, sh.shape_type, sh.label, sh.icon, sh.color, sh.width, sh.points, sh.ref, s.tactic_id
FROM tactic_shapes sh JOIN tactic_steps s ON s.id = sh.step_id WHERE sh.id = ?'
);
$stmt->execute([(int) ($input['shape_id'] ?? 0)]);
$shape = $stmt->fetch();
if (!$shape) {
json_response(false, 'Diese Zeichnung gibt es nicht mehr - bitte die Seite neu laden.');
}
tactic_load((int) $shape['tactic_id'], $userId);
$type = (string) $shape['shape_type'];
$points = json_decode((string) $shape['points'], true);
if (array_key_exists('points', $input)) {
$points = tactic_clean_points($input['points'], $type);
if ($points === null) {
json_response(false, 'Die Zeichnung ist ungültig oder liegt außerhalb der Karte.');
}
}
$label = (string) $shape['label'];
if (array_key_exists('label', $input)) {
$label = tactic_text($input, 'label', 200, 'die Beschriftung', $type === 'text');
}
tactic_snapshot_if_due((int) $shape['tactic_id'], $userId);
db()->prepare('UPDATE tactic_shapes SET points = ?, label = ? WHERE id = ?')
->execute([json_encode($points), $label, (int) $shape['id']]);
tactic_touch((int) $shape['tactic_id']);
$shape['points'] = json_encode($points);
$shape['label'] = $label;
json_response(true, '', ['shape' => tactic_shape_row($shape)]);
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());
}