LuminaWebsite/includes/live_updates.php
Maaxxs 592269d300 Permissions per person: grant single permissions to users in addition to their groups
In the user form (admin/user_form.php) a new section "Einzelne Berechtigungen" lists all
permissions, with the group-assign rights (roles.assign.<ID>) shown by group name as in the role
form. It opens by itself when the user already has some. A shield marks what the user already
gets through one of the ticked groups; the tooltip says who granted a permission and when.

- New table user_permissions (user, permission, granted_by, created_at; schema 52, also in
  sql/schema.sql). user_has_permission() now resolves through user_permission_keys() (groups UNION
  direct permissions, falls back to groups only while the table is missing), and
  discord_ids_with_permission() and the raids.manage recipients in bot_api.php include direct
  permissions too.
- New core permission users.permissions: only with it can someone grant or revoke direct
  permissions, and only ones they have themselves (current_user_permission_ids()); others are
  greyed out and ignored on the server even if submitted. Your own direct permissions can only be
  changed by someone else (except developers). Without the right the section is a read-only list.
  On update, groups with roles.manage get users.permissions.
- Saving applies only the changes, so the remaining entries keep who granted them and when.
  Grants and revokes go into the audit log ("Einzelrechte erteilt/entzogen/jetzt").
- User list: "+N Einzelrechte" badge next to the groups (title lists them), searchable; the live
  fingerprint of the page includes user_permissions.
- Data export gets a section "einzelrechte", account deletion removes them, and the privacy
  policy mentions both. Patch notes, README and the roles page intro updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 02:20:58 +02:00

354 lines
18 KiB
PHP

<?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')) {
// Wartet auf Freigabe und gemeldet, aber noch sichtbar - wie der Reiter "Freigabe"
[$pending, $reported] = moderation_open_counts();
if ($pending + $reported > 0) {
$badges['/moderation.php'] = $plain($pending + $reported, implode(', ', array_filter([
$pending > 0 ? $pending . ' ' . ($pending === 1 ? 'wartet' : 'warten') . ' auf Freigabe' : '',
$reported > 0 ? $reported . ' gemeldet' : '',
])));
}
}
// Offene (nicht archivierte) Reports aus dem Discord-Bot - zwischengespeichert, includes/raids_api.php
if (user_has_permission('reports.view')) {
require_once __DIR__ . '/raids_api.php';
$count = reports_nav_open();
if ($count > 0) {
$badges['/reports.php'] = $plain($count, $count === 1 ? '1 offener Report' : $count . ' offene Reports');
}
}
} 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'),
$sum('SELECT COUNT(*), ' . $crc('user_id, permission_id') . ' FROM user_permissions'),
];
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;
}
}