Audit log, abuse protection, gallery comments with moderation, safe image uploads, 404 page

- Audit log: every admin_log entry is also stored permanently in the database (admin/audit.php, audit.view)
- Rate limits per account, login throttling per IP (not per account), emergency lock after mass deletions, force logout / lock in user management
- Comments under gallery pictures (picture page, report button, owner can disable them)
- Moderation: new members, links, reported content and a "moderate everything" switch go to the approval list (moderation.php)
- Every uploaded image is re-encoded (strips appended code and EXIF data)
- Custom 404 page, also shown for pages without permission

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Maaxxs 2026-09-21 21:57:34 +02:00
parent a483ea8712
commit e4f23fcde4
36 changed files with 2016 additions and 70 deletions

View file

@ -20,3 +20,18 @@ AddDefaultCharset UTF-8
# includes/ und sql/ haben jeweils eine eigene .htaccess, die den Zugriff # includes/ und sql/ haben jeweils eine eigene .htaccess, die den Zugriff
# darauf sperrt (siehe includes/.htaccess und sql/.htaccess). # 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.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/assets/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /404.php [L]
</IfModule>

8
404.php Normal file
View file

@ -0,0 +1,8 @@
<?php
/**
* Seite nicht gefunden - statt der weissen Standardseite des Servers.
* Eingebunden per ErrorDocument/RewriteRule in .htaccess (auch fuer gesperrte Ordner, 403).
*/
require_once __DIR__ . '/includes/bootstrap.php';
show_not_found();

View file

@ -647,6 +647,14 @@ bei anderen Inhalte entfernen - das landet im Discord-Log. Bilder werden schon i
verkleinert (Upload-Limit des Webspaces) und liegen unter `assets/uploads/profiles/`; verkleinert (Upload-Limit des Webspaces) und liegen unter `assets/uploads/profiles/`;
höchstens 12 Charaktere und 30 Galeriebilder pro Mitglied. höchstens 12 Charaktere und 30 Galeriebilder pro Mitglied.
Unter jedem **Galeriebild** lässt sich kommentieren (nur dort - keine Pinnwand auf dem
Profil): Klick auf das Sprechblasen-Symbol am Bild oder auf „Kommentare“ in der Großansicht
öffnet die Bildseite (`member_picture.php`) mit Blättern und Kommentaren. Nur Text, Links
werden klickbar. Löschen dürfen Verfasser, Bild-Besitzer und wer `comments.moderate` hat
(fremde Kommentare löschen landet im Log). Galeriebilder und Kommentare werden moderiert
(siehe „Moderation“ unten). Jedes Mitglied kann Kommentare unter den eigenen
Bildern beim Bearbeiten der Profilseite abschalten (`users.gallery_comments_enabled`).
## Wiki (Einsteiger-Guide) ## Wiki (Einsteiger-Guide)
Unter **Wiki** im Menü liegt der Einsteiger-Guide der Legion: Kapitel mit Unterseiten, Unter **Wiki** im Menü liegt der Einsteiger-Guide der Legion: Kapitel mit Unterseiten,
@ -689,6 +697,60 @@ Auch die Anwesenheits-Erinnerung des Bots meldet dort, an wen die PN ging - oder
(niemand angemeldet, kein Angemeldeter mit `raids.manage`, Website nicht erreichbar, PNs (niemand angemeldet, kein Angemeldeter mit `raids.manage`, Website nicht erreichbar, PNs
geschlossen). geschlossen).
## Audit-Log
Jeder Eintrag des Discord-Logs landet zusätzlich dauerhaft in der Tabelle `audit_log` - auch
wenn der Bot gerade nicht erreichbar ist, und ohne dass ihn jemand wieder löschen kann (die
Website hat dafür keine Funktion). **Admin → Audit-Log** (`admin/audit.php`, Berechtigung
`audit.view`) zeigt alles mit Suche, Bereichs-Chips, Wichtigkeit (Warnungen/Kritisch),
Zeitraum und Filter nach Person (Klick auf den Namen). Gespeichert werden Wer, Was, Wann,
Details und die gekürzte IP (letzter Block genullt).
## Schutz vor Missbrauch
Zentral in `includes/security.php` (Grenzen in `SECURITY_LIMITS`):
- **Tempolimits pro Konto:** abgeschickte Formulare (120 in 5 Min.), hochgeladene Bilder
(30 in 10 Min.), Kommentare (6 in 5 Min., derselbe Text nicht zweimal in 10 Min.),
Fehlermeldungen (5 pro Stunde). Beim Überschreiten gibt es eine freundliche Meldung und
einmal pro Zeitfenster einen Eintrag „Tempolimit erreicht“ im Log.
- **Login-Bremse:** Nach 5 falschen Passwörtern für ein Konto von derselben IP bzw. 15 von
einer IP insgesamt sind Passwort-Logins von dieser IP 15 Minuten gesperrt. Bewusst pro IP
und nicht pro Konto - sonst könnte jemand ein bekanntes Konto mit Absicht gesperrt halten.
Der Discord-Login ist nie betroffen.
- **Notbremse:** Mehr als 20 Löschungen in 10 Minuten sperren das Konto automatisch und
beenden alle Sitzungen (gehacktes Konto); Meldung „🚨 Konto automatisch gesperrt“ im Log.
Entsperren über die Benutzerverwaltung (Status „Aktiv“). Entwickler-Konten werden nur
gemeldet, nicht gesperrt.
- **Uploads:** Der Dateityp wird am Inhalt erkannt, die Endung vergibt der Server. Jedes
Bild (Profil, Galerie, Charaktere, Wiki) wird neu gerechnet (`store_uploaded_image()`) - so
fällt an Bilder angehängter Code weg, ebenso EXIF-Daten wie die GPS-Position. Animierte GIFs
bleiben unverändert, werden aber abgelehnt, wenn Code darin steckt. In den Upload-Ordnern
ist PHP abgeschaltet.
- **Sofort eingreifen:** In der Benutzerverwaltung pro Konto „Abmelden erzwingen“ (alle
Sitzungen beenden) und „Sperren und überall abmelden“ - über `users.session_epoch`.
## Moderation (Galeriebilder und Kommentare)
`includes/moderation.php`, Seite **Admin → Moderation** (`moderation.php`, Berechtigung
`comments.moderate`, wartende Inhalte als Zahl am Menüpunkt). Grundsätzlich ist alles sofort
sichtbar - erst nach Freigabe sichtbar (für alle außer Verfasser und Moderation) wird:
- alles von **neuen Mitgliedern** (erste 14 Tage seit Discord-Beitritt bzw. Kontoerstellung),
- Kommentare und Bildunterschriften mit **Links**,
- alles, solange **„Alles manuell freigeben“** eingeschaltet ist (Schalter auf der Seite, z.B.
bei einer Spam-Welle),
- alles, was **2 Mitglieder gemeldet** haben (Fahnen-Knopf an Bild und Kommentar).
Die Moderation kann freigeben, ausblenden, Meldungen verwerfen oder löschen - alles landet im
Audit- und Discord-Log. Grenzen: `MODERATION_TRUST_DAYS`, `MODERATION_REPORT_THRESHOLD`.
## Fehlerseite (404)
Nicht vorhandene Seiten und Seiten **ohne Berechtigung** zeigen dieselbe 404-Seite
(`show_not_found()`, `includes/not_found.php`) - so lässt sich nicht ausprobieren, welche
Bereiche es gibt. Die `.htaccess` leitet nicht vorhandene Adressen und gesperrte Ordner dorthin.
## Einführung für neue Mitglieder ## Einführung für neue Mitglieder
Wer das Dashboard zum ersten Mal öffnet, bekommt eine kurze Tour (`assets/js/tour.js`): Sie Wer das Dashboard zum ersten Mal öffnet, bekommt eine kurze Tour (`assets/js/tour.js`): Sie

167
admin/audit.php Normal file
View file

@ -0,0 +1,167 @@
<?php
/**
* Audit-Log: alle Verwaltungsaktionen und Sicherheitsereignisse, dauerhaft in der Datenbank.
* Nur lesen - Eintraege lassen sich ueber die Website weder aendern noch loeschen.
*/
require_once __DIR__ . '/../includes/bootstrap.php';
require_permission('audit.view');
$query = mb_substr(trim((string) ($_GET['q'] ?? '')), 0, 100);
$area = isset(AUDIT_AREAS[$_GET['area'] ?? '']) ? (string) $_GET['area'] : '';
$tone = in_array($_GET['tone'] ?? '', ['danger', 'warning'], true) ? (string) $_GET['tone'] : '';
$actorId = (int) ($_GET['user'] ?? 0);
$from = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string) ($_GET['from'] ?? '')) ? (string) $_GET['from'] : '';
$to = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string) ($_GET['to'] ?? '')) ? (string) $_GET['to'] : '';
$conditions = [];
$params = [];
if ($query !== '') {
$like = '%' . addcslashes($query, '%_\\') . '%';
$conditions[] = '(a.title LIKE ? OR a.details LIKE ? OR a.actor_name LIKE ?)';
array_push($params, $like, $like, $like);
}
if ($area !== '') {
$conditions[] = 'a.area = ?';
$params[] = $area;
}
if ($tone !== '') {
$conditions[] = $tone === 'warning' ? "a.tone IN ('warning', 'danger')" : "a.tone = 'danger'";
}
if ($actorId > 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';
?>
<div class="panel">
<h1>Audit-Log</h1>
<p class="text-muted">
Alle Verwaltungsaktionen und Sicherheitsereignisse der Website - dieselben Einträge wie im
Discord-Log, aber dauerhaft gespeichert und hier nicht lösch- oder änderbar.
</p>
<form class="list-toolbar" method="get" action="/admin/audit.php">
<?php if ($actorId > 0): ?><input type="hidden" name="user" value="<?= $actorId ?>"><?php endif; ?>
<input type="hidden" name="area" value="<?= e($area) ?>">
<input type="hidden" name="tone" value="<?= e($tone) ?>">
<div class="audit-search-row">
<label class="search-field">
<?= icon('search') ?>
<input type="search" name="q" value="<?= e($query) ?>" placeholder="Aktion, Person oder Details suchen …" aria-label="Audit-Log durchsuchen">
</label>
<label class="audit-date">von <input type="date" name="from" value="<?= e($from) ?>" onchange="this.form.submit()"></label>
<label class="audit-date">bis <input type="date" name="to" value="<?= e($to) ?>" onchange="this.form.submit()"></label>
</div>
<div class="members-chips" role="group" aria-label="Nach Bereich filtern">
<button type="submit" name="area" value="" class="members-chip<?= $area === '' ? ' active' : '' ?>">Alle</button>
<?php foreach (AUDIT_AREAS as $key => $label): ?>
<?php if (empty($areaCounts[$key])) continue; ?>
<button type="submit" name="area" value="<?= e($key) ?>" class="members-chip<?= $area === $key ? ' active' : '' ?>">
<?= e($label) ?> <span class="chip-count"><?= number_format((int) $areaCounts[$key], 0, ',', '.') ?></span>
</button>
<?php endforeach; ?>
</div>
<div class="list-toolbar-row">
<div class="list-toolbar-meta">
<span class="members-filter-label">Wichtigkeit</span>
<div class="members-segment" role="group" aria-label="Nach Wichtigkeit filtern">
<button type="submit" name="tone" value="" class="<?= $tone === '' ? 'active' : '' ?>">Alle</button>
<button type="submit" name="tone" value="warning" class="<?= $tone === 'warning' ? 'active' : '' ?>">Warnungen</button>
<button type="submit" name="tone" value="danger" class="<?= $tone === 'danger' ? 'active' : '' ?>">Kritisch</button>
</div>
<?php if ($actorId > 0): ?>
<a class="audit-filter-pill" href="<?= e($auditUrl(['user' => '']) ) ?>" title="Filter entfernen">Person: <?= e($actorName) ?> <?= icon('x') ?></a>
<?php endif; ?>
</div>
<span class="list-search-count text-muted">
<?= number_format($total, 0, ',', '.') ?> <?= $total === 1 ? 'Eintrag' : 'Einträge' ?>
<?php if ($filtered): ?> · <a href="/admin/audit.php">Filter zurücksetzen</a><?php endif; ?>
</span>
</div>
</form>
<?php if (empty($entries)): ?>
<p class="text-muted"><?= $filtered ? 'Kein Eintrag passt zu Suche und Filter.' : 'Noch keine Einträge.' ?></p>
<?php else: ?>
<ol class="audit-list">
<?php foreach ($entries as $entry): ?>
<?php $details = json_decode((string) ($entry['details'] ?? ''), true) ?: []; ?>
<li class="audit-entry audit-<?= e((string) $entry['tone']) ?>">
<div class="audit-entry-head">
<strong class="audit-title"><?= e((string) $entry['title']) ?></strong>
<span class="badge audit-area"><?= e(AUDIT_AREAS[$entry['area']] ?? $entry['area']) ?></span>
</div>
<?php if ($details): ?>
<dl class="audit-details">
<?php foreach ($details as $name => $value): ?>
<div><dt><?= e((string) $name) ?></dt><dd><?= e((string) $value) ?></dd></div>
<?php endforeach; ?>
</dl>
<?php endif; ?>
<div class="audit-meta text-muted">
<time datetime="<?= e(date('c', strtotime((string) $entry['created_at']))) ?>"><?= e(date('d.m.Y H:i:s', strtotime((string) $entry['created_at']))) ?></time>
·
<?php if ($entry['user_id'] !== null): ?>
<a href="<?= e($auditUrl(['user' => (int) $entry['user_id']])) ?>" title="Nur Einträge dieser Person"><?= e($entry['actor_name'] !== '' ? (string) $entry['actor_name'] : 'Konto #' . $entry['user_id']) ?></a>
<?php else: ?>
<?= e($entry['actor_name'] !== '' ? (string) $entry['actor_name'] . ' (Konto gelöscht)' : 'nicht angemeldet') ?>
<?php endif; ?>
<?php if (!empty($entry['ip'])): ?>
· <span title="IP-Adresse, gekürzt">IP <?= e((string) $entry['ip']) ?></span>
<?php endif; ?>
</div>
</li>
<?php endforeach; ?>
</ol>
<div class="warehouse-pages">
<span class="text-muted">
Einträge <?= ($page - 1) * $perPage + 1 ?>–<?= min($page * $perPage, $total) ?> von <?= number_format($total, 0, ',', '.') ?>
</span>
<?php render_pagination($auditUrl(), $page, $pageCount); ?>
</div>
<?php endif; ?>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>

View file

@ -23,6 +23,7 @@ setting_set($key, isset($_POST['value']) ? '1' : '0');
$settingLabels = [ $settingLabels = [
'discord_unlink_allowed' => 'Mitglieder dürfen ihre Discord-Verknüpfung lösen', 'discord_unlink_allowed' => 'Mitglieder dürfen ihre Discord-Verknüpfung lösen',
'contributions_history_public' => 'Lumipunkte-Verlauf für alle sichtbar', 'contributions_history_public' => 'Lumipunkte-Verlauf für alle sichtbar',
'moderation_all' => 'Alle neuen Bilder und Kommentare manuell freigeben',
]; ];
admin_log('⚙️ Einstellung geändert', [ admin_log('⚙️ Einstellung geändert', [
'Einstellung' => $settingLabels[$key] ?? $key, 'Einstellung' => $settingLabels[$key] ?? $key,

53
admin/user_security.php Normal file
View file

@ -0,0 +1,53 @@
<?php
/**
* Schnelle Eingriffe bei einem verdaechtigen/gehackten Konto:
* - logout: alle Sitzungen sofort beenden (Konto bleibt aktiv)
* - lock: sperren (Status "Deaktiviert") und alle Sitzungen beenden
*/
require_once __DIR__ . '/../includes/bootstrap.php';
require_permission('users.edit');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
redirect('/admin/users.php');
}
verify_csrf();
$id = (int) ($_POST['id'] ?? 0);
$action = (string) ($_POST['action'] ?? '');
$currentUser = current_user();
if ($id === (int) $currentUser['id']) {
set_flash('error', 'Das geht nicht mit deinem eigenen Konto.');
redirect('/admin/users.php');
}
$stmt = db()->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');

View file

@ -184,6 +184,18 @@ include __DIR__ . '/../includes/header.php';
<?php if ($canEdit && !$protectedAdmin): ?> <?php if ($canEdit && !$protectedAdmin): ?>
<a class="icon-button" href="/admin/user_form.php?id=<?= (int) $u['id'] ?>" title="Bearbeiten" aria-label="Bearbeiten"><?= icon('edit') ?></a> <a class="icon-button" href="/admin/user_form.php?id=<?= (int) $u['id'] ?>" title="Bearbeiten" aria-label="Bearbeiten"><?= icon('edit') ?></a>
<?php endif; ?> <?php endif; ?>
<?php if ($canEdit && !$protectedAdmin && $u['status'] === 'active' && (int) $u['id'] !== (int) $currentUser['id']): ?>
<?php foreach (['logout' => ['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]): ?>
<form class="inline-form" method="post" action="/admin/user_security.php"
onsubmit="var r = prompt(<?= e(json_encode($secQuestion . "\n\nGrund (optional, erscheint im Audit-Log):", JSON_UNESCAPED_UNICODE)) ?>); if (r === null) return false; this.reason.value = r; return true;">
<?= csrf_field() ?>
<input type="hidden" name="id" value="<?= (int) $u['id'] ?>">
<input type="hidden" name="action" value="<?= $secAction ?>">
<input type="hidden" name="reason" value="">
<button type="submit" class="icon-button<?= $secAction === 'lock' ? ' icon-button-danger' : '' ?>" title="<?= e($secTitle) ?>" aria-label="<?= e($secTitle) ?>"><?= icon($secIcon) ?></button>
</form>
<?php endforeach; ?>
<?php endif; ?>
<?php if ($canDelete && !$protectedAdmin && (int) $u['id'] !== (int) $currentUser['id']): ?> <?php if ($canDelete && !$protectedAdmin && (int) $u['id'] !== (int) $currentUser['id']): ?>
<form class="inline-form" method="post" action="/admin/user_delete.php" onsubmit="return confirm('Diesen Benutzer wirklich löschen?');"> <form class="inline-form" method="post" action="/admin/user_delete.php" onsubmit="return confirm('Diesen Benutzer wirklich löschen?');">
<?= csrf_field() ?> <?= csrf_field() ?>

View file

@ -4959,3 +4959,206 @@ input[type="file"]::file-selector-button {
/* Bestand: Suche und Kategorie-Chips */ /* Bestand: Suche und Kategorie-Chips */
.warehouse-filters.list-toolbar { margin: 1rem 0; } .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; }

View file

@ -30,6 +30,15 @@
img.src = link.href; img.src = link.href;
img.alt = link.dataset.caption || ''; img.alt = link.dataset.caption || '';
caption.textContent = 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-prev').hidden = group.length < 2;
overlay.querySelector('.lightbox-next').hidden = group.length < 2; overlay.querySelector('.lightbox-next').hidden = group.length < 2;
} }

View file

@ -13,7 +13,11 @@ $user = current_user();
$pdo = db(); $pdo = db();
if ($action === 'create') { 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'] ?? '')); $title = trim((string) ($_POST['title'] ?? ''));
$area = (string) ($_POST['area'] ?? ''); $area = (string) ($_POST['area'] ?? '');
$description = trim((string) ($_POST['description'] ?? '')); $description = trim((string) ($_POST['description'] ?? ''));

106
gallery_comment_action.php Normal file
View file

@ -0,0 +1,106 @@
<?php
/**
* Kommentare unter Galeriebildern: schreiben und loeschen.
* Loeschen duerfen Verfasser, Bild-Besitzer und die Moderation (comments.moderate).
*/
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/member_profile.php';
require_permission('members.view');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
redirect('/members.php');
}
verify_csrf();
$action = (string) ($_POST['action'] ?? '');
$me = current_user();
$pdo = db();
if ($action === 'add') {
$pictureId = (int) ($_POST['picture_id'] ?? 0);
$back = '/member_picture.php?id=' . $pictureId . '#kommentare';
$stmt = $pdo->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');

View file

@ -27,12 +27,21 @@ const ADMIN_LOG_COLORS = [
* @param string $title Kurzbeschreibung mit Emoji, z.B. "👤 Benutzer bearbeitet" * @param string $title Kurzbeschreibung mit Emoji, z.B. "👤 Benutzer bearbeitet"
* @param array<string, scalar|null> $fields Details als Name => Wert (leere Werte werden weggelassen) * @param array<string, scalar|null> $fields Details als Name => Wert (leere Werte werden weggelassen)
* @param string $tone info | success | warning | danger * @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; 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'; $actor = 'Unbekannt';
if ($user) { if ($user) {
$actor = $user['display_name'] !== '' ? $user['display_name'] : $user['username']; $actor = $user['display_name'] !== '' ? $user['display_name'] : $user['username'];

View file

@ -19,7 +19,7 @@ function current_user(): ?array
$stmt = db()->prepare( $stmt = db()->prepare(
'SELECT id, username, display_name, class_name, status, must_change_password, password_login, discord_id, discord_username, '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 = ?' FROM users WHERE id = ?'
); );
$stmt->execute([$_SESSION['user_id']]); $stmt->execute([$_SESSION['user_id']]);
@ -32,6 +32,12 @@ function current_user(): ?array
return null; 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). // Mitgliedschaft und Rollen live mit Discord abgleichen (hoechstens alle paar Minuten).
$check = discord_live_check((int) $row['id']); $check = discord_live_check((int) $row['id']);
$viaDiscord = ($_SESSION['login_method'] ?? '') === 'discord'; $viaDiscord = ($_SESSION['login_method'] ?? '') === 'discord';
@ -63,6 +69,9 @@ function auth_login_session(int $userId, string $method): void
session_regenerate_id(true); session_regenerate_id(true);
$_SESSION['user_id'] = $userId; $_SESSION['user_id'] = $userId;
$_SESSION['login_method'] = $method; $_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]); 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 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 = db()->prepare('SELECT id, password_hash, status, password_login FROM users WHERE username = ?');
$stmt->execute([$username]); $stmt->execute([$username]);
$row = $stmt->fetch(); $row = $stmt->fetch();
if (!$row || !password_verify($password, $row['password_hash'])) { if (!$row || !password_verify($password, $row['password_hash'])) {
login_throttle_fail($username);
return 'Login fehlgeschlagen. Bitte Zugangsdaten prüfen.'; return 'Login fehlgeschlagen. Bitte Zugangsdaten prüfen.';
} }
if ($row['status'] === 'disabled') { if ($row['status'] === 'disabled') {

View file

@ -32,5 +32,10 @@ require_once __DIR__ . '/permissions.php';
require_once __DIR__ . '/schema.php'; require_once __DIR__ . '/schema.php';
require_once __DIR__ . '/settings.php'; require_once __DIR__ . '/settings.php';
require_once __DIR__ . '/admin_log.php'; require_once __DIR__ . '/admin_log.php';
require_once __DIR__ . '/security.php';
require_once __DIR__ . '/moderation.php';
ensure_schema(); ensure_schema();
// Tempolimit fuer abgeschickte Formulare (Spam-/Missbrauchsschutz, siehe includes/security.php)
security_guard_post();

View file

@ -1,10 +0,0 @@
<?php
$pageTitle = 'Zugriff verweigert';
include __DIR__ . '/header.php';
?>
<div class="panel">
<h1>Zugriff verweigert</h1>
<p>Du hast nicht die nötige Berechtigung, um diese Seite aufzurufen.</p>
<p><a class="button" href="/dashboard.php">Zurück zum Dashboard</a></p>
</div>
<?php include __DIR__ . '/footer.php'; ?>

View file

@ -355,3 +355,63 @@ function asset_url(string $path): string
$file = __DIR__ . '/..' . $path; $file = __DIR__ . '/..' . $path;
return $path . (is_file($file) ? '?v=' . filemtime($file) : ''); 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|<\?=|<script|<html|<svg|<iframe|javascript:/i', $raw)) {
return 'Die Datei enthält neben dem Bild noch etwas anderes und wurde abgelehnt.';
}
return move_uploaded_file($tmpPath, $target) || @copy($tmpPath, $target)
? null : 'Das Bild konnte nicht gespeichert werden (Schreibrechte auf dem Server prüfen).';
}
$width = imagesx($source);
$height = imagesy($source);
$scale = $maxSide > 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;
}

View file

@ -42,13 +42,16 @@ $canViewMembers = $currentUser && user_has_permission('members.view');
$canViewWiki = $currentUser && user_has_permission('wiki.view'); $canViewWiki = $currentUser && user_has_permission('wiki.view');
$canViewReports = $currentUser && user_has_permission('reports.view'); $canViewReports = $currentUser && user_has_permission('reports.view');
$canManageBugs = $currentUser && user_has_permission('bugs.manage'); $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. // Offene Fehlermeldungen als Zahl am Menuepunkt.
$bugOpenCount = 0; $bugOpenCount = 0;
if ($canManageBugs) { if ($canManageBugs) {
require_once __DIR__ . '/bugs.php'; require_once __DIR__ . '/bugs.php';
$bugOpenCount = bug_open_count(); $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. // Neue Discord-Anmeldungen, die auf Freischaltung warten - als Zahl am Menuepunkt.
$pendingUserCount = $canViewUsers $pendingUserCount = $canViewUsers
? (int) db()->query("SELECT COUNT(*) FROM users WHERE status = 'pending'")->fetchColumn() ? (int) db()->query("SELECT COUNT(*) FROM users WHERE status = 'pending'")->fetchColumn()
@ -64,10 +67,12 @@ $isMapActive = $currentScript === 'map.php';
$isWarehouseActive = $currentScript === 'warehouse.php'; $isWarehouseActive = $currentScript === 'warehouse.php';
$isContributionsActive = in_array($currentScript, ['contributions.php', 'contributions_award.php'], true); $isContributionsActive = in_array($currentScript, ['contributions.php', 'contributions_award.php'], true);
$isShopActive = in_array($currentScript, ['shop.php', 'shop_orders.php', 'shop_manage.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); $isWikiActive = in_array($currentScript, ['wiki.php', 'wiki_edit.php', 'wiki_history.php'], true);
$isReportsActive = $currentScript === 'reports.php'; $isReportsActive = $currentScript === 'reports.php';
$isBugsActive = $currentScript === 'bugs.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); $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); $isRolesActive = in_array($currentScript, ['roles.php', 'role_form.php', 'role_delete.php'], true);
@ -99,6 +104,9 @@ $pageBackgrounds = [
'role_delete.php' => 'bg-roles', 'role_delete.php' => 'bg-roles',
'reports.php' => 'bg-reports', 'reports.php' => 'bg-reports',
'bugs.php' => 'bg-reports', 'bugs.php' => 'bg-reports',
'audit.php' => 'bg-admin',
'moderation.php' => 'bg-reports',
'member_picture.php' => 'bg-members',
]; ];
$pageBackgroundClass = $pageBackgrounds[$currentScript] ?? ''; $pageBackgroundClass = $pageBackgrounds[$currentScript] ?? '';
@ -247,6 +255,19 @@ $otherFlashes = array_values(array_filter($allFlashes, fn (array $f): bool => ($
<?php endif; ?> <?php endif; ?>
</a> </a>
<?php endif; ?> <?php endif; ?>
<?php if ($canModerate): ?>
<a href="/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>
<?php endif; ?>
<?php if ($canViewAudit): ?>
<a href="/admin/audit.php" class="sidebar-link<?= $isAuditActive ? ' active' : '' ?>" title="Audit-Log">
<?= icon('shield-check') ?><span class="label">Audit-Log</span>
</a>
<?php endif; ?>
<?php endif; ?> <?php endif; ?>
</nav> </nav>
<?php if ($sidebarPoints !== null): ?> <?php if ($sidebarPoints !== null): ?>

View file

@ -56,33 +56,10 @@ function profile_store_upload(?array $file, string $prefix, int $maxSide): strin
$name = $prefix . '_' . bin2hex(random_bytes(8)) . '.' . $ext; $name = $prefix . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
$target = PROFILE_UPLOAD_DIR . $name; $target = PROFILE_UPLOAD_DIR . $name;
[$width, $height] = $info; // Immer neu rechnen (entfernt angehaengten Code und EXIF-Daten), zu grosse Bilder verkleinern
$canResize = $ext !== 'gif' && function_exists('imagecreatefromstring') && max($width, $height) > $maxSide; $error = store_uploaded_image($file['tmp_name'], $target, $info[2], $maxSide);
if ($canResize) { if ($error !== null) {
$source = @imagecreatefromstring((string) file_get_contents($file['tmp_name'])); throw new RuntimeException($error);
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).');
} }
return $name; return $name;
} }
@ -111,3 +88,52 @@ function profile_characters_by_user(?int $userId = null): array
} }
return $byUser; return $byUser;
} }
// ---- Kommentare unter Galeriebildern ----
const GALLERY_COMMENT_MAX = 1000;
/**
* Anzahl der Kommentare je Bild.
*
* @param array<int, int> $galleryIds
* @return array<int, int> 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 => '<a href="' . $m[0] . '" target="_blank" rel="noopener nofollow ugc">' . $m[0] . '</a>',
$html
);
return nl2br($html, false);
}

167
includes/moderation.php Normal file
View file

@ -0,0 +1,167 @@
<?php
declare(strict_types=1);
/**
* Moderation von Galeriebildern und Kommentaren.
*
* Wer darf direkt posten? Alles ist sofort sichtbar - ausser:
* - das Konto ist neu (erste MODERATION_TRUST_DAYS Tage seit Discord-Beitritt bzw. Kontoerstellung),
* - ein Kommentar enthaelt einen Link,
* - die Moderation hat "Alles manuell freigeben" eingeschaltet (z.B. bei einer Spam-Welle).
* Dann wartet der Inhalt in der Freigabe-Liste (moderation.php). Der Verfasser sieht ihn schon,
* alle anderen erst nach der Freigabe.
*
* Melden: Ab MODERATION_REPORT_THRESHOLD Meldungen verschiedener Mitglieder wird ein Inhalt
* automatisch ausgeblendet, bis die Moderation entscheidet.
*/
const MODERATION_TRUST_DAYS = 14;
const MODERATION_REPORT_THRESHOLD = 2;
// Inhaltsarten: Schluessel => [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<int, int> $ids
* @return array<int, true>
*/
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 [];
}
}

29
includes/not_found.php Normal file
View file

@ -0,0 +1,29 @@
<?php
/**
* Inhalt der 404-Seite - ueber show_not_found() (includes/functions.php). Erscheint fuer Seiten,
* die es nicht gibt, UND fuer Seiten ohne Berechtigung: So verraet die Website nicht, welche
* Bereiche (z.B. Admin-Seiten) es gibt.
*/
$pageTitle = 'Seite nicht gefunden';
$notFoundUser = current_user();
$loggedIn = $notFoundUser !== null && $notFoundUser['status'] === 'active';
include __DIR__ . '/header.php';
?>
<div class="panel not-found">
<div class="not-found-code" aria-hidden="true">404</div>
<h1>Hier ist nichts - nicht mal ein Balaur.</h1>
<p class="text-muted">
Die Seite <code><?= e(mb_strimwidth((string) parse_url((string) ($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH), 0, 80, '…')) ?></code>
gibt es nicht - oder du hast (noch) keinen Zugriff darauf. Vielleicht ein Tippfehler oder ein alter Link.
</p>
<div class="actions not-found-actions">
<?php if ($loggedIn): ?>
<a class="button" href="/dashboard.php">Zum Dashboard</a>
<a class="button button-secondary" href="/">Zur Startseite</a>
<?php else: ?>
<a class="button" href="/">Zur Startseite</a>
<a class="button button-secondary" href="/login.php">Anmelden</a>
<?php endif; ?>
</div>
</div>
<?php include __DIR__ . '/footer.php'; ?>

View file

@ -30,6 +30,8 @@ const CORE_PERMISSIONS = [
['key' => 'shop.view', 'description' => 'Lumishop: Angebot ansehen und Gegenstände gegen Lumipunkte beantragen'], ['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' => 'shop.manage', 'description' => 'Lumishop: Kategorien, Gegenstände, Bestand und Preise verwalten, Anträge bewilligen oder ablehnen'],
['key' => 'members.view', 'description' => 'Mitgliederliste einsehen'], ['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.view', 'description' => 'Eingegangene Reports einsehen'],
['key' => 'reports.manage', 'description' => 'Reports löschen/archivieren und die Punkte-Gewichtung verwalten'], ['key' => 'reports.manage', 'description' => 'Reports löschen/archivieren und die Punkte-Gewichtung verwalten'],
['key' => 'bugs.manage', 'description' => 'Fehlermeldungen der Mitglieder einsehen, beantworten und bearbeiten'], ['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 function require_permission(string $key): void
{ {
require_login(); require_login();
// Ohne Berechtigung dieselbe Seite wie fuer nicht vorhandene Seiten (verraet nichts).
if (!user_has_permission($key)) { if (!user_has_permission($key)) {
http_response_code(403); show_not_found();
include __DIR__ . '/forbidden.php';
exit;
} }
} }

View file

@ -11,7 +11,7 @@ declare(strict_types=1);
*/ */
// Hochzaehlen, sobald unten eine Aenderung dazukommt - dann pruefen alle Sitzungen neu. // 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). * 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, user_id INT UNSIGNED NOT NULL,
filename VARCHAR(120) NOT NULL, filename VARCHAR(120) NOT NULL,
caption VARCHAR(150) 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, sort_order INT NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, 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_status (status),
INDEX idx_bug_reports_user (user_id) INDEX idx_bug_reports_user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ) 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, SQL,
]; ];
} }
@ -326,10 +391,19 @@ function schema_column_upgrades(): array
"ALTER TABLE users ADD COLUMN tour_completed_at DATETIME NULL AFTER discord_synced_at", "ALTER TABLE users ADD COLUMN tour_completed_at DATETIME NULL AFTER discord_synced_at",
"UPDATE users SET tour_completed_at = NOW()", "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' => [ 'roles' => [
'discord_role_id' => "ALTER TABLE roles ADD COLUMN discord_role_id BIGINT UNSIGNED NULL AFTER roster_order", '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' => [ 'shop_orders' => [
'requested_quantity' => "ALTER TABLE shop_orders ADD COLUMN requested_quantity INT UNSIGNED NOT NULL DEFAULT 0 AFTER quantity", 'requested_quantity' => "ALTER TABLE shop_orders ADD COLUMN requested_quantity INT UNSIGNED NOT NULL DEFAULT 0 AFTER quantity",
], ],

314
includes/security.php Normal file
View file

@ -0,0 +1,314 @@
<?php
declare(strict_types=1);
/**
* Schutz vor Missbrauch und Audit-Log:
* - Audit-Log: jede Verwaltungsaktion (admin_log) und jedes Sicherheitsereignis landet dauerhaft
* in der Datenbank - unabhaengig davon, ob der Discord-Bot gerade erreichbar ist.
* - Tempolimits pro Konto (Formulare, Uploads, Kommentare, Fehlermeldungen).
* - Login-Bremse nach Fehlversuchen - pro IP bzw. IP + Benutzername, NICHT pro Konto: sonst
* koennte jemand ein bekanntes Konto mit Absicht dauerhaft sperren.
* - Notbremse: Wer in kurzer Zeit auffaellig viel loescht, wird automatisch gesperrt (gehacktes Konto).
* - Sitzungen eines Kontos sofort beenden (users.session_epoch).
*/
// Bereiche im Audit-Log: Schluessel => 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<string, scalar|null> $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]);
}

View file

@ -10,12 +10,15 @@ declare(strict_types=1);
const SETTINGS_DEFAULTS = [ const SETTINGS_DEFAULTS = [
'discord_unlink_allowed' => '1', 'discord_unlink_allowed' => '1',
'contributions_history_public' => '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. // Wer eine Einstellung aendern darf und wohin es danach zurueckgeht.
const SETTINGS_ACCESS = [ const SETTINGS_ACCESS = [
'discord_unlink_allowed' => ['users.edit', '/admin/users.php'], 'discord_unlink_allowed' => ['users.edit', '/admin/users.php'],
'contributions_history_public' => ['contributions.manage', '/contributions.php#verlauf'], 'contributions_history_public' => ['contributions.manage', '/contributions.php#verlauf'],
'moderation_all' => ['comments.moderate', '/moderation.php'],
]; ];
function setting_get(string $key): string function setting_get(string $key): string

View file

@ -6,15 +6,14 @@ require_permission('members.view');
$id = (int) ($_GET['id'] ?? 0); $id = (int) ($_GET['id'] ?? 0);
$stmt = db()->prepare( $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 COALESCE(discord_joined_at, created_at) AS joined_at, discord_joined_at IS NOT NULL AS joined_discord
FROM users WHERE id = ?" FROM users WHERE id = ?"
); );
$stmt->execute([$id]); $stmt->execute([$id]);
$member = $stmt->fetch(); $member = $stmt->fetch();
if (!$member || $member['status'] !== 'active') { if (!$member || $member['status'] !== 'active') {
set_flash('error', 'Dieses Mitglied gibt es nicht (mehr).'); show_not_found();
redirect('/members.php');
} }
$groupStmt = db()->prepare( $groupStmt = db()->prepare(
@ -25,9 +24,15 @@ $groupStmt->execute([$id]);
$groups = array_column($groupStmt->fetchAll(), 'name'); $groups = array_column($groupStmt->fetchAll(), 'name');
$characters = profile_characters_by_user($id)[$id] ?? []; $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]); $galleryStmt->execute([$id]);
$gallery = $galleryStmt->fetchAll(); $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']; $name = $member['display_name'] !== '' ? $member['display_name'] : $member['username'];
$canEdit = profile_can_edit($id); $canEdit = profile_can_edit($id);
@ -111,11 +116,25 @@ include __DIR__ . '/includes/header.php';
<h2>Galerie</h2> <h2>Galerie</h2>
<div class="gallery-grid"> <div class="gallery-grid">
<?php foreach ($gallery as $picture): ?> <?php foreach ($gallery as $picture): ?>
<?php $url = profile_image_url($picture['filename']); ?> <?php
<figure class="gallery-item"> $url = profile_image_url($picture['filename']);
<a href="<?= e($url) ?>" data-lightbox="gallery" data-caption="<?= e((string) $picture['caption']) ?>"> $pictureUrl = '/member_picture.php?id=' . (int) $picture['id'];
$commentCount = $commentCounts[(int) $picture['id']] ?? 0;
?>
<figure class="gallery-item<?= $picture['status'] === 'pending' ? ' is-pending' : '' ?>">
<?php if ($picture['status'] === 'pending'): ?>
<span class="pending-badge" title="<?= e((string) $picture['moderation_note']) ?>">Wartet auf Freigabe</span>
<?php endif; ?>
<a href="<?= e($url) ?>" data-lightbox="gallery" data-caption="<?= e((string) $picture['caption']) ?>"
<?php if ($commentsEnabled): ?>data-comments-url="<?= e($pictureUrl . '#kommentare') ?>" data-comments-count="<?= $commentCount ?>"<?php endif; ?>>
<img src="<?= e($url) ?>" alt="<?= e($picture['caption'] ?: 'Bild von ' . $name) ?>" loading="lazy"> <img src="<?= e($url) ?>" alt="<?= e($picture['caption'] ?: 'Bild von ' . $name) ?>" loading="lazy">
</a> </a>
<?php if ($commentsEnabled): ?>
<a class="gallery-comment-badge<?= $commentCount > 0 ? ' has-comments' : '' ?>" href="<?= e($pictureUrl . '#kommentare') ?>"
title="<?= $commentCount > 0 ? $commentCount . ' ' . ($commentCount === 1 ? 'Kommentar' : 'Kommentare') . ' ansehen' : 'Kommentieren' ?>">
<?= icon('message') ?><?= $commentCount > 0 ? ' ' . $commentCount : '' ?>
</a>
<?php endif; ?>
<?php if (!empty($picture['caption'])): ?><figcaption><?= e($picture['caption']) ?></figcaption><?php endif; ?> <?php if (!empty($picture['caption'])): ?><figcaption><?= e($picture['caption']) ?></figcaption><?php endif; ?>
</figure> </figure>
<?php endforeach; ?> <?php endforeach; ?>

View file

@ -150,9 +150,16 @@ switch ($action) {
'tmp_name' => $_FILES['images']['tmp_name'][$i] ?? '', 'tmp_name' => $_FILES['images']['tmp_name'][$i] ?? '',
]; ];
} }
$uploadCount = count(array_filter($files, static fn (array $f): bool => $f['error'] !== UPLOAD_ERR_NO_FILE));
if ($uploadCount > 0 && !security_throttle('upload', $uploadCount)) {
set_flash('error', 'Du hast in den letzten Minuten schon sehr viele Bilder hochgeladen. Bitte warte ein paar Minuten.');
redirect($back);
}
$added = 0; $added = 0;
$errors = []; $errors = [];
$insert = $pdo->prepare('INSERT INTO member_gallery (user_id, filename, caption, sort_order) VALUES (?, ?, ?, ?)'); // Neue Mitglieder, Links in der Bildunterschrift oder "Alles manuell": erst nach Freigabe sichtbar
[$status, $moderationNote] = moderation_initial_status('picture', $caption);
$insert = $pdo->prepare('INSERT INTO member_gallery (user_id, filename, caption, status, moderation_note, sort_order) VALUES (?, ?, ?, ?, ?, ?)');
foreach ($files as $file) { foreach ($files as $file) {
if ($file['error'] === UPLOAD_ERR_NO_FILE) { if ($file['error'] === UPLOAD_ERR_NO_FILE) {
continue; continue;
@ -164,14 +171,15 @@ switch ($action) {
try { try {
$filename = profile_store_upload($file, 'gal' . $userId, 1920); $filename = profile_store_upload($file, 'gal' . $userId, 1920);
$order += 10; $order += 10;
$insert->execute([$userId, $filename, $caption !== '' ? $caption : null, $order]); $insert->execute([$userId, $filename, $caption !== '' ? $caption : null, $status, $moderationNote, $order]);
$added++; $added++;
} catch (RuntimeException $e) { } catch (RuntimeException $e) {
$errors[] = $e->getMessage(); $errors[] = $e->getMessage();
} }
} }
if ($added > 0) { if ($added > 0) {
set_flash('success', $added === 1 ? 'Bild hochgeladen.' : $added . ' Bilder hochgeladen.'); set_flash('success', ($added === 1 ? 'Bild hochgeladen.' : $added . ' Bilder hochgeladen.')
. ($status === 'pending' ? ' Sichtbar für alle nach einer kurzen Freigabe durch die Moderation.' : ''));
} }
foreach (array_unique($errors) as $error) { foreach (array_unique($errors) as $error) {
set_flash('error', $error); set_flash('error', $error);
@ -179,10 +187,24 @@ switch ($action) {
$modLog($added . ' Bild(er) in die Galerie hochgeladen'); $modLog($added . ' Bild(er) in die Galerie hochgeladen');
redirect($back); redirect($back);
case 'gallery_comments_toggle':
$enabled = !empty($_POST['enabled']) ? 1 : 0;
$pdo->prepare('UPDATE users SET gallery_comments_enabled = ? WHERE id = ?')->execute([$enabled, $userId]);
$modLog($enabled ? 'Kommentare unter den Bildern eingeschaltet' : 'Kommentare unter den Bildern abgeschaltet');
set_flash('success', $enabled ? 'Kommentare unter deinen Bildern sind eingeschaltet.' : 'Kommentare unter deinen Bildern sind abgeschaltet - vorhandene werden ausgeblendet.');
redirect($back);
case 'gallery_update': case 'gallery_update':
$caption = mb_substr(trim((string) ($_POST['caption'] ?? '')), 0, 150); $caption = mb_substr(trim((string) ($_POST['caption'] ?? '')), 0, 150);
$pdo->prepare('UPDATE member_gallery SET caption = ? WHERE id = ? AND user_id = ?') $pdo->prepare('UPDATE member_gallery SET caption = ? WHERE id = ? AND user_id = ?')
->execute([$caption !== '' ? $caption : null, (int) ($_POST['picture_id'] ?? 0), $userId]); ->execute([$caption !== '' ? $caption : null, (int) ($_POST['picture_id'] ?? 0), $userId]);
// Nachtraeglich ein Link in die Unterschrift? Dann erst wieder nach Freigabe sichtbar.
if (!moderation_can() && moderation_has_link($caption)) {
$pdo->prepare("UPDATE member_gallery SET status = 'pending', moderation_note = ? WHERE id = ? AND user_id = ?")
->execute(['Link in der Bildunterschrift', (int) ($_POST['picture_id'] ?? 0), $userId]);
set_flash('success', 'Bildunterschrift gespeichert. Wegen des Links ist das Bild bis zur Freigabe nur für dich sichtbar.');
redirect($back);
}
set_flash('success', 'Bildunterschrift gespeichert.'); set_flash('success', 'Bildunterschrift gespeichert.');
redirect($back); redirect($back);
@ -193,6 +215,7 @@ switch ($action) {
if ($filename !== false) { if ($filename !== false) {
$pdo->prepare('DELETE FROM member_gallery WHERE id = ?')->execute([(int) ($_POST['picture_id'] ?? 0)]); $pdo->prepare('DELETE FROM member_gallery WHERE id = ?')->execute([(int) ($_POST['picture_id'] ?? 0)]);
profile_delete_file((string) $filename); profile_delete_file((string) $filename);
moderation_clear_reports('picture', (int) ($_POST['picture_id'] ?? 0));
$modLog('Bild aus der Galerie gelöscht'); $modLog('Bild aus der Galerie gelöscht');
set_flash('success', 'Bild gelöscht.'); set_flash('success', 'Bild gelöscht.');
} }

View file

@ -8,7 +8,7 @@ if (!profile_can_edit($id)) {
set_flash('error', 'Du darfst nur deine eigene Profilseite bearbeiten.'); set_flash('error', 'Du darfst nur deine eigene Profilseite bearbeiten.');
redirect('/member.php?id=' . $id); redirect('/member.php?id=' . $id);
} }
$stmt = db()->prepare("SELECT id, username, display_name, profile_bio, status FROM users WHERE id = ?"); $stmt = db()->prepare("SELECT id, username, display_name, profile_bio, gallery_comments_enabled, status FROM users WHERE id = ?");
$stmt->execute([$id]); $stmt->execute([$id]);
$member = $stmt->fetch(); $member = $stmt->fetch();
if (!$member) { if (!$member) {
@ -145,6 +145,16 @@ include __DIR__ . '/includes/header.php';
<div class="panel"> <div class="panel">
<h2>Galerie</h2> <h2>Galerie</h2>
<form class="settings-toggle" method="post" action="/member_action.php">
<?= csrf_field() ?>
<input type="hidden" name="action" value="gallery_comments_toggle">
<input type="hidden" name="user_id" value="<?= $id ?>">
<label>
<input type="checkbox" name="enabled" value="1" <?= !empty($member['gallery_comments_enabled']) ? 'checked' : '' ?> onchange="this.form.submit()">
Andere Mitglieder dürfen meine Bilder kommentieren
</label>
<noscript><button type="submit" class="button-secondary button-small">Speichern</button></noscript>
</form>
<?php if (count($gallery) < PROFILE_MAX_GALLERY): ?> <?php if (count($gallery) < PROFILE_MAX_GALLERY): ?>
<form method="post" action="/member_action.php" enctype="multipart/form-data" class="gallery-upload"> <form method="post" action="/member_action.php" enctype="multipart/form-data" class="gallery-upload">
<?= csrf_field() ?> <?= csrf_field() ?>
@ -162,7 +172,10 @@ include __DIR__ . '/includes/header.php';
<?php if (!empty($gallery)): ?> <?php if (!empty($gallery)): ?>
<div class="gallery-grid gallery-edit-grid"> <div class="gallery-grid gallery-edit-grid">
<?php foreach ($gallery as $picture): ?> <?php foreach ($gallery as $picture): ?>
<figure class="gallery-item"> <figure class="gallery-item<?= ($picture['status'] ?? 'visible') === 'pending' ? ' is-pending' : '' ?>">
<?php if (($picture['status'] ?? 'visible') === 'pending'): ?>
<span class="pending-badge" title="<?= e((string) $picture['moderation_note']) ?>">Wartet auf Freigabe</span>
<?php endif; ?>
<img src="<?= e(profile_image_url($picture['filename'])) ?>" alt="" loading="lazy"> <img src="<?= e(profile_image_url($picture['filename'])) ?>" alt="" loading="lazy">
<form method="post" action="/member_action.php" class="gallery-item-form"> <form method="post" action="/member_action.php" class="gallery-item-form">
<?= csrf_field() ?> <?= csrf_field() ?>

177
member_picture.php Normal file
View file

@ -0,0 +1,177 @@
<?php
/**
* Ein Bild aus der Galerie eines Mitglieds in gross, mit Blaettern und Kommentaren darunter.
*/
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/member_profile.php';
require_permission('members.view');
$pictureId = (int) ($_GET['id'] ?? 0);
$stmt = db()->prepare(
"SELECT g.*, g.status AS picture_status, u.username, u.display_name, u.avatar_filename, 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();
$me = current_user();
$isModerator = moderation_can();
$isOwner = $picture && (int) $me['id'] === (int) $picture['user_id'];
// Noch nicht freigegebene Bilder sehen nur der Besitzer und die Moderation.
if (!$picture || $picture['status'] !== 'active' || ($picture['picture_status'] === 'pending' && !$isOwner && !$isModerator)) {
show_not_found();
}
$ownerId = (int) $picture['user_id'];
$ownerName = $picture['display_name'] !== '' ? $picture['display_name'] : $picture['username'];
$commentsEnabled = !empty($picture['gallery_comments_enabled']);
// Vorheriges / naechstes Bild derselben Galerie (Reihenfolge wie auf der Profilseite)
$ids = db()->prepare('SELECT id FROM member_gallery WHERE user_id = ?' . ($isOwner || $isModerator ? '' : " AND status = 'visible'") . ' ORDER BY sort_order, id');
$ids->execute([$ownerId]);
$galleryIds = array_map('intval', $ids->fetchAll(PDO::FETCH_COLUMN));
$position = array_search($pictureId, $galleryIds, true);
$prevId = $position > 0 ? $galleryIds[$position - 1] : null;
$nextId = $position !== false && $position < count($galleryIds) - 1 ? $galleryIds[$position + 1] : null;
$comments = [];
if ($commentsEnabled) {
$commentStmt = db()->prepare(
"SELECT c.id, c.author_id, c.body, c.created_at, c.status AS comment_status, c.moderation_note,
u.username, u.display_name, u.avatar_filename, u.status
FROM gallery_comments c JOIN users u ON u.id = c.author_id
WHERE c.gallery_id = ? AND (c.status = 'visible' OR c.author_id = ? OR ?) ORDER BY c.created_at, c.id"
);
$commentStmt->execute([$pictureId, (int) $me['id'], $isModerator ? 1 : 0]);
$comments = $commentStmt->fetchAll();
}
// Schon gemeldet? (Knopf dann ausgegraut)
$reportedPicture = !empty(moderation_my_reports('picture', [$pictureId]));
$reportedComments = moderation_my_reports('comment', array_map('intval', array_column($comments, 'id')));
/** Melden-Knopf (fragt nach einem Grund) bzw. Freigeben-Knopf fuer die Moderation. */
$reportButton = static function (string $type, int $id, bool $already): string {
if ($already) {
return '<span class="report-done" title="Du hast das gemeldet - danke!">' . icon('flag') . ' Gemeldet</span>';
}
return '<form class="inline-form" method="post" action="/moderation_action.php" '
. 'onsubmit="var r = prompt(&quot;Was ist daran nicht in Ordnung? (optional)&quot;); if (r === null) return false; this.reason.value = r; return true;">'
. csrf_field()
. '<input type="hidden" name="action" value="report"><input type="hidden" name="type" value="' . $type . '">'
. '<input type="hidden" name="id" value="' . $id . '"><input type="hidden" name="reason" value="">'
. '<button type="submit" class="icon-button report-button" title="Melden" aria-label="Melden">' . icon('flag') . '</button></form>';
};
$approveButton = static function (string $type, int $id): string {
return '<form class="inline-form" method="post" action="/moderation_action.php">' . csrf_field()
. '<input type="hidden" name="action" value="approve"><input type="hidden" name="type" value="' . $type . '">'
. '<input type="hidden" name="id" value="' . $id . '"><input type="hidden" name="back" value="picture">'
. '<button type="submit" class="button-success button-small">Freigeben</button></form>';
};
$url = profile_image_url($picture['filename']);
$pageTitle = ($picture['caption'] ?: 'Bild') . ' - ' . $ownerName;
include __DIR__ . '/includes/header.php';
?>
<div class="panel picture-view">
<div class="picture-view-head">
<a class="picture-owner" href="/member.php?id=<?= $ownerId ?>">
<?= avatar_html(['id' => $ownerId, 'username' => $picture['username'], 'display_name' => $picture['display_name'], 'avatar_filename' => $picture['avatar_filename']], 36) ?>
<span>Galerie von <strong><?= e($ownerName) ?></strong></span>
</a>
<div class="picture-view-tools">
<span class="text-muted"><?= $position !== false ? ($position + 1) . ' / ' . count($galleryIds) : '' ?></span>
<?php if (!$isOwner): ?><?= $reportButton('picture', $pictureId, $reportedPicture) ?><?php endif; ?>
</div>
</div>
<?php if ($picture['picture_status'] === 'pending'): ?>
<div class="pending-notice">
<span><strong>Wartet auf Freigabe</strong> - nur <?= $isOwner ? 'du und die Moderation sehen' : 'der Besitzer und die Moderation sehen' ?> dieses Bild.
<?php if (!empty($picture['moderation_note'])): ?><span class="text-muted">(<?= e((string) $picture['moderation_note']) ?>)</span><?php endif; ?></span>
<?php if ($isModerator): ?><?= $approveButton('picture', $pictureId) ?><?php endif; ?>
</div>
<?php endif; ?>
<figure class="picture-view-image">
<?php if ($prevId !== null): ?>
<a class="picture-nav picture-nav-prev" href="/member_picture.php?id=<?= $prevId ?>" title="Vorheriges Bild (←)" aria-label="Vorheriges Bild">‹</a>
<?php endif; ?>
<a href="<?= e($url) ?>" target="_blank" rel="noopener" title="Originalgröße öffnen">
<img src="<?= e($url) ?>" alt="<?= e($picture['caption'] ?: 'Bild von ' . $ownerName) ?>">
</a>
<?php if ($nextId !== null): ?>
<a class="picture-nav picture-nav-next" href="/member_picture.php?id=<?= $nextId ?>" title="Nächstes Bild (→)" aria-label="Nächstes Bild">›</a>
<?php endif; ?>
<?php if (!empty($picture['caption'])): ?><figcaption><?= e($picture['caption']) ?></figcaption><?php endif; ?>
</figure>
</div>
<div class="panel picture-comments" id="kommentare">
<h2><?= icon('message') ?> Kommentare<?= $commentsEnabled && $comments ? ' <span class="chip-count">' . count($comments) . '</span>' : '' ?></h2>
<?php if (!$commentsEnabled): ?>
<p class="text-muted"><?= $isOwner ? 'Du hast Kommentare unter deinen Bildern abgeschaltet. Einschalten kannst du sie beim Bearbeiten deiner Profilseite.' : e($ownerName) . ' hat Kommentare unter den eigenen Bildern abgeschaltet.' ?></p>
<?php else: ?>
<?php if (empty($comments)): ?>
<p class="text-muted">Noch keine Kommentare - schreib den ersten.</p>
<?php else: ?>
<ol class="comment-list">
<?php foreach ($comments as $comment): ?>
<?php $authorName = $comment['display_name'] !== '' ? $comment['display_name'] : $comment['username']; ?>
<li class="comment<?= $comment['comment_status'] === 'pending' ? ' is-pending' : '' ?>" id="kommentar-<?= (int) $comment['id'] ?>">
<?= avatar_html(['id' => $comment['author_id'], 'username' => $comment['username'], 'display_name' => $comment['display_name'], 'avatar_filename' => $comment['avatar_filename']], 36) ?>
<div class="comment-body">
<div class="comment-head">
<?php if ($comment['status'] === 'active'): ?>
<a href="/member.php?id=<?= (int) $comment['author_id'] ?>"><strong><?= e($authorName) ?></strong></a>
<?php else: ?>
<strong><?= e($authorName) ?></strong>
<?php endif; ?>
<?php if ((int) $comment['author_id'] === $ownerId): ?><span class="badge">Galerie-Besitzer</span><?php endif; ?>
<?php if ($comment['comment_status'] === 'pending'): ?>
<span class="pending-badge-inline" title="<?= e((string) $comment['moderation_note']) ?>">Wartet auf Freigabe</span>
<?php if ($isModerator): ?><?= $approveButton('comment', (int) $comment['id']) ?><?php endif; ?>
<?php endif; ?>
<time class="text-muted" datetime="<?= e(date('c', strtotime((string) $comment['created_at']))) ?>"><?= e(date('d.m.Y H:i', strtotime((string) $comment['created_at']))) ?></time>
<?php if ((int) $comment['author_id'] !== (int) $me['id']): ?>
<span class="comment-report"><?= $reportButton('comment', (int) $comment['id'], isset($reportedComments[(int) $comment['id']])) ?></span>
<?php endif; ?>
<?php if (gallery_comment_can_delete($comment, $ownerId)): ?>
<form class="inline-form comment-delete" method="post" action="/gallery_comment_action.php" onsubmit="return confirm('Diesen Kommentar löschen?');">
<?= csrf_field() ?>
<input type="hidden" name="action" value="delete">
<input type="hidden" name="comment_id" value="<?= (int) $comment['id'] ?>">
<button type="submit" class="icon-button icon-button-danger" title="Kommentar löschen" aria-label="Kommentar löschen"><?= icon('trash') ?></button>
</form>
<?php endif; ?>
</div>
<p><?= gallery_comment_html((string) $comment['body']) ?></p>
</div>
</li>
<?php endforeach; ?>
</ol>
<?php endif; ?>
<form class="comment-form" method="post" action="/gallery_comment_action.php">
<?= csrf_field() ?>
<input type="hidden" name="action" value="add">
<input type="hidden" name="picture_id" value="<?= $pictureId ?>">
<?= avatar_html($me, 36) ?>
<div class="comment-form-body">
<textarea name="body" rows="2" maxlength="<?= GALLERY_COMMENT_MAX ?>" required placeholder="Kommentar schreiben …" aria-label="Kommentar"></textarea>
<div class="comment-form-actions">
<span class="field-hint">Nur Text, Links werden klickbar. Bitte freundlich bleiben.</span>
<button type="submit" class="button-small">Senden</button>
</div>
</div>
</form>
<?php endif; ?>
</div>
<script>
// Pfeiltasten blaettern (nicht beim Schreiben)
document.addEventListener('keydown', function (e) {
if (/^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement.tagName)) return;
var selector = { ArrowLeft: '.picture-nav-prev', ArrowRight: '.picture-nav-next' }[e.key];
var link = selector && document.querySelector(selector);
if (link) location.href = link.href;
});
</script>
<?php include __DIR__ . '/includes/footer.php'; ?>

190
moderation.php Normal file
View file

@ -0,0 +1,190 @@
<?php
/**
* Moderation: Freigabe-Liste (wartende Bilder und Kommentare) und gemeldete Inhalte.
*/
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/member_profile.php';
require_permission('comments.moderate');
$pdo = db();
$name = "COALESCE(NULLIF(u.display_name, ''), u.username)";
$pendingPictures = $pdo->query(
"SELECT g.id, g.filename, g.caption, g.moderation_note, g.created_at, g.user_id, $name AS author
FROM member_gallery g JOIN users u ON u.id = g.user_id WHERE g.status = 'pending' ORDER BY g.created_at"
)->fetchAll();
$pendingComments = $pdo->query(
"SELECT c.id, c.body, c.moderation_note, c.created_at, c.author_id, c.gallery_id, g.filename, $name AS author
FROM gallery_comments c JOIN users u ON u.id = c.author_id JOIN member_gallery g ON g.id = c.gallery_id
WHERE c.status = 'pending' ORDER BY c.created_at"
)->fetchAll();
// Gemeldet, aber (noch) sichtbar - unter der Schwelle fuers automatische Ausblenden
$reportedPictures = $pdo->query(
"SELECT g.id, g.filename, g.caption, g.created_at, g.user_id, $name AS author
FROM member_gallery g JOIN users u ON u.id = g.user_id
WHERE g.status = 'visible' AND EXISTS (SELECT 1 FROM content_reports r WHERE r.content_type = 'picture' AND r.content_id = g.id)"
)->fetchAll();
$reportedComments = $pdo->query(
"SELECT c.id, c.body, c.created_at, c.author_id, c.gallery_id, g.filename, $name AS author
FROM gallery_comments c JOIN users u ON u.id = c.author_id JOIN member_gallery g ON g.id = c.gallery_id
WHERE c.status = 'visible' AND EXISTS (SELECT 1 FROM content_reports r WHERE r.content_type = 'comment' AND r.content_id = c.id)"
)->fetchAll();
// Alle Meldungen mit Grund und Melder, gruppiert nach Inhalt
$reports = [];
foreach ($pdo->query(
"SELECT r.content_type, r.content_id, r.reason, r.created_at, $name AS reporter
FROM content_reports r JOIN users u ON u.id = r.reporter_id ORDER BY r.created_at"
)->fetchAll() as $row) {
$reports[$row['content_type'] . ':' . $row['content_id']][] = $row;
}
$pendingTotal = count($pendingPictures) + count($pendingComments);
$reportedTotal = count($reportedPictures) + count($reportedComments);
/** Knoepfe fuer einen Inhalt. */
$actions = static function (string $type, int $id, array $which): string {
$labels = [
'approve' => ['Freigeben', 'button-success'],
'hide' => ['Ausblenden', 'button-secondary'],
'dismiss' => ['Meldungen verwerfen', 'button-secondary'],
'delete' => ['Löschen', 'button-danger'],
];
$html = '<div class="moderation-actions">';
foreach ($which as $action) {
[$label, $class] = $labels[$action];
$confirm = $action === 'delete' ? ' onsubmit="return confirm(&quot;Endgültig löschen?&quot;);"' : '';
$html .= '<form class="inline-form" method="post" action="/moderation_action.php"' . $confirm . '>' . csrf_field()
. '<input type="hidden" name="action" value="' . $action . '"><input type="hidden" name="type" value="' . $type . '">'
. '<input type="hidden" name="id" value="' . $id . '">'
. '<button type="submit" class="button-small ' . $class . '">' . $label . '</button></form>';
}
return $html . '</div>';
};
/** Meldungen zu einem Inhalt als kleine Liste. */
$reportList = static function (string $type, int $id) use ($reports): string {
$list = $reports[$type . ':' . $id] ?? [];
if (!$list) {
return '';
}
$html = '<ul class="moderation-reports">';
foreach ($list as $report) {
$html .= '<li>' . icon('flag') . ' <strong>' . e((string) $report['reporter']) . '</strong>'
. ($report['reason'] ? ': ' . e((string) $report['reason']) : ' <span class="text-muted">(ohne Grund)</span>')
. ' <span class="text-muted">· ' . e(date('d.m.Y H:i', strtotime((string) $report['created_at']))) . '</span></li>';
}
return $html . '</ul>';
};
$pageTitle = 'Moderation';
$containerWide = true;
include __DIR__ . '/includes/header.php';
?>
<div class="panel">
<h1>Moderation</h1>
<p class="text-muted">
Bilder und Kommentare neuer Mitglieder (erste <?= MODERATION_TRUST_DAYS ?> Tage), Beiträge mit Links und alles,
was <?= MODERATION_REPORT_THRESHOLD ?>-mal gemeldet wurde, warten hier auf eine Entscheidung. Bis dahin sieht sie
nur der Verfasser. Alle Entscheidungen landen im Audit-Log.
</p>
<form class="settings-toggle" method="post" action="/admin/settings_action.php">
<?= csrf_field() ?>
<input type="hidden" name="setting" value="moderation_all">
<label>
<input type="checkbox" name="value" value="1" <?= moderation_all_manual() ? 'checked' : '' ?> onchange="this.form.submit()">
<span><strong>Alles manuell freigeben</strong> - jedes neue Bild und jeder Kommentar wartet auf Freigabe (z.B. bei einer Spam-Welle)</span>
</label>
<noscript><button type="submit" class="button-secondary button-small">Speichern</button></noscript>
</form>
</div>
<div class="panel">
<h2>Wartet auf Freigabe <span class="chip-count"><?= $pendingTotal ?></span></h2>
<?php if ($pendingTotal === 0): ?>
<p class="text-muted">Alles erledigt - nichts wartet auf Freigabe. 🎉</p>
<?php endif; ?>
<?php if ($pendingPictures): ?>
<div class="moderation-grid">
<?php foreach ($pendingPictures as $picture): ?>
<div class="moderation-card">
<a href="/member_picture.php?id=<?= (int) $picture['id'] ?>" class="moderation-thumb">
<img src="<?= e(profile_image_url($picture['filename'])) ?>" alt="" loading="lazy">
</a>
<div class="moderation-body">
<div class="moderation-meta">
<span class="badge">Bild</span>
<a href="/member.php?id=<?= (int) $picture['user_id'] ?>"><strong><?= e((string) $picture['author']) ?></strong></a>
<span class="text-muted"><?= e(date('d.m.Y H:i', strtotime((string) $picture['created_at']))) ?></span>
</div>
<?php if (!empty($picture['caption'])): ?><p><?= e((string) $picture['caption']) ?></p><?php endif; ?>
<?php if (!empty($picture['moderation_note'])): ?><p class="moderation-reason">Grund: <?= e((string) $picture['moderation_note']) ?></p><?php endif; ?>
<?= $reportList('picture', (int) $picture['id']) ?>
<?= $actions('picture', (int) $picture['id'], ['approve', 'delete']) ?>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php foreach ($pendingComments as $comment): ?>
<div class="moderation-card moderation-comment">
<a href="/member_picture.php?id=<?= (int) $comment['gallery_id'] ?>#kommentar-<?= (int) $comment['id'] ?>" class="moderation-thumb moderation-thumb-small" title="Zum Bild">
<img src="<?= e(profile_image_url($comment['filename'])) ?>" alt="" loading="lazy">
</a>
<div class="moderation-body">
<div class="moderation-meta">
<span class="badge">Kommentar</span>
<a href="/member.php?id=<?= (int) $comment['author_id'] ?>"><strong><?= e((string) $comment['author']) ?></strong></a>
<span class="text-muted"><?= e(date('d.m.Y H:i', strtotime((string) $comment['created_at']))) ?></span>
</div>
<p class="moderation-text"><?= nl2br(e((string) $comment['body']), false) ?></p>
<?php if (!empty($comment['moderation_note'])): ?><p class="moderation-reason">Grund: <?= e((string) $comment['moderation_note']) ?></p><?php endif; ?>
<?= $reportList('comment', (int) $comment['id']) ?>
<?= $actions('comment', (int) $comment['id'], ['approve', 'delete']) ?>
</div>
</div>
<?php endforeach; ?>
</div>
<?php if ($reportedTotal > 0): ?>
<div class="panel">
<h2>Gemeldet, aber noch sichtbar <span class="chip-count"><?= $reportedTotal ?></span></h2>
<p class="text-muted">Weniger als <?= MODERATION_REPORT_THRESHOLD ?> Meldungen - noch nicht automatisch ausgeblendet.</p>
<?php foreach ($reportedPictures as $picture): ?>
<div class="moderation-card moderation-comment">
<a href="/member_picture.php?id=<?= (int) $picture['id'] ?>" class="moderation-thumb moderation-thumb-small">
<img src="<?= e(profile_image_url($picture['filename'])) ?>" alt="" loading="lazy">
</a>
<div class="moderation-body">
<div class="moderation-meta">
<span class="badge">Bild</span>
<a href="/member.php?id=<?= (int) $picture['user_id'] ?>"><strong><?= e((string) $picture['author']) ?></strong></a>
<?php if (!empty($picture['caption'])): ?><span><?= e((string) $picture['caption']) ?></span><?php endif; ?>
</div>
<?= $reportList('picture', (int) $picture['id']) ?>
<?= $actions('picture', (int) $picture['id'], ['hide', 'dismiss', 'delete']) ?>
</div>
</div>
<?php endforeach; ?>
<?php foreach ($reportedComments as $comment): ?>
<div class="moderation-card moderation-comment">
<a href="/member_picture.php?id=<?= (int) $comment['gallery_id'] ?>#kommentar-<?= (int) $comment['id'] ?>" class="moderation-thumb moderation-thumb-small" title="Zum Bild">
<img src="<?= e(profile_image_url($comment['filename'])) ?>" alt="" loading="lazy">
</a>
<div class="moderation-body">
<div class="moderation-meta">
<span class="badge">Kommentar</span>
<a href="/member.php?id=<?= (int) $comment['author_id'] ?>"><strong><?= e((string) $comment['author']) ?></strong></a>
</div>
<p class="moderation-text"><?= nl2br(e((string) $comment['body']), false) ?></p>
<?= $reportList('comment', (int) $comment['id']) ?>
<?= $actions('comment', (int) $comment['id'], ['hide', 'dismiss', 'delete']) ?>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php include __DIR__ . '/includes/footer.php'; ?>

104
moderation_action.php Normal file
View file

@ -0,0 +1,104 @@
<?php
/**
* Moderation von Galeriebildern und Kommentaren:
* - report: jedes Mitglied meldet einen Inhalt (ab 2 Meldungen automatisch ausgeblendet)
* - approve: freigeben (sichtbar fuer alle, Meldungen verworfen)
* - hide: ausblenden (zurueck in die Freigabe-Liste)
* - dismiss: Meldungen verwerfen, Inhalt bleibt sichtbar
* - delete: endgueltig loeschen
*/
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/member_profile.php';
require_permission('members.view');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
redirect('/members.php');
}
verify_csrf();
$action = (string) ($_POST['action'] ?? '');
$type = (string) ($_POST['type'] ?? '');
$id = (int) ($_POST['id'] ?? 0);
if (!isset(MODERATION_TYPES[$type]) || $id <= 0) {
set_flash('error', 'Unbekannter Inhalt.');
redirect('/members.php');
}
[$table, $label] = MODERATION_TYPES[$type];
$pdo = db();
// Wohin danach: zur Bildseite (von dort aus gemeldet/freigegeben) oder zur Freigabe-Liste
$pictureId = $id;
if ($type === 'comment') {
$stmt = $pdo->prepare('SELECT gallery_id FROM gallery_comments WHERE id = ?');
$stmt->execute([$id]);
$pictureId = (int) $stmt->fetchColumn();
}
$back = ($action === 'report' || ($_POST['back'] ?? '') === 'picture')
? '/member_picture.php?id=' . $pictureId . ($type === 'comment' ? '#kommentare' : '')
: '/moderation.php';
if ($action === 'report') {
if (!security_throttle('report')) {
set_flash('error', 'Du hast in den letzten Minuten schon viel gemeldet. Bitte warte kurz.');
redirect($back);
}
$reason = mb_substr(trim((string) ($_POST['reason'] ?? '')), 0, 255);
set_flash('success', moderation_report($type, $id, $reason));
redirect($back);
}
// Ab hier nur die Moderation
if (!moderation_can()) {
show_not_found();
}
$owner = $type === 'picture' ? 'user_id' : 'author_id';
$stmt = $pdo->prepare("SELECT * , $owner AS owner_id FROM $table WHERE id = ?");
$stmt->execute([$id]);
$content = $stmt->fetch();
if (!$content) {
set_flash('error', 'Diesen Inhalt gibt es nicht (mehr).');
redirect('/moderation.php');
}
$logFields = [
'Von' => admin_log_user((int) $content['owner_id']),
$type === 'picture' ? 'Bildunterschrift' : 'Text' => mb_strimwidth((string) ($type === 'picture' ? ($content['caption'] ?? '') : $content['body']), 0, 300, '…'),
'Grund der Prüfung' => (string) ($content['moderation_note'] ?? ''),
];
switch ($action) {
case 'approve':
$pdo->prepare("UPDATE $table SET status = 'visible', moderation_note = NULL WHERE id = ?")->execute([$id]);
moderation_clear_reports($type, $id);
admin_log('✅ ' . $label . ' freigegeben', $logFields, 'success', 'members');
set_flash('success', $label . ' freigegeben - jetzt für alle sichtbar.');
break;
case 'hide':
$pdo->prepare("UPDATE $table SET status = 'pending', moderation_note = ? WHERE id = ?")
->execute(['Von der Moderation ausgeblendet', $id]);
admin_log('🙈 ' . $label . ' ausgeblendet', $logFields, 'warning', 'members');
set_flash('success', $label . ' ausgeblendet.');
break;
case 'dismiss':
moderation_clear_reports($type, $id);
admin_log('👌 Meldungen verworfen (' . $label . ' bleibt)', $logFields, 'info', 'members');
set_flash('success', 'Meldungen verworfen.');
break;
case 'delete':
$pdo->prepare("DELETE FROM $table WHERE id = ?")->execute([$id]);
moderation_clear_reports($type, $id);
if ($type === 'picture') {
profile_delete_file((string) $content['filename']); // Kommentare fallen per ON DELETE CASCADE weg
}
admin_log('🗑️ ' . $label . ' gelöscht (Moderation)', $logFields, 'warning', 'members');
set_flash('success', $label . ' gelöscht.');
$back = '/moderation.php';
break;
default:
set_flash('error', 'Unbekannte Aktion.');
}
redirect($back);

View file

@ -62,7 +62,9 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
} else { } else {
$filename = 'user' . $user['id'] . '_' . bin2hex(random_bytes(8)) . '.' . image_type_to_extension($imageInfo[2], false); $filename = 'user' . $user['id'] . '_' . bin2hex(random_bytes(8)) . '.' . image_type_to_extension($imageInfo[2], false);
if (move_uploaded_file($file['tmp_name'], $avatarUploadDir . $filename)) { // Neu rechnen (entfernt angehaengten Code/EXIF) und auf 512 px begrenzen
$storeError = store_uploaded_image($file['tmp_name'], $avatarUploadDir . $filename, $imageInfo[2], 512);
if ($storeError === null) {
$oldFilename = $user['avatar_filename'] ?? null; $oldFilename = $user['avatar_filename'] ?? null;
// Eigenes Bild: nicht mehr vom Discord-Profilbild ueberschreiben lassen. // Eigenes Bild: nicht mehr vom Discord-Profilbild ueberschreiben lassen.
db()->prepare('UPDATE users SET avatar_filename = ?, avatar_sync = 0, discord_avatar = NULL WHERE id = ?') db()->prepare('UPDATE users SET avatar_filename = ?, avatar_sync = 0, discord_avatar = NULL WHERE id = ?')
@ -73,7 +75,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
set_flash('success', 'Profilbild wurde aktualisiert.'); set_flash('success', 'Profilbild wurde aktualisiert.');
redirect('/profile.php'); redirect('/profile.php');
} else { } else {
$avatarError = 'Datei konnte nicht gespeichert werden (Berechtigungen auf dem Server prüfen).'; $avatarError = $storeError;
} }
} }
} }

View file

@ -112,9 +112,7 @@ switch ($action) {
// Ab hier nur die Verwaltung. // Ab hier nur die Verwaltung.
if (!user_has_permission('shop.manage')) { if (!user_has_permission('shop.manage')) {
http_response_code(403); show_not_found();
include __DIR__ . '/includes/forbidden.php';
exit;
} }
$url = shop_return_url(); $url = shop_return_url();

View file

@ -12,6 +12,8 @@ CREATE TABLE IF NOT EXISTS users (
class_name VARCHAR(30) NULL, class_name VARCHAR(30) NULL,
-- Profilseite: frei geschriebener Text (Wiki-Format) -- Profilseite: frei geschriebener Text (Wiki-Format)
profile_bio TEXT NULL, profile_bio TEXT NULL,
-- Kommentare unter den eigenen Galeriebildern (0 = abgeschaltet)
gallery_comments_enabled TINYINT(1) NOT NULL DEFAULT 1,
-- pending = per Discord angemeldet, aber noch nicht freigeschaltet. -- pending = per Discord angemeldet, aber noch nicht freigeschaltet.
status ENUM('active', 'disabled', 'pending') NOT NULL DEFAULT 'active', status ENUM('active', 'disabled', 'pending') NOT NULL DEFAULT 'active',
must_change_password TINYINT(1) NOT NULL DEFAULT 0, must_change_password TINYINT(1) NOT NULL DEFAULT 0,
@ -19,6 +21,8 @@ CREATE TABLE IF NOT EXISTS users (
password_login TINYINT(1) NOT NULL DEFAULT 1, password_login TINYINT(1) NOT NULL DEFAULT 1,
-- 1 = Administrator: hat alle Berechtigungen, unabhaengig von den Gruppen -- 1 = Administrator: hat alle Berechtigungen, unabhaengig von den Gruppen
is_admin TINYINT(1) NOT NULL DEFAULT 0, is_admin TINYINT(1) NOT NULL DEFAULT 0,
-- Hochzaehlen beendet alle Sitzungen des Kontos sofort
session_epoch INT UNSIGNED NOT NULL DEFAULT 0,
discord_id BIGINT UNSIGNED NULL UNIQUE, discord_id BIGINT UNSIGNED NULL UNIQUE,
discord_username VARCHAR(100) NULL, discord_username VARCHAR(100) NULL,
-- OAuth-Token des Discord-Logins (Scopes identify + guilds.members.read), damit -- OAuth-Token des Discord-Logins (Scopes identify + guilds.members.read), damit
@ -396,8 +400,70 @@ CREATE TABLE IF NOT EXISTS member_gallery (
user_id INT UNSIGNED NOT NULL, user_id INT UNSIGNED NOT NULL,
filename VARCHAR(120) NOT NULL, filename VARCHAR(120) NOT NULL,
caption VARCHAR(150) NULL, caption VARCHAR(150) 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,
sort_order INT NOT NULL DEFAULT 0, sort_order INT NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
INDEX idx_member_gallery_user (user_id, sort_order) INDEX idx_member_gallery_user (user_id, sort_order)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Audit-Log, Tempolimits (Spam-Schutz) und Kommentare unter Galeriebildern
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;
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;
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;
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;

View file

@ -11,8 +11,7 @@ $query = trim((string) ($_GET['q'] ?? ''));
$page = $slug !== '' ? wiki_page_by_slug($slug) : null; $page = $slug !== '' ? wiki_page_by_slug($slug) : null;
if ($slug !== '' && !$page) { if ($slug !== '' && !$page) {
set_flash('error', 'Diese Wiki-Seite gibt es nicht (mehr).'); show_not_found();
redirect('/wiki.php');
} }
// Position der Seite im Baum: Nummer, Kapitel, Vorgaenger/Nachfolger in Lesereihenfolge // Position der Seite im Baum: Nummer, Kapitel, Vorgaenger/Nachfolger in Lesereihenfolge

View file

@ -50,8 +50,9 @@ if ($action === 'preview' || $action === 'upload') {
wiki_json(false, ['message' => 'Nur PNG, JPG, GIF oder WEBP sind erlaubt.'], 400); wiki_json(false, ['message' => 'Nur PNG, JPG, GIF oder WEBP sind erlaubt.'], 400);
} }
$name = 'wiki_' . date('Ymd') . '_' . bin2hex(random_bytes(6)) . '.' . $types[$info[2]]; $name = 'wiki_' . date('Ymd') . '_' . bin2hex(random_bytes(6)) . '.' . $types[$info[2]];
if (!move_uploaded_file($file['tmp_name'], WIKI_UPLOAD_DIR . $name)) { $storeError = store_uploaded_image($file['tmp_name'], WIKI_UPLOAD_DIR . $name, $info[2], 2000);
wiki_json(false, ['message' => 'Das Bild konnte nicht gespeichert werden (Schreibrechte auf dem Server prüfen).'], 500); if ($storeError !== null) {
wiki_json(false, ['message' => $storeError], 400);
} }
wiki_json(true, ['url' => WIKI_UPLOAD_URL . $name]); wiki_json(true, ['url' => WIKI_UPLOAD_URL . $name]);
} }

View file

@ -5,8 +5,7 @@ require_permission('wiki.view');
$page = wiki_page_by_id((int) ($_GET['id'] ?? 0)); $page = wiki_page_by_id((int) ($_GET['id'] ?? 0));
if (!$page) { if (!$page) {
set_flash('error', 'Diese Wiki-Seite gibt es nicht (mehr).'); show_not_found();
redirect('/wiki.php');
} }
$canManage = wiki_can_manage(); $canManage = wiki_can_manage();