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), ]); } // ---- 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, 'Diese Taktik darfst du nicht bearbeiten - nur der Ersteller (und bei öffentlichen Taktiken die Leitung).'); } return $tactic; } /** Sucht einen Schritt, prueft das Bearbeitungsrecht an seiner Taktik und liefert ihn. */ function tactic_step_owner(int $stepId, int $userId): array { $stmt = db()->prepare('SELECT id, tactic_id, 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.'); } 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)'; } /** Legt einen Schritt am Ende der Taktik an und gibt seine ID zurueck. */ function tactic_append_step(int $tacticId, string $title, string $description = ''): int { $stmt = db()->prepare('SELECT COALESCE(MAX(sort_order), 0) + 1 FROM tactic_steps WHERE tactic_id = ?'); $stmt->execute([$tacticId]); $order = (int) $stmt->fetchColumn(); db()->prepare('INSERT INTO tactic_steps (tactic_id, title, description, sort_order) VALUES (?, ?, ?, ?)') ->execute([$tacticId, $title, $description, $order]); return (int) db()->lastInsertId(); } 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_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']; } // Private Taktiken koennen nicht hervorgehoben sein. $highlight = $visibility === 'public' ? (string) $old['highlight'] : 'none'; 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); $stepCount = db()->prepare('SELECT COUNT(*) FROM tactic_steps WHERE tactic_id = ?'); $stepCount->execute([(int) $tactic['id']]); $steps = (string) $stepCount->fetchColumn(); db()->prepare('DELETE FROM tactics WHERE id = ?')->execute([(int) $tactic['id']]); 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, ], '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); $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); 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); $count = db()->prepare('SELECT COUNT(*) FROM tactic_steps WHERE tactic_id = ?'); $count->execute([(int) $step['tactic_id']]); if ((int) $count->fetchColumn() <= 1) { json_response(false, 'Eine Taktik braucht mindestens einen Schritt.'); } db()->prepare('DELETE FROM tactic_steps WHERE id = ?')->execute([(int) $step['id']]); tactic_touch((int) $step['tactic_id']); 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]]; $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'); 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); db()->prepare('DELETE FROM tactic_shapes WHERE id = ?')->execute([$shapeId]); tactic_touch($tacticId); json_response(true, ''); default: json_response(false, 'Unbekannte Aktion.'); } } catch (Throwable $e) { if (db()->inTransaction()) { db()->rollBack(); } json_response(false, 'Speichern fehlgeschlagen: ' . $e->getMessage()); }