LuminaWebsite/includes/tactics.php
Maaxxs c4f94bf84a Member feedback: raid input checks and fixed raid points, premades in the raid form, live raid page, Lumina-style dialogs, leadership calendar entries, class-based weapon picker, map and tactics fixes
- Raids: "Max. Spieler" only whole numbers up to groups x 5 (max. 10 groups / 50), gearscore only a number; fixed +1 Lumipunkt per participation, other values only with the new raids.points permission; pick an existing premade per group when creating a raid; unchanged legacy values no longer block editing
- Raid page updates itself every 15 s while visible (raids_live.php, cards rendered by includes/raid_card.php), open editors and confirm dialogs are kept
- Restore takes the new raid_id from the bot (archived messages are now deleted in Discord) and moves settings, attendance and awards; website signups send the server display name
- Premades: dissolve by leadership needs a reason, lead gets DMs on join/assign/decline/remove (source/actor_id sent to the bot), transfer picker skips players who already lead a group, website accept keeps the one-group rule, no commas in names
- Site-wide Lumina dialog (assets/js/confirm-dialog.js) replaces confirm/prompt/alert via data-confirm; error flashes are a dialog you confirm with OK
- Calendar: audience per entry (all / leadership takes part / internal) with the new calendar.leadership permission; day cells list all entries and scroll
- Gear planner: main-hand picker filtered by the set's class, mismatches marked, "keine Klasse" option, link to an external skill/Daevanion plan per set
- Map: correct kisk icons (Elyos on Verteron/Abyss, Altgard fixed), per-map max zoom and bounded panning, German texts, data source note
- Tactics: toolbar as a uniform grid, whole-tactic copy, automatic versions with restore and a 90-day trash, official tactics protected
- Global thin gold scrollbars, readable hover colours, "Sedes Luminis" spelling, patch notes and README, schema version 34

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

742 lines
28 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
declare(strict_types=1);
/**
* Datenschicht der Taktiken auf der Karte. Die Karte selbst ist ein statischer Viewer
* (assets/map/), nur die Taktiken liegen in der Website-Datenbank - der Discord-Bot ist
* daran nicht beteiligt.
*/
// Die Tabellen in Anlegereihenfolge (Fremdschluessel!). tactic_revisions (Verlauf/Papierkorb)
// fehlt bewusst: sie legt die automatische Schema-Pruefung an (includes/schema.php).
const TACTIC_TABLES = ['tactics', 'tactic_steps', 'tactic_shapes'];
const TACTIC_SHAPE_TYPES = ['pen', 'line', 'arrow', 'area', 'circle', 'point', 'text'];
// Die Weltkoordinaten der Karte laufen von 0 bis 4096. Etwas Luft rundherum, damit ein
// Pfeil auch knapp ueber den Kartenrand hinaus zeigen darf.
const TACTIC_COORD_MIN = -512.0;
const TACTIC_COORD_MAX = 4608.0;
// Freihandlinien werden im Browser vereinfacht - mehr Punkte kommen normal nicht zusammen.
const TACTIC_MAX_POINTS = 4000;
/**
* Welche der Taktik-Tabellen fehlen noch? Bestehende Installationen kennen sie nicht -
* ohne diese Pruefung wuerde die erste Abfrage mit einer PDOException aussteigen.
*
* @return array<int, string>
*/
function tactics_missing_tables(): array
{
$placeholders = implode(',', array_fill(0, count(TACTIC_TABLES), '?'));
$stmt = db()->prepare(
"SELECT table_name FROM information_schema.tables
WHERE table_schema = DATABASE() AND table_name IN ($placeholders)"
);
$stmt->execute(TACTIC_TABLES);
$existing = array_map('strtolower', $stmt->fetchAll(PDO::FETCH_COLUMN));
return array_values(array_filter(
TACTIC_TABLES,
static fn (string $table): bool => !in_array(strtolower($table), $existing, true)
));
}
/**
* Legt die fehlenden Tabellen an. Die Befehle kommen aus sql/schema.sql, damit es genau
* eine Quelle fuer die Struktur gibt. Alle sind "IF NOT EXISTS" - ein zweiter Aufruf
* richtet keinen Schaden an.
*
* @throws RuntimeException
*/
function tactics_create_tables(): void
{
$path = __DIR__ . '/../sql/schema.sql';
$schema = is_file($path) ? (string) file_get_contents($path) : '';
$statements = [];
foreach (TACTIC_TABLES as $table) {
$pattern = '/CREATE TABLE IF NOT EXISTS\s+' . preg_quote($table, '/') . '\s*\(.*?\)\s*ENGINE[^;]*;/s';
if (preg_match($pattern, $schema, $match) === 1) {
$statements[] = $match[0];
}
}
if (count($statements) !== count(TACTIC_TABLES)) {
throw new RuntimeException(
'sql/schema.sql wurde nicht gefunden oder enthält nicht alle Taktik-Tabellen - '
. 'bitte den Abschnitt "Taktiken auf der Karte" aus sql/schema.sql von Hand ausführen.'
);
}
foreach ($statements as $sql) {
db()->exec($sql);
}
}
/**
* Die Regionen der Karte, wie sie der Viewer kennt (assets/map/data/maps.json).
* Fehlt die Datei - etwa weil der Datenordner noch nicht hochgeladen ist - wird nur
* das Format des Kartennamens geprueft.
*/
function tactics_valid_map(string $slug): bool
{
if (preg_match('/^[a-z0-9-]{1,60}$/', $slug) !== 1) {
return false;
}
static $slugs = null;
if ($slugs === null) {
$slugs = [];
$path = __DIR__ . '/../assets/map/data/maps.json';
$data = is_file($path) ? json_decode((string) file_get_contents($path), true) : null;
foreach ((is_array($data) ? ($data['maps'] ?? []) : []) as $map) {
if (isset($map['slug'])) {
$slugs[] = (string) $map['slug'];
}
}
}
return empty($slugs) || in_array($slug, $slugs, true);
}
const TACTIC_VISIBILITIES = ['private', 'public'];
const TACTIC_HIGHLIGHTS = ['none' => '', 'recommended' => 'Empfohlen', 'official' => 'Offiziell'];
/**
* Darf das aktuelle Konto diese Taktik bearbeiten (Name, Schritte, Zeichnungen, Verlauf; zum
* Loeschen siehe zusaetzlich tactic_can_delete)?
* Die eigene immer; fremde nur, wenn sie oeffentlich ist und man map.tactics hat ("Stratege").
* Offizielle Taktiken anderer bearbeitet nur, wer Taktiken auch hervorheben darf
* (map.tactics.highlight) - map.tactics allein reicht dafuer nicht. Private Taktiken anderer
* bleiben auch fuer die Leitung unsichtbar.
*
* @param array{created_by: mixed, visibility: string, highlight?: string} $tactic
*/
function tactic_can_edit(array $tactic, int $userId): bool
{
if ((int) ($tactic['created_by'] ?? 0) === $userId) {
return true;
}
if (($tactic['visibility'] ?? '') !== 'public') {
return false;
}
return user_has_permission(($tactic['highlight'] ?? '') === 'official' ? 'map.tactics.highlight' : 'map.tactics');
}
/**
* Darf das Konto die Taktik loeschen? Wer sie bearbeiten darf - hervorgehobene aber nur mit
* map.tactics.highlight, auch der Ersteller nicht ohne. Sonst waere eine offizielle Taktik mit
* einem Klick fuer alle weg.
*/
function tactic_can_delete(array $tactic, int $userId): bool
{
return tactic_can_edit($tactic, $userId)
&& (($tactic['highlight'] ?? 'none') === 'none' || user_has_permission('map.tactics.highlight'));
}
/**
* Die Sichtbarkeit aendert nur der Ersteller - bei einer hervorgehobenen Taktik nur mit
* map.tactics.highlight (privat waere sie sonst fuer alle ausser ihm verschwunden, auch fuer
* die Leitung, die sie hervorgehoben hat).
*/
function tactic_can_change_visibility(array $tactic, int $userId): bool
{
return (int) ($tactic['created_by'] ?? 0) === $userId
&& (($tactic['highlight'] ?? 'none') === 'none' || user_has_permission('map.tactics.highlight'));
}
/** Darf das aktuelle Konto die Taktik sehen? Oeffentliche alle, private nur der Ersteller. */
function tactic_can_view(array $tactic, int $userId): bool
{
return ($tactic['visibility'] ?? '') === 'public' || (int) ($tactic['created_by'] ?? 0) === $userId;
}
/**
* Alle Taktiken einer Region, die das Konto sehen darf, samt Schritten und Zeichnungen:
* oeffentliche und die eigenen privaten. Offizielle und empfohlene stehen vorn.
*
* @return array<int, array<string, mixed>>
*/
function tactics_for_map(string $slug, int $userId): array
{
$stmt = db()->prepare(
"SELECT t.id, t.name, t.description, t.visibility, t.highlight, t.created_by, t.created_at, t.updated_at,
COALESCE(NULLIF(u.display_name, ''), u.username) AS author,
COALESCE(NULLIF(h.display_name, ''), h.username) AS highlighted_by_name
FROM tactics t
LEFT JOIN users u ON u.id = t.created_by
LEFT JOIN users h ON h.id = t.highlighted_by
WHERE t.map_slug = ? AND (t.visibility = 'public' OR t.created_by = ?)
ORDER BY FIELD(t.highlight, 'official', 'recommended', 'none'), t.name, t.id"
);
$stmt->execute([$slug, $userId]);
$tactics = [];
foreach ($stmt->fetchAll() as $row) {
$isMine = (int) ($row['created_by'] ?? 0) === $userId;
$tactics[(int) $row['id']] = [
'id' => (int) $row['id'],
'name' => (string) $row['name'],
'description' => (string) ($row['description'] ?? ''),
'author' => (string) ($row['author'] ?? ''),
'is_mine' => $isMine,
'visibility' => (string) $row['visibility'],
'highlight' => (string) $row['highlight'],
'highlighted_by' => (string) ($row['highlighted_by_name'] ?? ''),
'can_edit' => tactic_can_edit($row, $userId),
'can_delete' => tactic_can_delete($row, $userId),
'can_change_visibility' => tactic_can_change_visibility($row, $userId),
'updated_at' => (string) ($row['updated_at'] ?? $row['created_at']),
'steps' => [],
];
}
if (empty($tactics)) {
return [];
}
$ids = array_keys($tactics);
$placeholders = implode(',', array_fill(0, count($ids), '?'));
$stepStmt = db()->prepare(
"SELECT id, tactic_id, title, description FROM tactic_steps
WHERE tactic_id IN ($placeholders) ORDER BY sort_order, id"
);
$stepStmt->execute($ids);
$steps = [];
foreach ($stepStmt->fetchAll() as $row) {
$steps[(int) $row['id']] = [
'id' => (int) $row['id'],
'tactic_id' => (int) $row['tactic_id'],
'title' => (string) $row['title'],
'description' => (string) ($row['description'] ?? ''),
'shapes' => [],
];
}
if (!empty($steps)) {
$stepIds = array_keys($steps);
$stepPlaceholders = implode(',', array_fill(0, count($stepIds), '?'));
$shapeStmt = db()->prepare(
"SELECT id, step_id, shape_type, label, color, width, points FROM tactic_shapes
WHERE step_id IN ($stepPlaceholders) ORDER BY id"
);
$shapeStmt->execute($stepIds);
foreach ($shapeStmt->fetchAll() as $row) {
$steps[(int) $row['step_id']]['shapes'][] = tactic_shape_row($row);
}
}
foreach ($steps as $step) {
$tacticId = $step['tactic_id'];
unset($step['tactic_id']);
$tactics[$tacticId]['steps'][] = $step;
}
return array_values($tactics);
}
/** @return array<string, mixed> */
function tactic_shape_row(array $row): array
{
$points = json_decode((string) $row['points'], true);
return [
'id' => (int) $row['id'],
'type' => (string) $row['shape_type'],
'label' => (string) $row['label'],
'color' => (string) $row['color'],
'width' => (int) $row['width'],
'points' => is_array($points) ? $points : [],
];
}
/**
* Prueft die Stuetzpunkte einer Zeichnung und gibt sie gerundet zurueck, oder null, wenn
* sie nicht zur Form passen.
*
* @return array<int, array{0: float, 1: float}>|null
*/
function tactic_clean_points($points, string $type): ?array
{
if (!is_array($points)) {
return null;
}
$clean = [];
foreach ($points as $point) {
if (!is_array($point) || count($point) !== 2) {
return null;
}
[$x, $y] = array_values($point);
if ((!is_int($x) && !is_float($x)) || (!is_int($y) && !is_float($y))) {
return null;
}
if ($x < TACTIC_COORD_MIN || $x > TACTIC_COORD_MAX || $y < TACTIC_COORD_MIN || $y > TACTIC_COORD_MAX) {
return null;
}
$clean[] = [round((float) $x, 2), round((float) $y, 2)];
}
$count = count($clean);
$valid = match ($type) {
'point', 'text' => $count === 1,
'line', 'arrow', 'circle' => $count === 2,
'pen' => $count >= 2 && $count <= TACTIC_MAX_POINTS,
'area' => $count >= 3 && $count <= TACTIC_MAX_POINTS,
default => false,
};
return $valid ? $clean : null;
}
/** Aktualisiert den Zeitstempel einer Taktik, damit die Liste zeigt, wann zuletzt gezeichnet wurde. */
function tactic_touch(int $tacticId): void
{
db()->prepare('UPDATE tactics SET updated_at = NOW() WHERE id = ?')->execute([$tacticId]);
}
/** 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();
}
// ---------------------------------------------------------------------------
// Verlauf und Papierkorb (Tabelle tactic_revisions)
// ---------------------------------------------------------------------------
// Vor einer Aenderung wird der bisherige Stand gesichert - hoechstens alle 30 Minuten je
// Person, damit nicht jeder Pinselstrich eine eigene Version wird.
const TACTIC_REVISION_INTERVAL = 1800;
// So lange bleiben alte Staende und geloeschte Taktiken (Papierkorb) erhalten ...
const TACTIC_REVISION_DAYS = 90;
// ... die neuesten Staende einer bestehenden Taktik aber immer.
const TACTIC_REVISION_KEEP = 5;
const TACTIC_REVISION_REASONS = ['edit', 'delete', 'restore'];
function tactic_revision_cutoff(): string
{
return date('Y-m-d H:i:s', time() - TACTIC_REVISION_DAYS * 86400);
}
/**
* Der komplette Stand einer Taktik fuer den Verlauf: ihre Felder und die Schritte in ihrer
* Reihenfolge samt Zeichnungen. null, wenn es die Taktik nicht gibt.
*
* @return array{tactic: array<string, mixed>, steps: array<int, array<string, mixed>>}|null
*/
function tactic_export(int $tacticId): ?array
{
$stmt = db()->prepare(
'SELECT id, map_slug, name, description, visibility, highlight, highlighted_by, highlighted_at,
created_by, created_at, updated_at
FROM tactics WHERE id = ?'
);
$stmt->execute([$tacticId]);
$tactic = $stmt->fetch();
if (!$tactic) {
return null;
}
$steps = [];
$stepStmt = db()->prepare('SELECT id, title, description FROM tactic_steps WHERE tactic_id = ? ORDER BY sort_order, id');
$stepStmt->execute([$tacticId]);
foreach ($stepStmt->fetchAll() as $row) {
$steps[(int) $row['id']] = [
'title' => (string) $row['title'],
'description' => (string) ($row['description'] ?? ''),
'shapes' => [],
];
}
$shapeStmt = db()->prepare(
'SELECT sh.step_id, sh.shape_type, sh.label, sh.color, sh.width, sh.points, sh.created_by, sh.created_at
FROM tactic_shapes sh JOIN tactic_steps s ON s.id = sh.step_id
WHERE s.tactic_id = ? ORDER BY sh.id'
);
$shapeStmt->execute([$tacticId]);
foreach ($shapeStmt->fetchAll() as $row) {
if (!isset($steps[(int) $row['step_id']])) {
continue;
}
$points = json_decode((string) $row['points'], true);
$steps[(int) $row['step_id']]['shapes'][] = [
'type' => (string) $row['shape_type'],
'label' => (string) $row['label'],
'color' => (string) $row['color'],
'width' => (int) $row['width'],
'points' => is_array($points) ? $points : [],
'created_by' => $row['created_by'] !== null ? (int) $row['created_by'] : null,
'created_at' => (string) $row['created_at'],
];
}
return [
'tactic' => [
'id' => (int) $tactic['id'],
'map_slug' => (string) $tactic['map_slug'],
'name' => (string) $tactic['name'],
'description' => (string) ($tactic['description'] ?? ''),
'visibility' => (string) $tactic['visibility'],
'highlight' => (string) $tactic['highlight'],
'highlighted_by' => $tactic['highlighted_by'] !== null ? (int) $tactic['highlighted_by'] : null,
'highlighted_at' => $tactic['highlighted_at'] !== null ? (string) $tactic['highlighted_at'] : null,
'created_by' => $tactic['created_by'] !== null ? (int) $tactic['created_by'] : null,
'created_at' => (string) $tactic['created_at'],
'updated_at' => $tactic['updated_at'] !== null ? (string) $tactic['updated_at'] : null,
],
'steps' => array_values($steps),
];
}
/**
* Sichert den jetzigen Stand einer Taktik ($reason: edit = vor einer Aenderung, delete = vor
* dem Loeschen, restore = vor dem Wiederherstellen eines anderen Stands). Schlaegt das fehl,
* gibt es eine Exception - die Aenderung, vor der gesichert werden sollte, unterbleibt dann
* ebenfalls (sonst liesse sie sich nicht mehr rueckgaengig machen).
*/
function tactic_snapshot(int $tacticId, string $reason, int $userId): void
{
$data = tactic_export($tacticId);
if ($data === null) {
return;
}
$json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
if ($json === false) {
throw new RuntimeException('Der bisherige Stand der Taktik ließ sich nicht sichern.');
}
$shapes = 0;
foreach ($data['steps'] as $step) {
$shapes += count($step['shapes']);
}
db()->prepare(
'INSERT INTO tactic_revisions (tactic_id, map_slug, name, visibility, highlight, owner_id, reason,
step_count, shape_count, snapshot, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
)->execute([
$tacticId,
$data['tactic']['map_slug'],
$data['tactic']['name'],
$data['tactic']['visibility'],
$data['tactic']['highlight'],
$data['tactic']['created_by'],
in_array($reason, TACTIC_REVISION_REASONS, true) ? $reason : 'edit',
count($data['steps']),
$shapes,
$json,
$userId,
]);
tactic_revisions_prune($tacticId);
// Ab und zu auch die uebrigen Taktiken und den Papierkorb aufraeumen (wie bei den Tempolimits).
if (random_int(1, 20) === 1) {
tactic_revisions_cleanup();
}
}
/**
* Sichert den Stand VOR einer Aenderung - aber nur, wenn der letzte gesicherte Stand dieser
* Taktik aelter als 30 Minuten ist oder von jemand anderem stammt. So gibt es einen Stand je
* Sitzung statt einer Version pro Strich, und vor dem ersten Eingriff eines anderen ist der
* bisherige Stand immer gesichert.
*/
function tactic_snapshot_if_due(int $tacticId, int $userId): void
{
// Massgeblich ist der eigene letzte Stand: Zeichnen zwei Leute abwechselnd in derselben Taktik,
// bekommt trotzdem jeder hoechstens alle 30 Minuten einen - nicht einen pro Strich.
$stmt = db()->prepare(
'SELECT created_at FROM tactic_revisions WHERE tactic_id = ? AND created_by = ? ORDER BY created_at DESC, id DESC LIMIT 1'
);
$stmt->execute([$tacticId, $userId]);
$last = $stmt->fetchColumn();
if ($last !== false && (string) $last > date('Y-m-d H:i:s', time() - TACTIC_REVISION_INTERVAL)) {
return;
}
try {
tactic_snapshot($tacticId, 'edit', $userId);
} catch (PDOException | RuntimeException $e) {
// Laesst sich der Stand vor einer Aenderung nicht sichern (z.B. eine riesige Taktik), bleibt
// die Taktik trotzdem bearbeitbar - fruehere Staende gibt es ja. Loeschen sichert streng (tactic_delete).
error_log('Taktik ' . $tacticId . ': Stand vor der Aenderung nicht gesichert: ' . $e->getMessage());
}
}
/** Entfernt Staende einer Taktik, die aelter als 90 Tage sind - die neuesten fuenf bleiben immer. */
function tactic_revisions_prune(int $tacticId): void
{
$keep = db()->prepare(
'SELECT id FROM tactic_revisions WHERE tactic_id = ? ORDER BY created_at DESC, id DESC LIMIT ' . TACTIC_REVISION_KEEP
);
$keep->execute([$tacticId]);
$ids = array_map('intval', $keep->fetchAll(PDO::FETCH_COLUMN));
$sql = 'DELETE FROM tactic_revisions WHERE tactic_id = ? AND created_at < ?';
if (!empty($ids)) {
$sql .= ' AND id NOT IN (' . implode(',', $ids) . ')';
}
db()->prepare($sql)->execute([$tacticId, tactic_revision_cutoff()]);
}
/**
* Aufraeumen ueber alle Taktiken: Geloeschte, die laenger als 90 Tage im Papierkorb liegen,
* verschwinden ganz; bei allen anderen gilt tactic_revisions_prune (auch bei Taktiken, an
* denen niemand mehr arbeitet).
*/
function tactic_revisions_cleanup(): void
{
$cutoff = tactic_revision_cutoff();
$stmt = db()->prepare('SELECT DISTINCT tactic_id FROM tactic_revisions WHERE created_at < ?');
$stmt->execute([$cutoff]);
$tacticIds = array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN));
if (empty($tacticIds)) {
return;
}
$placeholders = implode(',', array_fill(0, count($tacticIds), '?'));
$existing = db()->prepare("SELECT id FROM tactics WHERE id IN ($placeholders)");
$existing->execute($tacticIds);
$existingIds = array_flip(array_map('intval', $existing->fetchAll(PDO::FETCH_COLUMN)));
$newest = db()->prepare('SELECT MAX(created_at) FROM tactic_revisions WHERE tactic_id = ?');
foreach ($tacticIds as $tacticId) {
if (!isset($existingIds[$tacticId])) {
// Geloescht: der neueste Stand ist die Sicherung vor dem Loeschen. Ist auch die
// aelter als 90 Tage, ist die Taktik endgueltig weg.
$newest->execute([$tacticId]);
if ((string) $newest->fetchColumn() < $cutoff) {
db()->prepare('DELETE FROM tactic_revisions WHERE tactic_id = ?')->execute([$tacticId]);
continue;
}
}
tactic_revisions_prune($tacticId);
}
}
/**
* Die Felder eines gesicherten Stands, nach denen die Rechte geprueft werden - wie eine Zeile
* aus tactics (created_by, visibility, highlight), aber so, wie die Taktik damals war.
*
* @return array{created_by: mixed, visibility: string, highlight: string}
*/
function tactic_revision_subject(array $revision): array
{
return [
'created_by' => $revision['owner_id'] ?? null,
'visibility' => (string) ($revision['visibility'] ?? ''),
'highlight' => (string) ($revision['highlight'] ?? 'none'),
];
}
/** "22.09. 21:14" - aus einem anderen Jahr mit Jahreszahl. */
function tactic_revision_when(string $datetime): string
{
$time = strtotime($datetime);
if ($time === false) {
return $datetime;
}
return date(date('Y', $time) === date('Y') ? 'd.m. H:i' : 'd.m.Y H:i', $time);
}
/** "2 Schritte, 37 Zeichnungen" */
function tactic_revision_counts(array $revision): string
{
$steps = (int) ($revision['step_count'] ?? 0);
$shapes = (int) ($revision['shape_count'] ?? 0);
return $steps . ($steps === 1 ? ' Schritt, ' : ' Schritte, ') . $shapes . ($shapes === 1 ? ' Zeichnung' : ' Zeichnungen');
}
/** Wer einen Stand gesichert hat, fuer die Beschriftung: [nach "von", nach "durch"]. */
function tactic_revision_author(array $revision, int $userId): array
{
if ((int) ($revision['created_by'] ?? 0) === $userId) {
return ['dir', 'dich'];
}
$name = (string) ($revision['by_name'] ?? '');
$name = $name !== '' ? $name : 'unbekannt';
return [$name, $name];
}
/**
* Die gesicherten Staende einer bestehenden Taktik fuer "Verlauf", neueste zuerst. Das
* Bearbeitungsrecht an der Taktik muss schon geprueft sein; zusaetzlich zaehlt der Stand
* selbst: Staende aus der Zeit, als die Taktik privat war, sieht nur ihr Ersteller.
*
* @return array<int, array{id: int, label: string}>
*/
function tactic_revision_list(array $tactic, int $userId): array
{
$stmt = db()->prepare(
"SELECT r.id, r.name, r.visibility, r.highlight, r.owner_id, r.reason, r.step_count, r.shape_count,
r.created_by, r.created_at, COALESCE(NULLIF(u.display_name, ''), u.username) AS by_name
FROM tactic_revisions r
LEFT JOIN users u ON u.id = r.created_by
WHERE r.tactic_id = ?
ORDER BY r.created_at DESC, r.id DESC"
);
$stmt->execute([(int) $tactic['id']]);
$list = [];
foreach ($stmt->fetchAll() as $row) {
if (!tactic_can_view(tactic_revision_subject($row), $userId)) {
continue;
}
[$from, $by] = tactic_revision_author($row, $userId);
$what = match ((string) $row['reason']) {
'delete' => 'vor dem Löschen durch ' . $by,
'restore' => 'vor dem Wiederherstellen durch ' . $by,
default => 'vor Änderungen von ' . $from,
};
$label = tactic_revision_when((string) $row['created_at']) . ' – ' . $what . ' · ' . tactic_revision_counts($row);
if ((string) $row['name'] !== (string) $tactic['name']) {
$label .= ' · „' . $row['name'] . '“';
}
$list[] = ['id' => (int) $row['id'], 'label' => $label];
}
return $list;
}
/**
* Papierkorb einer Region: geloeschte Taktiken der letzten 90 Tage, die das Konto
* wiederherstellen darf. Dafuer braucht es dieselben Rechte wie zum Loeschen - gemessen am
* gesicherten Stand, denn die Taktik selbst gibt es nicht mehr. Private anderer tauchen nie auf.
*
* @return array<int, array{revision_id: int, tactic_id: int, name: string, label: string}>
*/
function tactics_deleted_for_map(string $slug, int $userId): array
{
$stmt = db()->prepare(
"SELECT r.id, r.tactic_id, r.name, r.visibility, r.highlight, r.owner_id, r.step_count, r.shape_count,
r.created_by, r.created_at, COALESCE(NULLIF(u.display_name, ''), u.username) AS by_name
FROM tactic_revisions r
LEFT JOIN tactics t ON t.id = r.tactic_id
LEFT JOIN users u ON u.id = r.created_by
WHERE r.map_slug = ? AND r.reason = 'delete' AND t.id IS NULL AND r.created_at >= ?
ORDER BY r.created_at DESC, r.id DESC"
);
$stmt->execute([$slug, tactic_revision_cutoff()]);
$list = [];
$seen = [];
foreach ($stmt->fetchAll() as $row) {
// Wurde eine Taktik mehrmals geloescht (und zwischendurch wiederhergestellt), zaehlt das letzte Mal.
$tacticId = (int) $row['tactic_id'];
if (isset($seen[$tacticId])) {
continue;
}
$seen[$tacticId] = true;
if (!tactic_can_delete(tactic_revision_subject($row), $userId)) {
continue;
}
[, $by] = tactic_revision_author($row, $userId);
$list[] = [
'revision_id' => (int) $row['id'],
'tactic_id' => $tacticId,
'name' => (string) $row['name'],
'label' => '„' . $row['name'] . '“ – gelöscht am ' . tactic_revision_when((string) $row['created_at'])
. ' durch ' . $by . ' · ' . tactic_revision_counts($row)
. ($row['visibility'] === 'private' ? ' · privat' : ''),
];
}
return $list;
}
/**
* Welche dieser Konten gibt es noch? Beim Wiederherstellen werden Verweise auf geloeschte
* Konten zu NULL - sonst scheitert das Einfuegen am Fremdschluessel.
*
* @param array<int, mixed> $ids
* @return array<int, true>
*/
function tactic_existing_users(array $ids): array
{
$ids = array_values(array_unique(array_filter(array_map('intval', $ids), static fn (int $id): bool => $id > 0)));
if (empty($ids)) {
return [];
}
$stmt = db()->prepare('SELECT id FROM users WHERE id IN (' . implode(',', array_fill(0, count($ids), '?')) . ')');
$stmt->execute($ids);
return array_fill_keys(array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN)), true);
}
/** Zeitpunkt aus einem gesicherten Stand, sonst jetzt. */
function tactic_datetime(mixed $value): string
{
$value = is_string($value) ? $value : '';
return preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $value) === 1 ? $value : date('Y-m-d H:i:s');
}
/**
* Legt die Schritte und Zeichnungen eines gesicherten Stands (tactic_export) am Ende einer
* Taktik an. Gibt die Zahl der Schritte zurueck - mindestens einer entsteht immer.
*
* @param array<int, mixed> $steps
*/
function tactic_import_steps(int $tacticId, array $steps): int
{
$userIds = [];
foreach ($steps as $step) {
foreach ((is_array($step) && is_array($step['shapes'] ?? null) ? $step['shapes'] : []) as $shape) {
$userIds[] = is_array($shape) ? ($shape['created_by'] ?? 0) : 0;
}
}
$users = tactic_existing_users($userIds);
$insert = db()->prepare(
'INSERT INTO tactic_shapes (step_id, shape_type, label, color, width, points, created_by, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
);
$count = 0;
foreach ($steps as $step) {
if (!is_array($step)) {
continue;
}
$stepId = tactic_append_step(
$tacticId,
mb_substr((string) ($step['title'] ?? ''), 0, 120),
(string) ($step['description'] ?? '')
);
$count++;
foreach ((is_array($step['shapes'] ?? null) ? $step['shapes'] : []) as $shape) {
$type = is_array($shape) ? (string) ($shape['type'] ?? '') : '';
if (!in_array($type, TACTIC_SHAPE_TYPES, true) || !is_array($shape['points'] ?? null)) {
continue;
}
$points = json_encode($shape['points']);
if ($points === false) {
continue;
}
$color = (string) ($shape['color'] ?? '');
$creator = (int) ($shape['created_by'] ?? 0);
$insert->execute([
$stepId,
$type,
mb_substr((string) ($shape['label'] ?? ''), 0, 200),
preg_match('/^#[0-9a-fA-F]{6}$/', $color) === 1 ? strtolower($color) : '#ffd700',
max(1, min(30, (int) ($shape['width'] ?? 4))),
$points,
isset($users[$creator]) ? $creator : null,
tactic_datetime($shape['created_at'] ?? null),
]);
}
}
if ($count === 0) {
tactic_append_step($tacticId, '');
$count = 1;
}
return $count;
}