LuminaWebsite/tactics_api.php
Maaxxs 338a00c21f Log all administrative website actions to the Discord log channel via the bot API
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 19:16:54 +02:00

281 lines
12 KiB
PHP

<?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.');
}
$canEdit = user_has_permission('map.tactics');
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, '', [
'can_edit' => $canEdit,
'tactics' => tactics_for_map($slug),
]);
}
// ---- Schreiben ----
$input = read_json_body();
verify_csrf_token($input['csrf_token'] ?? '');
if (!$canEdit) {
json_response(false, 'Dir fehlt die Berechtigung, Taktiken zu bearbeiten.');
}
$userId = (int) current_user()['id'];
$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;
}
/** Sucht einen Schritt und liefert die Taktik, zu der er gehoert. */
function tactic_step_owner(int $stepId): 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.');
}
return $step;
}
function tactic_exists(int $tacticId): void
{
$stmt = db()->prepare('SELECT 1 FROM tactics WHERE id = ?');
$stmt->execute([$tacticId]);
if (!$stmt->fetchColumn()) {
json_response(false, 'Diese Taktik gibt es nicht mehr - bitte die Seite neu laden.');
}
}
/** 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);
$pdo = db();
$pdo->beginTransaction();
$pdo->prepare('INSERT INTO tactics (map_slug, name, description, created_by) VALUES (?, ?, ?, ?)')
->execute([$slug, $name, $description, $userId]);
$tacticId = (int) $pdo->lastInsertId();
// Ohne Titel - angezeigt wird dann "Schritt 1".
$stepId = tactic_append_step($tacticId, '');
$pdo->commit();
// Nur ganze Taktiken ins Discord-Log - einzelne Zeichnungen wuerden den Kanal fluten.
admin_log('🗺️ Taktik angelegt', ['Taktik' => $name, 'Karte' => $slug], 'success');
json_response(true, 'Taktik angelegt.', ['tactic_id' => $tacticId, 'step_id' => $stepId]);
case 'tactic_update':
$tacticId = (int) ($input['tactic_id'] ?? 0);
tactic_exists($tacticId);
$name = tactic_text($input, 'name', 120, 'einen Namen', true);
$description = tactic_text($input, 'description', 5000, 'die Beschreibung', false);
db()->prepare('UPDATE tactics SET name = ?, description = ?, updated_at = NOW() WHERE id = ?')
->execute([$name, $description, $tacticId]);
admin_log('🗺️ Taktik bearbeitet', ['Taktik' => $name]);
json_response(true, 'Taktik gespeichert.');
case 'tactic_delete':
$tacticId = (int) ($input['tactic_id'] ?? 0);
$nameStmt = db()->prepare('SELECT name, map_slug FROM tactics WHERE id = ?');
$nameStmt->execute([$tacticId]);
$tactic = $nameStmt->fetch();
db()->prepare('DELETE FROM tactics WHERE id = ?')->execute([$tacticId]);
if ($tactic) {
admin_log('🗑️ Taktik gelöscht', ['Taktik' => $tactic['name'], 'Karte' => $tactic['map_slug']], 'danger');
}
json_response(true, 'Taktik gelöscht.');
// ---- Schritte ----
case 'step_create':
$tacticId = (int) ($input['tactic_id'] ?? 0);
tactic_exists($tacticId);
$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);
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));
$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));
$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));
$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));
$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();
db()->prepare('DELETE FROM tactic_shapes WHERE id = ?')->execute([$shapeId]);
if ($tacticId > 0) {
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());
}