Live updates: sidebar counts refresh themselves, pages reload when something new arrives

- Every open page in the member area asks live.php every 20 s while it is visible
  (assets/js/live.js). The counts at the menu items and the own Lumipunkte are replaced in
  place; header.php and live.php compute them with the same functions (nav_badges(),
  nav_points() in includes/live_updates.php, links marked with data-badge).
- Dashboard, gallery, picture page, profile, member list, calendar, shop, shop orders,
  Lumipunkte, warehouse, premades, bug reports, moderation, user management and wiki get a
  fingerprint of the data they show (count, highest id, checksum of the shown columns - no
  "last active"). When it changes, the page reloads - but only while nobody is typing, has a
  form started, a dialog, lightbox or menu open or clicked in the last 8 s; otherwise a notice
  "Es gibt Neues auf dieser Seite" with a reload button, and it reloads once things are quiet.
  At most 3 automatic reloads per minute.
- Tools and forms (map, gear planner, edit pages) never reload on their own; the raid page keeps
  its own live updates. The dashboard notices new raids and signups through the raid cache
  (now also stores a fingerprint of dates, slots and signups); premades ask the bot with a 3 s
  timeout (new timeout parameter for premades_api_request/fetch_premades).
- README and patch notes updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Maaxxs 2026-09-24 23:47:42 +02:00
parent 809e88d028
commit 7daffd5523
8 changed files with 678 additions and 122 deletions

View file

@ -1142,6 +1142,28 @@ Unter **Mein Profil → Einführung neu starten** lässt sie sich wiederholen. B
diese Version gelten alle bestehenden Konten als „schon gesehen“, die Tour erscheint also nur
für neue Mitglieder automatisch. Die Schritte stehen am Ende von `dashboard.php`.
## Live-Aktualisierung
Im Mitgliederbereich fragt jede offene Seite alle 20 Sekunden bei `live.php` nach, solange sie zu sehen
ist (`assets/js/live.js`, Werte aus `includes/live_updates.php`):
- **Menü:** Die Zahlen und Hinweise an den Menüpunkten (Raids, neue Galeriebilder, offene Shop-Anträge,
Freischaltungen, Fehlermeldungen, Moderation, Wartung, Impressum, Patchnotes) und der eigene Punktestand
werden direkt ersetzt. Der Seitenaufbau (`includes/header.php`) nutzt dieselben Funktionen
(`nav_badges()`, `nav_points()`), die Menüpunkte tragen dafür `data-badge`.
- **Seiteninhalt:** Für Dashboard, Galerie, Bildseite, Profilseite, Mitgliederliste, Kalender, Lumishop,
Anträge, Lumipunkte, Lagerhaus, Premades, Fehlermeldungen, Moderation, Benutzerverwaltung und Wiki
berechnet `live_fingerprint()` einen Fingerabdruck der angezeigten Daten (Anzahl, höchste ID und eine
Prüfsumme der Spalten - ohne „zuletzt aktiv“). Der Header schreibt ihn in `data-live-fp`; ändert er sich,
lädt die Seite neu. Aber nur, wenn gerade niemand tippt, ein Formular angefangen, ein Fenster, die
Großansicht oder das Menü offen oder in den letzten 8 Sekunden etwas angeklickt hat - sonst erscheint
unten „Es gibt Neues auf dieser Seite“ mit „Aktualisieren“, und sobald es passt, lädt sie von selbst.
Höchstens 3 automatische Neuladungen pro Minute.
- Werkzeuge und Formulare (Karte, Gear-Planer, Bearbeiten-Seiten) laden nie von selbst, die Raid-Seite hat
ihre eigene Live-Aktualisierung (`raids_live.php`). Weitere Seiten kommen in `live_fingerprint_parts()`
dazu; Felder, die dabei nicht als „angefangen“ zählen sollen, bekommen `data-live-ignore`.
- Das Dashboard merkt neue Raids, Termine und Anmeldungen am Zwischenspeicher der Raids
(`settings.raids_nav_cache`, siehe Raids), die Premades-Seite fragt dafür kurz den Bot (3 Sekunden).
## Fehlermeldungen
Im Dashboard können Mitglieder unter **Fehler gefunden?** Bugs der Website melden (Titel,

View file

@ -7260,6 +7260,30 @@ html.has-scroll-progress::-webkit-scrollbar { display: none; }
.member-picker { flex: 1 1 220px; min-width: 0; }
/* ---- Patchnotes (patchnotes.php) ---- */
/* Hinweis der Live-Aktualisierung (assets/js/live.js), wenn die Seite gerade nicht von selbst neu laden kann */
.live-notice {
position: fixed;
left: 50%;
bottom: 1.25rem;
z-index: 900;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 0.9rem;
max-width: calc(100vw - 2rem);
padding: 0.55rem 0.6rem 0.55rem 1.1rem;
border: 1px solid rgba(201, 162, 39, 0.6);
border-radius: 999px;
background: rgba(35, 35, 35, 0.96);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
color: var(--text);
font-size: 0.9rem;
animation: live-notice-in 0.25s ease;
}
.live-notice .button { border-radius: 999px; white-space: nowrap; }
@keyframes live-notice-in { from { opacity: 0; transform: translate(-50%, 12px); } }
@media (prefers-reduced-motion: reduce) { .live-notice { animation: none; } }
.sidebar-badge-new, .sidebar-badge-count { position: static; margin-left: auto; padding: 0 0.45rem; }
/* Zahl ohne Neuigkeit (anstehende Raids, schon gesehen): zurueckhaltend statt golden */
.sidebar-badge-count { background: var(--bg-panel-alt); color: var(--text-muted); box-shadow: inset 0 0 0 1px var(--border); }

192
assets/js/live.js Normal file
View file

@ -0,0 +1,192 @@
/**
* Live-Aktualisierung im Mitgliederbereich: Solange die Seite zu sehen ist, fragt sie alle 20 Sekunden
* bei live.php nach (includes/live_updates.php).
* - Die Zahlen an den Menuepunkten und der eigene Punktestand werden direkt ersetzt.
* - Hat sich der Inhalt der Seite geaendert (Fingerabdruck in data-live-fp), laedt sie neu - aber nur,
* wenn gerade niemand tippt, etwas ausfuellt, ein Fenster offen hat oder in den letzten Sekunden
* etwas angeklickt hat. Sonst erscheint unten ein Hinweis mit "Aktualisieren".
*/
(function () {
'use strict';
var INTERVAL = 20000; // Abstand der Nachfragen
var QUIET = 8000; // so lange nach der letzten Eingabe gilt die Seite als ruhig
var RETRY = 4000; // Wartet ein Neuladen, so oft nachsehen, ob es jetzt passt
var body = document.body;
var path = body.getAttribute('data-live-path') || location.pathname;
var fingerprint = body.getAttribute('data-live-fp') || '';
var timer = 0;
var retryTimer = 0;
var lastPoll = 0;
var inFlight = false;
var lastInput = Date.now();
var pending = false;
var stopped = false;
var notice = null;
// Auf- oder zugeklappte Bereiche gingen beim Neuladen verloren - Ausgangszustand merken
var details = Array.prototype.map.call(document.querySelectorAll('details'), function (el) {
return { el: el, open: el.open };
});
['pointerdown', 'keydown', 'wheel', 'touchstart', 'input'].forEach(function (type) {
window.addEventListener(type, function () { lastInput = Date.now(); }, { capture: true, passive: true });
});
// --- Darf die Seite gerade neu laden? -------------------------------------------------
function fieldChanged(field) {
if (field.closest('[data-live-ignore]')) return false;
if (field.tagName === 'SELECT') {
var fallback = field.multiple ? -1 : 0;
for (var i = 0; i < field.options.length; i++) {
var option = field.options[i];
if (field.multiple && option.selected !== option.defaultSelected) return true;
if (!field.multiple && option.defaultSelected) fallback = i;
}
return !field.multiple && field.selectedIndex !== fallback;
}
switch (field.type) {
case 'hidden': case 'submit': case 'button': case 'reset': case 'image':
return false;
case 'checkbox': case 'radio':
return field.checked !== field.defaultChecked;
case 'file':
return !!(field.files && field.files.length);
default:
return field.value !== field.defaultValue;
}
}
function busy() {
if (Date.now() - lastInput < QUIET) return true;
var active = document.activeElement;
if (active && active.matches && active.matches('textarea, select, [contenteditable], input:not([type=checkbox]):not([type=radio]):not([type=button]):not([type=submit])')) return true;
// Offene Fenster, Rueckfragen, Grossansicht, Einfuehrung, Menue-Bearbeitung, aufgeklapptes Handy-Menue
if (document.querySelector('.modal-overlay:not([hidden]), .lightbox:not([hidden]), .tour-root, #success-popup, dialog[open], .sidebar-nav.is-editing, .sidebar.open')) return true;
if (body.classList.contains('lumina-dialog-open')) return true;
if (Array.prototype.some.call(document.querySelectorAll('input, textarea, select'), fieldChanged)) return true;
if (details.some(function (d) { return d.el.isConnected && d.el.open !== d.open; })) return true;
var selection = window.getSelection ? String(window.getSelection()) : '';
return selection.trim() !== '';
}
// Bremse: hoechstens 3 automatische Neuladungen pro Minute (falls sich etwas staendig aendert)
function reloadAllowed() {
try {
var now = Date.now();
var recent = JSON.parse(sessionStorage.getItem('lumina-live-reloads') || '[]').filter(function (t) { return now - t < 60000; });
if (recent.length >= 3) return false;
recent.push(now);
sessionStorage.setItem('lumina-live-reloads', JSON.stringify(recent));
} catch (e) {
// ohne Speicher eben ohne Bremse
}
return true;
}
function showNotice() {
if (notice) return;
notice = document.createElement('div');
notice.className = 'live-notice';
notice.setAttribute('role', 'status');
notice.innerHTML = '<span>Es gibt Neues auf dieser Seite.</span>' +
'<button type="button" class="button button-small">Aktualisieren</button>';
notice.querySelector('button').addEventListener('click', function () { window.location.reload(); });
body.appendChild(notice);
}
function applyPending() {
window.clearTimeout(retryTimer);
retryTimer = 0;
if (!pending || document.hidden) return;
if (!busy() && reloadAllowed()) {
window.location.reload();
return;
}
showNotice();
retryTimer = window.setTimeout(applyPending, RETRY);
}
// --- Zahlen im Menue -----------------------------------------------------------------
function updateBadges(badges) {
Array.prototype.forEach.call(document.querySelectorAll('[data-badge]'), function (link) {
var want = badges[link.getAttribute('data-badge')];
var badge = link.querySelector('.sidebar-badge');
if (!want) {
if (badge) badge.remove();
return;
}
if (!badge) {
badge = document.createElement('span');
link.appendChild(badge);
}
badge.className = want['class'];
badge.title = want.title;
badge.textContent = want.text;
});
}
function updatePoints(points) {
var el = document.querySelector('[data-live-points]');
if (el && typeof points === 'number') el.textContent = points.toLocaleString('de-DE');
}
// --- Nachfragen ------------------------------------------------------------------------
function schedule(ms) {
window.clearTimeout(timer);
timer = window.setTimeout(poll, ms);
}
function poll() {
timer = 0;
if (stopped || inFlight || document.hidden) return;
lastPoll = Date.now();
inFlight = true;
var url = '/live.php?path=' + encodeURIComponent(path) + '&q=' + encodeURIComponent(location.search.replace(/^\?/, ''));
fetch(url, { credentials: 'same-origin', cache: 'no-store', headers: { Accept: 'application/json' } })
.then(function (res) {
inFlight = false;
if (res.status === 401) {
stopped = true; // abgemeldet - beim naechsten Klick fuehrt die Seite zur Anmeldung
return null;
}
if (res.status === 503) {
window.location.reload(); // Wartungsmodus: die Seite zeigt dann die Wartungsseite
return null;
}
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
})
.then(function (data) {
if (!data || stopped) return;
if (data.badges) updateBadges(data.badges);
updatePoints(data.points);
if (data.fp) {
if (!fingerprint) {
fingerprint = data.fp;
} else if (data.fp !== fingerprint) {
pending = true;
applyPending();
}
}
schedule(INTERVAL);
})
.catch(function () {
inFlight = false;
schedule(INTERVAL * 3); // Netz oder Server gerade weg - seltener nachfragen
});
}
// Wieder sichtbar (Tab gewechselt, Handy entsperrt): gleich nachsehen statt auf den Takt zu warten
document.addEventListener('visibilitychange', function () {
if (document.hidden || stopped) return;
if (pending) applyPending();
if (Date.now() - lastPoll > 5000) schedule(0);
});
schedule(INTERVAL);
})();

View file

@ -20,15 +20,6 @@ $canViewWarehouse = $currentUser && user_has_permission('warehouse.view');
$canViewGear = $currentUser && user_has_permission('gear.view');
$canViewContributions = $currentUser && user_has_permission('contributions.view');
$canViewShop = $currentUser && user_has_permission('shop.view');
// Offene Lumishop-Antraege als Zahl am Menuepunkt (nur fuer die, die sie bearbeiten).
$shopPendingCount = 0;
if ($canViewShop && user_has_permission('shop.manage')) {
try {
$shopPendingCount = (int) db()->query("SELECT COUNT(*) FROM shop_orders WHERE status = 'pending'")->fetchColumn();
} catch (PDOException $e) {
$shopPendingCount = 0;
}
}
// Taegliche Belohnung: beim ersten Seitenaufruf des Tages Lumipunkte (includes/contributions.php)
if ($shellUser && user_has_permission('dashboard.view')) {
require_once __DIR__ . '/contributions.php';
@ -36,39 +27,17 @@ if ($shellUser && user_has_permission('dashboard.view')) {
set_flash('success', '+' . CONTRIBUTION_DAILY_POINTS . ' Lumipunkte - deine tägliche Belohnung. Schön, dass du vorbeischaust!');
}
}
// Eigener Punktestand unten in der Seitenleiste.
$sidebarPoints = null;
if ($canViewContributions && $shellUser) {
try {
$pointsStmt = db()->prepare('SELECT COALESCE(SUM(points), 0) FROM contribution_entries WHERE user_id = ?');
$pointsStmt->execute([(int) $shellUser['id']]);
$sidebarPoints = (int) $pointsStmt->fetchColumn();
} catch (PDOException $e) {
$sidebarPoints = null;
}
}
$canViewMembers = $currentUser && user_has_permission('members.view');
$canViewWiki = $currentUser && user_has_permission('wiki.view');
$canViewReports = $currentUser && user_has_permission('reports.view');
$canManageBugs = $currentUser && user_has_permission('bugs.manage');
$canViewAudit = $currentUser && user_has_permission('audit.view');
$canModerate = $currentUser && user_has_permission('comments.moderate');
$moderationCount = $canModerate ? moderation_pending_count() : 0;
// Offene Fehlermeldungen als Zahl am Menuepunkt.
$bugOpenCount = 0;
if ($canManageBugs) {
require_once __DIR__ . '/bugs.php';
$bugOpenCount = bug_open_count();
}
// Daten zuruecksetzen (Testdaten loeschen) nur fuer Entwickler
$canResetData = $currentUser && is_developer($currentUser);
$canManageSite = $currentUser && (user_has_permission('site.maintenance') || user_has_permission('site.announce'));
$canManageLegal = $currentUser && user_has_permission('site.legal');
$showAdminMenu = $canViewUsers || $canManageRoles || $canManageActivity || $canViewReports || $canManageBugs || $canViewAudit || $canModerate || $canResetData || $canManageSite || $canManageLegal;
// Neue Discord-Anmeldungen, die auf Freischaltung warten - als Zahl am Menuepunkt.
$pendingUserCount = $canViewUsers
? (int) db()->query("SELECT COUNT(*) FROM users WHERE status = 'pending'")->fetchColumn()
: 0;
$currentScript = basename((string) ($_SERVER['SCRIPT_NAME'] ?? ''));
$isDashboardActive = $currentScript === 'dashboard.php';
@ -146,47 +115,27 @@ $pageBackgroundClass = $pageBackgrounds[$currentScript] ?? '';
// Eigene Reihenfolge der Menuepunkte (Seitenleiste -> "Menü anpassen", assets/js/sidebar-editor.js).
// Umgesetzt ueber die CSS-Eigenschaft "order" - so steht die Reihenfolge schon beim Laden fest.
$savedNavOrder = [];
$patchnotesUnseen = false;
$announcementDismissed = null;
$galleryNewCount = 0;
$raidsUpcomingCount = 0;
$raidsNewCount = 0;
$navBadges = [];
$sidebarPoints = null;
$liveFingerprint = null;
if ($shellUser) {
require_once __DIR__ . '/live_updates.php';
$navRow = [];
try {
$navStmt = db()->prepare('SELECT sidebar_order, patchnotes_seen, announcement_dismissed, gallery_seen_at, raids_seen_at FROM users WHERE id = ?');
$navStmt->execute([(int) $shellUser['id']]);
$navRow = $navStmt->fetch() ?: [];
$savedNavOrder = json_decode((string) ($navRow['sidebar_order'] ?? ''), true) ?: [];
// "Neu" an den Patchnotes, solange die neueste nicht gelesen ist (nicht auf der Seite selbst)
$patchnotesUnseen = $currentScript !== 'patchnotes.php' && patchnotes_unseen($navRow['patchnotes_seen'] ?? null);
$announcementDismissed = isset($navRow['announcement_dismissed']) ? (string) $navRow['announcement_dismissed'] : null;
// Neue Bilder anderer seit dem letzten Besuch der Galerie (wer nie dort war: die letzten 7 Tage)
if ($canViewMembers && $currentScript !== 'gallery.php') {
$galleryStmt = db()->prepare(
"SELECT COUNT(*) FROM member_gallery g JOIN users u ON u.id = g.user_id
WHERE g.status = 'visible' AND g.is_background = 0 AND u.status = 'active' AND g.user_id <> ?
AND g.created_at > COALESCE(?, NOW() - INTERVAL 7 DAY)"
);
$galleryStmt->execute([(int) $shellUser['id'], $navRow['gallery_seen_at'] ?? null]);
$galleryNewCount = (int) $galleryStmt->fetchColumn();
}
// Anstehende Raids (zwischengespeichert, includes/raids_api.php) - davon neu: seit dem letzten
// Besuch der Raid-Seite gepostet (wer nie dort war: die letzten 7 Tage)
// (Eigene Variablennamen - die Seite, die den Header einbindet, hat z.B. schon $upcomingRaids.)
if ($canViewRaids) {
require_once __DIR__ . '/raids_api.php';
$navUpcomingRaids = raids_nav_upcoming();
$raidsUpcomingCount = count($navUpcomingRaids);
$navRaidsSeenTs = !empty($navRow['raids_seen_at']) ? (int) strtotime((string) $navRow['raids_seen_at']) : time() - 7 * 86400;
foreach ($navUpcomingRaids as $navRaidId) {
if (raid_posted_at($navRaidId) > $navRaidsSeenTs) {
$raidsNewCount++;
}
}
}
} catch (PDOException $e) {
$savedNavOrder = [];
}
// Zahlen an den Menuepunkten, eigener Punktestand und Fingerabdruck der Seite - live.php liefert
// dieselben Werte fuer die Live-Aktualisierung (includes/live_updates.php, assets/js/live.js)
$navBadges = nav_badges($shellUser, $currentScript, $navRow);
$sidebarPoints = nav_points((int) $shellUser['id']);
$liveFingerprint = live_fingerprint((string) ($_SERVER['SCRIPT_NAME'] ?? ''), $_GET, (int) $shellUser['id']);
}
$navOrder = static function (string $key) use ($savedNavOrder): string {
$zone = in_array($key, SIDEBAR_NAV_ADMIN, true) ? 'admin' : 'main';
@ -245,7 +194,9 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => !i
<?php endif; ?>
<link rel="stylesheet" href="<?= e(asset_url('/assets/css/style.css')) ?>">
</head>
<body class="<?= e(trim(($shellUser ? '' : 'guest-bg') . (!empty($bodyClass) ? ' ' . $bodyClass : ''))) ?>">
<body class="<?= e(trim(($shellUser ? '' : 'guest-bg') . (!empty($bodyClass) ? ' ' . $bodyClass : ''))) ?>"<?= $shellUser
? ' data-live-path="' . e((string) ($_SERVER['SCRIPT_NAME'] ?? '')) . '" data-live-fp="' . e((string) $liveFingerprint) . '"'
: '' ?>>
<?php if (!empty($successFlashes)): ?>
<div class="success-popup-overlay" id="success-popup" role="status" title="Klicken zum Schließen">
<div class="success-popup">
@ -264,6 +215,8 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => !i
<script type="application/json" id="flash-errors"><?= json_encode(array_column($errorFlashes, 'message'), JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP) ?></script>
<?php endif; ?>
<?php if ($shellUser): ?>
<?php // Zahlen im Menue und Inhalt der Seite aktualisieren sich von selbst (live.php, includes/live_updates.php) ?>
<script src="<?= e(asset_url('/assets/js/live.js')) ?>" defer></script>
<div class="app-shell">
<div class="mobile-topbar">
<button type="button" class="sidebar-toggle" aria-label="Menü öffnen" aria-expanded="false">
@ -285,11 +238,8 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => !i
<a href="/members.php" data-nav="/members.php"<?= $navOrder('/members.php') ?> class="sidebar-link<?= $isMembersActive ? ' active' : '' ?>" title="Mitglieder">
<?= icon('users') ?><span class="label">Mitglieder</span>
</a>
<a href="/gallery.php" data-nav="/gallery.php"<?= $navOrder('/gallery.php') ?> class="sidebar-link<?= $isGalleryActive ? ' active' : '' ?>" title="Galerie: Screenshots aller Mitglieder">
<?= icon('grid') ?><span class="label">Galerie</span>
<?php if ($galleryNewCount > 0): ?>
<span class="sidebar-badge sidebar-badge-new" title="Neue Bilder seit deinem letzten Besuch"><?= $galleryNewCount > 9 ? '9+' : $galleryNewCount ?></span>
<?php endif; ?>
<a href="/gallery.php" data-nav="/gallery.php" data-badge="/gallery.php"<?= $navOrder('/gallery.php') ?> class="sidebar-link<?= $isGalleryActive ? ' active' : '' ?>" title="Galerie: Screenshots aller Mitglieder">
<?= icon('grid') ?><span class="label">Galerie</span><?= nav_badge_html($navBadges, '/gallery.php') ?>
</a>
<?php endif; ?>
<?php if ($canViewContributions): ?>
@ -298,11 +248,8 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => !i
</a>
<?php endif; ?>
<?php if ($canViewShop): ?>
<a href="/shop.php" data-nav="/shop.php"<?= $navOrder('/shop.php') ?> class="sidebar-link<?= $isShopActive ? ' active' : '' ?>" title="Lumishop">
<?= icon('bag') ?><span class="label">Lumishop</span>
<?php if ($shopPendingCount > 0): ?>
<span class="sidebar-badge" title="Offene Anträge"><?= $shopPendingCount ?></span>
<?php endif; ?>
<a href="/shop.php" data-nav="/shop.php" data-badge="/shop.php"<?= $navOrder('/shop.php') ?> class="sidebar-link<?= $isShopActive ? ' active' : '' ?>" title="Lumishop">
<?= icon('bag') ?><span class="label">Lumishop</span><?= nav_badge_html($navBadges, '/shop.php') ?>
</a>
<?php endif; ?>
@ -315,14 +262,8 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => !i
</a>
<?php endif; ?>
<?php if ($canViewRaids): ?>
<a href="/raids.php" data-nav="/raids.php"<?= $navOrder('/raids.php') ?> class="sidebar-link<?= $isRaidsActive ? ' active' : '' ?>" title="Raids">
<?= icon('calendar') ?><span class="label">Raids</span>
<?php if ($raidsUpcomingCount > 0): ?>
<?php // Golden, solange seit dem letzten Besuch ein neuer Raid dazugekommen ist ?>
<span class="sidebar-badge <?= $raidsNewCount > 0 ? 'sidebar-badge-new' : 'sidebar-badge-count' ?>"
title="<?= e($raidsUpcomingCount . ($raidsUpcomingCount === 1 ? ' anstehender Raid' : ' anstehende Raids')
. ($raidsNewCount > 0 ? ', davon ' . $raidsNewCount . ' neu seit deinem letzten Besuch' : '')) ?>"><?= $raidsUpcomingCount > 9 ? '9+' : $raidsUpcomingCount ?></span>
<?php endif; ?>
<a href="/raids.php" data-nav="/raids.php" data-badge="/raids.php"<?= $navOrder('/raids.php') ?> class="sidebar-link<?= $isRaidsActive ? ' active' : '' ?>" title="Raids">
<?= icon('calendar') ?><span class="label">Raids</span><?= nav_badge_html($navBadges, '/raids.php') ?>
</a>
<?php endif; ?>
<?php if ($canViewPremades): ?>
@ -358,11 +299,8 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => !i
<?php if ($showAdminMenu): ?>
<div class="sidebar-section-label" data-nav-admin-label style="order: 10000">Admin</div>
<?php if ($canViewUsers): ?>
<a href="/admin/users.php" data-nav="/admin/users.php"<?= $navOrder('/admin/users.php') ?> class="sidebar-link<?= $isUsersActive ? ' active' : '' ?>" title="Benutzerverwaltung">
<?= icon('users') ?><span class="label">Benutzerverwaltung</span>
<?php if ($pendingUserCount > 0): ?>
<span class="sidebar-badge" title="Warten auf Freischaltung"><?= $pendingUserCount ?></span>
<?php endif; ?>
<a href="/admin/users.php" data-nav="/admin/users.php" data-badge="/admin/users.php"<?= $navOrder('/admin/users.php') ?> class="sidebar-link<?= $isUsersActive ? ' active' : '' ?>" title="Benutzerverwaltung">
<?= icon('users') ?><span class="label">Benutzerverwaltung</span><?= nav_badge_html($navBadges, '/admin/users.php') ?>
</a>
<?php endif; ?>
<?php if ($canManageRoles): ?>
@ -381,35 +319,23 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => !i
</a>
<?php endif; ?>
<?php if ($canManageBugs): ?>
<a href="/bugs.php" data-nav="/bugs.php"<?= $navOrder('/bugs.php') ?> class="sidebar-link<?= $isBugsActive ? ' active' : '' ?>" title="Fehlermeldungen">
<?= icon('bug') ?><span class="label">Fehlermeldungen</span>
<?php if ($bugOpenCount > 0): ?>
<span class="sidebar-badge" title="Offene Fehlermeldungen"><?= $bugOpenCount ?></span>
<?php endif; ?>
<a href="/bugs.php" data-nav="/bugs.php" data-badge="/bugs.php"<?= $navOrder('/bugs.php') ?> class="sidebar-link<?= $isBugsActive ? ' active' : '' ?>" title="Fehlermeldungen">
<?= icon('bug') ?><span class="label">Fehlermeldungen</span><?= nav_badge_html($navBadges, '/bugs.php') ?>
</a>
<?php endif; ?>
<?php if ($canModerate): ?>
<a href="/moderation.php" data-nav="/moderation.php"<?= $navOrder('/moderation.php') ?> class="sidebar-link<?= $isModerationActive ? ' active' : '' ?>" title="Moderation">
<?= icon('flag') ?><span class="label">Moderation</span>
<?php if ($moderationCount > 0): ?>
<span class="sidebar-badge" title="Warten auf Freigabe"><?= $moderationCount ?></span>
<?php endif; ?>
<a href="/moderation.php" data-nav="/moderation.php" data-badge="/moderation.php"<?= $navOrder('/moderation.php') ?> class="sidebar-link<?= $isModerationActive ? ' active' : '' ?>" title="Moderation">
<?= icon('flag') ?><span class="label">Moderation</span><?= nav_badge_html($navBadges, '/moderation.php') ?>
</a>
<?php endif; ?>
<?php if ($canManageSite): ?>
<a href="/admin/site.php" data-nav="/admin/site.php"<?= $navOrder('/admin/site.php') ?> class="sidebar-link<?= $isSiteActive ? ' active' : '' ?>" title="Wartung & Ankündigung">
<?= icon('bell') ?><span class="label">Wartung & Ankündigung</span>
<?php if (maintenance_active()): ?>
<span class="sidebar-badge" title="Wartungsmodus ist aktiv">!</span>
<?php endif; ?>
<a href="/admin/site.php" data-nav="/admin/site.php" data-badge="/admin/site.php"<?= $navOrder('/admin/site.php') ?> class="sidebar-link<?= $isSiteActive ? ' active' : '' ?>" title="Wartung & Ankündigung">
<?= icon('bell') ?><span class="label">Wartung & Ankündigung</span><?= nav_badge_html($navBadges, '/admin/site.php') ?>
</a>
<?php endif; ?>
<?php if ($canManageLegal): ?>
<a href="/admin/legal.php" data-nav="/admin/legal.php"<?= $navOrder('/admin/legal.php') ?> class="sidebar-link<?= $isLegalActive ? ' active' : '' ?>" title="Impressum & Datenschutz">
<?= icon('lock') ?><span class="label">Impressum & Datenschutz</span>
<?php if (!legal_complete()): ?>
<span class="sidebar-badge" title="Name und Anschrift für das Impressum fehlen noch">!</span>
<?php endif; ?>
<a href="/admin/legal.php" data-nav="/admin/legal.php" data-badge="/admin/legal.php"<?= $navOrder('/admin/legal.php') ?> class="sidebar-link<?= $isLegalActive ? ' active' : '' ?>" title="Impressum & Datenschutz">
<?= icon('lock') ?><span class="label">Impressum & Datenschutz</span><?= nav_badge_html($navBadges, '/admin/legal.php') ?>
</a>
<?php endif; ?>
<?php if ($canViewAudit): ?>
@ -435,7 +361,7 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => !i
<img src="/assets/images/lumipunkt.svg" alt="" width="30" height="30">
<span>
<span class="sidebar-points-label">Deine Lumipunkte</span>
<strong><?= e(number_format($sidebarPoints, 0, ',', '.')) ?></strong>
<strong data-live-points><?= e(number_format($sidebarPoints, 0, ',', '.')) ?></strong>
</span>
</a>
<?php endif; ?>
@ -446,11 +372,8 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => !i
Angemeldet als<br><strong><?= e($currentUser['display_name'] !== '' ? $currentUser['display_name'] : $currentUser['username']) ?></strong>
</div>
</div>
<a href="/patchnotes.php" class="sidebar-link<?= $currentScript === 'patchnotes.php' ? ' active' : '' ?>" title="Patchnotes: Änderungen an der Website">
<?= icon('list') ?><span class="label">Patchnotes</span>
<?php if ($patchnotesUnseen): ?>
<span class="sidebar-badge sidebar-badge-new" title="Neue Änderungen seit deinem letzten Besuch">Neu</span>
<?php endif; ?>
<a href="/patchnotes.php" data-badge="/patchnotes.php" class="sidebar-link<?= $currentScript === 'patchnotes.php' ? ' active' : '' ?>" title="Patchnotes: Änderungen an der Website">
<?= icon('list') ?><span class="label">Patchnotes</span><?= nav_badge_html($navBadges, '/patchnotes.php') ?>
</a>
<button type="button" class="sidebar-link sidebar-edit-toggle" id="sidebar-edit-toggle" title="Reihenfolge der Menüpunkte ändern">
<?= icon('move') ?><span class="label">Menü anpassen</span>

341
includes/live_updates.php Normal file
View file

@ -0,0 +1,341 @@
<?php
declare(strict_types=1);
/**
* Live-Aktualisierung im Mitgliederbereich: Jede offene Seite fragt alle 20 Sekunden bei live.php nach,
* solange sie zu sehen ist (assets/js/live.js).
*
* - nav_badges()/nav_points(): die Zahlen und Hinweise an den Menuepunkten und der eigene Punktestand -
* dieselben Werte, die includes/header.php beim Seitenaufbau zeigt, damit beide nie auseinanderlaufen.
* - live_fingerprint(): ein Fingerabdruck der Daten, die eine Seite zeigt. Aendert er sich, laedt die Seite
* neu, sobald gerade niemand tippt oder ein Fenster offen hat - sonst erscheint ein Hinweis. Nur die
* Seiten in live_fingerprint_parts(); Werkzeuge und Formulare (Karte, Gear-Planer, Bearbeiten) nie, die
* Raid-Seite hat ihre eigene Live-Aktualisierung (raids_live.php).
*/
/**
* Zahlen und Hinweise an den Menuepunkten: Menuepunkt (href) => Abzeichen.
*
* @param array<string, mixed> $user aktuelles, freigeschaltetes Konto
* @param string $currentScript Dateiname der Seite - auf der Galerie und den Patchnotes selbst fehlt ihr "Neu"
* @param array<string, mixed>|null $seen patchnotes_seen, gallery_seen_at, raids_seen_at (sonst aus der Datenbank)
* @return array<string, array{text: string, class: string, title: string}>
*/
function nav_badges(array $user, string $currentScript, ?array $seen = null): array
{
$userId = (int) $user['id'];
$badges = [];
$plain = static fn (int $count, string $title): array => ['text' => (string) $count, 'class' => 'sidebar-badge', 'title' => $title];
try {
if ($seen === null) {
$stmt = db()->prepare('SELECT patchnotes_seen, gallery_seen_at, raids_seen_at FROM users WHERE id = ?');
$stmt->execute([$userId]);
$seen = $stmt->fetch() ?: [];
}
// Neue Bilder anderer seit dem letzten Besuch der Galerie (wer nie dort war: die letzten 7 Tage)
if (user_has_permission('members.view') && $currentScript !== 'gallery.php') {
$stmt = db()->prepare(
"SELECT COUNT(*) FROM member_gallery g JOIN users u ON u.id = g.user_id
WHERE g.status = 'visible' AND g.is_background = 0 AND u.status = 'active' AND g.user_id <> ?
AND g.created_at > COALESCE(?, NOW() - INTERVAL 7 DAY)"
);
$stmt->execute([$userId, $seen['gallery_seen_at'] ?? null]);
$count = (int) $stmt->fetchColumn();
if ($count > 0) {
$badges['/gallery.php'] = ['text' => $count > 9 ? '9+' : (string) $count, 'class' => 'sidebar-badge sidebar-badge-new', 'title' => 'Neue Bilder seit deinem letzten Besuch'];
}
}
// Offene Lumishop-Antraege - nur fuer die, die sie bearbeiten
if (user_has_permission('shop.view') && user_has_permission('shop.manage')) {
$count = (int) db()->query("SELECT COUNT(*) FROM shop_orders WHERE status = 'pending'")->fetchColumn();
if ($count > 0) {
$badges['/shop.php'] = $plain($count, 'Offene Anträge');
}
}
// Anstehende Raids (zwischengespeichert, includes/raids_api.php) - golden, solange seit dem letzten
// Besuch der Raid-Seite einer gepostet wurde (wer nie dort war: die letzten 7 Tage)
if (user_has_permission('raids.view')) {
require_once __DIR__ . '/raids_api.php';
$upcoming = raids_nav_upcoming();
$seenTs = !empty($seen['raids_seen_at']) ? (int) strtotime((string) $seen['raids_seen_at']) : time() - 7 * 86400;
$new = count(array_filter($upcoming, static fn (int $raidId): bool => raid_posted_at($raidId) > $seenTs));
$total = count($upcoming);
if ($total > 0) {
$badges['/raids.php'] = [
'text' => $total > 9 ? '9+' : (string) $total,
'class' => 'sidebar-badge ' . ($new > 0 ? 'sidebar-badge-new' : 'sidebar-badge-count'),
'title' => $total . ($total === 1 ? ' anstehender Raid' : ' anstehende Raids')
. ($new > 0 ? ', davon ' . $new . ' neu seit deinem letzten Besuch' : ''),
];
}
}
// Neue Discord-Anmeldungen, die auf Freischaltung warten
if (user_has_permission('users.view')) {
$count = (int) db()->query("SELECT COUNT(*) FROM users WHERE status = 'pending'")->fetchColumn();
if ($count > 0) {
$badges['/admin/users.php'] = $plain($count, 'Warten auf Freischaltung');
}
}
if (user_has_permission('bugs.manage')) {
require_once __DIR__ . '/bugs.php';
$count = bug_open_count();
if ($count > 0) {
$badges['/bugs.php'] = $plain($count, 'Offene Fehlermeldungen');
}
}
if (user_has_permission('comments.moderate')) {
$count = moderation_pending_count();
if ($count > 0) {
$badges['/moderation.php'] = $plain($count, 'Warten auf Freigabe');
}
}
} catch (PDOException $e) {
// Dann eben ohne die Zahlen, die sich gerade nicht abfragen lassen
}
if ((user_has_permission('site.maintenance') || user_has_permission('site.announce')) && maintenance_active()) {
$badges['/admin/site.php'] = ['text' => '!', 'class' => 'sidebar-badge', 'title' => 'Wartungsmodus ist aktiv'];
}
if (user_has_permission('site.legal') && !legal_complete()) {
$badges['/admin/legal.php'] = ['text' => '!', 'class' => 'sidebar-badge', 'title' => 'Name und Anschrift für das Impressum fehlen noch'];
}
// "Neu" an den Patchnotes, solange die neueste nicht gelesen ist (nicht auf der Seite selbst)
if ($currentScript !== 'patchnotes.php' && patchnotes_unseen(isset($seen['patchnotes_seen']) ? (string) $seen['patchnotes_seen'] : null)) {
$badges['/patchnotes.php'] = ['text' => 'Neu', 'class' => 'sidebar-badge sidebar-badge-new', 'title' => 'Neue Änderungen seit deinem letzten Besuch'];
}
return $badges;
}
/** Abzeichen eines Menuepunkts als HTML (leer, wenn es keins gibt). */
function nav_badge_html(array $badges, string $href): string
{
$badge = $badges[$href] ?? null;
return $badge === null ? '' : '<span class="' . e($badge['class']) . '" title="' . e($badge['title']) . '">' . e($badge['text']) . '</span>';
}
/** Eigener Punktestand unten in der Seitenleiste (null ohne contributions.view). */
function nav_points(int $userId): ?int
{
if (!user_has_permission('contributions.view')) {
return null;
}
try {
$stmt = db()->prepare('SELECT COALESCE(SUM(points), 0) FROM contribution_entries WHERE user_id = ?');
$stmt->execute([$userId]);
return (int) $stmt->fetchColumn();
} catch (PDOException $e) {
return null;
}
}
/**
* Fingerabdruck der Daten, die die Seite $path zeigt, oder null, wenn sie sich nicht selbst aktualisiert
* (bzw. das Konto sie nicht sehen darf oder die Daten gerade nicht abrufbar sind).
*
* @param array<string, mixed> $params Query-Parameter der Seite (z.B. id)
*/
function live_fingerprint(string $path, array $params, int $userId): ?string
{
try {
$parts = live_fingerprint_parts($path, $params, $userId);
} catch (PDOException $e) {
return null;
}
return $parts === null ? null : substr(md5(implode('#', $parts)), 0, 16);
}
/**
* Je Seite ein paar Kennzahlen ihrer Tabellen: Anzahl, hoechste ID und eine Pruefsumme der angezeigten
* Spalten - so fallen neue, geaenderte und geloeschte Eintraege auf. Bewusst ohne "zuletzt aktiv"
* (users.last_seen_at), sonst laede die Mitgliederliste staendig neu.
*
* @param array<string, mixed> $params
* @return array<int, string>|null
*/
function live_fingerprint_parts(string $path, array $params, int $userId): ?array
{
$sum = static function (string $sql, array $args = []): string {
$stmt = db()->prepare($sql);
$stmt->execute($args);
return implode('|', array_map('strval', $stmt->fetch(PDO::FETCH_NUM) ?: []));
};
$crc = static fn (string $columns): string => "COALESCE(SUM(CRC32(CONCAT_WS('|', $columns))), 0)";
$raidIds = static function (): string {
require_once __DIR__ . '/raids_api.php';
return implode(',', raids_nav_upcoming());
};
switch ($path) {
case '/dashboard.php':
if (!user_has_permission('dashboard.view')) {
return null;
}
$parts = [
$sum('SELECT COUNT(*), COALESCE(SUM(points), 0) FROM contribution_entries WHERE user_id = ?', [$userId]),
$sum('SELECT COUNT(*), ' . $crc('id, status, admin_note, updated_at') . ' FROM bug_reports WHERE user_id = ?', [$userId]),
$sum("SELECT COUNT(*) FROM users WHERE status = 'active'"),
setting_get('announcement_id') . '|' . setting_get('announcement_until'),
];
if (user_has_permission('raids.view')) {
// Neue Raids, Termine und Anmeldungen (Fingerabdruck im Zwischenspeicher, includes/raids_api.php)
$parts[] = $raidIds() . '|' . (string) (raids_nav_cache()['sig'] ?? '');
}
return $parts;
case '/gallery.php':
if (!user_has_permission('members.view')) {
return null;
}
return [
$sum('SELECT COUNT(*), COALESCE(MAX(id), 0), ' . $crc('id, status, caption, show_on_home, sort_order') . ' FROM member_gallery WHERE is_background = 0'),
$sum("SELECT COUNT(*), COALESCE(MAX(id), 0) FROM gallery_comments WHERE status = 'visible'"),
$sum("SELECT COUNT(*), COALESCE(MAX(id), 0) FROM reactions WHERE content_type = 'picture'"),
];
case '/member_picture.php':
if (!user_has_permission('members.view')) {
return null;
}
$pictureId = (int) ($params['id'] ?? 0);
return [
$sum('SELECT COUNT(*), ' . $crc('id, status, caption') . ' FROM member_gallery WHERE id = ?', [$pictureId]),
$sum('SELECT COUNT(*), COALESCE(MAX(id), 0), ' . $crc('id, status, body') . ' FROM gallery_comments WHERE gallery_id = ?', [$pictureId]),
$sum(
"SELECT COUNT(*), COALESCE(MAX(r.id), 0) FROM reactions r
WHERE (r.content_type = 'picture' AND r.content_id = ?)
OR (r.content_type = 'comment' AND r.content_id IN (SELECT c.id FROM gallery_comments c WHERE c.gallery_id = ?))",
[$pictureId, $pictureId]
),
];
case '/member.php':
if (!user_has_permission('members.view')) {
return null;
}
$memberId = (int) ($params['id'] ?? 0);
return [
$sum('SELECT ' . $crc('status, username, display_name, class_name, classes, main_class, profile_bio, profile_background, avatar_filename, gallery_comments_enabled') . ' FROM users WHERE id = ?', [$memberId]),
$sum('SELECT COUNT(*), ' . $crc('id, name, class_name, level, note, portrait_filename, image_filename, is_main, sort_order') . ' FROM member_characters WHERE user_id = ?', [$memberId]),
$sum('SELECT COUNT(*), ' . $crc('id, status, caption, sort_order, is_background') . ' FROM member_gallery WHERE user_id = ?', [$memberId]),
$sum("SELECT COUNT(*), COALESCE(MAX(c.id), 0) FROM gallery_comments c JOIN member_gallery g ON g.id = c.gallery_id WHERE g.user_id = ? AND c.status = 'visible'", [$memberId]),
$sum("SELECT COUNT(*), COALESCE(MAX(r.id), 0) FROM reactions r JOIN member_gallery g ON g.id = r.content_id WHERE r.content_type = 'picture' AND g.user_id = ?", [$memberId]),
$sum('SELECT COUNT(*), COALESCE(SUM(role_id), 0) FROM user_roles WHERE user_id = ?', [$memberId]),
];
case '/members.php':
if (!user_has_permission('members.view')) {
return null;
}
return [
$sum("SELECT COUNT(*), " . $crc('id, username, display_name, avatar_filename, class_name, classes, main_class, discord_joined_at') . " FROM users WHERE status = 'active'"),
$sum('SELECT COUNT(*), ' . $crc('user_id, role_id') . ' FROM user_roles'),
$sum('SELECT COUNT(*), ' . $crc('id, user_id, name, class_name, level, is_main') . ' FROM member_characters'),
$sum('SELECT ' . $crc('id, name, display_name, roster_order, tag_bg, tag_color') . ' FROM roles'),
];
case '/calendar.php':
if (!user_has_permission('raids.view') && !user_has_permission('events.view')) {
return null;
}
$parts = [
$sum('SELECT COUNT(*), COALESCE(MAX(id), 0), ' . $crc('id, status, title, starts_at, ends_at, audience, updated_at') . ' FROM calendar_entries'),
$sum('SELECT COUNT(*), ' . $crc('entry_id, user_id') . ' FROM calendar_participants'),
];
if (user_has_permission('raids.view')) {
$parts[] = $raidIds();
}
return $parts;
case '/shop.php':
if (!user_has_permission('shop.view')) {
return null;
}
return [
$sum('SELECT COUNT(*), ' . $crc('id, category_id, name, description, price, stock_mode, stock, active, updated_at') . ' FROM shop_items'),
$sum('SELECT COUNT(*), ' . $crc('id, name, sort_order') . ' FROM shop_categories'),
$sum('SELECT COUNT(*), ' . $crc('id, status, decided_at, delivered_at') . ' FROM shop_orders WHERE user_id = ?', [$userId]),
$sum('SELECT COUNT(*), COALESCE(SUM(points), 0) FROM contribution_entries WHERE user_id = ?', [$userId]),
// Bestand, der am Lagerhaus haengt
$sum('SELECT COUNT(*), COALESCE(MAX(id), 0) FROM warehouse_movements'),
];
case '/shop_orders.php':
if (!user_has_permission('shop.manage')) {
return null;
}
return [
$sum('SELECT COUNT(*), COALESCE(MAX(id), 0), ' . $crc('id, status, quantity, decision_note, decided_at, delivered_at') . ' FROM shop_orders'),
];
case '/contributions.php':
if (!user_has_permission('contributions.view')) {
return null;
}
return [
$sum('SELECT COUNT(*), COALESCE(MAX(id), 0), COALESCE(SUM(points), 0) FROM contribution_entries'),
$sum('SELECT COUNT(*), COALESCE(MAX(id), 0), ' . $crc('id, category, title, note, awarded_at') . ' FROM contribution_awards'),
];
case '/warehouse.php':
if (!user_has_permission('warehouse.view')) {
return null;
}
return [
$sum('SELECT COUNT(*), COALESCE(MAX(id), 0), ' . $crc('id, item_id, direction, quantity, occurred_at, counterpart_name, note') . ' FROM warehouse_movements'),
$sum('SELECT COUNT(*), ' . $crc('id, name, category, icon') . ' FROM warehouse_items'),
];
case '/premades.php':
if (!user_has_permission('premades.view')) {
return null;
}
// Die Premades liegen beim Bot - kurze Wartezeit, antwortet er nicht, gilt: nichts Neues
require_once __DIR__ . '/raids_api.php';
try {
return [md5((string) json_encode(fetch_premades(3)))];
} catch (Throwable $e) {
return null;
}
case '/bugs.php':
if (!user_has_permission('bugs.manage')) {
return null;
}
return [
$sum('SELECT COUNT(*), COALESCE(MAX(id), 0), ' . $crc('id, status, admin_note, handled_by, updated_at') . ' FROM bug_reports'),
$sum('SELECT COUNT(*), COALESCE(MAX(id), 0) FROM bug_report_images'),
];
case '/moderation.php':
if (!user_has_permission('comments.moderate')) {
return null;
}
return [
$sum('SELECT COUNT(*), COALESCE(MAX(id), 0), ' . $crc('id, status, caption') . ' FROM member_gallery'),
$sum('SELECT COUNT(*), COALESCE(MAX(id), 0), ' . $crc('id, status') . ' FROM gallery_comments'),
$sum('SELECT COUNT(*), ' . $crc('id, status') . ' FROM calendar_entries'),
$sum('SELECT COUNT(*), COALESCE(MAX(id), 0) FROM content_reports'),
];
case '/admin/users.php':
if (!user_has_permission('users.view')) {
return null;
}
return [
$sum('SELECT COUNT(*), COALESCE(MAX(id), 0), ' . $crc('id, status, username, display_name, is_admin, last_login, deletion_scheduled_at, deleted_at') . ' FROM users'),
$sum('SELECT COUNT(*), ' . $crc('user_id, role_id') . ' FROM user_roles'),
];
case '/wiki.php':
if (!user_has_permission('wiki.view')) {
return null;
}
return [
$sum('SELECT COUNT(*), ' . $crc('id, parent_id, title, slug, is_wip, sort_order, updated_at') . ' FROM wiki_pages'),
];
default:
return null;
}
}

View file

@ -19,6 +19,17 @@ const PATCHNOTE_TYPES = [
];
const PATCHNOTES = [
[
'id' => '2026-09-24-i',
'date' => '2026-09-24',
'title' => 'Die Website aktualisiert sich von selbst',
'summary' => 'Kein ständiges Neuladen mehr - was sich tut, erscheint von allein.',
'changes' => [
['type' => 'neu', 'area' => 'Allgemein', 'text' => 'Die Zahlen im Menü (Raids, neue Bilder, Patchnotes …) und deine Lumipunkte aktualisieren sich alle paar Sekunden von selbst.'],
['type' => 'neu', 'area' => 'Allgemein', 'text' => 'Dashboard, Galerie, Kommentare, Profilseiten, Mitgliederliste, Kalender, Lumishop, Lumipunkte, Lagerhaus, Premades und Wiki laden neu, sobald es dort etwas Neues gibt - aber nie, während du tippst oder ein Fenster offen hast. Dann erscheint unten ein Hinweis mit „Aktualisieren“.'],
['type' => 'neu', 'area' => 'Verwaltung', 'text' => 'Auch Shop-Anträge, Fehlermeldungen, Moderation und die Benutzerverwaltung aktualisieren sich von selbst.', 'audience' => 'leitung'],
],
],
[
'id' => '2026-09-24-h',
'date' => '2026-09-24',

View file

@ -160,7 +160,7 @@ const RAIDS_NAV_CACHE_TTL = 300;
* Liest (ohne Argument) oder schreibt den Zwischenspeicher der Seitenleiste. Innerhalb eines Aufrufs
* gilt der zuletzt geschriebene Stand - setting_get() kennt nur den vom Anfang des Aufrufs.
*
* @param array{fetched_at: int, raids: array<int, string>}|null $value
* @param array{fetched_at: int, raids: array<int, string>, sig: string}|null $value
* @return array<string, mixed>|null
*/
function raids_nav_cache(?array $value = null): ?array
@ -183,23 +183,31 @@ function raids_nav_cache(?array $value = null): ?array
}
/**
* Merkt sich von den Raids der API die IDs der aktiven.
* Merkt sich von den Raids der API die IDs der aktiven - und einen Fingerabdruck von Terminen, Plaetzen
* und Anmeldungen, an dem das Dashboard live merkt, dass sich etwas getan hat (includes/live_updates.php).
*
* @param array<int, array<string, mixed>> $raids
* @return array<int, string>
*/
function raids_nav_store(array $raids): array
{
$list = [];
$active = [];
foreach ($raids as $raid) {
if (empty($raid['archived']) && empty($raid['archived_at'])) {
$list[] = (string) (int) ($raid['raid_id'] ?? 0);
$active[(string) (int) ($raid['raid_id'] ?? 0)] = $raid;
}
}
// Nach ID sortiert - "all" und "active" liefern die Raids nicht unbedingt in derselben Reihenfolge
ksort($active, SORT_STRING);
$list = array_map('strval', array_keys($active));
$sig = substr(md5((string) json_encode(array_map(static fn (array $raid): array => [
$raid['title'] ?? '', $raid['timestamp'] ?? 0, $raid['max_slots'] ?? 0, $raid['groups'] ?? '', $raid['signups'] ?? [],
], array_values($active)))), 0, 16);
// Die Live-Aktualisierung der Raid-Seite fragt oft - unveraendert und frisch nicht jedes Mal schreiben
$cached = raids_nav_cache();
if (!is_array($cached) || ($cached['raids'] ?? null) !== $list || time() - (int) ($cached['fetched_at'] ?? 0) >= 60) {
raids_nav_cache(['fetched_at' => time(), 'raids' => $list]);
if (!is_array($cached) || ($cached['raids'] ?? null) !== $list || ($cached['sig'] ?? '') !== $sig
|| time() - (int) ($cached['fetched_at'] ?? 0) >= 60) {
raids_nav_cache(['fetched_at' => time(), 'raids' => $list, 'sig' => $sig]);
}
return $list;
}
@ -217,7 +225,7 @@ function raids_nav_upcoming(): array
$list = is_array($cached['raids'] ?? null) ? $cached['raids'] : [];
if (time() - (int) ($cached['fetched_at'] ?? 0) >= RAIDS_NAV_CACHE_TTL) {
// Zeitpunkt vorher merken - sonst fragt bei einem Ausfall des Bots jeder Seitenaufruf erneut
raids_nav_cache(['fetched_at' => time(), 'raids' => $list]);
raids_nav_cache(['fetched_at' => time(), 'raids' => $list, 'sig' => (string) ($cached['sig'] ?? '')]);
try {
$data = raids_api_request('GET', '', ['status' => 'active'], null, 3);
if (($data['status'] ?? '') === 'success' && is_array($data['raids'] ?? null)) {
@ -416,10 +424,11 @@ function invite_premade(int $raidId, int $premadeId, int $group): int
* JSON-Antwort zurueck. Analog zu raids_api_request(), nur mit eigener Basis-URL.
*
* @param array<string, mixed>|null $jsonBody
* @param int $timeout Sekunden bis zum Abbruch (die Live-Aktualisierung wartet kuerzer, includes/live_updates.php).
* @return array<string, mixed>
* @throws RuntimeException
*/
function premades_api_request(string $method, string $path = '', ?array $jsonBody = null): array
function premades_api_request(string $method, string $path = '', ?array $jsonBody = null, int $timeout = 10): array
{
if (!function_exists('curl_init')) {
throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.');
@ -436,7 +445,7 @@ function premades_api_request(string $method, string $path = '', ?array $jsonBod
$options = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_TIMEOUT => 10,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_SSL_VERIFYPEER => true,
];
@ -474,9 +483,9 @@ function premades_api_request(string $method, string $path = '', ?array $jsonBod
* @return array<int, array<string, mixed>>
* @throws RuntimeException
*/
function fetch_premades(): array
function fetch_premades(int $timeout = 10): array
{
$data = premades_api_request('GET');
$data = premades_api_request('GET', '', null, $timeout);
if (($data['status'] ?? '') !== 'success' || !is_array($data['premades'] ?? null)) {
throw new RuntimeException('Unerwartetes Antwortformat der Premades-API.');

34
live.php Normal file
View file

@ -0,0 +1,34 @@
<?php
/**
* Live-Aktualisierung im Mitgliederbereich (assets/js/live.js fragt alle 20 Sekunden nach, solange die
* Seite zu sehen ist):
*
* GET /live.php?path=/gallery.php&q=<Query der Seite, z.B. id=5>
*
* Antwort: die Zahlen an den Menuepunkten, der eigene Punktestand und der Fingerabdruck der Seite
* (null = die Seite aktualisiert sich nicht selbst) - siehe includes/live_updates.php.
*/
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/live_updates.php';
// Wird per fetch() aufgerufen - Fehler deshalb als JSON statt Weiterleitung auf die Login-Seite.
$user = current_user();
if (!$user || $user['status'] !== 'active') {
http_response_code(401);
json_response(false, 'Bitte neu anmelden.');
}
// Sitzung gleich freigeben, damit ein gleichzeitiger Seitenaufruf derselben Person nicht wartet
session_write_close();
$path = (string) ($_GET['path'] ?? '');
if (!preg_match('#^(/[\w-]+)+\.php$#', $path)) {
$path = '';
}
parse_str((string) ($_GET['q'] ?? ''), $params);
header('Cache-Control: no-store');
json_response(true, '', [
'badges' => (object) nav_badges($user, basename($path)),
'points' => nav_points((int) $user['id']),
'fp' => $path !== '' ? live_fingerprint($path, $params, (int) $user['id']) : null,
]);