Asked for: "das consilium elyseum wurde umbenannt zu DACH Elyos. pass das bitte an auf der website". - CONSILIUM_NAME is 'DACH Elyos', and every visible text follows it: sidebar, the alliance page, member tab, raid area, calendar audience and badge, iCal note, map live sessions and share buttons, admin pages (Verwaltung -> DACH Elyos, Discord-Bot, Berechtigungsgruppen), flash messages, log entries, permission descriptions (synced to the database by schema_sync_core_permissions()) and the privacy page. - The name takes no article, so the sentences around it changed too: "von DACH Elyos", "in DACH Elyos", "für DACH Elyos" instead of "des Consiliums", "im Consilium", "für das Consilium". The bot channel label is now "Raid-Kanal DACH Elyos". - Internal names stay "consilium": permission keys, tables, settings, files and URLs (?bereich=consilium, ?tab=consilium), so nothing in the database or in existing links changes. includes/consilium.php says so. - README: section renamed to "DACH Elyos" (anchor #dach-elyos). - No patch note (alliance topics stay out of them). The bot's two "Consilium" error texts in live_tactics.py never reach the page - the map only reads the status code - so the bot needs no update. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1038 lines
42 KiB
PHP
1038 lines
42 KiB
PHP
<?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', 'token'];
|
||
|
||
// Figuren (Form 'token') des Raidplaners - wie TOKEN_ICONS in assets/map/js/views/TokenIcons.js
|
||
const TACTIC_TOKEN_ICONS = [
|
||
'class-templar', 'class-gladiator', 'class-assassin', 'class-ranger',
|
||
'class-sorcerer', 'class-spiritmaster', 'class-cleric', 'class-chanter',
|
||
'role-tank', 'role-heal', 'role-dps',
|
||
'num-1', 'num-2', 'num-3', 'num-4', 'num-5', 'num-6', 'num-7', 'num-8',
|
||
'mark-a', 'mark-b', 'mark-c', 'mark-d', 'mark-star', 'mark-circle', 'mark-triangle', 'mark-square', 'mark-cross',
|
||
'boss', 'add', 'danger', 'stack', 'spread', 'tower', 'orb', 'bomb',
|
||
];
|
||
|
||
/**
|
||
* Kennung einer Zeichnung ueber die Schritte hinweg: "+ Kopie dieses Schritts" und das Kopieren
|
||
* einer Taktik uebernehmen sie, so erkennt die Karte beim Blaettern dieselbe Figur und laesst sie
|
||
* an ihre neue Stelle laufen.
|
||
*/
|
||
function tactic_new_ref(): string
|
||
{
|
||
return bin2hex(random_bytes(5));
|
||
}
|
||
|
||
/** Kennung aus einem gesicherten Stand o.ae. - ungueltige werden neu vergeben. */
|
||
function tactic_clean_ref(mixed $ref): string
|
||
{
|
||
return is_string($ref) && preg_match('/^[A-Za-z0-9]{1,16}$/', $ref) === 1 ? $ref : tactic_new_ref();
|
||
}
|
||
|
||
// 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 Karten, wie sie der Viewer kennt: die Regionen (assets/map/data/maps.json) und die Dungeon-
|
||
* und Raid-Karten des Raidplaners (assets/map/dungeons/dungeons.json). Fehlt maps.json - etwa weil
|
||
* der Datenordner noch nicht hochgeladen ist -, wird bei allen anderen Karten 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;
|
||
}
|
||
require_once __DIR__ . '/dungeon_maps.php';
|
||
if (isset(dungeon_maps()[$slug])) {
|
||
return true;
|
||
}
|
||
|
||
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.
|
||
* $guestIds: Gast des Consiliums - nur diese (oeffentlichen) Taktiken, nur zum Ansehen (Rechte alle aus).
|
||
*
|
||
* @param array<int, int>|null $guestIds
|
||
* @return array<int, array<string, mixed>>
|
||
*/
|
||
function tactics_for_map(string $slug, int $userId, ?array $guestIds = null): array
|
||
{
|
||
$guest = $guestIds !== null;
|
||
if ($guest && !$guestIds) {
|
||
return [];
|
||
}
|
||
$where = $guest
|
||
? "t.visibility = 'public' AND t.id IN (" . implode(',', array_fill(0, count($guestIds), '?')) . ')'
|
||
: "(t.visibility = 'public' OR t.created_by = ?)";
|
||
$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 $where
|
||
ORDER BY FIELD(t.highlight, 'official', 'recommended', 'none'), t.name, t.id"
|
||
);
|
||
$stmt->execute(array_merge([$slug], $guest ? array_map('intval', array_values($guestIds)) : [$userId]));
|
||
|
||
$tactics = [];
|
||
foreach ($stmt->fetchAll() as $row) {
|
||
$isMine = !$guest && (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' => !$guest && tactic_can_edit($row, $userId),
|
||
'can_delete' => !$guest && tactic_can_delete($row, $userId),
|
||
'can_change_visibility' => !$guest && 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, icon, color, width, points, ref 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'],
|
||
'icon' => (string) ($row['icon'] ?? ''),
|
||
'color' => (string) $row['color'],
|
||
'width' => (int) $row['width'],
|
||
'points' => is_array($points) ? $points : [],
|
||
'ref' => (string) ($row['ref'] ?? ''),
|
||
];
|
||
}
|
||
|
||
/**
|
||
* Figur einer Zeichnung pruefen: bei 'token' eine der bekannten, sonst keine. null, wenn eine
|
||
* Figur fehlt oder unbekannt ist.
|
||
*/
|
||
function tactic_clean_icon(string $type, mixed $icon): ?string
|
||
{
|
||
if ($type !== 'token') {
|
||
return '';
|
||
}
|
||
return is_string($icon) && in_array($icon, TACTIC_TOKEN_ICONS, true) ? $icon : null;
|
||
}
|
||
|
||
/**
|
||
* 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', 'token' => $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;
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Live-Ansicht: Striche erscheinen bei allen, die die Taktik offen haben, waehrend sie entstehen
|
||
// ---------------------------------------------------------------------------
|
||
|
||
// Verteiler ist die Bot-API (live_tactics.py im Bot) - sie prueft die Tickets mit demselben
|
||
// Schluessel (raids_api.key = API_SECRET_KEY im Bot). Der Kontext muss dort gleich lauten.
|
||
const TACTIC_LIVE_CONTEXT = 'lumina-tactics-live-v1.';
|
||
// So lange gilt ein Ticket - danach holt sich die Karte ein neues, die Rechte werden neu geprueft.
|
||
const TACTIC_LIVE_TTL = 1800;
|
||
|
||
function tactic_live_b64(string $bytes): string
|
||
{
|
||
return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
|
||
}
|
||
|
||
/**
|
||
* Ticket fuer die Live-Ansicht einer Taktik, die das Konto sehen darf (vorher pruefen): zuschauen
|
||
* darf jeder, der sie sieht - live zeichnen, wer sie bearbeiten darf. Der Browser verbindet sich
|
||
* damit direkt mit dem Bot; gespeichert wird weiterhin nur hier (tactics_api.php).
|
||
* $guest: Gast des Consiliums in einer freigegebenen Sitzung (vorher pruefen) - zeichnen nur mit
|
||
* consilium.draw, der Verteiler laesst ihn nur zeichnen und trennt ihn, sobald die Freigabe endet.
|
||
* null, wenn die Bot-API nicht eingerichtet ist.
|
||
*
|
||
* @param array{id: mixed, created_by: mixed, visibility: string, highlight?: string} $tactic
|
||
* @param array<string, mixed> $user
|
||
* @return array{stream_url: string, send_url: string, token: string, expires_in: int, can_draw: bool, user_id: int, guest: bool}|null
|
||
*/
|
||
function tactic_live_ticket(array $tactic, array $user, bool $guest = false): ?array
|
||
{
|
||
require_once __DIR__ . '/raids_api.php';
|
||
try {
|
||
$api = raids_api_config();
|
||
} catch (RuntimeException $e) {
|
||
return null;
|
||
}
|
||
$base = $api['live_url'] !== '' ? $api['live_url'] : (string) preg_replace('#/api/raids$#', '', $api['url']);
|
||
|
||
$userId = (int) $user['id'];
|
||
$name = trim((string) ($user['display_name'] ?? ''));
|
||
$canDraw = $guest ? user_has_permission('consilium.draw') : tactic_can_edit($tactic, $userId);
|
||
$ttl = $guest ? TACTIC_LIVE_GUEST_TTL : TACTIC_LIVE_TTL;
|
||
$claims = [
|
||
'u' => $userId,
|
||
'n' => mb_substr($name !== '' ? $name : (string) ($user['username'] ?? ''), 0, 60),
|
||
't' => (int) $tactic['id'],
|
||
'e' => $canDraw ? 1 : 0,
|
||
'x' => time() + $ttl,
|
||
];
|
||
if ($guest) {
|
||
require_once __DIR__ . '/consilium.php';
|
||
$claims['c'] = 1;
|
||
$claims['l'] = (string) consilium_legion_name(consilium_member_legion_id($userId));
|
||
}
|
||
$payload = tactic_live_b64((string) json_encode($claims, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE));
|
||
$token = $payload . '.' . tactic_live_b64(hash_hmac('sha256', TACTIC_LIVE_CONTEXT . $payload, $api['key'], true));
|
||
$path = $base . '/api/live/tactics/' . (int) $tactic['id'];
|
||
|
||
return [
|
||
'stream_url' => $path . '/stream?token=' . rawurlencode($token),
|
||
'send_url' => $path . '/send',
|
||
'token' => $token,
|
||
'expires_in' => $ttl,
|
||
'can_draw' => $canDraw,
|
||
'user_id' => $userId,
|
||
'guest' => $guest,
|
||
];
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Consilium Elyseum: laufende Live-Sitzungen fuer die verbuendeten Legionen freigeben
|
||
// ---------------------------------------------------------------------------
|
||
// Wer eine oeffentliche Taktik bearbeiten darf, gibt ihre laufende Live-Sitzung fuer das Consilium frei (Aktion
|
||
// consilium_share). Die Freigabe haelt der Verteiler im Bot: Sie gilt nur fuer diese Sitzung und endet von selbst,
|
||
// wenn eine Minute lang niemand aus der Legion mehr dabei ist. Mitglieder verbuendeter Legionen (consilium_only)
|
||
// sehen auf der Karte nur solche Sitzungen - zuschauen, mit consilium.draw auch zeichnen: Striche, Flaechen,
|
||
// Punkte und Text, aber keine Figuren, nichts loeschen oder verschieben, keine Taktiken oder Schritte.
|
||
|
||
const TACTIC_GUEST_SHAPE_TYPES = ['pen', 'line', 'arrow', 'area', 'circle', 'point', 'text'];
|
||
// Gaeste bekommen kuerzer gueltige Tickets - ihre Rechte werden oefter neu geprueft
|
||
const TACTIC_LIVE_GUEST_TTL = 600;
|
||
|
||
/**
|
||
* Anfrage an den Live-Verteiler im Bot (mit dem API-Schluessel, nicht aus dem Browser). Kurze Wartezeit - die
|
||
* Karte soll nicht haengen, wenn der Bot gerade neu startet.
|
||
*
|
||
* @return array{code: int, data: array<string, mixed>}
|
||
* @throws RuntimeException wenn der Bot nicht eingerichtet oder nicht erreichbar ist
|
||
*/
|
||
function tactic_live_api(string $method, string $path, ?array $body = null): array
|
||
{
|
||
require_once __DIR__ . '/raids_api.php';
|
||
if (!function_exists('curl_init')) {
|
||
throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.');
|
||
}
|
||
$api = raids_api_config();
|
||
$headers = ['X-API-Key: ' . $api['key']];
|
||
$ch = curl_init(preg_replace('#/raids$#', '', $api['url']) . $path);
|
||
$options = [CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_TIMEOUT => 4, CURLOPT_CONNECTTIMEOUT => 3];
|
||
if ($body !== null) {
|
||
$headers[] = 'Content-Type: application/json';
|
||
$options[CURLOPT_POSTFIELDS] = json_encode($body, JSON_UNESCAPED_UNICODE);
|
||
}
|
||
$options[CURLOPT_HTTPHEADER] = $headers;
|
||
curl_setopt_array($ch, $options);
|
||
$response = curl_exec($ch);
|
||
$code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||
$error = curl_error($ch);
|
||
curl_close($ch);
|
||
if ($response === false) {
|
||
throw new RuntimeException('Der Live-Verteiler ist nicht erreichbar: ' . $error);
|
||
}
|
||
$data = json_decode((string) $response, true);
|
||
return ['code' => $code, 'data' => is_array($data) ? $data : []];
|
||
}
|
||
|
||
/**
|
||
* Laufende Live-Sitzungen laut Verteiler (einmal je Seitenaufruf): Taktik-ID => wie viele aus der Legion
|
||
* (members) und wie viele Gaeste (guests) dabei sind und die Freigabe fuers Consilium (null = keine).
|
||
*
|
||
* @return array<int, array{members: int, guests: int, consilium: array{by: string, since: int}|null}>
|
||
* @throws RuntimeException
|
||
*/
|
||
function tactic_live_rooms(): array
|
||
{
|
||
static $rooms = null;
|
||
if ($rooms !== null) {
|
||
return $rooms;
|
||
}
|
||
$result = tactic_live_api('GET', '/live/rooms');
|
||
if ($result['code'] !== 200 || ($result['data']['status'] ?? '') !== 'success') {
|
||
throw new RuntimeException('Der Live-Verteiler antwortete mit Statuscode ' . $result['code'] . '.');
|
||
}
|
||
$rooms = [];
|
||
foreach ((array) ($result['data']['rooms'] ?? []) as $room) {
|
||
if (!is_array($room) || (int) ($room['tactic'] ?? 0) <= 0) {
|
||
continue;
|
||
}
|
||
$share = is_array($room['consilium'] ?? null) ? $room['consilium'] : null;
|
||
$rooms[(int) $room['tactic']] = [
|
||
'members' => (int) ($room['members'] ?? 0),
|
||
'guests' => (int) ($room['guests'] ?? 0),
|
||
'consilium' => $share !== null ? ['by' => (string) ($share['by'] ?? ''), 'since' => (int) ($share['since'] ?? 0)] : null,
|
||
];
|
||
}
|
||
return $rooms;
|
||
}
|
||
|
||
/**
|
||
* Die fuer das Consilium freigegebenen Live-Sitzungen, die gerade laufen - nur oeffentliche Taktiken,
|
||
* die zuletzt freigegebene zuerst.
|
||
*
|
||
* @return array<int, array{tactic_id: int, name: string, map_slug: string, map_name: string, url: string, author: string,
|
||
* steps: int, members: int, guests: int, shared_by: string, since: int}>
|
||
* @throws RuntimeException
|
||
*/
|
||
function tactics_consilium_sessions(): array
|
||
{
|
||
$shared = array_filter(tactic_live_rooms(), static fn (array $room): bool => $room['consilium'] !== null);
|
||
if (!$shared) {
|
||
return [];
|
||
}
|
||
require_once __DIR__ . '/map_links.php';
|
||
$ids = array_keys($shared);
|
||
$stmt = db()->prepare(
|
||
"SELECT t.id, t.name, t.map_slug, COALESCE(NULLIF(u.display_name, ''), u.username) AS author,
|
||
(SELECT COUNT(*) FROM tactic_steps s WHERE s.tactic_id = t.id) AS steps
|
||
FROM tactics t LEFT JOIN users u ON u.id = t.created_by
|
||
WHERE t.visibility = 'public' AND t.id IN (" . implode(',', array_fill(0, count($ids), '?')) . ')'
|
||
);
|
||
$stmt->execute($ids);
|
||
|
||
$names = map_link_names();
|
||
$sessions = [];
|
||
foreach ($stmt->fetchAll() as $row) {
|
||
$room = $shared[(int) $row['id']];
|
||
$slug = (string) $row['map_slug'];
|
||
$sessions[] = [
|
||
'tactic_id' => (int) $row['id'],
|
||
'name' => (string) $row['name'],
|
||
'map_slug' => $slug,
|
||
'map_name' => $names[$slug] ?? ucwords(str_replace('-', ' ', $slug)),
|
||
'url' => map_link_page($slug) . '?' . http_build_query(['karte' => $slug, 'taktik' => (int) $row['id']]),
|
||
'author' => (string) ($row['author'] ?? ''),
|
||
'steps' => (int) $row['steps'],
|
||
'members' => $room['members'],
|
||
'guests' => $room['guests'],
|
||
'shared_by' => $room['consilium']['by'],
|
||
'since' => $room['consilium']['since'],
|
||
];
|
||
}
|
||
usort($sessions, static fn (array $a, array $b): int => $b['since'] <=> $a['since']);
|
||
return $sessions;
|
||
}
|
||
|
||
/**
|
||
* Freigabe einer laufenden Live-Sitzung fuers Consilium an- oder ausschalten (Rechte vorher pruefen).
|
||
* Liefert die Freigabe danach ({by, since} bzw. null).
|
||
*
|
||
* @param array<string, mixed> $user
|
||
* @return array{by: string, since: int}|null
|
||
* @throws RuntimeException mit einer Meldung fuer die Karte
|
||
*/
|
||
function tactic_live_share(int $tacticId, bool $on, array $user): ?array
|
||
{
|
||
$name = trim((string) ($user['display_name'] ?? ''));
|
||
$result = tactic_live_api('POST', '/live/tactics/' . $tacticId . '/consilium', [
|
||
'on' => $on,
|
||
'by' => mb_substr($name !== '' ? $name : (string) ($user['username'] ?? ''), 0, 60),
|
||
]);
|
||
if ($result['code'] === 409) {
|
||
throw new RuntimeException('Die Live-Verbindung dieser Taktik steht gerade nicht – kurz warten und noch einmal versuchen.');
|
||
}
|
||
if ($result['code'] === 404) {
|
||
throw new RuntimeException('Der Live-Verteiler kann noch nicht für ' . CONSILIUM_NAME . ' freigeben – der Bot braucht ein Update.');
|
||
}
|
||
if ($result['code'] !== 200 || ($result['data']['status'] ?? '') !== 'success') {
|
||
throw new RuntimeException('Der Live-Verteiler antwortete mit Statuscode ' . $result['code'] . '.');
|
||
}
|
||
$share = $result['data']['consilium'] ?? null;
|
||
return is_array($share) ? ['by' => (string) ($share['by'] ?? ''), 'since' => (int) ($share['since'] ?? 0)] : null;
|
||
}
|
||
|
||
/** Freigabe fuers Consilium beenden, ohne dass es auffaellt, wenn es nicht klappt (Taktik privat gestellt/geloescht). */
|
||
function tactic_live_unshare_quietly(int $tacticId, array $user): void
|
||
{
|
||
require_once __DIR__ . '/consilium.php';
|
||
if (!consilium_enabled()) {
|
||
return;
|
||
}
|
||
try {
|
||
tactic_live_share($tacticId, false, $user);
|
||
} catch (RuntimeException $e) {
|
||
// Dann endet sie spaetestens mit der Sitzung - Gaeste sehen private/geloeschte Taktiken ohnehin nicht mehr
|
||
}
|
||
}
|
||
|
||
/** 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.icon, sh.color, sh.width, sh.points, sh.ref, 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'],
|
||
'icon' => (string) $row['icon'],
|
||
'color' => (string) $row['color'],
|
||
'width' => (int) $row['width'],
|
||
'points' => is_array($points) ? $points : [],
|
||
'ref' => (string) $row['ref'],
|
||
'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, icon, color, width, points, ref, 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;
|
||
}
|
||
$icon = tactic_clean_icon($type, $shape['icon'] ?? null);
|
||
$points = json_encode($shape['points']);
|
||
if ($icon === null || $points === false) {
|
||
continue;
|
||
}
|
||
$color = (string) ($shape['color'] ?? '');
|
||
$creator = (int) ($shape['created_by'] ?? 0);
|
||
$insert->execute([
|
||
$stepId,
|
||
$type,
|
||
mb_substr((string) ($shape['label'] ?? ''), 0, 200),
|
||
$icon,
|
||
preg_match('/^#[0-9a-fA-F]{6}$/', $color) === 1 ? strtolower($color) : '#ffd700',
|
||
max(1, min(30, (int) ($shape['width'] ?? 4))),
|
||
$points,
|
||
// Staende von vor dem Raidplaner haben keine Kennung - dann eine neue
|
||
tactic_clean_ref($shape['ref'] ?? null),
|
||
isset($users[$creator]) ? $creator : null,
|
||
tactic_datetime($shape['created_at'] ?? null),
|
||
]);
|
||
}
|
||
}
|
||
|
||
if ($count === 0) {
|
||
tactic_append_step($tacticId, '');
|
||
$count = 1;
|
||
}
|
||
return $count;
|
||
}
|