558 lines
25 KiB
PHP
558 lines
25 KiB
PHP
<?php
|
||
declare(strict_types=1);
|
||
|
||
/**
|
||
* Refugien-Planer (sanctuary.php): Wer hat an welchem Refugium (Sanctuary-Raid) Interesse und kann wann? Jedes
|
||
* Mitglied der Legion traegt seine wiederkehrenden Zeitfenster (Wochentag + von-bis) ein und waehlt je Charakter
|
||
* die Refugien - auch fuer Twinks. Zu jedem Refugium gehoeren eigene Angaben: Raidlead, Shotcaller, die Stufe
|
||
* ("Moeglich bei" Easy/Normal/Hard), der aktuelle Fortschritt und eine Notiz. Gearscore und Kampfkraft traegt
|
||
* man von Hand ein (die Werte aus dem Spiel sind nur der Vorschlag im Formular - sie kommen dort nicht immer
|
||
* aktuell an). Die Uebersicht zeigt immer ein Refugium, filtert nach Stufe, Tag, Uhrzeit, Rolle/Klasse und
|
||
* Mindest-Gearscore und klappt je Zeile die Einzelheiten auf; wer Raids anlegen darf, uebernimmt den Filter in
|
||
* "Neuer Raid" (raids.php).
|
||
*
|
||
* Eintraege veralten: Wer SANCTUARY_EXPIRE_DAYS Tage (SANCTUARY_EXPIRE_WEEKS Wochen) nichts bestaetigt oder
|
||
* geaendert hat, dessen Eintrag ist "updatepflichtig" - er bleibt in der Uebersicht und laesst sich aufklappen,
|
||
* steht aber ausgegraut am Ende der Liste. SANCTUARY_WARN_DAYS Tage vorher (2 Tage je Woche Laufzeit) und danach
|
||
* erinnern ein Hinweis auf jeder Seite (sanctuary_expiry_notice_html(), includes/header.php) und ein "!" am
|
||
* Menuepunkt; ein Klick auf "Stimmt noch" oder erneutes Speichern macht den Eintrag wieder aktuell. Geloescht
|
||
* wird erst nach SANCTUARY_PURGE_DAYS Tagen.
|
||
* Nur fuer die Legion (dashboard.view + raids.view) - Verbuendete sehen den Planer nicht.
|
||
*
|
||
* Tabellen: sanctuary_entries (je Charakter: Refugien, Angaben je Refugium als JSON, Werte von Hand, zuletzt
|
||
* bestaetigt) und sanctuary_times (je Mitglied: Wochentag, Beginn und Ende in Minuten seit Mitternacht).
|
||
*/
|
||
|
||
// Schluessel => Name im Spiel, Kurzname (Chips, Abzeichen). Gespeichert werden nur die Schluessel.
|
||
const SANCTUARY_RAIDS = [
|
||
'ludra' => ['label' => 'Abgrundsveredelung: Ludra', 'short' => 'Ludra'],
|
||
'korrosion' => ['label' => 'Läuterungsstätte der Korrosion', 'short' => 'Korrosion'],
|
||
'muspel' => ['label' => 'Kelch von Muspel', 'short' => 'Muspel'],
|
||
];
|
||
|
||
// Wochentage wie date('N'): 1 = Montag ... 7 = Sonntag
|
||
const SANCTUARY_WEEKDAYS = [1 => 'Mo', 2 => 'Di', 3 => 'Mi', 4 => 'Do', 5 => 'Fr', 6 => 'Sa', 7 => 'So'];
|
||
const SANCTUARY_WEEKDAY_NAMES = [1 => 'Montag', 2 => 'Dienstag', 3 => 'Mittwoch', 4 => 'Donnerstag', 5 => 'Freitag', 6 => 'Samstag', 7 => 'Sonntag'];
|
||
|
||
// Rolle je Klasse fuer den Rollenfilter
|
||
const SANCTUARY_ROLES = ['tank' => 'Tank', 'heal' => 'Heiler', 'support' => 'Support', 'dd' => 'DD'];
|
||
const SANCTUARY_CLASS_ROLES = ['Templer' => 'tank', 'Kleriker' => 'heal', 'Kantor' => 'support'];
|
||
|
||
// Stufen eines Refugiums ("Moeglich bei") - gespeichert werden nur die Schluessel
|
||
const SANCTUARY_DIFFICULTIES = ['easy' => 'Easy', 'normal' => 'Normal', 'hard' => 'Hard'];
|
||
|
||
// Ein Eintrag gilt so viele Wochen als aktuell, danach ist er "updatepflichtig" (ausgegraut am Ende der Liste).
|
||
// Der Hinweis davor kommt 2 Tage je Woche Laufzeit vorher (2 Wochen: 4 Tage, 3 Wochen: 6 Tage, 4 Wochen: 8 Tage) -
|
||
// hier nur die Wochen aendern.
|
||
const SANCTUARY_EXPIRE_WEEKS = 4;
|
||
const SANCTUARY_EXPIRE_DAYS = SANCTUARY_EXPIRE_WEEKS * 7;
|
||
const SANCTUARY_WARN_DAYS = SANCTUARY_EXPIRE_WEEKS * 2;
|
||
// Wer so viele Tage nichts bestaetigt oder geaendert hat, dessen Eintrag wird geloescht
|
||
const SANCTUARY_PURGE_DAYS = 90;
|
||
// Zeilen im Formular (eine Zeile = mehrere Tage mit derselben Uhrzeit)
|
||
const SANCTUARY_MAX_WINDOWS = 10;
|
||
// Je Refugium: aktueller Fortschritt und Notiz
|
||
const SANCTUARY_PROGRESS_MAX = 120;
|
||
const SANCTUARY_NOTE_MAX = 200;
|
||
const SANCTUARY_GEARSCORE_MAX = 99999;
|
||
const SANCTUARY_POWER_MAX = 9999999;
|
||
|
||
/** Darf das angemeldete Konto den Planer nutzen? Nur die Legion, mit Blick auf die Raids. */
|
||
function sanctuary_can_use(): bool
|
||
{
|
||
return is_legion_member() && user_has_permission('raids.view');
|
||
}
|
||
|
||
/** Rolle einer Klasse (tank, heal, support, dd) - unbekannte Klasse: dd. */
|
||
function sanctuary_class_role(?string $className): string
|
||
{
|
||
return SANCTUARY_CLASS_ROLES[(string) $className] ?? 'dd';
|
||
}
|
||
|
||
/** "17:30" -> 1050 (Minuten seit Mitternacht), ungueltig: null. */
|
||
function sanctuary_time_parse(string $value): ?int
|
||
{
|
||
if (!preg_match('/^([01]?\d|2[0-3]):([0-5]\d)$/', trim($value), $m)) {
|
||
return null;
|
||
}
|
||
return (int) $m[1] * 60 + (int) $m[2];
|
||
}
|
||
|
||
/** 1050 -> "17:30" */
|
||
function sanctuary_time_text(int $minutes): string
|
||
{
|
||
return sprintf('%02d:%02d', intdiv($minutes, 60) % 24, $minutes % 60);
|
||
}
|
||
|
||
/** Refugien aus der Spalte raids ("ludra,muspel"): nur gueltige Schluessel, in fester Reihenfolge. */
|
||
function sanctuary_raids_parse(?string $value): array
|
||
{
|
||
$given = explode(',', (string) $value);
|
||
return array_values(array_filter(array_keys(SANCTUARY_RAIDS), static fn (string $key): bool => in_array($key, $given, true)));
|
||
}
|
||
|
||
/** Leere Angaben zu einem Refugium. */
|
||
function sanctuary_detail_empty(): array
|
||
{
|
||
return ['lead' => false, 'shot' => false, 'difficulty' => '', 'progress' => '', 'note' => ''];
|
||
}
|
||
|
||
/**
|
||
* Angaben je Refugium aus der Spalte details (JSON): [Refugium => ['lead' => bool, 'shot' => bool,
|
||
* 'difficulty' => Schluessel aus SANCTUARY_DIFFICULTIES oder '', 'progress' => string, 'note' => string]] fuer
|
||
* genau die Refugien in $raids. Eintraege von vor den Angaben je Refugium haben keine details - ihre eine Notiz
|
||
* ($legacyNote) galt fuer alles und steht deshalb bei jedem Refugium, die Stufe ist offen.
|
||
*/
|
||
function sanctuary_details_parse(?string $json, array $raids, string $legacyNote = ''): array
|
||
{
|
||
$data = $json !== null && $json !== '' ? json_decode($json, true) : null;
|
||
$legacy = !is_array($data);
|
||
$out = [];
|
||
foreach ($raids as $raid) {
|
||
$detail = sanctuary_detail_empty();
|
||
$given = !$legacy && is_array($data[$raid] ?? null) ? $data[$raid] : [];
|
||
$detail['lead'] = !empty($given['lead']);
|
||
$detail['shot'] = !empty($given['shot']);
|
||
$difficulty = is_string($given['diff'] ?? null) ? $given['diff'] : '';
|
||
$detail['difficulty'] = isset(SANCTUARY_DIFFICULTIES[$difficulty]) ? $difficulty : '';
|
||
$detail['progress'] = is_string($given['progress'] ?? null) ? $given['progress'] : '';
|
||
$detail['note'] = $legacy ? $legacyNote : (is_string($given['note'] ?? null) ? $given['note'] : '');
|
||
$out[$raid] = $detail;
|
||
}
|
||
return $out;
|
||
}
|
||
|
||
/** Angaben je Refugium fuer die Spalte details. */
|
||
function sanctuary_details_encode(array $details): string
|
||
{
|
||
$out = [];
|
||
foreach ($details as $raid => $detail) {
|
||
if (!isset(SANCTUARY_RAIDS[$raid])) {
|
||
continue;
|
||
}
|
||
$out[$raid] = [
|
||
'lead' => !empty($detail['lead']) ? 1 : 0,
|
||
'shot' => !empty($detail['shot']) ? 1 : 0,
|
||
'diff' => (string) ($detail['difficulty'] ?? ''),
|
||
'progress' => (string) ($detail['progress'] ?? ''),
|
||
'note' => (string) ($detail['note'] ?? ''),
|
||
];
|
||
}
|
||
return (string) json_encode($out, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||
}
|
||
|
||
/** Freitext aus dem Formular: Leerraum zusammengezogen, auf $max Zeichen gekuerzt. */
|
||
function sanctuary_text_input($value, int $max): string
|
||
{
|
||
return is_string($value) ? mb_substr(trim((string) preg_replace('/\s+/u', ' ', $value)), 0, $max) : '';
|
||
}
|
||
|
||
/**
|
||
* Zeitfenster eines Mitglieds: [['weekday' => 1-7, 'start' => Minuten, 'end' => Minuten], ...] nach Tag und Beginn.
|
||
* Liegt das Ende nicht nach dem Beginn, geht das Fenster ueber Mitternacht.
|
||
*/
|
||
function sanctuary_windows(int $userId): array
|
||
{
|
||
return sanctuary_windows_for([$userId])[$userId] ?? [];
|
||
}
|
||
|
||
/**
|
||
* @param int[] $userIds
|
||
* @return array<int, array<int, array{weekday: int, start: int, end: int}>> je Mitglied
|
||
*/
|
||
function sanctuary_windows_for(array $userIds): array
|
||
{
|
||
$userIds = array_values(array_unique(array_filter(array_map('intval', $userIds))));
|
||
if (!$userIds) {
|
||
return [];
|
||
}
|
||
try {
|
||
$stmt = db()->prepare(
|
||
'SELECT user_id, weekday, start_min, end_min FROM sanctuary_times
|
||
WHERE user_id IN (' . implode(',', array_fill(0, count($userIds), '?')) . ')
|
||
ORDER BY weekday, start_min, end_min'
|
||
);
|
||
$stmt->execute($userIds);
|
||
} catch (PDOException $e) {
|
||
return []; // Tabelle entsteht erst beim naechsten Schema-Abgleich
|
||
}
|
||
$out = [];
|
||
foreach ($stmt->fetchAll() as $row) {
|
||
$out[(int) $row['user_id']][] = ['weekday' => (int) $row['weekday'], 'start' => (int) $row['start_min'], 'end' => (int) $row['end_min']];
|
||
}
|
||
return $out;
|
||
}
|
||
|
||
/**
|
||
* Zeitfenster mit derselben Uhrzeit zusammenfassen (fuers Formular und die Anzeige):
|
||
* [['days' => [1, 2, 3], 'start' => 1080, 'end' => 1320], ...] in der Reihenfolge des ersten Tages.
|
||
*/
|
||
function sanctuary_windows_grouped(array $windows): array
|
||
{
|
||
$groups = [];
|
||
foreach ($windows as $window) {
|
||
$key = $window['start'] . '-' . $window['end'];
|
||
$groups[$key] ??= ['days' => [], 'start' => $window['start'], 'end' => $window['end']];
|
||
$groups[$key]['days'][] = $window['weekday'];
|
||
}
|
||
foreach ($groups as &$group) {
|
||
$group['days'] = array_values(array_unique($group['days']));
|
||
sort($group['days']);
|
||
}
|
||
unset($group);
|
||
usort($groups, static fn (array $a, array $b): int => [$a['days'][0], $a['start']] <=> [$b['days'][0], $b['start']]);
|
||
return $groups;
|
||
}
|
||
|
||
/** Tage als Text: [1,2,3,4,5] -> "Mo–Fr", [3,7] -> "Mi, So", [1,2,6] -> "Mo, Di, Sa". */
|
||
function sanctuary_days_text(array $days): string
|
||
{
|
||
$parts = [];
|
||
$count = count($days);
|
||
for ($i = 0; $i < $count; $i++) {
|
||
$from = $days[$i];
|
||
$to = $from;
|
||
while ($i + 1 < $count && $days[$i + 1] === $to + 1) {
|
||
$to = $days[++$i];
|
||
}
|
||
if ($to - $from >= 2) {
|
||
$parts[] = SANCTUARY_WEEKDAYS[$from] . '–' . SANCTUARY_WEEKDAYS[$to];
|
||
} else {
|
||
for ($day = $from; $day <= $to; $day++) {
|
||
$parts[] = SANCTUARY_WEEKDAYS[$day];
|
||
}
|
||
}
|
||
}
|
||
return implode(', ', $parts);
|
||
}
|
||
|
||
/** Zeitfenster als Liste von Texten: ["Mo–Fr 18:00–22:00", "So 15:00–20:00"]. */
|
||
function sanctuary_windows_text(array $windows): array
|
||
{
|
||
return array_map(
|
||
static fn (array $group): string => sanctuary_days_text($group['days']) . ' ' . sanctuary_time_text($group['start']) . '–' . sanctuary_time_text($group['end']),
|
||
sanctuary_windows_grouped($windows)
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Zeitfenster aus dem Formular: win_days[i][] = Wochentage, win_from[i] / win_to[i] = "HH:MM". Leere Zeilen zaehlen
|
||
* nicht, halb ausgefuellte sind ein Fehler.
|
||
*
|
||
* @return array{0: array<int, array{weekday: int, start: int, end: int}>, 1: string[]} Zeitfenster, Fehler
|
||
*/
|
||
function sanctuary_windows_from_input(array $input): array
|
||
{
|
||
$daysInput = is_array($input['win_days'] ?? null) ? $input['win_days'] : [];
|
||
$fromInput = is_array($input['win_from'] ?? null) ? $input['win_from'] : [];
|
||
$toInput = is_array($input['win_to'] ?? null) ? $input['win_to'] : [];
|
||
$indexes = array_slice(array_unique(array_merge(array_keys($daysInput), array_keys($fromInput), array_keys($toInput))), 0, SANCTUARY_MAX_WINDOWS * 3);
|
||
$windows = [];
|
||
$errors = [];
|
||
$rows = 0;
|
||
foreach ($indexes as $index) {
|
||
$days = array_values(array_intersect(array_keys(SANCTUARY_WEEKDAYS), array_map('intval', is_array($daysInput[$index] ?? null) ? $daysInput[$index] : [])));
|
||
$fromRaw = is_string($fromInput[$index] ?? null) ? trim($fromInput[$index]) : '';
|
||
$toRaw = is_string($toInput[$index] ?? null) ? trim($toInput[$index]) : '';
|
||
if (!$days && $fromRaw === '' && $toRaw === '') {
|
||
continue;
|
||
}
|
||
$from = sanctuary_time_parse($fromRaw);
|
||
$to = sanctuary_time_parse($toRaw);
|
||
if (!$days || $from === null || $to === null) {
|
||
$errors['incomplete'] = 'Ein Zeitfenster braucht mindestens einen Wochentag sowie Beginn und Ende.';
|
||
continue;
|
||
}
|
||
if ($from === $to) {
|
||
$errors['same'] = 'Beginn und Ende eines Zeitfensters dürfen nicht gleich sein.';
|
||
continue;
|
||
}
|
||
if (++$rows > SANCTUARY_MAX_WINDOWS) {
|
||
$errors['max'] = 'Höchstens ' . SANCTUARY_MAX_WINDOWS . ' Zeitfenster.';
|
||
break;
|
||
}
|
||
foreach ($days as $day) {
|
||
$windows[$day . '-' . $from . '-' . $to] = ['weekday' => $day, 'start' => $from, 'end' => $to];
|
||
}
|
||
}
|
||
return [array_values($windows), array_values($errors)];
|
||
}
|
||
|
||
/** Zahl aus einem Feld wie "2.450" oder "98 986": nur die Ziffern; leer = null, zu gross oder Unsinn = false. */
|
||
function sanctuary_number_input($value, int $max)
|
||
{
|
||
$raw = is_string($value) ? trim($value) : '';
|
||
if ($raw === '') {
|
||
return null;
|
||
}
|
||
$digits = preg_replace('/[.\s\x{00A0}\']/u', '', $raw);
|
||
if (!preg_match('/^\d{1,9}$/', (string) $digits) || (int) $digits > $max) {
|
||
return false;
|
||
}
|
||
return (int) $digits === 0 ? null : (int) $digits;
|
||
}
|
||
|
||
/**
|
||
* Eigene Eintraege je Charakter: [Charakter-ID => ['raids' => [...], 'details' => [Refugium => Angaben, siehe
|
||
* sanctuary_details_parse()], 'gearscore' => ?int, 'combat_power' => ?int, 'confirmed_at' => string]].
|
||
*/
|
||
function sanctuary_entries_for_user(int $userId): array
|
||
{
|
||
try {
|
||
$stmt = db()->prepare('SELECT character_id, raids, details, gearscore, combat_power, note, confirmed_at FROM sanctuary_entries WHERE user_id = ?');
|
||
$stmt->execute([$userId]);
|
||
} catch (PDOException $e) {
|
||
return [];
|
||
}
|
||
$out = [];
|
||
foreach ($stmt->fetchAll() as $row) {
|
||
$raids = sanctuary_raids_parse($row['raids']);
|
||
$out[(int) $row['character_id']] = [
|
||
'raids' => $raids,
|
||
'details' => sanctuary_details_parse($row['details'], $raids, (string) $row['note']),
|
||
'gearscore' => $row['gearscore'] !== null ? (int) $row['gearscore'] : null,
|
||
'combat_power' => $row['combat_power'] !== null ? (int) $row['combat_power'] : null,
|
||
'confirmed_at' => (string) $row['confirmed_at'],
|
||
];
|
||
}
|
||
return $out;
|
||
}
|
||
|
||
/**
|
||
* Stand des eigenen Eintrags: 'none' (nichts eingetragen), 'active', 'expiring' (ist in days_left Tagen
|
||
* updatepflichtig - ab SANCTUARY_WARN_DAYS Tagen vorher) oder 'expired' (updatepflichtig: steht ausgegraut am Ende
|
||
* der Uebersicht).
|
||
*
|
||
* @return array{state: string, days_left: int, confirmed_at: ?string}
|
||
*/
|
||
function sanctuary_state(int $userId): array
|
||
{
|
||
static $cache = [];
|
||
if (isset($cache[$userId])) {
|
||
return $cache[$userId];
|
||
}
|
||
try {
|
||
$stmt = db()->prepare('SELECT MAX(confirmed_at) FROM sanctuary_entries WHERE user_id = ?');
|
||
$stmt->execute([$userId]);
|
||
$confirmedAt = $stmt->fetchColumn();
|
||
} catch (PDOException $e) {
|
||
$confirmedAt = null;
|
||
}
|
||
if (!$confirmedAt) {
|
||
return $cache[$userId] = ['state' => 'none', 'days_left' => 0, 'confirmed_at' => null];
|
||
}
|
||
$expires = (int) strtotime((string) $confirmedAt) + SANCTUARY_EXPIRE_DAYS * 86400;
|
||
$daysLeft = (int) ceil(($expires - time()) / 86400);
|
||
$state = $expires <= time() ? 'expired' : ($daysLeft <= SANCTUARY_WARN_DAYS ? 'expiring' : 'active');
|
||
return $cache[$userId] = ['state' => $state, 'days_left' => max(0, $daysLeft), 'confirmed_at' => (string) $confirmedAt];
|
||
}
|
||
|
||
/** "in 5 Tagen" bzw. am letzten Tag "in weniger als einem Tag". */
|
||
function sanctuary_days_left_text(int $daysLeft): string
|
||
{
|
||
return $daysLeft <= 1 ? 'in weniger als einem Tag' : 'in ' . $daysLeft . ' Tagen';
|
||
}
|
||
|
||
/** Ist ein Eintrag mit diesem Stand (confirmed_at) updatepflichtig? */
|
||
function sanctuary_is_stale(string $confirmedAt): bool
|
||
{
|
||
return (int) strtotime($confirmedAt) + SANCTUARY_EXPIRE_DAYS * 86400 <= time();
|
||
}
|
||
|
||
/** Hinweis am Menuepunkt: der eigene Eintrag ist bald oder schon updatepflichtig - sonst null. */
|
||
function sanctuary_nav_badge(int $userId): ?array
|
||
{
|
||
$state = sanctuary_state($userId);
|
||
if ($state['state'] === 'expiring') {
|
||
return ['text' => '!', 'class' => 'sidebar-badge', 'title' => 'Dein Eintrag im Refugien-Planer ist '
|
||
. sanctuary_days_left_text($state['days_left']) . ' updatepflichtig – bitte bestätigen'];
|
||
}
|
||
if ($state['state'] === 'expired') {
|
||
return ['text' => '!', 'class' => 'sidebar-badge', 'title' => 'Dein Eintrag im Refugien-Planer ist updatepflichtig – bestätige oder aktualisiere ihn'];
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* Hinweis oben auf jeder Seite (includes/header.php): Der eigene Eintrag ist bald oder schon updatepflichtig - mit
|
||
* "Stimmt noch" (macht ihn wieder aktuell) und "Heute ausblenden" (merkt sich die Sitzung fuer den Tag). Leer, wenn
|
||
* nichts ansteht. $back: Seite, auf die es danach zurueckgeht.
|
||
*/
|
||
function sanctuary_expiry_notice_html(int $userId, string $back): string
|
||
{
|
||
$state = sanctuary_state($userId);
|
||
if (!in_array($state['state'], ['expiring', 'expired'], true) || ($_SESSION['sanctuary_notice_snooze'] ?? '') === date('Y-m-d')) {
|
||
return '';
|
||
}
|
||
$form = static fn (string $action, string $label, string $class): string => '<form method="post" action="/sanctuary_action.php" class="inline-form">'
|
||
. csrf_field() . '<input type="hidden" name="action" value="' . $action . '"><input type="hidden" name="back" value="' . e($back) . '">'
|
||
. '<button type="submit" class="button-small' . $class . '">' . $label . '</button></form>';
|
||
$text = $state['state'] === 'expired'
|
||
? 'ist seit dem ' . date('d.m.', (int) strtotime((string) $state['confirmed_at'])) . ' nicht aktualisiert und steht als updatepflichtig ausgegraut am Ende der Liste.'
|
||
: 'ist ' . sanctuary_days_left_text($state['days_left']) . ' updatepflichtig und rutscht dann ausgegraut ans Ende der Liste.';
|
||
return '<div class="flash flash-info sanctuary-notice" role="status">'
|
||
. '<span>' . icon('bell') . ' Dein Eintrag im <a href="/sanctuary.php">Refugien-Planer</a> ' . e($text) . ' Stimmt er noch?</span>'
|
||
. '<span class="sanctuary-notice-actions">'
|
||
. $form('confirm', 'Stimmt noch', '')
|
||
. '<a class="button button-secondary button-small" href="/sanctuary.php#mein-eintrag">Aktualisieren</a>'
|
||
. $form('snooze', 'Heute ausblenden', ' button-secondary')
|
||
. '</span></div>';
|
||
}
|
||
|
||
/**
|
||
* Eintrag speichern: ersetzt die Zeitfenster und die Eintraege je Charakter (nur eigene Charaktere, die die
|
||
* Aufrufer geprueft haben) und gilt als frisch bestaetigt.
|
||
*
|
||
* @param array<int, array{weekday: int, start: int, end: int}> $windows
|
||
* @param array<int, array{raids: string[], details: array, gearscore: ?int, combat_power: ?int}> $entries je Charakter-ID
|
||
*/
|
||
function sanctuary_save(int $userId, array $windows, array $entries): void
|
||
{
|
||
$pdo = db();
|
||
$pdo->beginTransaction();
|
||
try {
|
||
$pdo->prepare('DELETE FROM sanctuary_times WHERE user_id = ?')->execute([$userId]);
|
||
$insertTime = $pdo->prepare('INSERT INTO sanctuary_times (user_id, weekday, start_min, end_min) VALUES (?, ?, ?, ?)');
|
||
foreach ($windows as $window) {
|
||
$insertTime->execute([$userId, $window['weekday'], $window['start'], $window['end']]);
|
||
}
|
||
$pdo->prepare('DELETE FROM sanctuary_entries WHERE user_id = ?')->execute([$userId]);
|
||
$insertEntry = $pdo->prepare(
|
||
'INSERT INTO sanctuary_entries (character_id, user_id, raids, details, gearscore, combat_power, confirmed_at) VALUES (?, ?, ?, ?, ?, ?, NOW())'
|
||
);
|
||
foreach ($entries as $characterId => $entry) {
|
||
$insertEntry->execute([
|
||
(int) $characterId, $userId, implode(',', $entry['raids']), sanctuary_details_encode($entry['details']),
|
||
$entry['gearscore'], $entry['combat_power'],
|
||
]);
|
||
}
|
||
$pdo->commit();
|
||
} catch (Throwable $e) {
|
||
$pdo->rollBack();
|
||
throw $e;
|
||
}
|
||
}
|
||
|
||
/** "Stimmt noch": alle eigenen Eintraege gelten wieder als frisch. Gibt zurueck, ob es welche gab. */
|
||
function sanctuary_confirm(int $userId): bool
|
||
{
|
||
$stmt = db()->prepare('UPDATE sanctuary_entries SET confirmed_at = NOW() WHERE user_id = ?');
|
||
$stmt->execute([$userId]);
|
||
return $stmt->rowCount() > 0;
|
||
}
|
||
|
||
/** Eigenen Eintrag samt Zeitfenstern entfernen. */
|
||
function sanctuary_remove(int $userId): void
|
||
{
|
||
db()->prepare('DELETE FROM sanctuary_entries WHERE user_id = ?')->execute([$userId]);
|
||
db()->prepare('DELETE FROM sanctuary_times WHERE user_id = ?')->execute([$userId]);
|
||
}
|
||
|
||
/**
|
||
* Lange nicht mehr bestaetigte Eintraege loeschen (SANCTUARY_PURGE_DAYS), dazu Zeitfenster ohne Eintrag (laeuft
|
||
* beim Oeffnen des Planers).
|
||
*/
|
||
function sanctuary_purge(): void
|
||
{
|
||
try {
|
||
$pdo = db();
|
||
$pdo->prepare('DELETE FROM sanctuary_entries WHERE confirmed_at < ?')
|
||
->execute([date('Y-m-d H:i:s', time() - SANCTUARY_PURGE_DAYS * 86400)]);
|
||
$pdo->exec('DELETE t FROM sanctuary_times t LEFT JOIN sanctuary_entries e ON e.user_id = t.user_id WHERE e.user_id IS NULL');
|
||
} catch (PDOException $e) {
|
||
// Dann beim naechsten Mal
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Gearscore und Kampfkraft eines Eintrags: die von Hand eingetragenen Werte. Nur wo keiner eingetragen ist (aeltere
|
||
* Eintraege verknuepfter Charaktere, Vorschlag im Formular), der Wert aus dem Spiel - 'live' sagt, ob das so ist.
|
||
* $row braucht gearscore, combat_power und fuer den Ersatz aion_char_id, live_gearscore/live_power (aus aion_data).
|
||
*
|
||
* @return array{gearscore: ?int, combat_power: ?int, live: bool}
|
||
*/
|
||
function sanctuary_stats(array $row): array
|
||
{
|
||
$linked = !empty($row['aion_char_id']);
|
||
$liveScore = $linked ? (int) ($row['live_gearscore'] ?? 0) : 0;
|
||
$livePower = $linked ? (int) ($row['live_power'] ?? 0) : 0;
|
||
$manualScore = isset($row['gearscore']) ? (int) $row['gearscore'] : 0;
|
||
$manualPower = isset($row['combat_power']) ? (int) $row['combat_power'] : 0;
|
||
$score = $manualScore > 0 ? $manualScore : $liveScore;
|
||
$power = $manualPower > 0 ? $manualPower : $livePower;
|
||
return [
|
||
'gearscore' => $score > 0 ? $score : null,
|
||
'combat_power' => $power > 0 ? $power : null,
|
||
'live' => ($manualScore <= 0 && $liveScore > 0) || ($manualPower <= 0 && $livePower > 0),
|
||
];
|
||
}
|
||
|
||
/** SQL-Ausdruecke fuer Gearscore und Kampfkraft aus den gespeicherten Spieldaten (member_characters als $alias). */
|
||
function sanctuary_live_columns(string $alias = 'c'): string
|
||
{
|
||
return "JSON_VALUE($alias.aion_data, '$.item_level') AS live_gearscore, JSON_VALUE($alias.aion_data, '$.combat_power') AS live_power";
|
||
}
|
||
|
||
/**
|
||
* Alle Eintraege der Legion mit Charakter, Mitglied, Werten, Angaben je Refugium und Zeitfenstern - die Zeilen
|
||
* der Uebersicht. 'stale' = updatepflichtig (seit SANCTUARY_EXPIRE_DAYS Tagen nicht bestaetigt): diese stehen am
|
||
* Ende. Sonst sortiert nach Kampfkraft (hoch zuerst), ohne Angabe zuletzt.
|
||
*
|
||
* @return array<int, array<string, mixed>>
|
||
*/
|
||
function sanctuary_overview(): array
|
||
{
|
||
try {
|
||
$stmt = db()->prepare(
|
||
'SELECT e.character_id, e.user_id, e.raids, e.details, e.gearscore, e.combat_power, e.note, e.confirmed_at,
|
||
c.name AS character_name, c.class_name, c.is_main, c.aion_char_id, c.aion_fetched_at, ' . sanctuary_live_columns('c') . ",
|
||
u.username, u.display_name, u.avatar_filename
|
||
FROM sanctuary_entries e
|
||
JOIN member_characters c ON c.id = e.character_id
|
||
JOIN users u ON u.id = e.user_id
|
||
WHERE u.status = 'active' AND e.confirmed_at >= ? AND " . sql_is_legion_member('u')
|
||
);
|
||
$stmt->execute([date('Y-m-d H:i:s', time() - SANCTUARY_PURGE_DAYS * 86400)]);
|
||
$rows = $stmt->fetchAll();
|
||
} catch (PDOException $e) {
|
||
return [];
|
||
}
|
||
$windows = sanctuary_windows_for(array_column($rows, 'user_id'));
|
||
$out = [];
|
||
foreach ($rows as $row) {
|
||
$raids = sanctuary_raids_parse($row['raids']);
|
||
$userWindows = $windows[(int) $row['user_id']] ?? [];
|
||
if (!$raids || !$userWindows) {
|
||
continue;
|
||
}
|
||
$stats = sanctuary_stats($row);
|
||
$out[] = [
|
||
'character_id' => (int) $row['character_id'],
|
||
'user_id' => (int) $row['user_id'],
|
||
'member' => $row['display_name'] !== '' ? (string) $row['display_name'] : (string) $row['username'],
|
||
'user' => ['id' => (int) $row['user_id'], 'username' => $row['username'], 'display_name' => $row['display_name'], 'avatar_filename' => $row['avatar_filename']],
|
||
'character' => (string) $row['character_name'],
|
||
'class' => (string) $row['class_name'],
|
||
'role' => sanctuary_class_role($row['class_name']),
|
||
'is_main' => (int) $row['is_main'] === 1,
|
||
'raids' => $raids,
|
||
'details' => sanctuary_details_parse($row['details'], $raids, (string) $row['note']),
|
||
'gearscore' => $stats['gearscore'],
|
||
'combat_power' => $stats['combat_power'],
|
||
'live' => $stats['live'],
|
||
'stats_at' => $stats['live'] ? (string) $row['aion_fetched_at'] : (string) $row['confirmed_at'],
|
||
'confirmed_at' => (string) $row['confirmed_at'],
|
||
'stale' => sanctuary_is_stale((string) $row['confirmed_at']),
|
||
'windows' => $userWindows,
|
||
];
|
||
}
|
||
usort($out, static fn (array $a, array $b): int => [$a['stale'], $b['combat_power'] ?? -1, $b['gearscore'] ?? -1, mb_strtolower($a['member'])]
|
||
<=> [$b['stale'], $a['combat_power'] ?? -1, $a['gearscore'] ?? -1, mb_strtolower($b['member'])]);
|
||
return $out;
|
||
}
|
||
|
||
/** Kampfkraft kurz ("98,9k"), wie auf den Charakterkarten (armory_power_label). */
|
||
function sanctuary_power_label(int $power): string
|
||
{
|
||
return $power < 1000 ? (string) $power : number_format(floor($power / 100) / 10, 1, ',', '.') . 'k';
|
||
}
|