diff --git a/assets/map/index.html b/assets/map/index.html index 9f96366..b363a3b 100644 --- a/assets/map/index.html +++ b/assets/map/index.html @@ -59,7 +59,7 @@

Taktiken

- + +

+

Schritte

    diff --git a/assets/map/js/controllers/TacticController.js b/assets/map/js/controllers/TacticController.js index 9af839f..5daec45 100644 --- a/assets/map/js/controllers/TacticController.js +++ b/assets/map/js/controllers/TacticController.js @@ -2,8 +2,10 @@ * TacticController - Taktiken auf der Karte: anlegen, in Schritte gliedern, zeichnen. * * Eine Taktik gehoert zu einer Region und besteht aus Schritten (Schritt 1, Schritt 2 ...), - * jeder Schritt ist eine eigene Zeichenebene. Ansehen darf jeder mit map.view, anlegen und - * zeichnen nur, wer map.tactics hat - das entscheidet der Server (can_edit). + * jeder Schritt ist eine eigene Zeichenebene. Jeder mit map.view legt eigene Taktiken an - + * privat oder oeffentlich. Fremde oeffentliche bearbeitet nur, wer map.tactics hat, und mit + * map.tactics.highlight lassen sie sich als "Empfohlen"/"Offiziell" markieren. Was erlaubt + * ist, entscheidet der Server (can_create, can_highlight, pro Taktik can_edit). */ class TacticController { @@ -15,7 +17,8 @@ class TacticController { this.slug = null; this.tactics = []; - this.canEdit = false; + this.canCreate = false; + this.canHighlight = false; this.selectedId = null; this.stepIndex = 0; this.showGhosts = false; @@ -39,6 +42,9 @@ class TacticController { detail: $('tp-detail'), name: $('tp-name'), desc: $('tp-desc'), + meta: $('tp-meta'), + highlight: $('tp-highlight'), + highlightSelect: $('tp-highlight-select'), edit: $('tp-edit'), del: $('tp-delete'), steps: $('tp-steps'), @@ -84,6 +90,12 @@ class TacticController { return this.tactics.find(t => t.id === this.selectedId) || null; } + /** Darf das Konto die gewaehlte Taktik bearbeiten (eigene bzw. als Leitung)? */ + canEditCurrent() { + const tactic = this.currentTactic(); + return !!(tactic && tactic.can_edit); + } + currentStep() { const tactic = this.currentTactic(); return tactic ? tactic.steps[this.stepIndex] || null : null; @@ -109,11 +121,13 @@ class TacticController { const data = await this.service.list(this.slug); if (token !== this.loadToken) return; this.tactics = data.tactics || []; - this.canEdit = !!data.can_edit; + this.canCreate = !!data.can_create; + this.canHighlight = !!data.can_highlight; } catch (e) { if (token !== this.loadToken) return; this.tactics = []; - this.canEdit = false; + this.canCreate = false; + this.canHighlight = false; error = e; } @@ -130,7 +144,7 @@ class TacticController { if (focused >= 0) this.stepIndex = focused; this.stepIndex = Math.max(0, Math.min(this.stepIndex, tactic.steps.length - 1)); } - if (!this.canEdit || !tactic) this.setTool('pan'); + if (!this.canEditCurrent()) this.setTool('pan'); this.renderUI(); this.redraw(); @@ -164,37 +178,71 @@ class TacticController { this.el.message.classList.toggle('hidden', !text); } + /** Kleine Kennzeichen hinter dem Namen: Offiziell/Empfohlen, privat. */ + static badges(tactic) { + const badges = []; + if (tactic.highlight === 'official') badges.push('★ Offiziell'); + if (tactic.highlight === 'recommended') badges.push('👍 Empfohlen'); + if (tactic.visibility === 'private') badges.push('🔒 Privat'); + return badges.join(''); + } + renderUI() { const esc = TacticController.esc; const tactic = this.currentTactic(); - this.el.panel.classList.toggle('can-edit', this.canEdit); - this.el.newBtn.classList.toggle('hidden', !this.canEdit); + this.el.panel.classList.toggle('can-edit', this.canEditCurrent()); + this.el.newBtn.classList.toggle('hidden', !this.canCreate); - // Liste der Taktiken + // Liste der Taktiken - hervorgehobene zuerst, dann die eigenen, dann die der anderen if (this.tactics.length === 0) { this.el.list.innerHTML = this.el.message.classList.contains('hidden') - ? `

    Noch keine Taktiken für diese Karte.${this.canEdit ? ' Mit „+ Neu“ legst du die erste an.' : ''}

    ` + ? `

    Noch keine Taktiken für diese Karte.${this.canCreate ? ' Mit „+ Neu“ legst du deine erste an – nur für dich oder für alle.' : ''}

    ` : ''; } else { - this.el.list.innerHTML = this.tactics.map(t => ` - `).join(''); + const groups = [ + { title: 'Offiziell & empfohlen', items: this.tactics.filter(t => t.highlight !== 'none') }, + { title: 'Meine Taktiken', items: this.tactics.filter(t => t.highlight === 'none' && t.is_mine) }, + { title: 'Von anderen', items: this.tactics.filter(t => t.highlight === 'none' && !t.is_mine) } + ].filter(g => g.items.length > 0); + const showTitles = groups.length > 1; + + this.el.list.innerHTML = groups.map(group => ` + ${showTitles ? `
    ${group.title}
    ` : ''} + ${group.items.map(t => ` + `).join('')}`).join(''); } // Details der gewaehlten Taktik this.el.detail.classList.toggle('hidden', !tactic); if (tactic) { this.el.name.textContent = tactic.name; + const meta = [ + tactic.is_mine ? 'Deine Taktik' : (tactic.author ? `Von ${tactic.author}` : ''), + tactic.visibility === 'private' ? 'nur für dich sichtbar' : 'für alle sichtbar', + tactic.highlight !== 'none' && tactic.highlighted_by + ? `${tactic.highlight === 'official' ? 'offiziell' : 'empfohlen'} von ${tactic.highlighted_by}` : '' + ].filter(Boolean); + this.el.meta.innerHTML = TacticController.badges(tactic) + `${esc(meta.join(' · '))}`; + + // Hervorheben: nur mit Berechtigung und nur bei oeffentlichen Taktiken + const canHighlight = this.canHighlight && tactic.visibility === 'public'; + this.el.highlight.classList.toggle('hidden', !canHighlight); + if (canHighlight) this.el.highlightSelect.value = tactic.highlight; + this.el.desc.textContent = tactic.description; this.el.desc.classList.toggle('hidden', !tactic.description); this.el.ghosts.checked = this.showGhosts; this.renderSteps(tactic); } - this.el.toolbar.classList.toggle('hidden', !(this.canEdit && tactic)); + this.el.toolbar.classList.toggle('hidden', !this.canEditCurrent()); this.renderStepBar(); } @@ -207,7 +255,7 @@ class TacticController { ${i + 1} ${esc(TacticController.stepLabel(step, i))} ${step.shapes.length} - ${this.canEdit ? ` + ${tactic.can_edit ? ` @@ -279,11 +327,22 @@ class TacticController { // Taktiken und Schritte bearbeiten // ------------------------------------------------------------------ + static visibilityField(value) { + return { + name: 'visibility', label: 'Sichtbarkeit', type: 'select', value: value || 'private', + options: [ + { value: 'private', label: '🔒 Privat – nur ich sehe sie' }, + { value: 'public', label: '🌐 Öffentlich – alle Mitglieder können sie ansehen' } + ] + }; + } + async newTactic() { const values = await this.dialog('Neue Taktik', [ { name: 'name', label: 'Name', required: true, max: 120, placeholder: 'z. B. Festung Süd – Angriff' }, { name: 'description', label: 'Beschreibung (optional)', type: 'textarea', max: 5000, - placeholder: 'Ziel, Aufstellung, Rollen …' } + placeholder: 'Ziel, Aufstellung, Rollen …' }, + TacticController.visibilityField('private') ], 'Anlegen'); if (!values) return; @@ -292,23 +351,40 @@ class TacticController { this.selectedId = result.tactic_id; this.stepIndex = 0; await this.reload(); - if (this.canEdit) this.setTool('pen'); - this.toast('Taktik angelegt – zeichne jetzt Schritt 1 ein.'); + if (this.canEditCurrent()) this.setTool('pen'); + this.toast(values.visibility === 'public' + ? 'Öffentliche Taktik angelegt – zeichne jetzt Schritt 1 ein.' + : 'Private Taktik angelegt – nur du siehst sie. Zeichne jetzt Schritt 1 ein.'); } async editTactic() { const tactic = this.currentTactic(); if (!tactic) return; - const values = await this.dialog('Taktik bearbeiten', [ + const fields = [ { name: 'name', label: 'Name', required: true, max: 120, value: tactic.name }, { name: 'description', label: 'Beschreibung (optional)', type: 'textarea', max: 5000, value: tactic.description } - ]); + ]; + // Die Sichtbarkeit legt nur der Ersteller fest. + if (tactic.is_mine) fields.push(TacticController.visibilityField(tactic.visibility)); + const values = await this.dialog('Taktik bearbeiten', fields); if (!values) return; + if (values.visibility === 'private' && tactic.visibility === 'public' && tactic.highlight !== 'none' + && !confirm('Die Taktik ist hervorgehoben. Wird sie privat, geht die Hervorhebung verloren. Trotzdem privat stellen?')) { + return; + } if (await this.run('tactic_update', { tactic_id: tactic.id, ...values })) { await this.reload(); } } + async setHighlight(value) { + const tactic = this.currentTactic(); + if (!tactic || value === tactic.highlight) return; + const result = await this.run('tactic_highlight', { tactic_id: tactic.id, highlight: value }); + if (result && result.message) this.toast(result.message); + await this.reload(); + } + async deleteTactic() { const tactic = this.currentTactic(); if (!tactic || !confirm(`Taktik „${tactic.name}“ mit allen Schritten und Zeichnungen löschen?`)) return; @@ -624,9 +700,17 @@ class TacticController { label.className = 'td-field'; label.textContent = field.label; - const input = document.createElement(field.type === 'textarea' ? 'textarea' : 'input'); + const tag = field.type === 'textarea' ? 'textarea' : (field.type === 'select' ? 'select' : 'input'); + const input = document.createElement(tag); if (field.type === 'textarea') { input.rows = 4; + } else if (field.type === 'select') { + (field.options || []).forEach(option => { + const el = document.createElement('option'); + el.value = option.value; + el.textContent = option.label; + input.appendChild(el); + }); } else { input.type = 'text'; } @@ -683,6 +767,7 @@ class TacticController { el.newBtn.addEventListener('click', () => this.newTactic()); el.edit.addEventListener('click', () => this.editTactic()); el.del.addEventListener('click', () => this.deleteTactic()); + el.highlightSelect.addEventListener('change', () => this.setHighlight(el.highlightSelect.value)); el.stepAdd.addEventListener('click', () => this.addStep(false)); el.stepCopy.addEventListener('click', () => this.addStep(true)); @@ -779,7 +864,7 @@ class TacticController { this.finishArea(); } else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'z') { event.preventDefault(); - if (this.canEdit) this.undoLast(); + if (this.canEditCurrent()) this.undoLast(); } else if (event.key === 'ArrowLeft' && this.currentTactic()) { this.goToStep(this.stepIndex - 1); } else if (event.key === 'ArrowRight' && this.currentTactic()) { diff --git a/assets/map/styles.css b/assets/map/styles.css index c10b550..7c4c26d 100644 --- a/assets/map/styles.css +++ b/assets/map/styles.css @@ -610,6 +610,103 @@ button.tp-item.active { color: var(--text-secondary); } +/* Eintrag: oben Name + Kennzeichen, darunter Ersteller und Schritte */ +button.tp-item { + flex-direction: column; + align-items: stretch; + gap: 2px; +} + +.tp-item-main { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; +} + +.tp-item-badges { + display: inline-flex; + flex-shrink: 0; + gap: 4px; +} + +button.tp-item.tp-item-official { + border-left: 3px solid var(--accent-gold); +} + +button.tp-item.tp-item-recommended { + border-left: 3px solid #6fcf97; +} + +.tp-group-title { + margin: 8px 0 4px; + font-size: 10px; + font-weight: 600; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--text-secondary); +} + +.tp-group-title:first-child { + margin-top: 0; +} + +.tp-badge { + display: inline-block; + padding: 1px 5px; + border: 1px solid var(--border-color); + border-radius: 3px; + font-size: 10px; + line-height: 1.4; + white-space: nowrap; + color: var(--text-secondary); +} + +.tp-badge-official { + border-color: rgba(255, 215, 0, 0.6); + background: rgba(255, 215, 0, 0.12); + color: var(--accent-gold); +} + +.tp-badge-recommended { + border-color: rgba(111, 207, 151, 0.6); + background: rgba(111, 207, 151, 0.12); + color: #6fcf97; +} + +.tp-meta { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px 6px; + margin-top: 6px; + font-size: 11px; + color: var(--text-secondary); +} + +.tp-highlight { + display: flex; + align-items: center; + gap: 8px; + margin-top: 8px; + font-size: 12px; + color: var(--text-secondary); +} + +.tp-highlight.hidden { + display: none; +} + +.tp-highlight select { + flex: 1; + padding: 4px 6px; + border: 1px solid var(--border-color); + border-radius: 4px; + background: rgba(30, 30, 60, 0.9); + color: var(--text-primary); + font: inherit; +} + .tp-detail { margin-top: 10px; padding-top: 10px; @@ -850,6 +947,7 @@ button.tp-item.active { } .td-field input, +.td-field select, .td-field textarea { display: block; width: 100%; @@ -865,6 +963,7 @@ button.tp-item.active { } .td-field input:focus, +.td-field select:focus, .td-field textarea:focus { outline: none; border-color: var(--accent-gold); diff --git a/includes/permissions.php b/includes/permissions.php index dfd6e59..b9dedce 100644 --- a/includes/permissions.php +++ b/includes/permissions.php @@ -21,8 +21,9 @@ const CORE_PERMISSIONS = [ ['key' => 'events.view', 'description' => 'Geplante Event-Erinnerungen einsehen'], ['key' => 'events.manage', 'description' => 'Event-Erinnerungen planen, bearbeiten und löschen'], ['key' => 'activity.manage', 'description' => 'Aktivitätschecks im Discord starten, ansehen und beenden (inkl. Folgen wie PN und Rollenänderung)'], - ['key' => 'map.view', 'description' => 'Interaktive Karte und Taktiken ansehen'], - ['key' => 'map.tactics', 'description' => 'Taktiken auf der Karte anlegen, zeichnen und bearbeiten'], + ['key' => 'map.view', 'description' => 'Interaktive Karte und öffentliche Taktiken ansehen, eigene (private oder öffentliche) Taktiken anlegen und zeichnen'], + ['key' => 'map.tactics', 'description' => 'Alle öffentlichen Taktiken bearbeiten, darin zeichnen und löschen - auch die anderer Mitglieder'], + ['key' => 'map.tactics.highlight', 'description' => 'Öffentliche Taktiken als „Empfohlen“ oder „Offiziell“ hervorheben'], ['key' => 'warehouse.view', 'description' => 'Lagerhaus: Bestand und Verlauf einsehen'], ['key' => 'warehouse.manage', 'description' => 'Lagerhaus: Gegenstände einlagern, entnehmen und Einträge löschen'], ['key' => 'contributions.view', 'description' => 'Lumipunkte: Punktestände und Verlauf einsehen'], diff --git a/includes/schema.php b/includes/schema.php index 73eb6ce..969c99e 100644 --- a/includes/schema.php +++ b/includes/schema.php @@ -11,7 +11,7 @@ declare(strict_types=1); */ // Hochzaehlen, sobald unten eine Aenderung dazukommt - dann pruefen alle Sitzungen neu. -const SCHEMA_VERSION = 29; +const SCHEMA_VERSION = 30; /** * Tabellen, die nachtraeglich dazugekommen sind: Tabelle => CREATE-Befehl (wie in sql/schema.sql). @@ -535,6 +535,17 @@ SQL, function schema_column_upgrades(): array { return [ + // Persoenliche Taktiken und Hervorhebung (tactics_api.php) - bisherige Taktiken bleiben + // oeffentlich, sie stammen alle von der Leitung. + 'tactics' => [ + 'visibility' => "ALTER TABLE tactics ADD COLUMN visibility ENUM('private', 'public') NOT NULL DEFAULT 'public' AFTER description", + 'highlight' => "ALTER TABLE tactics ADD COLUMN highlight ENUM('none', 'recommended', 'official') NOT NULL DEFAULT 'none' AFTER visibility", + 'highlighted_by' => [ + "ALTER TABLE tactics ADD COLUMN highlighted_by INT UNSIGNED NULL AFTER highlight", + "ALTER TABLE tactics ADD CONSTRAINT fk_tactics_highlighted_by FOREIGN KEY (highlighted_by) REFERENCES users(id) ON DELETE SET NULL", + ], + 'highlighted_at' => "ALTER TABLE tactics ADD COLUMN highlighted_at DATETIME NULL AFTER highlighted_by", + ], 'users' => [ // Eigene Reihenfolge der Menuepunkte (JSON, siehe SIDEBAR_NAV_MAIN) 'sidebar_order' => "ALTER TABLE users ADD COLUMN sidebar_order TEXT NULL AFTER tour_completed_at", @@ -727,6 +738,15 @@ function schema_sync_core_permissions(): void WHERE p.`key` = 'dashboard.view'" )->execute([$newPermissionId]); } + // Wer bisher Taktiken verwalten durfte, kann sie auch weiterhin hervorheben. + if ($permission['key'] === 'map.tactics.highlight') { + $pdo->prepare( + "INSERT IGNORE INTO role_permissions (role_id, permission_id) + SELECT rp.role_id, ? FROM role_permissions rp + JOIN permissions p ON p.id = rp.permission_id + WHERE p.`key` = 'map.tactics'" + )->execute([$newPermissionId]); + } // Bisher durfte jeder mit users.edit alle Gruppen vergeben - damit das nach dem // Update nicht ploetzlich wegfaellt, bekommen diese Gruppen roles.assign einmalig mit. if ($permission['key'] === 'roles.assign') { diff --git a/includes/tactics.php b/includes/tactics.php index e7335d1..9fdc303 100644 --- a/includes/tactics.php +++ b/includes/tactics.php @@ -101,30 +101,63 @@ function tactics_valid_map(string $slug): bool return empty($slugs) || in_array($slug, $slugs, true); } +const TACTIC_VISIBILITIES = ['private', 'public']; +const TACTIC_HIGHLIGHTS = ['none' => '', 'recommended' => 'Empfohlen', 'official' => 'Offiziell']; + /** - * Alle Taktiken einer Region samt Schritten und Zeichnungen. + * Darf das aktuelle Konto diese Taktik bearbeiten (Name, Schritte, Zeichnungen, Loeschen)? + * Die eigene immer; fremde nur, wenn sie oeffentlich ist und man map.tactics hat. Private + * Taktiken anderer bleiben auch fuer die Leitung unsichtbar. + * + * @param array{created_by: mixed, visibility: string} $tactic + */ +function tactic_can_edit(array $tactic, int $userId): bool +{ + if ((int) ($tactic['created_by'] ?? 0) === $userId) { + return true; + } + return ($tactic['visibility'] ?? '') === 'public' && user_has_permission('map.tactics'); +} + +/** 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> */ -function tactics_for_map(string $slug): array +function tactics_for_map(string $slug, int $userId): array { $stmt = db()->prepare( - 'SELECT t.id, t.name, t.description, t.created_at, t.updated_at, - COALESCE(NULLIF(u.display_name, \'\'), u.username) AS author + "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 - WHERE t.map_slug = ? - ORDER BY t.name, t.id' + 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]); + $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), 'updated_at' => (string) ($row['updated_at'] ?? $row['created_at']), 'steps' => [], ]; diff --git a/sql/schema.sql b/sql/schema.sql index 10b4999..5580ba9 100644 --- a/sql/schema.sql +++ b/sql/schema.sql @@ -338,10 +338,17 @@ CREATE TABLE IF NOT EXISTS tactics ( map_slug VARCHAR(60) NOT NULL, name VARCHAR(120) NOT NULL, description TEXT NULL, + -- private = nur der Ersteller sieht sie, public = alle mit map.view + visibility ENUM('private', 'public') NOT NULL DEFAULT 'public', + -- Hervorhebung durch map.tactics.highlight (nur bei oeffentlichen Taktiken) + highlight ENUM('none', 'recommended', 'official') NOT NULL DEFAULT 'none', + highlighted_by INT UNSIGNED NULL, + highlighted_at DATETIME NULL, created_by INT UNSIGNED NULL, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NULL, FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL, + FOREIGN KEY (highlighted_by) REFERENCES users(id) ON DELETE SET NULL, INDEX idx_tactics_map (map_slug) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/tactics_api.php b/tactics_api.php index 532e54c..be2c302 100644 --- a/tactics_api.php +++ b/tactics_api.php @@ -13,7 +13,7 @@ if (!user_has_permission('map.view')) { json_response(false, 'Dir fehlt die Berechtigung, die Karte zu sehen.'); } -$canEdit = user_has_permission('map.tactics'); +$userId = (int) current_user()['id']; try { $missing = tactics_missing_tables(); @@ -33,8 +33,10 @@ if ($_SERVER['REQUEST_METHOD'] === 'GET') { json_response(false, 'Unbekannte Karte.'); } json_response(true, '', [ - 'can_edit' => $canEdit, - 'tactics' => tactics_for_map($slug), + // 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), ]); } @@ -42,11 +44,6 @@ if ($_SERVER['REQUEST_METHOD'] === 'GET') { $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. */ @@ -62,8 +59,28 @@ function tactic_text(array $input, string $key, int $max, string $label, bool $r return $value; } -/** Sucht einen Schritt und liefert die Taktik, zu der er gehoert. */ -function tactic_step_owner(int $stepId): array +/** + * 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]); @@ -71,16 +88,22 @@ function tactic_step_owner(int $stepId): array 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; } -function tactic_exists(int $tacticId): void +/** + * 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 { - $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.'); - } + 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. */ @@ -106,54 +129,118 @@ try { } $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, created_by) VALUES (?, ?, ?, ?)') - ->execute([$slug, $name, $description, $userId]); + $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 Taktiken ins Discord-Log - einzelne Zeichnungen wuerden den Kanal fluten. - admin_log('🗺️ Taktik angelegt', ['Taktik' => $name, 'Karte' => $slug], 'success'); + // 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); - tactic_exists($tacticId); + $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'; - $oldStmt = db()->prepare('SELECT name, description, map_slug FROM tactics WHERE id = ?'); - $oldStmt->execute([$tacticId]); - $old = $oldStmt->fetch() ?: []; - db()->prepare('UPDATE tactics SET name = ?, description = ?, updated_at = NOW() WHERE id = ?') - ->execute([$name, $description, $tacticId]); - admin_log('🗺️ Taktik bearbeitet', [ - 'Taktik' => $name, - 'Karte' => (string) ($old['map_slug'] ?? ''), - 'Name' => admin_log_change($old['name'] ?? '', $name), - 'Beschreibung' => admin_log_text_change((string) ($old['description'] ?? ''), (string) $description), - ]); + 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': - $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'); + $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_exists($tacticId); + 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); @@ -165,7 +252,7 @@ try { // "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); + $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.'); @@ -181,7 +268,7 @@ try { json_response(true, 'Schritt angelegt.', ['step_id' => $stepId]); case 'step_update': - $step = tactic_step_owner((int) ($input['step_id'] ?? 0)); + $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); @@ -191,7 +278,7 @@ try { json_response(true, 'Schritt gespeichert.'); case 'step_delete': - $step = tactic_step_owner((int) ($input['step_id'] ?? 0)); + $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']]); @@ -204,7 +291,7 @@ try { json_response(true, 'Schritt gelöscht.'); case 'step_move': - $step = tactic_step_owner((int) ($input['step_id'] ?? 0)); + $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 @@ -232,7 +319,7 @@ try { // ---- Zeichnungen ---- case 'shape_create': - $step = tactic_step_owner((int) ($input['step_id'] ?? 0)); + $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.'); @@ -271,11 +358,13 @@ try { ); $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]); - if ($tacticId > 0) { - tactic_touch($tacticId); - } + tactic_touch($tacticId); json_response(true, ''); default: