diff --git a/.htaccess b/.htaccess index 4b632b9..a2583e2 100644 --- a/.htaccess +++ b/.htaccess @@ -20,3 +20,18 @@ AddDefaultCharset UTF-8 # includes/ und sql/ haben jeweils eine eigene .htaccess, die den Zugriff # darauf sperrt (siehe includes/.htaccess und sql/.htaccess). + +# Eigene Fehlerseite statt der weissen Standardseite des Servers (auch fuer gesperrte Ordner). +ErrorDocument 404 /404.php +ErrorDocument 403 /404.php + +# Nicht vorhandene Seiten (z.B. /admin.php) direkt auf die Fehlerseite - sonst antwortet bei +# manchen Hostern PHP-FPM selbst mit "File not found." und die ErrorDocument-Regel greift nicht. +# Fehlende Dateien unter assets/ bekommen weiter die schlanke Standardantwort. + + RewriteEngine On + RewriteCond %{REQUEST_URI} !^/assets/ + RewriteCond %{REQUEST_FILENAME} !-f + RewriteCond %{REQUEST_FILENAME} !-d + RewriteRule ^ /404.php [L] + diff --git a/404.php b/404.php new file mode 100644 index 0000000..bde82ea --- /dev/null +++ b/404.php @@ -0,0 +1,8 @@ + 0) { + $conditions[] = 'a.user_id = ?'; + $params[] = $actorId; +} +if ($from !== '') { + $conditions[] = 'a.created_at >= ?'; + $params[] = $from . ' 00:00:00'; +} +if ($to !== '') { + $conditions[] = 'a.created_at <= ?'; + $params[] = $to . ' 23:59:59'; +} +$where = $conditions ? 'WHERE ' . implode(' AND ', $conditions) : ''; + +$countStmt = db()->prepare("SELECT COUNT(*) FROM audit_log a $where"); +$countStmt->execute($params); +$total = (int) $countStmt->fetchColumn(); + +$perPage = 50; +$pageCount = max(1, (int) ceil($total / $perPage)); +$page = min($pageCount, max(1, (int) ($_GET['page'] ?? 1))); +$stmt = db()->prepare( + "SELECT a.*, u.discord_id FROM audit_log a LEFT JOIN users u ON u.id = a.user_id + $where ORDER BY a.created_at DESC, a.id DESC LIMIT $perPage OFFSET " . (($page - 1) * $perPage) +); +$stmt->execute($params); +$entries = $stmt->fetchAll(); + +// Anzahl je Bereich (fuer die Chips) und der Name der gefilterten Person +$areaCounts = db()->query('SELECT area, COUNT(*) FROM audit_log GROUP BY area')->fetchAll(PDO::FETCH_KEY_PAIR); +$actorName = ''; +if ($actorId > 0) { + $nameStmt = db()->prepare("SELECT actor_name FROM audit_log WHERE user_id = ? AND actor_name <> '' ORDER BY id DESC LIMIT 1"); + $nameStmt->execute([$actorId]); + $actorName = (string) ($nameStmt->fetchColumn() ?: 'Konto #' . $actorId); +} +$filtered = $query !== '' || $area !== '' || $tone !== '' || $actorId > 0 || $from !== '' || $to !== ''; + +/** Link mit den aktuellen Filtern, einzelne Werte ueberschrieben ('' = weglassen). */ +$auditUrl = static function (array $overrides = []) use ($query, $area, $tone, $actorId, $from, $to): string { + $params = array_merge(['q' => $query, 'area' => $area, 'tone' => $tone, 'user' => $actorId ?: '', 'from' => $from, 'to' => $to], $overrides); + $params = array_filter($params, static fn ($value): bool => $value !== '' && $value !== null && $value !== 0); + return '/admin/audit.php?' . ($params ? http_build_query($params) . '&' : ''); +}; + +$pageTitle = 'Audit-Log'; +$containerWide = true; +include __DIR__ . '/../includes/header.php'; +?> +
+

Audit-Log

+

+ Alle Verwaltungsaktionen und Sicherheitsereignisse der Website - dieselben Einträge wie im + Discord-Log, aber dauerhaft gespeichert und hier nicht lösch- oder änderbar. +

+ +
+ 0): ?> + + +
+ + + +
+
+ + $label): ?> + + + +
+
+
+ Wichtigkeit +
+ + + +
+ 0): ?> + Person: + +
+ + + · Filter zurücksetzen + +
+
+ + +

+ +
    + + +
  1. +
    + + +
    + +
    + $value): ?> +
    + +
    + +
    + + · + + + + + + + · IP + +
    +
  2. + +
+
+ + Einträge – von + + +
+ +
+ diff --git a/admin/settings_action.php b/admin/settings_action.php index 728701b..a9baebd 100644 --- a/admin/settings_action.php +++ b/admin/settings_action.php @@ -23,6 +23,7 @@ setting_set($key, isset($_POST['value']) ? '1' : '0'); $settingLabels = [ 'discord_unlink_allowed' => 'Mitglieder dürfen ihre Discord-Verknüpfung lösen', 'contributions_history_public' => 'Lumipunkte-Verlauf für alle sichtbar', + 'moderation_all' => 'Alle neuen Bilder und Kommentare manuell freigeben', ]; admin_log('⚙️ Einstellung geändert', [ 'Einstellung' => $settingLabels[$key] ?? $key, diff --git a/admin/user_security.php b/admin/user_security.php new file mode 100644 index 0000000..5bdc4af --- /dev/null +++ b/admin/user_security.php @@ -0,0 +1,53 @@ +prepare('SELECT id, is_admin, discord_id, status FROM users WHERE id = ?'); +$stmt->execute([$id]); +$target = $stmt->fetch(); +if (!$target) { + set_flash('error', 'Diesen Benutzer gibt es nicht (mehr).'); + redirect('/admin/users.php'); +} +// Gleiche Schutzregeln wie beim Bearbeiten/Loeschen +if (is_developer($target) && !is_developer($currentUser)) { + set_flash('error', 'Das Konto des Entwicklers kann nur ein Entwickler sperren.'); + redirect('/admin/users.php'); +} +if ((int) $target['is_admin'] === 1 && !user_has_permission('users.admin')) { + set_flash('error', 'Administratoren kann nur sperren, wer die Berechtigung users.admin hat.'); + redirect('/admin/users.php'); +} + +$reason = mb_substr(trim((string) ($_POST['reason'] ?? '')), 0, 200); + +if ($action === 'logout') { + security_end_sessions($id); + security_log('🚪 Abmeldung erzwungen', ['Konto' => admin_log_user($id), 'Grund' => $reason], 'warning'); + set_flash('success', 'Alle Sitzungen des Kontos wurden beendet.'); +} elseif ($action === 'lock') { + security_lock_account($id, $reason !== '' ? $reason : 'Manuell über die Benutzerverwaltung'); + set_flash('success', 'Das Konto ist gesperrt und überall abgemeldet. Entsperren: Benutzer bearbeiten, Status „Aktiv“.'); +} else { + set_flash('error', 'Unbekannte Aktion.'); +} +redirect('/admin/users.php'); diff --git a/admin/users.php b/admin/users.php index 580d846..9d149fd 100644 --- a/admin/users.php +++ b/admin/users.php @@ -184,6 +184,18 @@ include __DIR__ . '/../includes/header.php'; + + ['log-out', 'Abmelden erzwingen (alle Sitzungen beenden)', 'Alle Sitzungen dieses Kontos beenden?'], 'lock' => ['lock', 'Sperren und überall abmelden', 'Dieses Konto sperren und überall abmelden?']] as $secAction => [$secIcon, $secTitle, $secQuestion]): ?> +
); if (r === null) return false; this.reason.value = r; return true;"> + + + + + +
+ +
diff --git a/assets/css/style.css b/assets/css/style.css index f01baef..3a89788 100644 --- a/assets/css/style.css +++ b/assets/css/style.css @@ -4959,3 +4959,206 @@ input[type="file"]::file-selector-button { /* Bestand: Suche und Kategorie-Chips */ .warehouse-filters.list-toolbar { margin: 1rem 0; } + +/* ---- Kommentare unter Galeriebildern ---- */ +.gallery-item { position: relative; } +.gallery-comment-badge { + position: absolute; + top: 0.45rem; + right: 0.45rem; + display: inline-flex; + align-items: center; + gap: 0.25rem; + padding: 0.2rem 0.5rem; + border-radius: 999px; + background: rgba(0, 0, 0, 0.6); + color: #fff; + font-size: 0.78rem; + backdrop-filter: blur(4px); + opacity: 0; + transition: opacity 0.15s ease; +} +.gallery-comment-badge .icon { width: 14px; height: 14px; } +.gallery-comment-badge.has-comments, +.gallery-item:hover .gallery-comment-badge, +.gallery-comment-badge:focus-visible { opacity: 1; } +.gallery-comment-badge:hover { color: var(--gold); text-decoration: none; } +@media (hover: none) { .gallery-comment-badge { opacity: 1; } } + +.lightbox-comments { + display: inline-block; + margin-left: 0.75rem; + padding: 0.2rem 0.7rem; + border-radius: 999px; + background: rgba(201, 162, 39, 0.2); + color: var(--gold); + font-size: 0.9rem; +} + +.picture-view-head { display: flex; align-items: center; justify-content: space-between; gap: 1rem; margin-bottom: 1rem; } +.picture-owner { display: inline-flex; align-items: center; gap: 0.6rem; color: var(--text); } +.picture-owner:hover { text-decoration: none; color: var(--gold); } +.picture-view-image { position: relative; margin: 0; text-align: center; } +.picture-view-image img { max-width: 100%; max-height: 75vh; border-radius: 10px; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.45); } +.picture-view-image figcaption { margin-top: 0.6rem; color: var(--text-muted); } +.picture-nav { + position: absolute; + top: 50%; + transform: translateY(-50%); + display: grid; + place-items: center; + width: 44px; + height: 44px; + border-radius: 50%; + background: rgba(0, 0, 0, 0.55); + color: #fff; + font-size: 1.8rem; + line-height: 1; + z-index: 1; +} +.picture-nav:hover { background: rgba(201, 162, 39, 0.8); color: #111; text-decoration: none; } +.picture-nav-prev { left: 0.5rem; } +.picture-nav-next { right: 0.5rem; } + +.picture-comments h2 { display: flex; align-items: center; gap: 0.5rem; } +.comment-list { list-style: none; margin: 0 0 1rem; padding: 0; display: flex; flex-direction: column; gap: 0.9rem; } +.comment { display: flex; gap: 0.75rem; align-items: flex-start; } +.comment-body { + flex: 1; + min-width: 0; + padding: 0.55rem 0.85rem; + border-radius: 4px 12px 12px 12px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid var(--border); +} +.comment-head { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; font-size: 0.9rem; } +.comment-head time { font-size: 0.8rem; } +.comment-delete { margin-left: auto; } +.comment-delete .icon-button { width: 28px; height: 28px; } +.comment-body p { margin: 0.3rem 0 0; overflow-wrap: anywhere; } + +.comment-form { display: flex; gap: 0.75rem; align-items: flex-start; } +.comment-form-body { flex: 1; min-width: 0; } +.comment-form textarea { width: 100%; border-radius: 12px; resize: vertical; min-height: 3rem; } +.comment-form-actions { display: flex; justify-content: space-between; align-items: center; gap: 0.75rem; margin-top: 0.4rem; flex-wrap: wrap; } + +/* ---- Audit-Log ---- */ +.audit-search-row { display: flex; flex-wrap: wrap; gap: 0.6rem; align-items: center; } +.audit-search-row .search-field { flex: 1 1 280px; } +.audit-date { display: inline-flex; align-items: center; gap: 0.4rem; margin: 0; font-size: 0.85rem; color: var(--text-muted); font-weight: 400; } +.audit-date input { width: auto; padding: 0.45rem 0.6rem; border-radius: 10px; background: var(--bg-panel-alt); color: var(--text); border: 1px solid var(--border); color-scheme: dark; } +.audit-filter-pill { + display: inline-flex; + align-items: center; + gap: 0.35rem; + padding: 0.25rem 0.7rem; + border-radius: 999px; + background: rgba(201, 162, 39, 0.16); + border: 1px solid rgba(201, 162, 39, 0.5); + font-size: 0.85rem; +} +.audit-filter-pill .icon { width: 14px; height: 14px; } +.audit-filter-pill:hover { text-decoration: none; background: rgba(201, 162, 39, 0.25); } + +.audit-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 0.5rem; } +.audit-entry { + padding: 0.7rem 0.95rem; + border: 1px solid var(--border); + border-left: 4px solid #5865f2; + border-radius: 10px; + background: rgba(255, 255, 255, 0.025); +} +.audit-success { border-left-color: #3ba55d; } +.audit-warning { border-left-color: #f0b232; } +.audit-danger { border-left-color: #ed4245; background: rgba(237, 66, 69, 0.06); } +.audit-entry-head { display: flex; align-items: center; justify-content: space-between; gap: 0.75rem; flex-wrap: wrap; } +.audit-area { font-size: 0.72rem; } +.audit-details { display: flex; flex-wrap: wrap; gap: 0.3rem 1.2rem; margin: 0.4rem 0 0; font-size: 0.88rem; } +.audit-details div { display: flex; gap: 0.35rem; min-width: 0; } +.audit-details dt { color: var(--text-muted); } +.audit-details dt::after { content: ':'; } +.audit-details dd { margin: 0; overflow-wrap: anywhere; } +.audit-meta { margin-top: 0.4rem; font-size: 0.8rem; } + +/* ---- 404-Seite ---- */ +.not-found { max-width: 640px; margin: 3rem auto; text-align: center; padding: 2.5rem 1.5rem; } +.not-found-code { + font-size: clamp(4.5rem, 16vw, 8rem); + font-weight: 800; + line-height: 1; + letter-spacing: 0.05em; + background: linear-gradient(135deg, #f3d77a, var(--gold) 45%, #7a5c12); + -webkit-background-clip: text; + background-clip: text; + color: transparent; + text-shadow: 0 0 40px rgba(201, 162, 39, 0.25); +} +.not-found h1 { margin: 0.8rem 0 0.5rem; font-size: 1.4rem; } +.not-found code { overflow-wrap: anywhere; } +.not-found-actions { justify-content: center; margin-top: 1.5rem; } + +/* ---- Moderation: Freigabe, Melden ---- */ +.pending-badge { + position: absolute; + top: 0.45rem; + left: 0.45rem; + z-index: 1; + padding: 0.15rem 0.55rem; + border-radius: 999px; + background: rgba(240, 178, 50, 0.92); + color: #1a1a1a; + font-size: 0.72rem; + font-weight: 700; +} +.gallery-item.is-pending img { opacity: 0.55; filter: grayscale(0.4); } +.pending-badge-inline { + padding: 0.05rem 0.5rem; + border-radius: 999px; + background: rgba(240, 178, 50, 0.18); + color: #f0b232; + font-size: 0.75rem; + font-weight: 600; +} +.comment.is-pending .comment-body { border-style: dashed; border-color: rgba(240, 178, 50, 0.5); } +.pending-notice { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.75rem; + flex-wrap: wrap; + margin-bottom: 1rem; + padding: 0.6rem 0.9rem; + border-radius: 10px; + background: rgba(240, 178, 50, 0.1); + border: 1px solid rgba(240, 178, 50, 0.4); +} +.picture-view-tools { display: flex; align-items: center; gap: 0.6rem; } +.report-button { opacity: 0.7; } +.report-button:hover { opacity: 1; color: #f0b232; } +.report-done { display: inline-flex; align-items: center; gap: 0.25rem; font-size: 0.78rem; color: var(--text-muted); } +.report-done .icon { width: 14px; height: 14px; } +.comment-report .icon-button { width: 28px; height: 28px; } +.comment-head .comment-report { margin-left: auto; } +.comment-head .comment-report + .comment-delete { margin-left: 0; } + +.moderation-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 0.9rem; margin-bottom: 0.9rem; } +.moderation-card { + display: flex; + flex-direction: column; + border: 1px solid var(--border); + border-radius: 12px; + background: rgba(255, 255, 255, 0.025); + overflow: hidden; +} +.moderation-grid .moderation-thumb img { display: block; width: 100%; aspect-ratio: 16 / 10; object-fit: cover; } +.moderation-comment { flex-direction: row; align-items: flex-start; gap: 0.8rem; padding: 0.7rem; margin-bottom: 0.7rem; } +.moderation-thumb-small img { width: 72px; height: 72px; object-fit: cover; border-radius: 8px; display: block; } +.moderation-body { padding: 0.7rem 0.9rem; flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 0.4rem; } +.moderation-comment .moderation-body { padding: 0; } +.moderation-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; font-size: 0.88rem; } +.moderation-body p { margin: 0; overflow-wrap: anywhere; } +.moderation-text { padding: 0.45rem 0.7rem; border-radius: 8px; background: rgba(255, 255, 255, 0.04); } +.moderation-reason { font-size: 0.82rem; color: #f0b232; } +.moderation-reports { list-style: none; margin: 0; padding: 0; font-size: 0.82rem; display: flex; flex-direction: column; gap: 0.2rem; } +.moderation-reports .icon { width: 13px; height: 13px; color: #ed4245; vertical-align: -2px; } +.moderation-actions { display: flex; flex-wrap: wrap; gap: 0.4rem; margin-top: 0.2rem; } diff --git a/assets/js/lightbox.js b/assets/js/lightbox.js index e7613d4..de2cb5a 100644 --- a/assets/js/lightbox.js +++ b/assets/js/lightbox.js @@ -30,6 +30,15 @@ img.src = link.href; img.alt = link.dataset.caption || ''; caption.textContent = link.dataset.caption || ''; + // Galeriebilder mit Kommentaren: Link zur Bildseite + if (link.dataset.commentsUrl) { + var count = parseInt(link.dataset.commentsCount || '0', 10); + var comments = document.createElement('a'); + comments.className = 'lightbox-comments'; + comments.href = link.dataset.commentsUrl; + comments.textContent = count > 0 ? '💬 ' + count + (count === 1 ? ' Kommentar' : ' Kommentare') : '💬 Kommentieren'; + caption.appendChild(comments); + } overlay.querySelector('.lightbox-prev').hidden = group.length < 2; overlay.querySelector('.lightbox-next').hidden = group.length < 2; } diff --git a/bug_action.php b/bug_action.php index 7123e9d..0786108 100644 --- a/bug_action.php +++ b/bug_action.php @@ -13,7 +13,11 @@ $user = current_user(); $pdo = db(); if ($action === 'create') { - // Jedes Mitglied mit Dashboard-Zugang darf Fehler melden. + // Jedes Mitglied mit Dashboard-Zugang darf Fehler melden - aber nicht im Sekundentakt. + if (!security_throttle('bug')) { + set_flash('error', 'Du hast in der letzten Stunde schon mehrere Fehler gemeldet. Bitte warte etwas, bevor du den nächsten meldest.'); + redirect('/dashboard.php#fehler-melden'); + } $title = trim((string) ($_POST['title'] ?? '')); $area = (string) ($_POST['area'] ?? ''); $description = trim((string) ($_POST['description'] ?? '')); diff --git a/gallery_comment_action.php b/gallery_comment_action.php new file mode 100644 index 0000000..da779a4 --- /dev/null +++ b/gallery_comment_action.php @@ -0,0 +1,106 @@ +prepare( + 'SELECT g.id, g.user_id, g.status AS picture_status, u.status, u.gallery_comments_enabled FROM member_gallery g JOIN users u ON u.id = g.user_id WHERE g.id = ?' + ); + $stmt->execute([$pictureId]); + $picture = $stmt->fetch(); + $canSeePicture = $picture && ($picture['picture_status'] === 'visible' + || (int) $picture['user_id'] === (int) $me['id'] || moderation_can()); + if (!$picture || $picture['status'] !== 'active' || !$canSeePicture) { + set_flash('error', 'Dieses Bild gibt es nicht (mehr).'); + redirect('/members.php'); + } + if (empty($picture['gallery_comments_enabled'])) { + set_flash('error', 'Unter diesen Bildern sind Kommentare abgeschaltet.'); + redirect($back); + } + + $body = trim(str_replace("\r\n", "\n", (string) ($_POST['body'] ?? ''))); + // Mehr als zwei Leerzeilen am Stueck sind nur Platzverschwendung + $body = (string) preg_replace("/\n{3,}/", "\n\n", $body); + if ($body === '') { + set_flash('error', 'Der Kommentar ist leer.'); + redirect($back); + } + if (mb_strlen($body) > GALLERY_COMMENT_MAX) { + set_flash('error', 'Der Kommentar ist zu lang (höchstens ' . GALLERY_COMMENT_MAX . ' Zeichen).'); + redirect($back); + } + // Derselbe Text kurz hintereinander = doppelt abgeschickt oder Spam + $dupe = $pdo->prepare('SELECT COUNT(*) FROM gallery_comments WHERE author_id = ? AND body = ? AND created_at > ?'); + $dupe->execute([(int) $me['id'], $body, date('Y-m-d H:i:s', time() - 600)]); + if ((int) $dupe->fetchColumn() > 0) { + set_flash('error', 'Diesen Kommentar hast du gerade schon geschrieben.'); + redirect($back); + } + if (!security_throttle('comment')) { + set_flash('error', 'Du hast in den letzten Minuten schon viele Kommentare geschrieben. Bitte warte kurz.'); + redirect($back); + } + + [$status, $moderationNote] = moderation_initial_status('comment', $body); + $pdo->prepare('INSERT INTO gallery_comments (gallery_id, author_id, body, status, moderation_note) VALUES (?, ?, ?, ?, ?)') + ->execute([$pictureId, (int) $me['id'], $body, $status, $moderationNote]); + if ($status === 'pending') { + set_flash('success', 'Kommentar gespeichert. Für alle sichtbar nach einer kurzen Freigabe durch die Moderation (' + . mb_strtolower((string) $moderationNote) . ').'); + } + redirect('/member_picture.php?id=' . $pictureId . '#kommentar-' . (int) $pdo->lastInsertId()); +} + +if ($action === 'delete') { + $commentId = (int) ($_POST['comment_id'] ?? 0); + $stmt = $pdo->prepare( + 'SELECT c.id, c.author_id, c.body, c.gallery_id, g.user_id AS owner_id + FROM gallery_comments c JOIN member_gallery g ON g.id = c.gallery_id WHERE c.id = ?' + ); + $stmt->execute([$commentId]); + $comment = $stmt->fetch(); + if (!$comment) { + set_flash('error', 'Diesen Kommentar gibt es nicht (mehr).'); + redirect('/members.php'); + } + $back = '/member_picture.php?id=' . (int) $comment['gallery_id'] . '#kommentare'; + if (!gallery_comment_can_delete($comment, (int) $comment['owner_id'])) { + set_flash('error', 'Diesen Kommentar darfst du nicht löschen.'); + redirect($back); + } + + $pdo->prepare('DELETE FROM gallery_comments WHERE id = ?')->execute([$commentId]); + moderation_clear_reports('comment', $commentId); + // Loescht die Moderation einen fremden Kommentar auf einem fremden Bild -> ins Log + $isAuthor = (int) $comment['author_id'] === (int) $me['id']; + $isOwner = (int) $comment['owner_id'] === (int) $me['id']; + if (!$isAuthor && !$isOwner) { + admin_log('💬 Kommentar gelöscht (Moderation)', [ + 'Verfasser' => admin_log_user((int) $comment['author_id']), + 'Unter Bild von' => admin_log_user((int) $comment['owner_id']), + 'Text' => mb_strimwidth((string) $comment['body'], 0, 300, '…'), + ], 'warning', 'members'); + } + set_flash('success', 'Kommentar gelöscht.'); + redirect($back); +} + +set_flash('error', 'Unbekannte Aktion.'); +redirect('/members.php'); diff --git a/includes/admin_log.php b/includes/admin_log.php index 8e29f66..c4ab6f3 100644 --- a/includes/admin_log.php +++ b/includes/admin_log.php @@ -27,12 +27,21 @@ const ADMIN_LOG_COLORS = [ * @param string $title Kurzbeschreibung mit Emoji, z.B. "👤 Benutzer bearbeitet" * @param array $fields Details als Name => Wert (leere Werte werden weggelassen) * @param string $tone info | success | warning | danger + * @param string|null $area Bereich im Audit-Log (Standard: aus dem Skriptnamen, siehe AUDIT_AREAS) + * @param array|null $actor Wer es war, falls nicht das angemeldete Konto ([] = niemand angemeldet) */ -function admin_log(string $title, array $fields = [], string $tone = 'info'): void +function admin_log(string $title, array $fields = [], string $tone = 'info', ?string $area = null, ?array $actor = null): void { static $registered = false; - $user = current_user(); + // Dauerhaft in der Datenbank (Audit-Log) - auch wenn der Bot gerade nicht erreichbar ist. + audit_store($title, $fields, $tone, $area, $actor); + // Viele Loeschungen in kurzer Zeit -> Notbremse (siehe includes/security.php) + if ($tone === 'danger' && $area !== 'security') { + security_note_destructive(); + } + + $user = $actor ?? current_user(); $actor = 'Unbekannt'; if ($user) { $actor = $user['display_name'] !== '' ? $user['display_name'] : $user['username']; diff --git a/includes/auth.php b/includes/auth.php index b72a091..1c56619 100644 --- a/includes/auth.php +++ b/includes/auth.php @@ -19,7 +19,7 @@ function current_user(): ?array $stmt = db()->prepare( 'SELECT id, username, display_name, class_name, status, must_change_password, password_login, discord_id, discord_username, - avatar_filename, avatar_sync, tour_completed_at, is_admin + avatar_filename, avatar_sync, tour_completed_at, is_admin, session_epoch FROM users WHERE id = ?' ); $stmt->execute([$_SESSION['user_id']]); @@ -32,6 +32,12 @@ function current_user(): ?array return null; } + // Sitzungen beendet (gesperrt, "Abmelden erzwingen" oder Notbremse): Zaehler passt nicht mehr. + if ((int) ($_SESSION['session_epoch'] ?? 0) !== (int) $row['session_epoch']) { + auth_force_logout('Du wurdest abgemeldet. Bitte melde dich erneut an.'); + return null; + } + // Mitgliedschaft und Rollen live mit Discord abgleichen (hoechstens alle paar Minuten). $check = discord_live_check((int) $row['id']); $viaDiscord = ($_SESSION['login_method'] ?? '') === 'discord'; @@ -63,6 +69,9 @@ function auth_login_session(int $userId, string $method): void session_regenerate_id(true); $_SESSION['user_id'] = $userId; $_SESSION['login_method'] = $method; + $epoch = db()->prepare('SELECT session_epoch FROM users WHERE id = ?'); + $epoch->execute([$userId]); + $_SESSION['session_epoch'] = (int) $epoch->fetchColumn(); db()->prepare('UPDATE users SET last_login = NOW() WHERE id = ?')->execute([$userId]); } @@ -97,11 +106,18 @@ function require_login(): void */ function attempt_login(string $username, string $password): string { + // Bremse nach Fehlversuchen - pro IP, nicht pro Konto (siehe includes/security.php) + $blocked = login_throttle_check($username); + if ($blocked !== '') { + return $blocked; + } + $stmt = db()->prepare('SELECT id, password_hash, status, password_login FROM users WHERE username = ?'); $stmt->execute([$username]); $row = $stmt->fetch(); if (!$row || !password_verify($password, $row['password_hash'])) { + login_throttle_fail($username); return 'Login fehlgeschlagen. Bitte Zugangsdaten prüfen.'; } if ($row['status'] === 'disabled') { diff --git a/includes/bootstrap.php b/includes/bootstrap.php index b4572d9..55efb9c 100644 --- a/includes/bootstrap.php +++ b/includes/bootstrap.php @@ -32,5 +32,10 @@ require_once __DIR__ . '/permissions.php'; require_once __DIR__ . '/schema.php'; require_once __DIR__ . '/settings.php'; require_once __DIR__ . '/admin_log.php'; +require_once __DIR__ . '/security.php'; +require_once __DIR__ . '/moderation.php'; ensure_schema(); + +// Tempolimit fuer abgeschickte Formulare (Spam-/Missbrauchsschutz, siehe includes/security.php) +security_guard_post(); diff --git a/includes/forbidden.php b/includes/forbidden.php deleted file mode 100644 index 97d08bf..0000000 --- a/includes/forbidden.php +++ /dev/null @@ -1,10 +0,0 @@ - -
-

Zugriff verweigert

-

Du hast nicht die nötige Berechtigung, um diese Seite aufzurufen.

-

Zurück zum Dashboard

-
- diff --git a/includes/functions.php b/includes/functions.php index dfb05da..901ccbb 100644 --- a/includes/functions.php +++ b/includes/functions.php @@ -355,3 +355,63 @@ function asset_url(string $path): string $file = __DIR__ . '/..' . $path; return $path . (is_file($file) ? '?v=' . filemtime($file) : ''); } + +/** + * Speichert ein hochgeladenes Bild sicher unter $target. JPG, PNG und WEBP werden immer neu + * gerechnet (GD): Dabei faellt alles weg, was kein Bild ist - an ein Bild angehaengter Code + * ("Polyglot"-Dateien) ebenso wie EXIF-Daten (z.B. GPS-Position aus Handyfotos). Zu grosse + * Bilder werden dabei auf $maxSide verkleinert. Animierte GIFs bleiben unveraendert (GD kann + * keine Animation), werden aber auf eingebetteten Code geprueft. + * + * @param int $imageType IMAGETYPE_* aus getimagesize() + * @return string|null Fehlermeldung, null bei Erfolg + */ +function store_uploaded_image(string $tmpPath, string $target, int $imageType, int $maxSide = 0): ?string +{ + $raw = (string) @file_get_contents($tmpPath); + if ($raw === '') { + return 'Das Bild konnte nicht gelesen werden.'; + } + $isAnimatedGif = $imageType === IMAGETYPE_GIF && substr_count($raw, "\x21\xF9\x04") > 1; + $source = !$isAnimatedGif && function_exists('imagecreatefromstring') ? @imagecreatefromstring($raw) : false; + + if ($source === false) { + // Unveraendert speichern (animiertes GIF oder kein GD) - dann wenigstens auf Code pruefen. + if (preg_match('/<\?php|<\?=| 0 && max($width, $height) > $maxSide ? $maxSide / max($width, $height) : 1; + $newW = max(1, (int) round($width * $scale)); + $newH = max(1, (int) round($height * $scale)); + $image = imagecreatetruecolor($newW, $newH); + imagealphablending($image, false); + imagesavealpha($image, true); + imagecopyresampled($image, $source, 0, 0, 0, 0, $newW, $newH, $width, $height); + imagedestroy($source); + + $saved = match ($imageType) { + IMAGETYPE_PNG => imagepng($image, $target, 6), + IMAGETYPE_WEBP => function_exists('imagewebp') && imagewebp($image, $target, 85), + IMAGETYPE_GIF => imagegif($image, $target), + default => imagejpeg($image, $target, 86), + }; + imagedestroy($image); + return $saved ? null : 'Das Bild konnte nicht gespeichert werden (Schreibrechte auf dem Server prüfen).'; +} + +/** + * 404-Seite ausgeben und beenden. Auch fuer fehlende Berechtigungen (siehe require_permission()), + * damit niemand ausprobieren kann, welche Seiten es gibt. + */ +function show_not_found(): void +{ + http_response_code(404); + include __DIR__ . '/not_found.php'; + exit; +} diff --git a/includes/header.php b/includes/header.php index 50b2bee..1db6090 100644 --- a/includes/header.php +++ b/includes/header.php @@ -42,13 +42,16 @@ $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(); } -$showAdminMenu = $canViewUsers || $canManageRoles || $canViewReports || $canManageBugs; +$showAdminMenu = $canViewUsers || $canManageRoles || $canViewReports || $canManageBugs || $canViewAudit || $canModerate; // Neue Discord-Anmeldungen, die auf Freischaltung warten - als Zahl am Menuepunkt. $pendingUserCount = $canViewUsers ? (int) db()->query("SELECT COUNT(*) FROM users WHERE status = 'pending'")->fetchColumn() @@ -64,10 +67,12 @@ $isMapActive = $currentScript === 'map.php'; $isWarehouseActive = $currentScript === 'warehouse.php'; $isContributionsActive = in_array($currentScript, ['contributions.php', 'contributions_award.php'], true); $isShopActive = in_array($currentScript, ['shop.php', 'shop_orders.php', 'shop_manage.php'], true); -$isMembersActive = in_array($currentScript, ['members.php', 'member.php', 'member_edit.php'], true); +$isMembersActive = in_array($currentScript, ['members.php', 'member.php', 'member_edit.php', 'member_picture.php'], true); $isWikiActive = in_array($currentScript, ['wiki.php', 'wiki_edit.php', 'wiki_history.php'], true); $isReportsActive = $currentScript === 'reports.php'; $isBugsActive = $currentScript === 'bugs.php'; +$isAuditActive = $currentScript === 'audit.php'; +$isModerationActive = $currentScript === 'moderation.php'; $isUsersActive = in_array($currentScript, ['users.php', 'user_form.php', 'user_delete.php', 'user_approve.php'], true); $isRolesActive = in_array($currentScript, ['roles.php', 'role_form.php', 'role_delete.php'], true); @@ -99,6 +104,9 @@ $pageBackgrounds = [ 'role_delete.php' => 'bg-roles', 'reports.php' => 'bg-reports', 'bugs.php' => 'bg-reports', + 'audit.php' => 'bg-admin', + 'moderation.php' => 'bg-reports', + 'member_picture.php' => 'bg-members', ]; $pageBackgroundClass = $pageBackgrounds[$currentScript] ?? ''; @@ -247,6 +255,19 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => ($ + + + Moderation + 0): ?> + + + + + + + Audit-Log + + diff --git a/includes/member_profile.php b/includes/member_profile.php index cf0acf6..898a9b5 100644 --- a/includes/member_profile.php +++ b/includes/member_profile.php @@ -56,33 +56,10 @@ function profile_store_upload(?array $file, string $prefix, int $maxSide): strin $name = $prefix . '_' . bin2hex(random_bytes(8)) . '.' . $ext; $target = PROFILE_UPLOAD_DIR . $name; - [$width, $height] = $info; - $canResize = $ext !== 'gif' && function_exists('imagecreatefromstring') && max($width, $height) > $maxSide; - if ($canResize) { - $source = @imagecreatefromstring((string) file_get_contents($file['tmp_name'])); - if ($source !== false) { - $scale = $maxSide / max($width, $height); - $newW = max(1, (int) round($width * $scale)); - $newH = max(1, (int) round($height * $scale)); - $resized = imagecreatetruecolor($newW, $newH); - imagealphablending($resized, false); - imagesavealpha($resized, true); - imagecopyresampled($resized, $source, 0, 0, 0, 0, $newW, $newH, $width, $height); - $saved = match ($ext) { - 'png' => imagepng($resized, $target, 6), - 'webp' => function_exists('imagewebp') && imagewebp($resized, $target, 85), - default => imagejpeg($resized, $target, 86), - }; - imagedestroy($source); - imagedestroy($resized); - if ($saved) { - return $name; - } - } - } - - if (!move_uploaded_file($file['tmp_name'], $target)) { - throw new RuntimeException('Das Bild konnte nicht gespeichert werden (Schreibrechte auf dem Server prüfen).'); + // Immer neu rechnen (entfernt angehaengten Code und EXIF-Daten), zu grosse Bilder verkleinern + $error = store_uploaded_image($file['tmp_name'], $target, $info[2], $maxSide); + if ($error !== null) { + throw new RuntimeException($error); } return $name; } @@ -111,3 +88,52 @@ function profile_characters_by_user(?int $userId = null): array } return $byUser; } + +// ---- Kommentare unter Galeriebildern ---- + +const GALLERY_COMMENT_MAX = 1000; + +/** + * Anzahl der Kommentare je Bild. + * + * @param array $galleryIds + * @return array Bild-ID => Anzahl + */ +function gallery_comment_counts(array $galleryIds): array +{ + if (empty($galleryIds)) { + return []; + } + $placeholders = implode(',', array_fill(0, count($galleryIds), '?')); + try { + $stmt = db()->prepare("SELECT gallery_id, COUNT(*) FROM gallery_comments WHERE status = 'visible' AND gallery_id IN ($placeholders) GROUP BY gallery_id"); + $stmt->execute(array_values(array_map('intval', $galleryIds))); + return array_map('intval', $stmt->fetchAll(PDO::FETCH_KEY_PAIR)); + } catch (PDOException $e) { + return []; + } +} + +/** Darf das angemeldete Konto diesen Kommentar loeschen? (Verfasser, Bild-Besitzer, Moderation) */ +function gallery_comment_can_delete(array $comment, int $pictureOwnerId): bool +{ + $me = current_user(); + if (!$me) { + return false; + } + return (int) $comment['author_id'] === (int) $me['id'] + || $pictureOwnerId === (int) $me['id'] + || user_has_permission('comments.moderate'); +} + +/** Kommentartext: nur Text mit Zeilenumbruechen und klickbaren Links, kein HTML/Markdown. */ +function gallery_comment_html(string $body): string +{ + $html = e($body); + $html = (string) preg_replace_callback( + '~https?://[^\s<>"\']+~i', + static fn (array $m): string => '' . $m[0] . '', + $html + ); + return nl2br($html, false); +} diff --git a/includes/moderation.php b/includes/moderation.php new file mode 100644 index 0000000..8bacdd1 --- /dev/null +++ b/includes/moderation.php @@ -0,0 +1,167 @@ + [Tabelle, Beschriftung] +const MODERATION_TYPES = [ + 'picture' => ['member_gallery', 'Bild'], + 'comment' => ['gallery_comments', 'Kommentar'], +]; + +/** Darf das angemeldete Konto moderieren? */ +function moderation_can(): bool +{ + return user_has_permission('comments.moderate'); +} + +function moderation_all_manual(): bool +{ + return setting_get('moderation_all') === '1'; +} + +/** Ist das angemeldete Konto schon lange genug dabei, um ohne Freigabe zu posten? */ +function moderation_user_trusted(): bool +{ + $user = current_user(); + if (!$user) { + return false; + } + $stmt = db()->prepare('SELECT COALESCE(discord_joined_at, created_at) FROM users WHERE id = ?'); + $stmt->execute([(int) $user['id']]); + $since = strtotime((string) $stmt->fetchColumn()); + return $since !== false && $since < time() - MODERATION_TRUST_DAYS * 86400; +} + +/** Enthaelt der Text einen Link (auch ohne http, z.B. www.… oder discord.gg/…)? */ +function moderation_has_link(string $text): bool +{ + return (bool) preg_match('~https?://|www\.|discord\.gg/|\b[a-z0-9-]+\.(com|de|net|org|io|gg|ru|xyz|ly|me|tk|top|shop)\b~i', $text); +} + +/** + * Status fuer neuen Inhalt des angemeldeten Kontos. + * + * @return array{0: string, 1: ?string} [status, Grund] + */ +function moderation_initial_status(string $type, string $text = ''): array +{ + if (moderation_can()) { + return ['visible', null]; + } + if (moderation_all_manual()) { + return ['pending', 'Alles wird gerade manuell freigegeben']; + } + if (!moderation_user_trusted()) { + return ['pending', 'Neues Mitglied (erste ' . MODERATION_TRUST_DAYS . ' Tage)']; + } + // Links (auch in Bildunterschriften) - beliebter Weg fuer Spam und Phishing + if ($text !== '' && moderation_has_link($text)) { + return ['pending', 'Enthält einen Link']; + } + return ['visible', null]; +} + +/** Wartende Inhalte (fuer die Zahl in der Seitenleiste). */ +function moderation_pending_count(): int +{ + try { + return (int) db()->query( + "SELECT (SELECT COUNT(*) FROM member_gallery WHERE status = 'pending') + + (SELECT COUNT(*) FROM gallery_comments WHERE status = 'pending')" + )->fetchColumn(); + } catch (PDOException $e) { + return 0; // Spalten/Tabellen noch nicht angelegt + } +} + +/** + * Inhalt melden. Ab MODERATION_REPORT_THRESHOLD Meldungen wird er ausgeblendet. + * + * @return string Meldung fuer den Nutzer + */ +function moderation_report(string $type, int $contentId, string $reason): string +{ + $me = current_user(); + [$table, $label] = MODERATION_TYPES[$type]; + $owner = $type === 'picture' ? 'user_id' : 'author_id'; + $stmt = db()->prepare("SELECT id, $owner AS owner_id, status FROM $table WHERE id = ?"); + $stmt->execute([$contentId]); + $content = $stmt->fetch(); + if (!$content) { + return 'Diesen Inhalt gibt es nicht (mehr).'; + } + if ((int) $content['owner_id'] === (int) $me['id']) { + return 'Eigene Inhalte kannst du nicht melden - aber löschen.'; + } + + try { + db()->prepare('INSERT INTO content_reports (content_type, content_id, reporter_id, reason) VALUES (?, ?, ?, ?)') + ->execute([$type, $contentId, (int) $me['id'], $reason !== '' ? $reason : null]); + } catch (PDOException $e) { + return 'Du hast diesen Inhalt schon gemeldet - danke, die Moderation schaut es sich an.'; + } + + $count = db()->prepare('SELECT COUNT(*) FROM content_reports WHERE content_type = ? AND content_id = ?'); + $count->execute([$type, $contentId]); + $reports = (int) $count->fetchColumn(); + + $hidden = false; + if ($content['status'] === 'visible' && $reports >= MODERATION_REPORT_THRESHOLD) { + db()->prepare("UPDATE $table SET status = 'pending', moderation_note = ? WHERE id = ?") + ->execute([$reports . ' Meldungen', $contentId]); + $hidden = true; + } + admin_log($hidden ? '🚩 ' . $label . ' nach Meldungen ausgeblendet' : '🚩 ' . $label . ' gemeldet', [ + 'Von' => admin_log_user((int) $content['owner_id']), + 'Grund' => $reason, + 'Meldungen' => (string) $reports, + 'Prüfen' => 'Moderation → Freigabe-Liste', + ], 'warning', 'members'); + + return $hidden + ? 'Danke für die Meldung. Der Inhalt ist ausgeblendet, bis die Moderation entschieden hat.' + : 'Danke für die Meldung - die Moderation schaut es sich an.'; +} + +/** Meldungen zu einem Inhalt verwerfen (nach Freigabe oder Loeschen). */ +function moderation_clear_reports(string $type, int $contentId): void +{ + db()->prepare('DELETE FROM content_reports WHERE content_type = ? AND content_id = ?')->execute([$type, $contentId]); +} + +/** + * Welche der Inhalte hat das angemeldete Konto schon gemeldet? + * + * @param array $ids + * @return array + */ +function moderation_my_reports(string $type, array $ids): array +{ + $me = current_user(); + if (!$me || empty($ids)) { + return []; + } + $placeholders = implode(',', array_fill(0, count($ids), '?')); + try { + $stmt = db()->prepare("SELECT content_id FROM content_reports WHERE content_type = ? AND reporter_id = ? AND content_id IN ($placeholders)"); + $stmt->execute(array_merge([$type, (int) $me['id']], array_map('intval', $ids))); + return array_fill_keys(array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN)), true); + } catch (PDOException $e) { + return []; + } +} diff --git a/includes/not_found.php b/includes/not_found.php new file mode 100644 index 0000000..65cb58c --- /dev/null +++ b/includes/not_found.php @@ -0,0 +1,29 @@ + +
+ +

Hier ist nichts - nicht mal ein Balaur.

+

+ Die Seite + gibt es nicht - oder du hast (noch) keinen Zugriff darauf. Vielleicht ein Tippfehler oder ein alter Link. +

+ +
+ diff --git a/includes/permissions.php b/includes/permissions.php index a7925af..2d476a5 100644 --- a/includes/permissions.php +++ b/includes/permissions.php @@ -30,6 +30,8 @@ const CORE_PERMISSIONS = [ ['key' => 'shop.view', 'description' => 'Lumishop: Angebot ansehen und Gegenstände gegen Lumipunkte beantragen'], ['key' => 'shop.manage', 'description' => 'Lumishop: Kategorien, Gegenstände, Bestand und Preise verwalten, Anträge bewilligen oder ablehnen'], ['key' => 'members.view', 'description' => 'Mitgliederliste einsehen'], + ['key' => 'comments.moderate', 'description' => 'Moderation: Galeriebilder und Kommentare freigeben, ausblenden und löschen (Freigabe-Liste, Meldungen)'], + ['key' => 'audit.view', 'description' => 'Audit-Log einsehen: alle Verwaltungsaktionen und Sicherheitsereignisse der Website'], ['key' => 'reports.view', 'description' => 'Eingegangene Reports einsehen'], ['key' => 'reports.manage', 'description' => 'Reports löschen/archivieren und die Punkte-Gewichtung verwalten'], ['key' => 'bugs.manage', 'description' => 'Fehlermeldungen der Mitglieder einsehen, beantworten und bearbeiten'], @@ -135,9 +137,8 @@ function sync_role_assign_permissions(): void function require_permission(string $key): void { require_login(); + // Ohne Berechtigung dieselbe Seite wie fuer nicht vorhandene Seiten (verraet nichts). if (!user_has_permission($key)) { - http_response_code(403); - include __DIR__ . '/forbidden.php'; - exit; + show_not_found(); } } diff --git a/includes/schema.php b/includes/schema.php index 6a151bc..79bb353 100644 --- a/includes/schema.php +++ b/includes/schema.php @@ -11,7 +11,7 @@ declare(strict_types=1); */ // Hochzaehlen, sobald unten eine Aenderung dazukommt - dann pruefen alle Sitzungen neu. -const SCHEMA_VERSION = 18; +const SCHEMA_VERSION = 19; /** * Tabellen, die nachtraeglich dazugekommen sind: Tabelle => CREATE-Befehl (wie in sql/schema.sql). @@ -215,6 +215,9 @@ CREATE TABLE IF NOT EXISTS member_gallery ( user_id INT UNSIGNED NOT NULL, filename VARCHAR(120) NOT NULL, caption VARCHAR(150) NULL, + -- visible = fuer alle sichtbar, pending = wartet auf Freigabe + status VARCHAR(10) NOT NULL DEFAULT 'visible', + moderation_note VARCHAR(255) NULL, sort_order INT NOT NULL DEFAULT 0, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, @@ -291,6 +294,68 @@ CREATE TABLE IF NOT EXISTS bug_reports ( INDEX idx_bug_reports_status (status), INDEX idx_bug_reports_user (user_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci +SQL, + 'audit_log' => <<<'SQL' +CREATE TABLE IF NOT EXISTS audit_log ( + id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + -- Wer (NULL = unbekannt/abgemeldet, z.B. fehlgeschlagener Login); Name bleibt auch nach dem Loeschen des Kontos + user_id INT UNSIGNED NULL, + actor_name VARCHAR(100) NOT NULL DEFAULT '', + -- Bereich (siehe AUDIT_AREAS in includes/security.php), Titel und Details (JSON: Name => Wert) + area VARCHAR(30) NOT NULL, + title VARCHAR(256) NOT NULL, + details TEXT NULL, + tone VARCHAR(10) NOT NULL DEFAULT 'info', + -- gekuerzte IP (letzter Block genullt) - reicht zum Wiedererkennen, ohne sie ganz zu speichern + ip VARCHAR(45) NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL, + INDEX idx_audit_log_time (created_at), + INDEX idx_audit_log_user (user_id, created_at), + INDEX idx_audit_log_area (area, created_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci +SQL, + 'rate_limits' => <<<'SQL' +CREATE TABLE IF NOT EXISTS rate_limits ( + id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + -- Art der Aktion (z.B. post, upload, login) und wer (Konto-ID, IP oder Benutzername) + bucket VARCHAR(40) NOT NULL, + subject VARCHAR(120) NOT NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + INDEX idx_rate_limits_lookup (bucket, subject, created_at), + INDEX idx_rate_limits_time (created_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci +SQL, + 'gallery_comments' => <<<'SQL' +CREATE TABLE IF NOT EXISTS gallery_comments ( + id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + -- Kommentar unter einem Bild der Profil-Galerie + gallery_id INT UNSIGNED NOT NULL, + author_id INT UNSIGNED NULL, + body TEXT NOT NULL, + -- visible = fuer alle sichtbar, pending = wartet auf Freigabe (Vertrauensstufe, Link, KI-Pruefung, Meldungen) + status VARCHAR(10) NOT NULL DEFAULT 'visible', + moderation_note VARCHAR(255) NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (gallery_id) REFERENCES member_gallery(id) ON DELETE CASCADE, + FOREIGN KEY (author_id) REFERENCES users(id) ON DELETE CASCADE, + INDEX idx_gallery_comments_picture (gallery_id, created_at), + INDEX idx_gallery_comments_author (author_id, created_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci +SQL, + 'content_reports' => <<<'SQL' +CREATE TABLE IF NOT EXISTS content_reports ( + id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, + -- Gemeldeter Inhalt: picture = member_gallery.id, comment = gallery_comments.id + content_type VARCHAR(20) NOT NULL, + content_id INT UNSIGNED NOT NULL, + reporter_id INT UNSIGNED NOT NULL, + reason VARCHAR(255) NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (reporter_id) REFERENCES users(id) ON DELETE CASCADE, + UNIQUE KEY uq_content_reports (content_type, content_id, reporter_id), + INDEX idx_content_reports_content (content_type, content_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci SQL, ]; } @@ -326,10 +391,19 @@ function schema_column_upgrades(): array "ALTER TABLE users ADD COLUMN tour_completed_at DATETIME NULL AFTER discord_synced_at", "UPDATE users SET tour_completed_at = NOW()", ], + // Wird hochgezaehlt, um alle Sitzungen eines Kontos sofort zu beenden (Sperren/Abmelden). + 'session_epoch' => "ALTER TABLE users ADD COLUMN session_epoch INT UNSIGNED NOT NULL DEFAULT 0 AFTER is_admin", + // Kommentare unter den eigenen Galeriebildern (0 = vom Mitglied abgeschaltet) + 'gallery_comments_enabled' => "ALTER TABLE users ADD COLUMN gallery_comments_enabled TINYINT(1) NOT NULL DEFAULT 1 AFTER profile_bio", ], 'roles' => [ 'discord_role_id' => "ALTER TABLE roles ADD COLUMN discord_role_id BIGINT UNSIGNED NULL AFTER roster_order", ], + // Freigabe von Galeriebildern (Moderation) - vorhandene Bilder bleiben sichtbar + 'member_gallery' => [ + 'status' => "ALTER TABLE member_gallery ADD COLUMN status VARCHAR(10) NOT NULL DEFAULT 'visible' AFTER caption", + 'moderation_note' => "ALTER TABLE member_gallery ADD COLUMN moderation_note VARCHAR(255) NULL AFTER status", + ], 'shop_orders' => [ 'requested_quantity' => "ALTER TABLE shop_orders ADD COLUMN requested_quantity INT UNSIGNED NOT NULL DEFAULT 0 AFTER quantity", ], diff --git a/includes/security.php b/includes/security.php new file mode 100644 index 0000000..c1795af --- /dev/null +++ b/includes/security.php @@ -0,0 +1,314 @@ + Beschriftung +const AUDIT_AREAS = [ + 'users' => 'Benutzer & Rechte', + 'security' => 'Sicherheit', + 'raids' => 'Raids', + 'premades' => 'Premades', + 'events' => 'Events', + 'map' => 'Karte', + 'warehouse' => 'Lagerhaus', + 'contributions' => 'Lumipunkte', + 'shop' => 'Lumishop', + 'members' => 'Profile', + 'wiki' => 'Wiki', + 'reports' => 'Reports', + 'bugs' => 'Fehlermeldungen', + 'other' => 'Sonstiges', +]; + +// Tempolimits: Art => [hoechstens, in Sekunden] +const SECURITY_LIMITS = [ + 'post' => [120, 300], // abgeschickte Formulare/Aktionen pro Konto + 'upload' => [30, 600], // hochgeladene Bilder pro Konto + 'comment' => [6, 300], // Kommentare unter Galeriebildern pro Konto + 'report' => [10, 600], // Meldungen (Melden-Knopf) pro Konto + 'bug' => [5, 3600], // Fehlermeldungen pro Konto + 'login_ip' => [15, 900], // fehlgeschlagene Logins pro IP (egal welches Konto) + 'login_pair' => [5, 900], // fehlgeschlagene Logins pro IP + Benutzername + 'destructive' => [20, 600], // Loeschungen pro Konto, danach automatische Sperre +]; + +// Diese Skripte schicken im Hintergrund viele kleine Anfragen (Zeichnen, Tour, Bot) - kein Tempolimit. +const SECURITY_POST_EXEMPT = ['bot_api.php', 'tactics_api.php', 'tour_action.php']; + +/** Bereich einer Aktion anhand des aufgerufenen Skripts (raid_delete_action.php -> raids). */ +function audit_area_for_script(string $script): string +{ + $name = basename($script, '.php'); + $prefixes = [ + 'raid' => 'raids', 'premade' => 'premades', 'event' => 'events', 'tactics' => 'map', 'map' => 'map', + 'warehouse' => 'warehouse', 'contributions' => 'contributions', 'shop' => 'shop', + 'member' => 'members', 'gallery' => 'members', 'moderation' => 'members', 'wiki' => 'wiki', 'report' => 'reports', 'bug' => 'bugs', + 'user' => 'users', 'role' => 'users', 'discord' => 'users', 'settings' => 'users', + ]; + foreach ($prefixes as $prefix => $area) { + if (strpos($name, $prefix) === 0) { + return $area; + } + } + return 'other'; +} + +/** IP des Besuchers, gekuerzt (IPv4: letzter Block 0, IPv6: nur die ersten vier Bloecke). */ +function client_ip_masked(): ?string +{ + $ip = (string) ($_SERVER['REMOTE_ADDR'] ?? ''); + if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + return preg_replace('/\.\d+$/', '.0', $ip); + } + if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { + return implode(':', array_slice(explode(':', $ip), 0, 4)) . '::'; + } + return null; +} + +/** Schluessel fuer die IP in den Tempolimits (gehasht, die Tabelle wird nach 2 Tagen geleert). */ +function client_ip_key(): string +{ + return substr(hash('sha256', 'ip|' . ($_SERVER['REMOTE_ADDR'] ?? '')), 0, 40); +} + +/** + * Eintrag ins Audit-Log. Discord-Erwaehnungen "(<@123>)" werden fuer die Anzeige entfernt. + * + * @param array $fields + */ +function audit_store(string $title, array $fields, string $tone, ?string $area = null, ?array $actor = null): void +{ + $actor = $actor ?? current_user(); + $clean = []; + foreach ($fields as $name => $value) { + $value = trim(preg_replace('/\s*\(<@!?\d+>\)/', '', (string) $value) ?? ''); + if ($value !== '') { + $clean[(string) $name] = mb_substr($value, 0, 1000); + } + } + $actorName = ''; + if ($actor) { + $actorName = ($actor['display_name'] ?? '') !== '' ? (string) $actor['display_name'] : (string) ($actor['username'] ?? ''); + } + try { + db()->prepare( + 'INSERT INTO audit_log (user_id, actor_name, area, title, details, tone, ip) VALUES (?, ?, ?, ?, ?, ?, ?)' + )->execute([ + $actor ? (int) $actor['id'] : null, + mb_substr($actorName, 0, 100), + $area ?? audit_area_for_script((string) ($_SERVER['SCRIPT_NAME'] ?? '')), + mb_substr($title, 0, 256), + $clean ? json_encode($clean, JSON_UNESCAPED_UNICODE) : null, + $tone, + client_ip_masked(), + ]); + } catch (PDOException $e) { + // Tabelle fehlt (noch) - die eigentliche Aktion soll daran nicht scheitern. + } +} + +/** Sicherheitsereignis: Audit-Log (Bereich "Sicherheit") und Discord-Log. */ +function security_log(string $title, array $fields = [], string $tone = 'warning', ?array $actor = null): void +{ + admin_log($title, $fields, $tone, 'security', $actor); +} + +// ---- Tempolimits ---- + +function rate_limit_count(string $bucket, string $subject, int $windowSeconds): int +{ + try { + $stmt = db()->prepare( + 'SELECT COUNT(*) FROM rate_limits WHERE bucket = ? AND subject = ? AND created_at > ?' + ); + $stmt->execute([$bucket, $subject, date('Y-m-d H:i:s', time() - $windowSeconds)]); + return (int) $stmt->fetchColumn(); + } catch (PDOException $e) { + return 0; + } +} + +function rate_limit_add(string $bucket, string $subject, int $times = 1): void +{ + try { + $insert = db()->prepare('INSERT INTO rate_limits (bucket, subject) VALUES (?, ?)'); + for ($i = 0; $i < $times; $i++) { + $insert->execute([$bucket, $subject]); + } + // Ab und zu aufraeumen - laenger als zwei Tage braucht kein Limit zurueckzuschauen. + if (random_int(1, 50) === 1) { + db()->prepare('DELETE FROM rate_limits WHERE created_at < ?')->execute([date('Y-m-d H:i:s', time() - 172800)]); + } + } catch (PDOException $e) { + // Tabelle fehlt (noch) + } +} + +/** + * Prueft ein Tempolimit fuer das angemeldete Konto und zaehlt die Aktion mit. + * Beim ersten Ueberschreiten im Zeitfenster gibt es einen Eintrag im Audit- und Discord-Log. + * + * @return bool true = erlaubt + */ +function security_throttle(string $bucket, int $amount = 1): bool +{ + $user = current_user(); + if (!$user || !isset(SECURITY_LIMITS[$bucket])) { + return true; + } + [$max, $window] = SECURITY_LIMITS[$bucket]; + $subject = 'u' . (int) $user['id']; + + if (rate_limit_count($bucket, $subject, $window) + $amount > $max) { + if (rate_limit_count('notice_' . $bucket, $subject, $window) === 0) { + rate_limit_add('notice_' . $bucket, $subject); + security_log('⏱️ Tempolimit erreicht', [ + 'Art' => security_bucket_label($bucket), + 'Limit' => $max . ' in ' . round($window / 60) . ' Minuten', + 'Seite' => basename((string) ($_SERVER['SCRIPT_NAME'] ?? '')), + ]); + } + return false; + } + rate_limit_add($bucket, $subject, $amount); + return true; +} + +function security_bucket_label(string $bucket): string +{ + return [ + 'post' => 'Aktionen/Formulare', + 'upload' => 'Bilder hochladen', + 'comment' => 'Kommentare', + 'report' => 'Meldungen', + 'bug' => 'Fehlermeldungen', + 'destructive' => 'Löschungen', + ][$bucket] ?? $bucket; +} + +/** Meldung und zurueck zur vorigen Seite (bzw. JSON-Fehler bei Hintergrund-Anfragen). */ +function security_reject(string $message): void +{ + $accept = (string) ($_SERVER['HTTP_ACCEPT'] ?? ''); + if (stripos($accept, 'application/json') !== false || !empty($_SERVER['HTTP_X_REQUESTED_WITH'])) { + http_response_code(429); + header('Content-Type: application/json; charset=UTF-8'); + echo json_encode(['ok' => false, 'error' => $message], JSON_UNESCAPED_UNICODE); + exit; + } + set_flash('error', $message); + $back = (string) ($_SERVER['HTTP_REFERER'] ?? ''); + $host = (string) ($_SERVER['HTTP_HOST'] ?? ''); + $path = parse_url($back, PHP_URL_HOST) === $host ? (string) parse_url($back, PHP_URL_PATH) : ''; + $query = (string) parse_url($back, PHP_URL_QUERY); + redirect($path !== '' ? $path . ($query !== '' ? '?' . $query : '') : '/dashboard.php'); +} + +/** Allgemeines Tempolimit fuer alle abgeschickten Formulare angemeldeter Konten (aus bootstrap.php). */ +function security_guard_post(): void +{ + if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST' || empty($_SESSION['user_id'])) { + return; + } + $script = basename((string) ($_SERVER['SCRIPT_NAME'] ?? '')); + // Die Live-Vorschau im Wiki-Editor schickt beim Tippen laufend Anfragen. + if (in_array($script, SECURITY_POST_EXEMPT, true) || ($_POST['action'] ?? '') === 'preview') { + return; + } + if (!security_throttle('post')) { + security_reject('Zu viele Aktionen in kurzer Zeit. Bitte warte ein paar Minuten und versuche es dann erneut.'); + } +} + +// ---- Login-Bremse ---- + +/** Leer = Login-Versuch erlaubt, sonst die Meldung fuer die Login-Seite. */ +function login_throttle_check(string $username): string +{ + [$maxIp, $window] = SECURITY_LIMITS['login_ip']; + [$maxPair] = SECURITY_LIMITS['login_pair']; + if (rate_limit_count('login_ip', client_ip_key(), $window) >= $maxIp + || rate_limit_count('login_pair', login_pair_key($username), $window) >= $maxPair) { + return 'Zu viele fehlgeschlagene Anmeldungen von deinem Anschluss. Bitte warte 15 Minuten ' + . 'und versuche es dann erneut - oder melde dich über Discord an.'; + } + return ''; +} + +function login_pair_key(string $username): string +{ + return substr(hash('sha256', 'pair|' . ($_SERVER['REMOTE_ADDR'] ?? '') . '|' . mb_strtolower(trim($username))), 0, 40); +} + +/** Fehlversuch zaehlen; beim Erreichen einer Sperre ein Eintrag im Audit- und Discord-Log. */ +function login_throttle_fail(string $username): void +{ + [$maxIp, $window] = SECURITY_LIMITS['login_ip']; + [$maxPair] = SECURITY_LIMITS['login_pair']; + rate_limit_add('login_ip', client_ip_key()); + rate_limit_add('login_pair', login_pair_key($username)); + + $ipCount = rate_limit_count('login_ip', client_ip_key(), $window); + $pairCount = rate_limit_count('login_pair', login_pair_key($username), $window); + if ($ipCount === $maxIp || $pairCount === $maxPair) { + security_log('🔐 Login-Sperre nach Fehlversuchen', [ + 'Benutzername' => mb_substr($username, 0, 60), + 'IP (gekürzt)' => (string) client_ip_masked(), + 'Gesperrt' => $ipCount >= $maxIp ? 'diese IP für alle Konten (15 Min.)' : 'diese IP für dieses Konto (15 Min.)', + ], 'warning', []); + } +} + +// ---- Notbremse und Sitzungen ---- + +/** Wird bei jeder Loeschung (admin_log mit Ton "danger") aufgerufen. */ +function security_note_destructive(): void +{ + $user = current_user(); + if (!$user) { + return; + } + [$max, $window] = SECURITY_LIMITS['destructive']; + $subject = 'u' . (int) $user['id']; + rate_limit_add('destructive', $subject); + if (rate_limit_count('destructive', $subject, $window) !== $max + 1) { + return; + } + // Entwickler werden nicht gesperrt (sonst kaeme niemand mehr an ihr Konto), aber gemeldet. + if (is_developer($user)) { + security_log('🚨 Auffällig viele Löschungen (Entwickler-Konto, nicht gesperrt)', [ + 'Konto' => admin_log_user((int) $user['id']), + 'Löschungen' => 'mehr als ' . $max . ' in ' . round($window / 60) . ' Minuten', + ], 'danger'); + return; + } + security_lock_account((int) $user['id'], 'Mehr als ' . $max . ' Löschungen in ' . round($window / 60) . ' Minuten', true); +} + +/** Konto sperren und alle Sitzungen beenden. */ +function security_lock_account(int $userId, string $reason, bool $automatic = false): void +{ + db()->prepare("UPDATE users SET status = 'disabled', session_epoch = session_epoch + 1 WHERE id = ?")->execute([$userId]); + security_log($automatic ? '🚨 Konto automatisch gesperrt' : '🔒 Konto gesperrt und abgemeldet', [ + 'Konto' => admin_log_user($userId), + 'Grund' => $reason, + 'Hinweis' => $automatic ? 'Möglicherweise gehackt - bitte prüfen. Entsperren über die Benutzerverwaltung (Status „Aktiv“).' : '', + ], 'danger'); +} + +/** Alle Sitzungen eines Kontos beenden (naechster Seitenaufruf meldet ab). */ +function security_end_sessions(int $userId): void +{ + db()->prepare('UPDATE users SET session_epoch = session_epoch + 1 WHERE id = ?')->execute([$userId]); +} diff --git a/includes/settings.php b/includes/settings.php index 72babb1..83ded44 100644 --- a/includes/settings.php +++ b/includes/settings.php @@ -10,12 +10,15 @@ declare(strict_types=1); const SETTINGS_DEFAULTS = [ 'discord_unlink_allowed' => '1', 'contributions_history_public' => '1', + // Moderation: alle neuen Bilder/Kommentare warten auf Freigabe (z.B. bei einer Spam-Welle) + 'moderation_all' => '0', ]; // Wer eine Einstellung aendern darf und wohin es danach zurueckgeht. const SETTINGS_ACCESS = [ 'discord_unlink_allowed' => ['users.edit', '/admin/users.php'], 'contributions_history_public' => ['contributions.manage', '/contributions.php#verlauf'], + 'moderation_all' => ['comments.moderate', '/moderation.php'], ]; function setting_get(string $key): string diff --git a/member.php b/member.php index 6a88f24..5f6fdb8 100644 --- a/member.php +++ b/member.php @@ -6,15 +6,14 @@ require_permission('members.view'); $id = (int) ($_GET['id'] ?? 0); $stmt = db()->prepare( - "SELECT id, username, display_name, class_name, profile_bio, discord_id, discord_username, avatar_filename, status, + "SELECT id, username, display_name, class_name, profile_bio, gallery_comments_enabled, discord_id, discord_username, avatar_filename, status, COALESCE(discord_joined_at, created_at) AS joined_at, discord_joined_at IS NOT NULL AS joined_discord FROM users WHERE id = ?" ); $stmt->execute([$id]); $member = $stmt->fetch(); if (!$member || $member['status'] !== 'active') { - set_flash('error', 'Dieses Mitglied gibt es nicht (mehr).'); - redirect('/members.php'); + show_not_found(); } $groupStmt = db()->prepare( @@ -25,9 +24,15 @@ $groupStmt->execute([$id]); $groups = array_column($groupStmt->fetchAll(), 'name'); $characters = profile_characters_by_user($id)[$id] ?? []; -$galleryStmt = db()->prepare('SELECT * FROM member_gallery WHERE user_id = ? ORDER BY sort_order, id'); +// Noch nicht freigegebene Bilder sehen nur der Besitzer und die Moderation. +$seesPending = (int) current_user()['id'] === $id || moderation_can(); +$galleryStmt = db()->prepare( + 'SELECT * FROM member_gallery WHERE user_id = ?' . ($seesPending ? '' : " AND status = 'visible'") . ' ORDER BY sort_order, id' +); $galleryStmt->execute([$id]); $gallery = $galleryStmt->fetchAll(); +$commentsEnabled = !empty($member['gallery_comments_enabled']); +$commentCounts = $commentsEnabled ? gallery_comment_counts(array_map('intval', array_column($gallery, 'id'))) : []; $name = $member['display_name'] !== '' ? $member['display_name'] : $member['username']; $canEdit = profile_can_edit($id); @@ -111,11 +116,25 @@ include __DIR__ . '/includes/header.php';

Galerie