- New permission raids.create (granted on update to every group that has raids.view): whoever creates a raid on the website becomes its raid lead (raid_settings.lead_user_id, schema v49), shown with a crown on the raid card and in the signup list. - The raid lead manages their own raid: edit, move players, invite premades, fill in the attendance list and archive it. Restoring, deleting for good and the Lumipunkte stay with the leadership (raids.manage, raids.points). Checked on the server via raid_can_manage() in every raid action. - Raids created by a member without raids.points bring no automatic points (0/0) until the leadership sets them when editing; raids of the leadership keep the fixed +1. - The attendance reminder of the bot (bot_api.php) goes to the raid lead, even if not signed up; raids without a lead (created in Discord) remind the signed-up raids.manage members as before. - Core permission descriptions are cut to the 255 characters of the column when synced - a longer one made the schema sync throw on every request (found while testing this change). - Privacy policy (raid lead is visible to all), data export, patch notes, README and the tour updated; raid_created_at() folded into raid_posted_at(). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
433 lines
17 KiB
PHP
433 lines
17 KiB
PHP
<?php
|
||
declare(strict_types=1);
|
||
|
||
require_once __DIR__ . '/raids_api.php';
|
||
require_once __DIR__ . '/contributions.php';
|
||
|
||
/**
|
||
* Anwesenheit bei Raids und automatische Lumipunkte beim Archivieren.
|
||
*
|
||
* Die Raids selbst liegen beim Bot (Raid-API). Hier auf der Website liegen nur Zusaetze, die
|
||
* ueber die raid_id (= Discord-Nachrichten-ID) zugeordnet sind: die Punkte-Einstellungen und der
|
||
* Raid-Lead (raid_settings) und die Anwesenheitsliste (raid_attendance, je Discord-ID).
|
||
*
|
||
* Raid-Lead ist, wer den Raid auf der Website angelegt hat (raid_settings.lead_user_id, raids.create
|
||
* oder raids.manage). Er verwaltet seinen Raid selbst - bearbeiten, Spieler verschieben, Premades
|
||
* einladen, Anwesenheit eintragen, archivieren - und bekommt die Erinnerung zur Anwesenheitsliste
|
||
* (bot_api.php). Wiederherstellen, endgueltig loeschen und die Lumipunkte bleiben der Leitung
|
||
* (raids.manage, raids.points).
|
||
*/
|
||
|
||
// Nur noch anwesend/abwesend. Alte Eintraege "excused" (Entschuldigt) gelten als nicht erfasst
|
||
// und verschwinden beim naechsten Speichern der Liste; die Spalte kennt den Wert weiterhin.
|
||
const RAID_ATTENDANCE_STATUSES = [
|
||
'present' => 'Anwesend',
|
||
'absent' => 'Abwesend',
|
||
];
|
||
|
||
// Lumipunkte pro Raid: fest +1 fuer jede Teilnahme, kein Abzug. Andere Werte (bis 10) legt nur
|
||
// fest, wer raids.points hat (die Sedes Luminis).
|
||
const RAID_POINTS_DEFAULT_PRESENT = 1;
|
||
const RAID_POINTS_DEFAULT_ABSENT = 0;
|
||
const RAID_POINTS_MAX = 10;
|
||
// Seit diesem Tag gilt der feste Punkt auch fuer Raids, die im Discord erstellt wurden (die Website
|
||
// legt ihre Einstellungen dann beim ersten Anzeigen an). Aeltere Raids bleiben, wie sie waren.
|
||
const RAID_POINTS_DEFAULT_SINCE = '2026-09-23 00:00:00';
|
||
|
||
/** Liefert die Fehlermeldung, wenn die Punkte fuer einen Raid nicht zwischen 0 und 10 liegen. */
|
||
function raid_points_error(int $present, int $absent): ?string
|
||
{
|
||
if ($present < 0 || $present > RAID_POINTS_MAX || $absent < 0 || $absent > RAID_POINTS_MAX) {
|
||
return 'Lumipunkte: 0 bis ' . RAID_POINTS_MAX . ' pro Raid.';
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/** "+1 Lumipunkt pro Teilnahme, kein Abzug" - fuer alle, die die Werte nicht selbst festlegen. */
|
||
function raid_points_summary(int $present, int $absent): string
|
||
{
|
||
if ($present <= 0 && $absent <= 0) {
|
||
return 'Keine automatischen Lumipunkte';
|
||
}
|
||
$text = $present > 0 ? '+' . $present . ' Lumipunkt' . ($present === 1 ? '' : 'e') . ' pro Teilnahme' : 'Keine Punkte für die Teilnahme';
|
||
return $text . ($absent > 0 ? ', −' . $absent . ' bei Abwesenheit' : ', kein Abzug');
|
||
}
|
||
|
||
/** Ganze Zahl aus einem Formularwert - oder null, wenn es keine ist. */
|
||
function raid_points_input($value): ?int
|
||
{
|
||
$raw = is_int($value) ? (string) $value : trim((string) $value);
|
||
return ctype_digit($raw) ? (int) $raw : null;
|
||
}
|
||
|
||
/**
|
||
* Lumipunkte fuer einen neuen Raid, wenn der Ersteller sie nicht selbst festlegen darf (raids.points):
|
||
* Raids der Leitung (raids.manage) bringen den festen Punkt, Raids eines Mitglieds als Raid-Lead keine -
|
||
* die legt die Leitung bei Bedarf nachtraeglich fest.
|
||
*
|
||
* @return array{0: int, 1: int} [fuer Anwesende, Abzug fuer Abwesende]
|
||
*/
|
||
function raid_points_defaults_for_creator(): array
|
||
{
|
||
return user_has_permission('raids.manage') ? [RAID_POINTS_DEFAULT_PRESENT, RAID_POINTS_DEFAULT_ABSENT] : [0, 0];
|
||
}
|
||
|
||
/** Raid-Lead eines Raids (Website-Konto) oder null. */
|
||
function raid_lead_id(int $raidId): ?int
|
||
{
|
||
$stmt = db()->prepare('SELECT lead_user_id FROM raid_settings WHERE raid_id = ?');
|
||
$stmt->execute([$raidId]);
|
||
$lead = $stmt->fetchColumn();
|
||
return $lead !== false && $lead !== null ? (int) $lead : null;
|
||
}
|
||
|
||
/** Darf das aktuelle Konto den Raid verwalten? Die Leitung jeden, der Raid-Lead seinen eigenen. */
|
||
function raid_can_manage(int $raidId): bool
|
||
{
|
||
if (user_has_permission('raids.manage')) {
|
||
return true;
|
||
}
|
||
$user = current_user();
|
||
return $user !== null && $raidId > 0 && user_has_permission('raids.view') && raid_lead_id($raidId) === (int) $user['id'];
|
||
}
|
||
|
||
function raid_settings_save_lead(int $raidId, int $userId): void
|
||
{
|
||
db()->prepare('INSERT INTO raid_settings (raid_id, lead_user_id) VALUES (?, ?) ON DUPLICATE KEY UPDATE lead_user_id = VALUES(lead_user_id)')
|
||
->execute([$raidId, $userId]);
|
||
}
|
||
|
||
/**
|
||
* Legt fuer neue Raids ohne eigene Einstellungen (z.B. im Discord erstellt) den festen Punkt
|
||
* (+1 pro Teilnahme) an, damit auch sie beim Archivieren Lumipunkte bringen.
|
||
*
|
||
* @param array<int, int|string> $raidIds
|
||
*/
|
||
function raid_settings_ensure_defaults(array $raidIds): void
|
||
{
|
||
$since = strtotime(RAID_POINTS_DEFAULT_SINCE);
|
||
$ids = [];
|
||
foreach ($raidIds as $raidId) {
|
||
$raidId = (int) $raidId;
|
||
if ($raidId > 0 && raid_posted_at($raidId) >= $since) {
|
||
$ids[$raidId] = true;
|
||
}
|
||
}
|
||
if (empty($ids)) {
|
||
return;
|
||
}
|
||
try {
|
||
$pdo = db();
|
||
$placeholders = implode(',', array_fill(0, count($ids), '?'));
|
||
$stmt = $pdo->prepare("SELECT raid_id FROM raid_settings WHERE raid_id IN ($placeholders)");
|
||
$stmt->execute(array_keys($ids));
|
||
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $existing) {
|
||
unset($ids[(int) $existing]);
|
||
}
|
||
$insert = $pdo->prepare('INSERT IGNORE INTO raid_settings (raid_id, points_present, points_absent) VALUES (?, ?, ?)');
|
||
foreach (array_keys($ids) as $raidId) {
|
||
$insert->execute([$raidId, RAID_POINTS_DEFAULT_PRESENT, RAID_POINTS_DEFAULT_ABSENT]);
|
||
}
|
||
} catch (PDOException $e) {
|
||
// Nicht kritisch - beim naechsten Aufruf erneut.
|
||
}
|
||
}
|
||
|
||
/** @return array{points_present: int, points_absent: int, auto_processed_at: ?string, auto_result: ?string, attendance_checked_at: ?string, checked_by: ?string, lead_user_id: ?int, lead_name: ?string} */
|
||
function raid_settings_get(int $raidId): array
|
||
{
|
||
$stmt = db()->prepare(
|
||
"SELECT s.points_present, s.points_absent, s.auto_processed_at, s.auto_result, s.attendance_checked_at,
|
||
COALESCE(NULLIF(u.display_name, ''), u.username) AS checked_by,
|
||
s.lead_user_id, COALESCE(NULLIF(l.display_name, ''), l.username) AS lead_name
|
||
FROM raid_settings s
|
||
LEFT JOIN users u ON u.id = s.attendance_checked_by
|
||
LEFT JOIN users l ON l.id = s.lead_user_id
|
||
WHERE s.raid_id = ?"
|
||
);
|
||
$stmt->execute([$raidId]);
|
||
$row = $stmt->fetch();
|
||
|
||
return [
|
||
'points_present' => (int) ($row['points_present'] ?? 0),
|
||
'points_absent' => (int) ($row['points_absent'] ?? 0),
|
||
'auto_processed_at' => $row['auto_processed_at'] ?? null,
|
||
'auto_result' => $row['auto_result'] ?? null,
|
||
'attendance_checked_at' => $row['attendance_checked_at'] ?? null,
|
||
'checked_by' => $row['checked_by'] ?? null,
|
||
'lead_user_id' => isset($row['lead_user_id']) ? (int) $row['lead_user_id'] : null,
|
||
'lead_name' => $row['lead_name'] ?? null,
|
||
];
|
||
}
|
||
|
||
/**
|
||
* Alle Einstellungen auf einmal (fuer die Raid-Uebersicht), mit Name, Discord-ID und Status des Raid-Leads.
|
||
*
|
||
* @return array<string, array<string, mixed>> raid_id => Einstellungen
|
||
*/
|
||
function raid_settings_all(): array
|
||
{
|
||
$settings = [];
|
||
$rows = db()->query(
|
||
"SELECT s.*, COALESCE(NULLIF(l.display_name, ''), l.username) AS lead_name, l.discord_id AS lead_discord_id,
|
||
l.status AS lead_status
|
||
FROM raid_settings s LEFT JOIN users l ON l.id = s.lead_user_id"
|
||
)->fetchAll();
|
||
foreach ($rows as $row) {
|
||
$settings[(string) $row['raid_id']] = $row;
|
||
}
|
||
return $settings;
|
||
}
|
||
|
||
function raid_settings_save_points(int $raidId, int $present, int $absent): void
|
||
{
|
||
db()->prepare(
|
||
'INSERT INTO raid_settings (raid_id, points_present, points_absent) VALUES (?, ?, ?)
|
||
ON DUPLICATE KEY UPDATE points_present = VALUES(points_present), points_absent = VALUES(points_absent)'
|
||
)->execute([$raidId, $present, $absent]);
|
||
}
|
||
|
||
/**
|
||
* Die Raid-API postet die Discord-Nachricht neu, wenn sie geloescht wurde - dann aendert sich
|
||
* die raid_id. Einstellungen, Anwesenheit und Vergaben ziehen mit um.
|
||
*/
|
||
function raid_rename_id(int $oldId, int $newId): void
|
||
{
|
||
if ($oldId === $newId || $newId <= 0) {
|
||
return;
|
||
}
|
||
$pdo = db();
|
||
$pdo->beginTransaction();
|
||
try {
|
||
// Hat eine andere Seite fuer die neue ID inzwischen schon den festen Punkt angelegt (unberuehrt),
|
||
// weicht diese Zeile den Einstellungen des Raids.
|
||
$hasOld = $pdo->prepare('SELECT 1 FROM raid_settings WHERE raid_id = ?');
|
||
$hasOld->execute([$oldId]);
|
||
if ($hasOld->fetchColumn()) {
|
||
$pdo->prepare('DELETE FROM raid_settings WHERE raid_id = ? AND auto_processed_at IS NULL AND attendance_checked_at IS NULL')
|
||
->execute([$newId]);
|
||
$pdo->prepare('UPDATE IGNORE raid_settings SET raid_id = ? WHERE raid_id = ?')->execute([$newId, $oldId]);
|
||
}
|
||
$pdo->prepare('UPDATE IGNORE raid_attendance SET raid_id = ? WHERE raid_id = ?')->execute([$newId, $oldId]);
|
||
$pdo->prepare('UPDATE contribution_awards SET raid_id = ? WHERE raid_id = ?')->execute([$newId, $oldId]);
|
||
$pdo->commit();
|
||
} catch (Throwable $e) {
|
||
$pdo->rollBack();
|
||
throw $e;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Anwesenheitsliste eines Raids.
|
||
*
|
||
* @return array<string, array{status: string, name: string}> Discord-ID => Eintrag
|
||
*/
|
||
function raid_attendance_get(int $raidId): array
|
||
{
|
||
$stmt = db()->prepare('SELECT discord_id, name, status FROM raid_attendance WHERE raid_id = ?');
|
||
$stmt->execute([$raidId]);
|
||
$list = [];
|
||
foreach ($stmt->fetchAll() as $row) {
|
||
$list[(string) $row['discord_id']] = ['status' => (string) $row['status'], 'name' => (string) $row['name']];
|
||
}
|
||
return $list;
|
||
}
|
||
|
||
/**
|
||
* Anmeldungen eines Raids, aufgeteilt: in einer Gruppe, auf der Ersatzbank, abgemeldet.
|
||
* Ausstehende Premade-Einladungen zaehlen nicht als Anmeldung.
|
||
*
|
||
* @return array{groups: array<int, array>, bench: array<int, array>, declined: array<int, array>}
|
||
*/
|
||
function raid_signups_split(array $raid): array
|
||
{
|
||
$split = ['groups' => [], 'bench' => [], 'declined' => []];
|
||
foreach ((array) ($raid['signups'] ?? []) as $signup) {
|
||
$group = (int) ($signup['group'] ?? 0);
|
||
if ($group < 0) {
|
||
$split['declined'][] = $signup;
|
||
} elseif (($signup['class'] ?? '') === 'Ausstehend') {
|
||
continue;
|
||
} elseif ($group === 0) {
|
||
$split['bench'][] = $signup;
|
||
} else {
|
||
$split['groups'][] = $signup;
|
||
}
|
||
}
|
||
return $split;
|
||
}
|
||
|
||
/**
|
||
* Aktive Website-Konten je Discord-ID.
|
||
*
|
||
* @return array<string, int> Discord-ID => user_id
|
||
*/
|
||
function raid_user_ids_by_discord(): array
|
||
{
|
||
$map = [];
|
||
$rows = db()->query("SELECT id, discord_id FROM users WHERE status = 'active' AND discord_id IS NOT NULL")->fetchAll();
|
||
foreach ($rows as $row) {
|
||
$map[(string) $row['discord_id']] = (int) $row['id'];
|
||
}
|
||
return $map;
|
||
}
|
||
|
||
/** Wurden fuer diesen Raid schon Lumipunkte vergeben (von Hand oder automatisch)? */
|
||
function raid_has_awards(int $raidId): bool
|
||
{
|
||
$stmt = db()->prepare('SELECT 1 FROM contribution_awards WHERE raid_id = ? LIMIT 1');
|
||
$stmt->execute([$raidId]);
|
||
return (bool) $stmt->fetchColumn();
|
||
}
|
||
|
||
/**
|
||
* Automatische Lumipunkte fuer archivierte Raids.
|
||
*
|
||
* Laeuft bei jedem Aufruf der Raid- und Punkteseiten und direkt nach dem Archivieren - so
|
||
* werden auch Raids erfasst, die im Discord ueber den Knopf archiviert wurden (die Website
|
||
* erfaehrt davon sonst nichts). Kosten: eine Abfrage, solange nichts offen ist.
|
||
*
|
||
* - Schon Punkte fuer den Raid vergeben? Dann entfaellt die Automatik.
|
||
* - Anwesenheitsliste gefuehrt: Anwesende bekommen die Punkte, Abwesende den Abzug.
|
||
* - Keine Liste: alle, die in einer Gruppe angemeldet waren, bekommen die Punkte (kein Abzug).
|
||
*
|
||
* @param array<int, array<string, mixed>>|null $raids Bereits geladene Raids (spart eine API-Abfrage)
|
||
* @return array<int, string> Meldungen je verarbeitetem Raid
|
||
*/
|
||
function raid_process_auto_points(?array $raids = null): array
|
||
{
|
||
if ($raids !== null) {
|
||
raid_settings_ensure_defaults(array_map(static fn (array $raid) => $raid['raid_id'] ?? 0, $raids));
|
||
}
|
||
try {
|
||
$pending = db()->query(
|
||
'SELECT raid_id, points_present, points_absent FROM raid_settings
|
||
WHERE auto_processed_at IS NULL AND (points_present > 0 OR points_absent > 0)'
|
||
)->fetchAll();
|
||
} catch (PDOException $e) {
|
||
return [];
|
||
}
|
||
if (empty($pending)) {
|
||
return [];
|
||
}
|
||
|
||
// Nur archivierte Raids zaehlen. Sind die mitgegebenen Raids nicht alle dabei, frisch laden.
|
||
$raidsById = [];
|
||
foreach ((array) $raids as $raid) {
|
||
$raidsById[(string) ($raid['raid_id'] ?? '')] = $raid;
|
||
}
|
||
$missing = array_filter($pending, static fn (array $p): bool => !isset($raidsById[(string) $p['raid_id']]));
|
||
if (!empty($missing)) {
|
||
try {
|
||
foreach (fetch_raids('all') as $raid) {
|
||
$raidsById[(string) ($raid['raid_id'] ?? '')] = $raid;
|
||
}
|
||
} catch (Throwable $e) {
|
||
return []; // Raid-API nicht erreichbar - beim naechsten Aufruf erneut
|
||
}
|
||
}
|
||
|
||
$messages = [];
|
||
$userIds = null;
|
||
foreach ($pending as $setting) {
|
||
$raidId = (int) $setting['raid_id'];
|
||
$raid = $raidsById[(string) $raidId] ?? null;
|
||
if ($raid === null || (empty($raid['archived']) && empty($raid['archived_at']))) {
|
||
continue; // noch aktiv (oder geloescht) - nichts zu tun
|
||
}
|
||
|
||
$messages[] = raid_run_auto_points($raidId, $raid, (int) $setting['points_present'], (int) $setting['points_absent'], $userIds);
|
||
}
|
||
return $messages;
|
||
}
|
||
|
||
/** Vergibt die automatischen Punkte fuer einen archivierten Raid und merkt sich das Ergebnis. */
|
||
function raid_run_auto_points(int $raidId, array $raid, int $pointsPresent, int $pointsAbsent, ?array &$userIds): string
|
||
{
|
||
$pdo = db();
|
||
$title = (string) ($raid['title'] ?? 'Raid');
|
||
$timestamp = (int) ($raid['timestamp'] ?? 0);
|
||
$awardedAt = $timestamp > 0 ? date('Y-m-d H:i:s', $timestamp) : date('Y-m-d H:i:s');
|
||
|
||
// Gegen doppelte Vergabe bei gleichzeitigen Seitenaufrufen: Zeile sperren und erneut pruefen.
|
||
$pdo->beginTransaction();
|
||
$lock = $pdo->prepare('SELECT auto_processed_at FROM raid_settings WHERE raid_id = ? FOR UPDATE');
|
||
$lock->execute([$raidId]);
|
||
if ($lock->fetchColumn() !== null) {
|
||
$pdo->commit();
|
||
return '';
|
||
}
|
||
|
||
$finish = static function (string $result) use ($pdo, $raidId): string {
|
||
$pdo->prepare('UPDATE raid_settings SET auto_processed_at = NOW(), auto_result = ? WHERE raid_id = ?')
|
||
->execute([mb_substr($result, 0, 255), $raidId]);
|
||
$pdo->commit();
|
||
return $result;
|
||
};
|
||
|
||
if (raid_has_awards($raidId)) {
|
||
return $finish('Übersprungen: Für „' . $title . '“ wurden schon vorher Punkte vergeben.');
|
||
}
|
||
|
||
$userIds ??= raid_user_ids_by_discord();
|
||
$attendance = raid_attendance_get($raidId);
|
||
$present = [];
|
||
$absent = [];
|
||
if (!empty($attendance)) {
|
||
foreach ($attendance as $discordId => $entry) {
|
||
$userId = $userIds[$discordId] ?? null;
|
||
if ($userId === null) {
|
||
continue;
|
||
}
|
||
if ($entry['status'] === 'present') {
|
||
$present[] = $userId;
|
||
} elseif ($entry['status'] === 'absent') {
|
||
$absent[] = $userId;
|
||
}
|
||
}
|
||
} else {
|
||
foreach (raid_signups_split($raid)['groups'] as $signup) {
|
||
$userId = $userIds[(string) ($signup['user_id'] ?? '')] ?? null;
|
||
if ($userId !== null) {
|
||
$present[] = $userId;
|
||
}
|
||
}
|
||
}
|
||
$present = array_values(array_unique($present));
|
||
$absent = array_values(array_unique($absent));
|
||
|
||
$insertAward = $pdo->prepare(
|
||
"INSERT INTO contribution_awards (category, title, note, raid_id, awarded_at, created_by) VALUES ('raid', ?, ?, ?, ?, NULL)"
|
||
);
|
||
$insertEntry = $pdo->prepare('INSERT INTO contribution_entries (award_id, user_id, points) VALUES (?, ?, ?)');
|
||
$parts = [];
|
||
|
||
if ($pointsPresent > 0 && !empty($present)) {
|
||
$insertAward->execute([mb_substr($title, 0, 150), 'Automatisch beim Archivieren' . (empty($attendance) ? ' (ohne Anwesenheitsliste: alle Teilnehmer)' : ''), $raidId, $awardedAt]);
|
||
$awardId = (int) $pdo->lastInsertId();
|
||
foreach ($present as $userId) {
|
||
$insertEntry->execute([$awardId, $userId, $pointsPresent]);
|
||
}
|
||
$parts[] = count($present) . '× +' . $pointsPresent;
|
||
}
|
||
if ($pointsAbsent > 0 && !empty($absent)) {
|
||
$insertAward->execute([mb_substr('Abwesend: ' . $title, 0, 150), 'Automatisch beim Archivieren', $raidId, $awardedAt]);
|
||
$awardId = (int) $pdo->lastInsertId();
|
||
foreach ($absent as $userId) {
|
||
$insertEntry->execute([$awardId, $userId, -$pointsAbsent]);
|
||
}
|
||
$parts[] = count($absent) . '× −' . $pointsAbsent;
|
||
}
|
||
|
||
return $finish(empty($parts)
|
||
? 'Keine automatischen Punkte für „' . $title . '“: niemand mit Website-Konto zu berücksichtigen.'
|
||
: 'Automatische Lumipunkte für „' . $title . '“ vergeben: ' . implode(', ', $parts) . '.');
|
||
}
|
||
|
||
/** Ist fuer den Bot-Rueckkanal ein gemeinsamer Schluessel eingetragen? (config.php: bot_callback.key) */
|
||
function bot_callback_key(): ?string
|
||
{
|
||
$config = require __DIR__ . '/../config.php';
|
||
$key = (string) ($config['bot_callback']['key'] ?? '');
|
||
return strlen($key) >= 16 ? $key : null;
|
||
}
|